@graview/core 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +8 -2
  2. package/dist/cli/document-schema.js +1 -1
  3. package/dist/cli/document-schema.js.map +1 -1
  4. package/dist/document/connection-findings.d.ts.map +1 -1
  5. package/dist/document/connection-findings.js +103 -10
  6. package/dist/document/connection-findings.js.map +1 -1
  7. package/dist/document/connection-spec.d.ts +43 -3
  8. package/dist/document/connection-spec.d.ts.map +1 -1
  9. package/dist/document/connection-spec.js +51 -4
  10. package/dist/document/connection-spec.js.map +1 -1
  11. package/dist/document/describe-place.d.ts.map +1 -1
  12. package/dist/document/describe-place.js +2 -0
  13. package/dist/document/describe-place.js.map +1 -1
  14. package/dist/document/described.d.ts +6 -0
  15. package/dist/document/described.d.ts.map +1 -1
  16. package/dist/document/edit.js +1 -1
  17. package/dist/document/edit.js.map +1 -1
  18. package/dist/document/kept-in-step-with.d.ts +4 -4
  19. package/dist/document/kept-in-step-with.d.ts.map +1 -1
  20. package/dist/document/kept-in-step-with.js +5 -1
  21. package/dist/document/kept-in-step-with.js.map +1 -1
  22. package/dist/document/kept-in-step.js +1 -1
  23. package/dist/document/kept-in-step.js.map +1 -1
  24. package/dist/document.schema.json +154 -3
  25. package/dist/scaffold/domain.js +1 -1
  26. package/dist/scaffold/from-template.js +3 -3
  27. package/dist/scaffold/from-template.js.map +1 -1
  28. package/dist/scaffold/index.d.ts.map +1 -1
  29. package/dist/scaffold/index.js +2 -3
  30. package/dist/scaffold/index.js.map +1 -1
  31. package/dist/scaffold/names.d.ts +0 -1
  32. package/dist/scaffold/names.d.ts.map +1 -1
  33. package/dist/scaffold/names.js.map +1 -1
  34. package/dist/scaffold/project.d.ts.map +1 -1
  35. package/dist/scaffold/project.js +18 -13
  36. package/dist/scaffold/project.js.map +1 -1
  37. package/dist/scaffold/ui.d.ts +1 -1
  38. package/dist/scaffold/ui.d.ts.map +1 -1
  39. package/dist/scaffold/ui.js +115 -164
  40. package/dist/scaffold/ui.js.map +1 -1
  41. package/dist/sync/connection.d.ts +22 -5
  42. package/dist/sync/connection.d.ts.map +1 -1
  43. package/dist/sync/connection.js +274 -6
  44. package/dist/sync/connection.js.map +1 -1
  45. package/dist/sync/engine.d.ts +38 -1
  46. package/dist/sync/engine.d.ts.map +1 -1
  47. package/dist/sync/engine.js +184 -12
  48. package/dist/sync/engine.js.map +1 -1
  49. package/dist/sync/google-calendar.d.ts.map +1 -1
  50. package/dist/sync/google-calendar.js +27 -4
  51. package/dist/sync/google-calendar.js.map +1 -1
  52. package/dist/sync/guests.d.ts +7 -2
  53. package/dist/sync/guests.d.ts.map +1 -1
  54. package/dist/sync/guests.js +33 -15
  55. package/dist/sync/guests.js.map +1 -1
  56. package/dist/sync/index.d.ts +10 -3
  57. package/dist/sync/index.d.ts.map +1 -1
  58. package/dist/sync/index.js +6 -2
  59. package/dist/sync/index.js.map +1 -1
  60. package/dist/sync/notion.d.ts.map +1 -1
  61. package/dist/sync/notion.js +18 -10
  62. package/dist/sync/notion.js.map +1 -1
  63. package/dist/sync/todoist-due.d.ts +35 -0
  64. package/dist/sync/todoist-due.d.ts.map +1 -0
  65. package/dist/sync/todoist-due.js +132 -0
  66. package/dist/sync/todoist-due.js.map +1 -0
  67. package/dist/sync/todoist-stub.d.ts +85 -0
  68. package/dist/sync/todoist-stub.d.ts.map +1 -0
  69. package/dist/sync/todoist-stub.js +316 -0
  70. package/dist/sync/todoist-stub.js.map +1 -0
  71. package/dist/sync/todoist-types.d.ts +27 -0
  72. package/dist/sync/todoist-types.d.ts.map +1 -0
  73. package/dist/sync/todoist-types.js +46 -0
  74. package/dist/sync/todoist-types.js.map +1 -0
  75. package/dist/sync/todoist.d.ts +112 -0
  76. package/dist/sync/todoist.d.ts.map +1 -0
  77. package/dist/sync/todoist.js +892 -0
  78. package/dist/sync/todoist.js.map +1 -0
  79. package/dist/sync/types.d.ts +53 -2
  80. package/dist/sync/types.d.ts.map +1 -1
  81. package/dist/sync/types.js.map +1 -1
  82. package/dist/version.d.ts +1 -1
  83. package/dist/version.js +1 -1
  84. package/package.json +1 -1
