-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-engine.mjs
More file actions
185 lines (162 loc) · 6.54 KB
/
sync-engine.mjs
File metadata and controls
185 lines (162 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { stableHash } from './hash.mjs';
import {
mapGitHubIssueToMirrorProperties,
mapGitHubProjectItemToMirrorProperties,
mapRowToFollowUpComment,
mapRowToIssue,
priorityLabelForRow,
} from './mapper.mjs';
export async function syncOnce({ config, notion, github, now = () => new Date().toISOString() }) {
const rows = await notion.listRows();
const result = {
scannedRows: rows.length,
createdIssues: 0,
linkedExistingIssues: 0,
commentsPosted: 0,
priorityLabelsApplied: 0,
mirroredIssues: 0,
ensuredProjectItems: 0,
initializedProjectItems: 0,
mirroredProjectItems: 0,
errors: 0,
};
for (const row of rows) {
try {
await syncRow({ row, config, notion, github, now, result });
} catch (error) {
result.errors += 1;
await notion.updateRow(row.id, errorProperties(config, error, now()));
}
}
return result;
}
async function syncRow({ row, config, notion, github, now, result }) {
if (!hasGitHubIssue(row, config)) {
await createOrLinkIssue({ row, config, notion, github, now, result });
return;
}
const commentResult = await syncFollowUpComment({ row, config, notion, github, now });
if (commentResult.posted) result.commentsPosted += 1;
const priorityResult = await syncPriorityLabel({ row, config, github });
if (priorityResult.applied) result.priorityLabelsApplied += 1;
await mirrorGitHubIssue({ row, config, notion, github, now, result });
result.mirroredIssues += 1;
}
async function createOrLinkIssue({ row, config, notion, github, now, result }) {
const existing = await github.findIssueByNotionPageId(row.id);
const issue = existing || await github.createIssue(mapRowToIssue(row, config));
const created = !existing;
if (existing) {
result.linkedExistingIssues += 1;
} else {
result.createdIssues += 1;
}
await notion.updateRow(row.id, {
...await githubMirrorProperties({
issue,
row,
config,
github,
now,
result,
initializeProject: created,
}),
[config.properties.syncStatus]: 'synced',
[config.properties.syncError]: '',
[config.properties.lastSyncDirection]: 'notion_to_github',
[config.properties.lastSyncActor]: 'worker',
[config.properties.lastProcessedAt]: now(),
});
}
async function syncFollowUpComment({ row, config, notion, github, now }) {
const comment = mapRowToFollowUpComment(row, config);
if (!comment || !row.values?.[config.properties.sendFollowUp]) {
return { posted: false };
}
const commentHash = stableHash(comment);
if (row.values?.[config.properties.lastCommentHash] === commentHash) {
await notion.updateRow(row.id, {
[config.properties.sendFollowUp]: false,
[config.properties.lastProcessedAt]: now(),
});
return { posted: false };
}
await github.addComment(Number(row.values[config.properties.githubIssueNumber]), comment);
await notion.updateRow(row.id, {
[config.properties.sendFollowUp]: false,
[config.properties.lastCommentHash]: commentHash,
[config.properties.syncStatus]: 'synced',
[config.properties.syncError]: '',
[config.properties.lastSyncDirection]: 'notion_to_github',
[config.properties.lastSyncActor]: 'worker',
[config.properties.lastProcessedAt]: now(),
});
return { posted: true };
}
async function syncPriorityLabel({ row, config, github }) {
const label = priorityLabelForRow(row, config);
if (!label) return { applied: false };
await github.setPriorityLabel?.(Number(row.values[config.properties.githubIssueNumber]), label, config.allowedPriorityLabels);
return { applied: true };
}
async function mirrorGitHubIssue({ row, config, notion, github, now, result }) {
const issue = await github.getIssue(Number(row.values[config.properties.githubIssueNumber]));
await notion.updateRow(row.id, {
...await githubMirrorProperties({ issue, config, github, now, result }),
[config.properties.syncStatus]: 'synced',
[config.properties.syncError]: '',
[config.properties.lastSyncDirection]: 'github_to_notion',
[config.properties.lastSyncActor]: 'worker',
[config.properties.lastProcessedAt]: now(),
});
}
async function githubMirrorProperties({ issue, row, config, github, now, result, initializeProject = false }) {
const timestamp = now();
const properties = mapGitHubIssueToMirrorProperties(issue, { ...config, now: timestamp });
if (!config.projectSyncEnabled || !issue.node_id) return properties;
const ensured = await github.ensureProjectItem?.(issue.node_id);
if (ensured && result) result.ensuredProjectItems += 1;
if (initializeProject && ensured?.id && github.setProjectItemFields) {
const fields = initialProjectFields(row, config);
if (Object.keys(fields).length > 0) {
await github.setProjectItemFields(ensured.id, fields);
if (result) result.initializedProjectItems += 1;
}
}
const projectItem = await github.getProjectItemForIssue?.(issue.node_id) || ensured;
if (!projectItem) return properties;
if (result) result.mirroredProjectItems += 1;
return {
...properties,
...mapGitHubProjectItemToMirrorProperties(projectItem, { ...config, now: timestamp }),
};
}
function initialProjectFields(row, config) {
const projectFields = config.githubProjectFields || {};
const defaults = config.githubProjectDefaults || {};
const fields = {};
if (projectFields.status && defaults.status) fields[projectFields.status] = defaults.status;
if (projectFields.source && defaults.source) fields[projectFields.source] = defaults.source;
const requestType = row?.values?.[config.properties.requestType];
if (projectFields.requestType && requestType) fields[projectFields.requestType] = requestType;
const priority = projectPriority(row?.values?.[config.properties.businessPriority]);
if (projectFields.priority && priority) fields[projectFields.priority] = priority;
return fields;
}
function projectPriority(value) {
const text = String(value || '').trim();
if (!text) return '';
const priority = text.includes(':') ? text.split(':').pop().trim() : text;
return priority.replace(/\w\S*/g, (word) => word[0].toUpperCase() + word.slice(1).toLowerCase());
}
function hasGitHubIssue(row, config) {
return Boolean(row.values?.[config.properties.githubIssueUrl] || row.values?.[config.properties.githubIssueNumber]);
}
function errorProperties(config, error, timestamp) {
return {
[config.properties.syncStatus]: 'error',
[config.properties.syncError]: error instanceof Error ? error.message : String(error),
[config.properties.lastSyncActor]: 'worker',
[config.properties.lastProcessedAt]: timestamp,
};
}