@@ -0,0 +1,892 @@
1
+ import { dueDay, dueInstant, dueToWrite, dueWall, readRepeat, sameZone, sayRepeat } from "./todoist-due.js";
2
+ /**
3
+ * A Todoist project, as a transport.
4
+ *
5
+ * Todoist's API v1 and its `/sync` endpoint (developer.todoist.com/api/v1,
6
+ * read 2026-11-25; the pages relied on are named where they are). One
7
+ * project, or one section or label of it, is one resource (`tasks`), and
8
+ * each of its tasks one record. Everything Todoist-specific is here; the
9
+ * engine sees plain values keyed by a task's parts (`content`, `due`, …):
10
+ *
11
+ * - A PULL sends the last sync token and is answered what changed since
12
+ * (sync/overview.md, "Incremental sync"); `*` answers "all active resource
13
+ * data", so a whole read does not list a completed task. A task is
14
+ * `checked` when completed and `is_deleted` when deleted (sync/tasks.md).
15
+ * - COMPLETED IS NEVER GONE. A completed task is a task whose `completed`
16
+ * is true. A task this sync knew that a whole read does not list is looked
17
+ * for among the completed ones, then asked for by id; one neither answers
18
+ * for is left as it is, and said. Only `is_deleted`, or a task moved out
19
+ * of what the connection keeps, takes a record away.
20
+ * - A VERSION is a hash of the parts kept, so our own write coming back is
21
+ * an echo exactly when it holds what was sent, and an edit in the same
22
+ * second is still news.
23
+ * - A PUSH sends only the parts that changed (`RemoteWrite.changed`) as
24
+ * commands, up to 100 to a request (request-limits.md): `item_add`,
25
+ * `item_update`, `item_move` (its section or parent, which
26
+ * `item_update` does not change), `item_uncomplete`, `item_delete`, and
27
+ * then `item_close`, which completes a task and moves one that repeats to
28
+ * its next date. It goes last and alone, so it is never sent twice for
29
+ * another part's refusal. Every command carries a `uuid` Todoist executes
30
+ * once, so a request whose answer was lost is made again as it was.
31
+ * - THE CONNECTION'S LABEL is put on every task sent and left out of what a
32
+ * record's labels say.
33
+ * - A RECORD SET ASIDE leaves its task as it is (`aside`): nothing is sent
34
+ * for it, and no task above it is deleted while it is, for a delete takes
35
+ * "all its sub-tasks" (sync/tasks.md) and nothing undoes one.
36
+ * - A PART THAT CANNOT BE SENT is held, and said ("held unsent"): a due
37
+ * date whose repeat there are no words for, a section there is not. The
38
+ * rest of a task already there goes; one not made yet waits whole. A part
39
+ * held in conflict is never read as empty.
40
+ * - Todoist asking us to slow down (429) is waited out as its `Retry-After`
41
+ * says, within a bound; a refused token (401) and a project it cannot
42
+ * find are said as sentences that say what to do.
43
+ */
44
+ export const TODOIST_API = "https://api.todoist.com/api/v1";
45
+ /** request-limits.md: "The maximum number of commands is 100 per request", and a 1 MiB body. */
46
+ const MOST_COMMANDS = 100;
47
+ const MOST_BYTES = 900_000;
48
+ /** tasks.md, "Tasks Completed By Completion Date": a range of "up to 3 months". */
49
+ const COMPLETED_DAYS = 89;
50
+ const COMPLETED_PAGE = 200;
51
+ const DAY_MS = 86_400_000;
52
+ export const isUnsayable = (value) => typeof value === "object" && value !== null && typeof value.held === "string";
53
+ /** What Todoist answered, when it was not a yes. */
54
+ export class TodoistError extends Error {
55
+ status;
56
+ tag;
57
+ constructor(message, status, tag) {
58
+ super(message);
59
+ this.status = status;
60
+ this.tag = tag;
61
+ this.name = "TodoistError";
62
+ }
63
+ }
64
+ const loose = (word) => word.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
65
+ const words = (value) => (typeof value === "string" && value !== "" ? value : null);
66
+ const asWords = (value) => (value === null || value === undefined ? "" : String(value));
67
+ /** A short, stable hash of a task's parts: what makes it the one last agreed, or news. */
68
+ export function todoistVersion(values) {
69
+ const text = JSON.stringify(Object.keys(values).sort().map((key) => [key, values[key] ?? null]));
70
+ let one = 0x811c9dc5;
71
+ let two = 0x1000193;
72
+ for (let at = 0; at < text.length; at++) {
73
+ one = Math.imul(one ^ text.charCodeAt(at), 0x01000193) >>> 0;
74
+ two = Math.imul(two ^ text.charCodeAt(text.length - 1 - at), 0x01000193) >>> 0;
75
+ }
76
+ return one.toString(16).padStart(8, "0") + two.toString(16).padStart(8, "0");
77
+ }
78
+ export function todoist(options) {
79
+ const doFetch = options.fetch ?? globalThis.fetch;
80
+ const base = options.baseUrl ?? TODOIST_API;
81
+ const secret = options.secretName ?? "the API token";
82
+ const now = options.now ?? (() => Date.now());
83
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
84
+ const uuid = options.uuid ?? (() => globalThis.crypto.randomUUID());
85
+ const maxWait = options.maxWait ?? 60_000;
86
+ const { refs } = options;
87
+ const keeps = (ref) => ref in refs;
88
+ const dueAs = refs["due"] === "date" ? "day" : "moment";
89
+ const said = new Set();
90
+ let fresh = [];
91
+ const note = (line) => {
92
+ if (said.has(line))
93
+ return;
94
+ said.add(line);
95
+ fresh.push(line);
96
+ options.say?.(line);
97
+ };
98
+ /** One request, Todoist's rate limit waited out; anything but a yes thrown as a `TodoistError`. */
99
+ const call = async (method, path, form) => {
100
+ let waited = 0;
101
+ for (;;) {
102
+ const response = await doFetch(`${base}${path}`, {
103
+ method,
104
+ headers: { authorization: `Bearer ${await options.token()}`, ...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}) },
105
+ ...(form ? { body: new URLSearchParams(form).toString() } : {}),
106
+ });
107
+ const answer = ((await response.json().catch(() => ({}))) ?? {});
108
+ if (response.status === 429) {
109
+ // `Retry-After`, and `error_extra.retry_after` beside it (sync/overview.md).
110
+ const after = Number(response.headers?.get("retry-after") ?? answer["error_extra"]?.["retry_after"] ?? "");
111
+ const wait = Number.isFinite(after) && after > 0 ? after * 1000 : 1000;
112
+ if (waited + wait > maxWait)
113
+ throw new TodoistError(`todoist: Todoist is still limiting the rate after ${Math.round(waited / 1000)} s of waiting (HTTP 429); the next pass tries again`, 429);
114
+ waited += wait;
115
+ await sleep(wait);
116
+ continue;
117
+ }
118
+ if (response.ok)
119
+ return answer;
120
+ const tag = typeof answer["error_tag"] === "string" ? answer["error_tag"] : undefined;
121
+ if (response.status === 401)
122
+ throw new TodoistError(`todoist: Todoist refused ${secret} (HTTP 401): copy the API token from Todoist's Settings → Integrations → Developer again`, 401, tag);
123
+ throw new TodoistError(`todoist: HTTP ${response.status}${sentenceOf(answer)}`, response.status, tag);
124
+ }
125
+ };
126
+ /*
127
+ * WHAT WAS SENT AND NOT ANSWERED, judged by what the next pull shows
128
+ * rather than sent again blind. A task that may have been made is known by
129
+ * its words, being new there since: the write that made it then takes it
130
+ * up and sets the rest. One that repeats and may have been completed is
131
+ * known by its date having moved on. Kept while the process runs; a
132
+ * process that stops between the two makes its task again, and a record
133
+ * removed in between comes back with its task.
134
+ */
135
+ /** Our id → the words an unanswered `item_add` sent. */
136
+ const unheard = new Map();
137
+ /** Our id → the task that turned up holding them, withheld from the pull until its write takes it up. */
138
+ const found = new Map();
139
+ /** A task whose `item_close` was not answered → the date it was due then. */
140
+ const closing = new Map();
141
+ /** Tasks read again as they stand on the next pull. */
142
+ const recheck = new Set();
143
+ let pushed = false;
144
+ /** Our ids among those that were set aside at the last pull. */
145
+ let waited = new Set();
146
+ /** Each subtask's parent, a completed one's too: kept in the cursor, so what is under a task is known whatever a read lists. */
147
+ let under = new Map();
148
+ /** Subtasks set aside, kept until they are out from under what was above them: bringing one back is not leave to delete it with its parent. */
149
+ const spared = new Set();
150
+ /** The records set aside that have been said. */
151
+ const saidAside = new Set();
152
+ const letGo = (localId) => {
153
+ const id = found.get(localId);
154
+ if (id !== undefined)
155
+ recheck.add(id);
156
+ found.delete(localId);
157
+ unheard.delete(localId);
158
+ };
159
+ const sync = (token, resources) => call("POST", "/sync", { sync_token: token, resource_types: JSON.stringify(resources) });
160
+ /* ------------------------------------------------ the project, and the names its tasks use */
161
+ let around;
162
+ let aroundToken = "*";
163
+ const readAround = async () => {
164
+ const answer = await sync(aroundToken, ["user", "projects", "sections", "collaborators", "collaborator_states"]).catch((error) => {
165
+ if (aroundToken === "*" || !isTokenRefused(error))
166
+ throw error;
167
+ aroundToken = "*";
168
+ return sync("*", ["user", "projects", "sections", "collaborators", "collaborator_states"]);
169
+ });
170
+ if (!around || answer["full_sync"] === true)
171
+ around = { projects: new Map(), sections: new Map(), people: new Map(), places: new Map(), user: {} };
172
+ const held = around;
173
+ const merge = (into, list, key) => {
174
+ for (const one of list ?? [])
175
+ into.set(key(one), one);
176
+ };
177
+ merge(held.projects, answer["projects"], (one) => String(one["id"]));
178
+ merge(held.sections, answer["sections"], (one) => String(one["id"]));
179
+ merge(held.people, answer["collaborators"], (one) => String(one["id"]));
180
+ merge(held.places, answer["collaborator_states"], (one) => `${String(one["project_id"])} ${String(one["user_id"])}`);
181
+ if (answer["user"] && Object.keys(answer["user"]).length > 0)
182
+ held.user = { ...held.user, ...answer["user"] };
183
+ if (typeof answer["sync_token"] === "string")
184
+ aroundToken = answer["sync_token"];
185
+ return held;
186
+ };
187
+ const here = async () => around ?? (await readAround());
188
+ /** One of several by its id, else by its name: as written, then loosely when only one has it. */
189
+ const pick = (list, named) => {
190
+ const exact = list.find((one) => one["id"] === named) ?? list.find((one) => one["name"] === named);
191
+ const near = list.filter((one) => loose(String(one["name"])) === loose(named));
192
+ return exact ?? (near.length === 1 ? near[0] : undefined);
193
+ };
194
+ const projectId = (held) => {
195
+ const found = pick([...held.projects.values()].filter((one) => one["is_deleted"] !== true), options.projectId);
196
+ if (!found)
197
+ throw new TodoistError(`todoist: the account of ${secret} has no project ${options.projectId}: name it by its id, the letters and digits at the end of its link, or share the project with that account`, 404);
198
+ if (found["is_archived"] === true)
199
+ throw new TodoistError(`todoist: the project ${String(found["name"])} is archived in Todoist: unarchive it there, or name another`, 404);
200
+ return String(found["id"]);
201
+ };
202
+ const sectionsOf = (held) => [...held.sections.values()].filter((one) => one["project_id"] === projectId(held) && one["is_deleted"] !== true);
203
+ const sectionId = (held, named) => {
204
+ const found = pick(sectionsOf(held).filter((one) => one["is_archived"] !== true), named);
205
+ if (!found)
206
+ throw new TodoistError(`todoist: the project has no section ${named}: make it in Todoist, or name one it has (${sectionsOf(held).map((one) => String(one["name"])).join(", ") || "it has none"})`, 404);
207
+ return String(found["id"]);
208
+ };
209
+ /** Who a task of the project may be assigned to: the people on it, and the account itself. */
210
+ const peopleOf = (held) => {
211
+ const project = projectId(held);
212
+ const on = [...held.places.values()].filter((one) => one["project_id"] === project && one["is_deleted"] !== true).map((one) => held.people.get(String(one["user_id"]))).filter((one) => one !== undefined);
213
+ return [...on, held.user].filter((one) => one["id"] !== undefined);
214
+ };
215
+ const personId = (held, named) => {
216
+ const want = named.trim().toLowerCase();
217
+ const people = peopleOf(held);
218
+ const found = people.find((one) => String(one["email"] ?? "").toLowerCase() === want) ?? only(people.filter((one) => String(one["full_name"] ?? "").toLowerCase() === want));
219
+ if (!found)
220
+ throw new TodoistError(`todoist: nobody on the project is ${named}, so the task is not assigned: say an email or a name of somebody the project is shared with`, 404);
221
+ return String(found["id"]);
222
+ };
223
+ const zoneOf = (held) => words(held.user["tz_info"]?.["timezone"]) ?? options.zone ?? "UTC";
224
+ /** The names this connection's values are read through, as one word: when they change, every task is read again. */
225
+ const namesNow = (held) => todoistVersion({
226
+ project: projectId(held),
227
+ ...(keeps("section") || options.section ? { sections: sectionsOf(held).map((one) => [one["id"], one["name"]]) } : {}),
228
+ ...(keeps("assignee") ? { people: peopleOf(held).map((one) => [one["id"], one["full_name"], one["email"]]) } : {}),
229
+ ...(keeps("due") ? { zone: zoneOf(held) } : {}),
230
+ });
231
+ /* ------------------------------------------------------------ a task, as plain parts */
232
+ /** The words a due date repeats in, when a repeat here can hold them and the two clocks agree. */
233
+ const repeatIn = (due, zone) => {
234
+ if (!due?.is_recurring || !due.string)
235
+ return null;
236
+ if (due.lang && due.lang !== "en")
237
+ return null;
238
+ if (due.timezone && !sameZone(due.timezone, zone))
239
+ return null;
240
+ if (options.zone && !sameZone(options.zone, zone))
241
+ return null;
242
+ const repeat = readRepeat(due.string);
243
+ return (repeat && sayRepeat(repeat)) ?? null;
244
+ };
245
+ const dueOf = (item) => (item["due"] && typeof item["due"] === "object" && typeof item["due"]["date"] === "string" ? item["due"] : undefined);
246
+ const valuesOf = (item, held) => {
247
+ const out = {};
248
+ const zone = zoneOf(held);
249
+ const due = dueOf(item);
250
+ for (const ref of Object.keys(refs)) {
251
+ switch (ref) {
252
+ case "content":
253
+ case "description":
254
+ out[ref] = words(item[ref]);
255
+ break;
256
+ case "due":
257
+ out[ref] = due ? (dueAs === "day" ? dueDay(due, zone) : dueInstant(due, zone)) : null;
258
+ break;
259
+ case "repeat": {
260
+ const repeat = repeatIn(due, zone);
261
+ if (due?.is_recurring && repeat === null)
262
+ note(`${String(item["content"])} repeats in Todoist as "${due.string ?? ""}", which is not a repeat this app can keep: its date is kept, and how it repeats stays in Todoist`);
263
+ out[ref] = repeat;
264
+ break;
265
+ }
266
+ case "deadline":
267
+ out[ref] = words(item["deadline"]?.["date"]);
268
+ break;
269
+ case "priority": {
270
+ // "p1 will return 4 in the API" (sync/tasks.md): kept as people see it, 1 the most urgent.
271
+ const api = Number(item["priority"]);
272
+ out[ref] = api >= 1 && api <= 4 ? 5 - api : 4;
273
+ break;
274
+ }
275
+ case "labels": {
276
+ const named = (item["labels"] ?? []).filter((label) => label !== options.label);
277
+ out[ref] = named.length > 0 ? [...new Set(named)].sort() : null;
278
+ break;
279
+ }
280
+ case "section":
281
+ out[ref] = item["section_id"] ? (words(held.sections.get(String(item["section_id"]))?.["name"]) ?? null) : null;
282
+ break;
283
+ case "assignee": {
284
+ const id = item["responsible_uid"];
285
+ const person = id ? peopleOf(held).find((one) => String(one["id"]) === String(id)) ?? held.people.get(String(id)) : undefined;
286
+ out[ref] = !id ? null : words(person?.[refs["assignee"] === "email" ? "email" : "full_name"]);
287
+ break;
288
+ }
289
+ case "parent":
290
+ out[ref] = item["parent_id"] ? [String(item["parent_id"])] : null;
291
+ break;
292
+ case "completed":
293
+ out[ref] = item["checked"] === true;
294
+ break;
295
+ }
296
+ }
297
+ return out;
298
+ };
299
+ /** The tasks the last pulls listed, as Todoist has them: what a write reads a due date's repeat and time from. */
300
+ const listed = new Map();
301
+ const taskNow = async (id) => {
302
+ const have = listed.get(id);
303
+ if (have)
304
+ return have;
305
+ try {
306
+ const task = await call("GET", `/tasks/${encodeURIComponent(id)}`);
307
+ listed.set(id, task);
308
+ return task;
309
+ }
310
+ catch (error) {
311
+ // Refused for this one task (404 for one completed or deleted, 403 for one out of reach) is a task not read, not a pass that failed.
312
+ if (error instanceof TodoistError && error.status !== 401 && error.status !== 429 && error.status < 500)
313
+ return undefined;
314
+ throw error;
315
+ }
316
+ };
317
+ /** The completed tasks of the project among these, by id: pages of the last three months' (tasks.md). */
318
+ const completedAmong = async (ids, project) => {
319
+ const found = [];
320
+ let cursor;
321
+ do {
322
+ const query = new URLSearchParams({
323
+ since: new Date(now() - COMPLETED_DAYS * DAY_MS).toISOString(),
324
+ until: new Date(now() + DAY_MS / 24).toISOString(),
325
+ project_id: project,
326
+ limit: String(COMPLETED_PAGE),
327
+ ...(cursor ? { cursor } : {}),
328
+ });
329
+ const answer = await call("GET", `/tasks/completed/by_completion_date?${query.toString()}`);
330
+ for (const item of answer["items"] ?? [])
331
+ if (ids.has(String(item["id"])))
332
+ found.push({ ...item, checked: true });
333
+ cursor = words(answer["next_cursor"]) ?? undefined;
334
+ } while (cursor);
335
+ return found;
336
+ };
337
+ const itemsSince = async (token) => {
338
+ let answer;
339
+ try {
340
+ answer = await sync(token, ["items"]);
341
+ }
342
+ catch (error) {
343
+ // A token Todoist no longer takes is a whole read, as none is.
344
+ if (token === "*" || !isTokenRefused(error))
345
+ throw error;
346
+ answer = await sync("*", ["items"]);
347
+ }
348
+ const items = new Map((answer["items"] ?? []).map((item) => [String(item["id"]), item]));
349
+ const whole = token === "*" || answer["full_sync"] === true;
350
+ let next = String(answer["sync_token"] ?? token);
351
+ // "For big accounts, the data in the initial sync may be returned with some delay … do an incremental sync" (sync/overview.md).
352
+ const dated = whole ? Date.parse(String(answer["full_sync_date_utc"] ?? "")) : NaN;
353
+ if (Number.isFinite(dated) && now() - dated > 60_000) {
354
+ const later = await sync(next, ["items"]);
355
+ for (const item of later["items"] ?? [])
356
+ items.set(String(item["id"]), item);
357
+ next = String(later["sync_token"] ?? next);
358
+ }
359
+ return { items, token: next, whole };
360
+ };
361
+ /** Whether a command of this push was answered: the first request that fails is a run that failed, a later one is not. */
362
+ let sent = false;
363
+ /** Whether a task that repeats moved on since its completion was sent and not answered. */
364
+ const movedOn = (id) => {
365
+ const was = closing.get(id);
366
+ const due = dueOf(listed.get(id) ?? {});
367
+ return was !== undefined && due !== undefined && due.date !== was;
368
+ };
369
+ return {
370
+ name: "todoist",
371
+ async pull(cursor) {
372
+ const held = await readAround();
373
+ // Nothing was owed after the last pull, so nothing is taken up: a task like any other.
374
+ if (!pushed) {
375
+ // Save for a record set aside, or just brought back: what it owes is worked out on the pass after.
376
+ for (const localId of [...unheard.keys()])
377
+ if (!waited.has(localId) && !options.isAside?.(localId))
378
+ letGo(localId);
379
+ const waits = new Set((options.aside?.() ?? []).map((one) => one.id));
380
+ for (const id of [...closing.keys()])
381
+ if (!waits.has(id) && !saidAside.has(id))
382
+ closing.delete(id);
383
+ }
384
+ const project = projectId(held);
385
+ const section = options.section ? sectionId(held, options.section) : undefined;
386
+ const names = namesNow(held);
387
+ const kept = readCursor(cursor);
388
+ const scope = todoistVersion({ project, section: section ?? null, label: options.label ?? null });
389
+ // Another project's tasks are not this one's moved out: nothing is taken away for a change of what is declared.
390
+ if (kept && kept.scope !== scope) {
391
+ throw new TodoistError("todoist: this connection kept another project, section or label before, and the records it made are of that one: put it back, or keep the new one with a connection of another name", 400);
392
+ }
393
+ under = new Map(Object.entries(kept?.under ?? {}));
394
+ const read = await itemsSince(kept && kept.names === names ? kept.token : "*");
395
+ const known = new Map((options.known?.() ?? []).map((one) => [one.id, one]));
396
+ if (read.whole) {
397
+ listed.clear();
398
+ // A whole read is of active tasks: what it does not list is completed, deleted, or out of sight.
399
+ const absent = new Set([...known.values()].filter((one) => (!one.completed || !kept) && !read.items.has(one.id)).map((one) => one.id));
400
+ if (absent.size > 0) {
401
+ for (const item of await completedAmong(absent, project)) {
402
+ read.items.set(String(item["id"]), item);
403
+ absent.delete(String(item["id"]));
404
+ }
405
+ for (const id of absent) {
406
+ if (known.get(id)?.completed)
407
+ continue;
408
+ const item = await taskNow(id);
409
+ if (item)
410
+ read.items.set(id, item);
411
+ else
412
+ note(`Todoist no longer lists the task ${id}, so what it made here is kept as it was`);
413
+ }
414
+ }
415
+ }
416
+ for (const id of recheck) {
417
+ const item = read.items.has(id) ? undefined : await taskNow(id);
418
+ if (item)
419
+ read.items.set(id, item);
420
+ }
421
+ recheck.clear();
422
+ for (const [id, item] of read.items) {
423
+ const parent = item["is_deleted"] === true ? null : words(item["parent_id"]);
424
+ if (parent === null || item["project_id"] !== project)
425
+ under.delete(id);
426
+ else
427
+ under.set(id, parent);
428
+ }
429
+ waited = new Set([...unheard.keys()].filter((localId) => options.isAside?.(localId)));
430
+ const aside = new Map((options.aside?.() ?? []).map((one) => [one.id, one]));
431
+ for (const id of kept?.spared ?? [])
432
+ spared.add(id);
433
+ const asides = asideNow();
434
+ for (const id of asides.keys())
435
+ spared.add(id);
436
+ // Let go once nothing is above it, or it is brought back with no record above it removed here: a task like any other.
437
+ for (const id of [...spared])
438
+ if (!under.has(id) || (!asides.has(id) && !climb(id).some((one) => known.get(one)?.removed)))
439
+ spared.delete(id);
440
+ for (const id of kept?.aside ?? [])
441
+ saidAside.add(id);
442
+ for (const id of [...saidAside]) {
443
+ if (aside.has(id))
444
+ continue;
445
+ saidAside.delete(id);
446
+ // Brought back: read as it stands, for what was let be while it was aside.
447
+ const item = read.items.has(id) ? undefined : await taskNow(id);
448
+ if (item)
449
+ read.items.set(id, item);
450
+ }
451
+ for (const { id, label } of aside.values()) {
452
+ if (saidAside.has(id))
453
+ continue;
454
+ saidAside.add(id);
455
+ const line = `${label} is set aside here: its task is left as it is in Todoist, and nothing is sent for it until it is brought back`;
456
+ fresh.push(line);
457
+ options.say?.(line);
458
+ }
459
+ const changes = [];
460
+ for (const [id, item] of read.items) {
461
+ const isKnown = known.has(id);
462
+ const checked = item["checked"] === true;
463
+ const inScope = item["project_id"] === project && (section === undefined || item["section_id"] === section) && (options.label === undefined || (item["labels"] ?? []).includes(options.label));
464
+ if (item["is_deleted"] === true || (!inScope && !(isKnown && checked))) {
465
+ listed.delete(id);
466
+ // Out of what the connection keeps while its record is aside: judged when the record is brought back.
467
+ if (item["is_deleted"] !== true && aside.has(id))
468
+ continue;
469
+ if (isKnown)
470
+ changes.push({ resource: "tasks", id, version: "gone", deleted: true });
471
+ continue;
472
+ }
473
+ // A task already completed when first seen is a record only where a field says it is completed.
474
+ if (!isKnown && checked && !keeps("completed"))
475
+ continue;
476
+ listed.set(id, item);
477
+ const fields = valuesOf(item, held);
478
+ if (!isKnown) {
479
+ const said = asWords(item["content"]).trim();
480
+ const ours = [...unheard].find(([localId, sent]) => sent === said && !found.has(localId));
481
+ if (ours || [...found.values()].includes(id)) {
482
+ if (ours)
483
+ found.set(ours[0], id);
484
+ continue;
485
+ }
486
+ }
487
+ changes.push({ resource: "tasks", id, version: todoistVersion(fields), fields });
488
+ }
489
+ // Only a pull that was answered is one nothing was owed after.
490
+ pushed = false;
491
+ // What did not turn up by the first pull that was answered was not made.
492
+ for (const localId of [...unheard.keys()])
493
+ if (!found.has(localId))
494
+ unheard.delete(localId);
495
+ const said = fresh;
496
+ fresh = [];
497
+ return { changes, cursor: JSON.stringify({ token: read.token, names, scope, ...(under.size > 0 ? { under: Object.fromEntries(under) } : {}), ...(saidAside.size > 0 ? { aside: [...saidAside] } : {}), ...(spared.size > 0 ? { spared: [...spared] } : {}) }), ...(said.length > 0 ? { said } : {}) };
498
+ },
499
+ async push(writes) {
500
+ const around = await here();
501
+ const acks = new Map();
502
+ const refuse = (write, error) => acks.set(write.localId, { localId: write.localId, id: write.id ?? "", version: "", error: error instanceof Error ? error.message : String(error) });
503
+ const planned = [];
504
+ pushed = true;
505
+ sent = false;
506
+ const owedNow = new Set(writes.map((write) => write.localId));
507
+ for (const localId of [...unheard.keys()])
508
+ if (!owedNow.has(localId) && !options.isAside?.(localId))
509
+ letGo(localId);
510
+ const completing = new Set(writes.filter((write) => write.fields?.["completed"] === true && write.changed?.includes("completed")).map((write) => write.id));
511
+ const waits = new Set((options.aside?.() ?? []).map((one) => one.id));
512
+ for (const id of [...closing.keys()])
513
+ if (!completing.has(id) && !waits.has(id))
514
+ closing.delete(id);
515
+ for (const write of writes) {
516
+ try {
517
+ planned.push(await plan(write, around));
518
+ }
519
+ catch (error) {
520
+ // One refusal is not a failed run: the engine keeps the local state for this write and says so.
521
+ if (error instanceof TodoistError && (error.status === 401 || error.status === 429))
522
+ throw error;
523
+ refuse(write, error);
524
+ }
525
+ }
526
+ /* Made and changed first, deleted next, completed last: a part refused then never repeats a completion, and a task goes only once what was under it has been moved out. */
527
+ const clean = new Set();
528
+ const toClose = [];
529
+ const first = await execute(planned.filter((one) => !one.write.deleted).flatMap((one) => one.commands), (lost) => {
530
+ for (const one of planned)
531
+ if (one.made && lost.has(one.made.uuid))
532
+ unheard.set(one.write.localId, asWords(one.write.fields?.["content"]).trim());
533
+ });
534
+ for (const one of planned) {
535
+ if (one.write.deleted)
536
+ continue;
537
+ const outcome = one.commands.map((command) => first.status.get(command.uuid));
538
+ const bad = outcome.find((status) => status !== undefined && !status.ok && !status.later);
539
+ const id = one.id ?? (one.made ? first.ids.get(one.made.temp_id) : undefined);
540
+ if (bad)
541
+ refuse(one.write, `todoist: ${bad.said}`);
542
+ else if (outcome.some((status) => status === undefined || status.later)) {
543
+ // Not answered for, or asked to wait: still owed, and worked out again on the next pass.
544
+ }
545
+ else if (id === undefined)
546
+ refuse(one.write, "todoist: Todoist did not say the id of the task it made");
547
+ else if (one.close && !movedOn(id))
548
+ toClose.push({ one, id });
549
+ else {
550
+ // Completed on a pass that did not hear so: it is agreed, and read again as it stands.
551
+ if (one.close)
552
+ recheck.add(id);
553
+ closing.delete(id);
554
+ acks.set(one.write.localId, one.ack(id));
555
+ if (!one.partly)
556
+ clean.add(id);
557
+ }
558
+ }
559
+ /* A task is deleted with everything under it, so not while a change to something under it is still owed or refused. */
560
+ const deletes = planned.filter((one) => one.write.deleted);
561
+ const open = new Set(writes.flatMap((write) => (write.id && !write.deleted && !clean.has(write.id) && !toClose.some((one) => one.id === write.id) ? [write.id] : [])));
562
+ /* Nor while the task of a record set aside is under it, however far: that one is not deleted until its record is. */
563
+ const above = new Set();
564
+ const asides = asideNow();
565
+ for (const [id, parent] of asides)
566
+ for (const at of climb(id, parent))
567
+ above.add(at);
568
+ for (const id of spared)
569
+ for (const at of climb(id))
570
+ above.add(at);
571
+ const waiting = (id) => above.has(id) || [...under].some(([child, parent]) => parent === id && (options.movedElsewhere?.(child) ?? false)) || [...open].some((other) => under.get(other) === id);
572
+ for (const { write } of deletes) {
573
+ if (above.has(write.id))
574
+ note(`the task ${write.id} is not deleted in Todoist while the task of a record set aside is under it, or of one that was: bring it back and move it out from under this one, or remove its record`);
575
+ }
576
+ for (let grew = true; grew;) {
577
+ grew = false;
578
+ for (const { write } of deletes) {
579
+ if (open.has(write.id) || !waiting(write.id))
580
+ continue;
581
+ open.add(write.id);
582
+ grew = true;
583
+ }
584
+ }
585
+ const going = deletes.filter((one) => !open.has(one.write.id));
586
+ const gone = await execute(going.flatMap((one) => one.commands));
587
+ for (const one of going) {
588
+ const status = gone.status.get(one.commands[0].uuid);
589
+ // Already gone there is what a delete asks for.
590
+ if (status?.ok || status?.tag === "ITEM_NOT_FOUND")
591
+ acks.set(one.write.localId, one.ack(one.write.id));
592
+ else if (status && !status.later)
593
+ refuse(one.write, `todoist: ${status.said}`);
594
+ }
595
+ const closes = toClose.map(({ one, id }) => ({ one, id, command: { type: "item_close", uuid: uuid(), args: { id } } }));
596
+ const last = await execute(closes.map((one) => one.command), (lost) => {
597
+ for (const { one, id, command } of closes) {
598
+ // The date it was due as it was closed: the one just sent, where this write sent one.
599
+ const sentDue = one.commands.map((sent) => sent.args["due"]).find((due) => due !== undefined && due !== null);
600
+ const due = dueOf(sentDue ? { due: sentDue } : (listed.get(id) ?? {}));
601
+ if (lost.has(command.uuid) && due?.is_recurring)
602
+ closing.set(id, due.date);
603
+ }
604
+ });
605
+ for (const { one, id, command } of closes) {
606
+ const status = last.status.get(command.uuid);
607
+ // The rest of it went: only its completion is owed, and Todoist still has it open.
608
+ const opened = { ...one.ack(id), fields: { ...one.ack(id).fields, completed: false } };
609
+ if (status)
610
+ closing.delete(id);
611
+ if (status?.ok)
612
+ acks.set(one.write.localId, one.ack(id));
613
+ else if (status === undefined) {
614
+ if (one.commands.length > 0)
615
+ acks.set(one.write.localId, opened);
616
+ }
617
+ else if (one.commands.length > 0)
618
+ acks.set(one.write.localId, status.later ? opened : { ...opened, held: [opened.held, `todoist: ${status.said}`].filter(Boolean).join("; ") });
619
+ else if (!status.later)
620
+ refuse(one.write, `todoist: ${status.said}`);
621
+ }
622
+ for (const { localId, error } of acks.values()) {
623
+ if (error !== undefined)
624
+ continue;
625
+ unheard.delete(localId);
626
+ found.delete(localId);
627
+ }
628
+ return [...acks.values()];
629
+ },
630
+ };
631
+ /* ------------------------------------------------------------ writing */
632
+ /**
633
+ * One write as its commands, and whether it completes the task after them.
634
+ * A part that cannot be sent — a repeat there are no words for, a section
635
+ * there is not — holds that part alone of a task already there, and the
636
+ * whole of one not made yet.
637
+ */
638
+ async function plan(write, around) {
639
+ const fields = write.fields ?? {};
640
+ const command = (type, args, temp) => ({ type, uuid: uuid(), ...(temp ? { temp_id: uuid() } : {}), args });
641
+ if (write.deleted && write.id)
642
+ return { write, id: write.id, commands: [command("item_delete", { id: write.id })], close: false, partly: false, ack: (id) => ({ localId: write.localId, id, version: "" }) };
643
+ // Made already, its answer lost on an earlier pass: what it holds is set rather than made again.
644
+ const at = write.id ?? found.get(write.localId);
645
+ const changed = new Set(write.id ? (write.changed ?? Object.keys(fields)) : Object.keys(fields));
646
+ const unsent = new Map();
647
+ const part = async (named, act) => {
648
+ if (!named.some((ref) => changed.has(ref)))
649
+ return;
650
+ try {
651
+ for (const ref of named)
652
+ if (changed.has(ref) && isUnsayable(fields[ref]))
653
+ throw new Error(`held unsent: ${fields[ref].held}`);
654
+ await act();
655
+ }
656
+ catch (error) {
657
+ if (!at || (error instanceof TodoistError && (error.status === 401 || error.status === 429)))
658
+ throw error;
659
+ for (const ref of named)
660
+ if (changed.has(ref))
661
+ unsent.set(ref, error instanceof Error ? error.message : String(error));
662
+ }
663
+ };
664
+ const args = {};
665
+ await part(["content"], () => (args["content"] = asWords(fields["content"])));
666
+ await part(["description"], () => (args["description"] = asWords(fields["description"])));
667
+ await part(["deadline"], () => (args["deadline"] = fields["deadline"] ? { date: String(fields["deadline"]) } : null));
668
+ await part(["priority"], () => (args["priority"] = 5 - Number(fields["priority"] ?? 4)));
669
+ if (changed.has("labels") || (!at && options.label))
670
+ args["labels"] = [...new Set([...(fields["labels"] ?? []), ...(options.label ? [options.label] : [])])];
671
+ await part(["assignee"], () => (args["responsible_uid"] = fields["assignee"] ? personId(around, String(fields["assignee"])) : null));
672
+ await part(["due", "repeat"], async () => {
673
+ args["due"] = await dueFor({ ...write, ...(at ? { id: at } : {}) }, changed, around);
674
+ });
675
+ await part(["completed"], async () => {
676
+ if (at)
677
+ await reachesAside(at, fields["completed"] === true);
678
+ });
679
+ let move;
680
+ await part(["parent", "section"], async () => (move = await moveFor(at, fields, changed, around)));
681
+ if (!at) {
682
+ for (const key of Object.keys(args))
683
+ if (args[key] === null)
684
+ delete args[key];
685
+ const adds = command("item_add", { ...args, project_id: projectId(around), ...(move ?? (options.section ? { section_id: sectionId(around, options.section) } : {})) }, true);
686
+ return { write, commands: [adds], made: adds, close: fields["completed"] === true, partly: false, ack: ackOf(write, {}) };
687
+ }
688
+ const commands = [];
689
+ if (write.id && changed.has("completed") && !unsent.has("completed") && fields["completed"] !== true)
690
+ commands.push(command("item_uncomplete", { id: at }));
691
+ if (Object.keys(args).length > 0)
692
+ commands.push(command("item_update", { id: at, ...args }));
693
+ // "Only one of parent_id, section_id or project_id must be set" (sync/tasks.md): a subtask is where its parent is.
694
+ if (move)
695
+ commands.push(command("item_move", { id: at, ...move }));
696
+ const close = changed.has("completed") && !unsent.has("completed") && fields["completed"] === true;
697
+ if (unsent.size === 0)
698
+ return { write, id: at, commands, close, partly: false, ack: ackOf(write, {}) };
699
+ const said = [...new Set(unsent.values())].join("; ");
700
+ const task = await taskNow(at);
701
+ if ((commands.length === 0 && !close) || !task)
702
+ throw new Error(said);
703
+ // What was not sent is agreed as Todoist has it, so it is owed still.
704
+ const values = valuesOf(task, around);
705
+ return { write, id: at, commands, close, partly: true, ack: ackOf(write, Object.fromEntries([...unsent.keys()].map((ref) => [ref, values[ref] ?? null])), said) };
706
+ }
707
+ /** The ack of a write that went, with the version it comes back at should nobody else have touched it. */
708
+ function ackOf(write, instead, held) {
709
+ return (id) => ({
710
+ localId: write.localId,
711
+ id,
712
+ version: todoistVersion(Object.fromEntries(Object.keys(refs).map((ref) => [ref, (ref in instead ? instead[ref] : write.fields?.[ref]) ?? null]))),
713
+ ...(held !== undefined ? { fields: instead, held } : {}),
714
+ });
715
+ }
716
+ /** The tasks of the records set aside, whoever keeps them, each with its parent as last agreed where that is known. */
717
+ function asideNow() {
718
+ const all = new Map((options.asideElsewhere?.() ?? []).map((id) => [id, undefined]));
719
+ for (const { id, parent } of options.aside?.() ?? [])
720
+ all.set(id, parent);
721
+ return all;
722
+ }
723
+ /** What is above a task, nearest first. */
724
+ function climb(id, parent) {
725
+ const above = [];
726
+ for (let at = under.get(id) ?? parent; at !== undefined && !above.includes(at); at = under.get(at))
727
+ above.push(at);
728
+ return above;
729
+ }
730
+ /** Refuses to complete or reopen a task where Todoist would do it to the task of a record set aside: completing one completes its sub-tasks, and reopening one reopens what is above it (sync/tasks.md). */
731
+ async function reachesAside(id, completing) {
732
+ const own = new Map((options.aside?.() ?? []).map((one) => [one.id, one]));
733
+ const isOpen = async (task) => (own.get(task)?.completed !== undefined ? !own.get(task).completed : (await taskNow(task))?.["checked"] === false);
734
+ if (completing) {
735
+ if (dueOf((await taskNow(id)) ?? {})?.is_recurring)
736
+ return;
737
+ for (const [task, parent] of asideNow()) {
738
+ if (climb(task, parent).includes(id) && (await isOpen(task)))
739
+ throw new Error("held unsent: completing this task would complete the task of a record set aside under it — bring that one back, or complete it, first");
740
+ }
741
+ return;
742
+ }
743
+ const aside = asideNow();
744
+ for (const task of climb(id))
745
+ if (aside.has(task) && !(await isOpen(task)))
746
+ throw new Error("held unsent: reopening this task would reopen the task of a record set aside above it — bring that one back first");
747
+ }
748
+ /** Where a task goes when its parent or its section changed here; a part held in conflict is left where Todoist has it. */
749
+ async function moveFor(id, fields, changed, around) {
750
+ const own = options.section ? sectionId(around, options.section) : undefined;
751
+ const parent = fields["parent"]?.[0];
752
+ if (!id)
753
+ return parent ? { parent_id: parent } : own ? { section_id: own } : fields["section"] ? { section_id: sectionId(around, String(fields["section"])) } : undefined;
754
+ const task = await taskNow(id);
755
+ if (!task)
756
+ throw new Error("held unsent: Todoist does not list the task, so where it is there is not known");
757
+ if (changed.has("parent")) {
758
+ if (parent)
759
+ return { parent_id: parent };
760
+ // A parent this connection no longer keeps is not one somebody here took it out of.
761
+ const was = words(task["parent_id"]);
762
+ if (was === null || !((options.known?.() ?? []).some((one) => one.id === was) || (options.keptElsewhere?.(was) ?? false))) {
763
+ if (!changed.has("section"))
764
+ return undefined;
765
+ }
766
+ }
767
+ else if (task["parent_id"])
768
+ throw new Error("held unsent: a subtask is in its parent's section, so it is moved by moving its parent, or by taking it out of it");
769
+ const into = own ?? (keeps("section") && changed.has("section") ? (fields["section"] ? sectionId(around, String(fields["section"])) : undefined) : (words(task["section_id"]) ?? undefined));
770
+ return into ? { section_id: into } : { project_id: projectId(around) };
771
+ }
772
+ /** The due date a write says, or a refusal where saying it would end a repeat this app cannot say, or settle one that is held in conflict. */
773
+ async function dueFor(write, changed, held) {
774
+ const fields = write.fields ?? {};
775
+ if (!("due" in fields) || (keeps("repeat") && !("repeat" in fields)))
776
+ throw new Error("held unsent: a due date and how it repeats are written together, and one of them is held in conflict");
777
+ const value = words(fields["due"]);
778
+ const zone = zoneOf(held);
779
+ let was;
780
+ if (write.id) {
781
+ const task = await taskNow(write.id);
782
+ if (!task)
783
+ throw new Error("held unsent: Todoist does not list the task, so whether its due date repeats is not known");
784
+ was = dueOf(task);
785
+ if (was?.is_recurring && repeatIn(was, zone) === null) {
786
+ throw new Error(`held unsent: the task repeats in Todoist as "${was.string ?? ""}", which this app cannot say, and setting its date from here would end that repeat — change it in Todoist`);
787
+ }
788
+ if (was?.is_recurring && !keeps("repeat")) {
789
+ throw new Error(`held unsent: the task repeats in Todoist as "${was.string ?? ""}", and the field its due date is in keeps no repeat, so setting it from here would end that one — change it in Todoist`);
790
+ }
791
+ }
792
+ const repeat = words(fields["repeat"]);
793
+ if (value === null) {
794
+ if (repeat && changed.has("repeat"))
795
+ throw new Error("held unsent: a date that repeats needs its first date");
796
+ return null;
797
+ }
798
+ if (repeat) {
799
+ if (options.zone && !sameZone(options.zone, zone))
800
+ throw new Error(`held unsent: it repeats at a time in ${options.zone}, and the Todoist account is in ${zone}, where the same words are other times`);
801
+ if (was?.timezone && !sameZone(was.timezone, zone))
802
+ throw new Error(`held unsent: the task's due date is fixed in ${was.timezone}, and the Todoist account is in ${zone}`);
803
+ }
804
+ // A time fixed in its own zone keeps it; its wall is the account's, as its words are.
805
+ if (was && dueWall(was, zone).fixed && !was.timezone)
806
+ was = { ...was, timezone: zone };
807
+ return dueToWrite(value, dueAs, zone, was, repeat);
808
+ }
809
+ /** Sends commands in order, a hundred to a request, and answers what became of each. */
810
+ async function execute(commands, unanswered = () => undefined) {
811
+ const status = new Map();
812
+ const ids = new Map();
813
+ for (let at = 0; at < commands.length;) {
814
+ const batch = [];
815
+ let bytes = 0;
816
+ while (at < commands.length && batch.length < MOST_COMMANDS) {
817
+ const size = encodeURIComponent(JSON.stringify(commands[at])).length;
818
+ if (batch.length > 0 && bytes + size > MOST_BYTES)
819
+ break;
820
+ bytes += size;
821
+ batch.push(commands[at]);
822
+ at += 1;
823
+ }
824
+ let answer;
825
+ try {
826
+ answer = await again({ commands: JSON.stringify(batch) });
827
+ }
828
+ catch (error) {
829
+ // Carried out, perhaps, where the answer was lost; a request refused was not.
830
+ if (!(error instanceof TodoistError) || error.status >= 500)
831
+ unanswered(new Set(batch.map((command) => command.uuid)));
832
+ // What went before is kept; this and what follows is not answered for, and stays owed. Nothing sent yet is a run that failed.
833
+ if (!sent) {
834
+ sent = true;
835
+ throw error;
836
+ }
837
+ note(error instanceof Error ? error.message : String(error));
838
+ break;
839
+ }
840
+ sent = true;
841
+ for (const [temporary, id] of Object.entries(answer["temp_id_mapping"] ?? {}))
842
+ ids.set(temporary, String(id));
843
+ for (const [key, value] of Object.entries(answer["sync_status"] ?? {})) {
844
+ if (value === "ok") {
845
+ status.set(key, { ok: true, later: false, said: "" });
846
+ continue;
847
+ }
848
+ const refused = (value ?? {});
849
+ const http = Number(refused["http_code"] ?? 0);
850
+ // "Clients should treat 400 command errors as a terminal signal"; a wait or a fault there is not one (sync/overview.md).
851
+ const later = http === 429 || http >= 500;
852
+ status.set(key, { ok: false, later, said: sentenceOf(refused).replace(/^: /, "") || "the command was refused", ...(typeof refused["error_tag"] === "string" ? { tag: refused["error_tag"] } : {}) });
853
+ }
854
+ }
855
+ return { status, ids };
856
+ }
857
+ /** A write made again as it was when its answer was lost: "Todoist will not execute a command that has same UUID as a previously executed command" (sync/overview.md). */
858
+ async function again(form) {
859
+ for (let tries = 0;; tries += 1) {
860
+ try {
861
+ return await call("POST", "/sync", form);
862
+ }
863
+ catch (error) {
864
+ const lost = !(error instanceof TodoistError) || error.status >= 500;
865
+ if (!lost || tries >= 2)
866
+ throw error;
867
+ await sleep(500 * (tries + 1));
868
+ }
869
+ }
870
+ }
871
+ }
872
+ const only = (list) => (list.length === 1 ? list[0] : undefined);
873
+ /** Todoist's words for a refusal. */
874
+ function sentenceOf(answer) {
875
+ const explanation = answer["error_extra"]?.["explanation"];
876
+ const error = answer["error"];
877
+ return typeof explanation === "string" && explanation ? `: ${explanation}` : typeof error === "string" && error ? `: ${error}` : "";
878
+ }
879
+ /** Whether a read was refused for its sync token, which the documentation does not give a tag: any bad request that names it. */
880
+ const isTokenRefused = (error) => error instanceof TodoistError && error.status === 400 && /sync.?token/i.test(`${error.tag ?? ""} ${error.message}`);
881
+ function readCursor(cursor) {
882
+ if (!cursor)
883
+ return undefined;
884
+ try {
885
+ const parsed = JSON.parse(cursor);
886
+ return typeof parsed.token === "string" && typeof parsed.names === "string" && typeof parsed.scope === "string" ? { token: parsed.token, names: parsed.names, scope: parsed.scope, ...(parsed.under ? { under: parsed.under } : {}), ...(parsed.aside ? { aside: parsed.aside } : {}), ...(parsed.spared ? { spared: parsed.spared } : {}) } : undefined;
887
+ }
888
+ catch {
889
+ return undefined;
890
+ }
891
+ }
892
+ //# sourceMappingURL=todoist.js.map