buckyos 0.7.180 → 0.7.183

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 (74) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +35 -0
  3. package/README.md +4 -0
  4. package/cli/deno.json +3 -2
  5. package/cli/dist/cli.mjs +1534 -216
  6. package/cli/dist/cli.mjs.map +1 -1
  7. package/cli/modules/aiws.ts +761 -58
  8. package/cli/modules/aiws_place.ts +383 -0
  9. package/cli/modules/aiws_schedule.ts +256 -0
  10. package/cli/runtime/host.ts +18 -0
  11. package/cli/runtime/host_deno.ts +34 -0
  12. package/cli/runtime/host_node.ts +32 -1
  13. package/cli/runtime/node_entry.ts +1 -0
  14. package/cli/system_bootstrap.ts +1 -0
  15. package/cli/system_launcher.ts +1 -0
  16. package/cli/version.ts +1 -1
  17. package/dist/aicc_client.d.ts +1 -1
  18. package/dist/aicc_client.d.ts.map +1 -1
  19. package/dist/aiworkspace_client.d.ts +253 -2
  20. package/dist/aiworkspace_client.d.ts.map +1 -1
  21. package/dist/aiws_bind-3b874f77.mjs +2235 -0
  22. package/dist/aiws_bind-3b874f77.mjs.map +1 -0
  23. package/dist/aiws_bind-82bace11.js +2 -0
  24. package/dist/aiws_bind-82bace11.js.map +1 -0
  25. package/dist/aiws_bind.d.ts +233 -0
  26. package/dist/aiws_bind.d.ts.map +1 -0
  27. package/dist/aiws_ext.cjs +1 -1
  28. package/dist/aiws_ext.cjs.map +1 -1
  29. package/dist/aiws_ext.d.ts +9 -5
  30. package/dist/aiws_ext.d.ts.map +1 -1
  31. package/dist/aiws_ext.mjs +146 -11
  32. package/dist/aiws_ext.mjs.map +1 -1
  33. package/dist/aiws_rrule.d.ts +121 -0
  34. package/dist/aiws_rrule.d.ts.map +1 -0
  35. package/dist/aiws_schedule.d.ts +324 -0
  36. package/dist/aiws_schedule.d.ts.map +1 -0
  37. package/dist/aiws_write-89b5cc2a.js +13 -0
  38. package/dist/aiws_write-89b5cc2a.js.map +1 -0
  39. package/dist/{executor_client-bfc8a1e1.mjs → aiws_write-c2de498e.mjs} +724 -285
  40. package/dist/aiws_write-c2de498e.mjs.map +1 -0
  41. package/dist/aiws_write.d.ts +178 -0
  42. package/dist/aiws_write.d.ts.map +1 -0
  43. package/dist/browser.cjs +1 -1
  44. package/dist/browser.cjs.map +1 -1
  45. package/dist/browser.d.ts +4 -0
  46. package/dist/browser.d.ts.map +1 -1
  47. package/dist/browser.mjs +112 -21
  48. package/dist/browser.mjs.map +1 -1
  49. package/dist/{content_objid-9232bcaf.mjs → content_objid-a2cafba9.mjs} +2 -2
  50. package/dist/{content_objid-9232bcaf.mjs.map → content_objid-a2cafba9.mjs.map} +1 -1
  51. package/dist/content_objid-dff803ff.js +2 -0
  52. package/dist/{content_objid-1aff74b6.js.map → content_objid-dff803ff.js.map} +1 -1
  53. package/dist/{did_object_client-7fa36f90.mjs → did_object_client-cb2f9aba.mjs} +2 -2
  54. package/dist/{did_object_client-7fa36f90.mjs.map → did_object_client-cb2f9aba.mjs.map} +1 -1
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.ts +4 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.mjs +113 -22
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/node.cjs +1 -1
  62. package/dist/node.cjs.map +1 -1
  63. package/dist/node.d.ts +5 -0
  64. package/dist/node.d.ts.map +1 -1
  65. package/dist/node.mjs +99 -6
  66. package/dist/node.mjs.map +1 -1
  67. package/dist/{object_url-f72c1704.mjs → object_url-376c5222.mjs} +4 -4
  68. package/dist/{object_url-f72c1704.mjs.map → object_url-376c5222.mjs.map} +1 -1
  69. package/dist/xllm.mjs +2 -2
  70. package/package.json +5 -4
  71. package/dist/content_objid-1aff74b6.js +0 -2
  72. package/dist/executor_client-7ce0ddc7.js +0 -13
  73. package/dist/executor_client-7ce0ddc7.js.map +0 -1
  74. package/dist/executor_client-bfc8a1e1.mjs.map +0 -1
@@ -0,0 +1,2235 @@
1
+ import { e as encodeObjQueryComponent, c as canonicalJson, b as objServiceUrl, n as normalizeObjectUrl, p as parseObjectUrl, d as objectSegments } from "./object_url-376c5222.mjs";
2
+ const AIWORKSPACE_SERVICE_NAME = "aiworkspace";
3
+ class AiwsFailure extends Error {
4
+ constructor(error) {
5
+ super(`${error.code}${error.sub_code ? `/${error.sub_code}` : ""}: ${error.detail}`);
6
+ this.name = "AiwsFailure";
7
+ this.code = error.code;
8
+ this.subCode = error.sub_code;
9
+ this.data = error.data;
10
+ }
11
+ }
12
+ function aiwsReferenceUrl(reference, workspaceId) {
13
+ const ws = reference.workspace_id ?? workspaceId;
14
+ if (!ws)
15
+ throw new Error("reference names no workspace");
16
+ const query = [];
17
+ if (reference.mode === "fixed")
18
+ query.push("mode=fixed");
19
+ if (reference.selector != null)
20
+ query.push(`selector=${encodeObjQueryComponent(canonicalJson(reference.selector))}`);
21
+ if (reference.version != null)
22
+ query.push(`version=${encodeObjQueryComponent(canonicalJson(reference.version))}`);
23
+ const base = objServiceUrl("aiworkspace", [ws, "entities", reference.entity_id]);
24
+ return normalizeObjectUrl(query.length ? `${base}?${query.join("&")}` : base);
25
+ }
26
+ function parseAiwsReferenceUrl(url) {
27
+ const parsed = parseObjectUrl(url);
28
+ const segments = objectSegments(parsed);
29
+ if (parsed.kind !== "obj" || parsed.host.name !== "aiworkspace" || segments.length !== 3 || segments[1] !== "entities") {
30
+ throw new Error(`${url} is not an AI Workspace entity url`);
31
+ }
32
+ const reference = {
33
+ workspace_id: segments[0],
34
+ entity_id: segments[2],
35
+ mode: parsed.query.mode === "fixed" ? "fixed" : "live"
36
+ };
37
+ if (parsed.query.selector !== void 0)
38
+ reference.selector = JSON.parse(parsed.query.selector);
39
+ if (parsed.query.version !== void 0)
40
+ reference.version = JSON.parse(parsed.query.version);
41
+ return reference;
42
+ }
43
+ function aiwsTarget(target) {
44
+ return target.startsWith("/") || target.startsWith("~") ? { path: target } : { entity_id: target };
45
+ }
46
+ const AIWS_COMMIT_PART_BYTES = 6 * 1024 * 1024;
47
+ const AIWS_COMMIT_MAX_BYTES = 32 * 1024 * 1024;
48
+ const AIWS_COMMIT_MAX_OPERATIONS = 5e4;
49
+ const utf8 = new TextEncoder();
50
+ function jsonBytes(value) {
51
+ const text = JSON.stringify(value);
52
+ return text.length + (/[^\x00-\x7f]/.test(text) ? utf8.encode(text).length - text.length : 0);
53
+ }
54
+ function splitCommitOperations(operations, partBytes = AIWS_COMMIT_PART_BYTES) {
55
+ const parts = [];
56
+ let current = [];
57
+ let size = 2;
58
+ for (const op of operations) {
59
+ const bytes = jsonBytes(op) + 1;
60
+ if (current.length > 0 && size + bytes > partBytes) {
61
+ parts.push(current);
62
+ current = [];
63
+ size = 2;
64
+ }
65
+ current.push(op);
66
+ size += bytes;
67
+ }
68
+ if (current.length > 0 || parts.length === 0)
69
+ parts.push(current);
70
+ return parts;
71
+ }
72
+ function commitOverLimit(operations) {
73
+ if (operations.length > AIWS_COMMIT_MAX_OPERATIONS)
74
+ return { limit: "operations", value: operations.length, max: AIWS_COMMIT_MAX_OPERATIONS };
75
+ let bytes = 2;
76
+ for (const op of operations)
77
+ bytes += jsonBytes(op) + 1;
78
+ return bytes + 4096 > AIWS_COMMIT_MAX_BYTES ? { limit: "bytes", value: bytes, max: AIWS_COMMIT_MAX_BYTES } : null;
79
+ }
80
+ async function commitWithParts(call, request, options = {}) {
81
+ var _a, _b;
82
+ const method = options.method ?? "doc.commit";
83
+ const operations = Array.isArray(request.operations) ? request.operations : [];
84
+ const parts = splitCommitOperations(operations, options.partBytes ?? AIWS_COMMIT_PART_BYTES);
85
+ if (parts.length <= 1)
86
+ return await call(method, request);
87
+ const { workspace_id, epoch, idempotency_key } = request;
88
+ for (let attempt = 0; ; attempt++) {
89
+ const staged = [];
90
+ for (let part = 0; part < parts.length - 1; part++) {
91
+ (_a = options.onPart) == null ? void 0 : _a.call(options, part + 1, parts.length);
92
+ const held = await call("doc.stage", { workspace_id, epoch, idempotency_key, part, operations: parts[part] });
93
+ if (!held || held.ok === false || typeof held.digest !== "string") {
94
+ const error = (held == null ? void 0 : held.error) ?? { code: "STORAGE_IO_ERROR", retryable: true, detail: "doc.stage returned no digest" };
95
+ return { status: "rejected", code: error.code, retryable: error.retryable, detail: error.detail, ...error.sub_code ? { sub_code: error.sub_code } : {}, errors: [error] };
96
+ }
97
+ staged.push(held.digest);
98
+ }
99
+ (_b = options.onPart) == null ? void 0 : _b.call(options, parts.length, parts.length);
100
+ const result = await call(method, { ...request, staged, operations: parts[parts.length - 1] });
101
+ if (attempt === 0 && (result == null ? void 0 : result.status) === "rejected" && result.sub_code === "STAGED_PARTS_MISSING")
102
+ continue;
103
+ return result;
104
+ }
105
+ }
106
+ class AiWorkspaceClient {
107
+ constructor(rpcClient) {
108
+ this.rpcClient = rpcClient;
109
+ this.raw = (method, params) => this.rpcClient.call(method, params);
110
+ }
111
+ async call(method, params) {
112
+ const raw = await this.rpcClient.call(method, params);
113
+ if (raw && typeof raw === "object" && raw.ok === false)
114
+ throw new AiwsFailure(raw.error);
115
+ return raw;
116
+ }
117
+ // ---- workspace
118
+ /** A new Workspace; `name` (unique among the caller's, fixed) answers `NAME_CONFLICT` when the caller already uses it. */
119
+ create(title, opts = {}) {
120
+ return this.call("ws.create", { title, ...opts });
121
+ }
122
+ /** The caller's Workspace named `name`, created (titled `title`, else the name) when it has none. */
123
+ ensure(name, title) {
124
+ return this.call("ws.ensure", { name, ...title === void 0 ? {} : { title } });
125
+ }
126
+ /** The service clock (unix ms): calibrate against half the round trip. */
127
+ time() {
128
+ return this.call("ws.time", {});
129
+ }
130
+ list() {
131
+ return this.call("ws.list", {});
132
+ }
133
+ info(workspace_id) {
134
+ return this.call("ws.get_info", { workspace_id });
135
+ }
136
+ getUserState(workspace_id) {
137
+ return this.call("ws.get_user_state", { workspace_id });
138
+ }
139
+ setUserState(workspace_id, entries, expect) {
140
+ return this.call("ws.set_user_state", { workspace_id, entries, ...expect ? { expect } : {} });
141
+ }
142
+ // ---- document
143
+ resolve(workspace_id, reference) {
144
+ return this.call("doc.resolve", { workspace_id, reference });
145
+ }
146
+ resolvePath(workspace_id, path) {
147
+ return this.call("doc.resolve", { workspace_id, path });
148
+ }
149
+ /** The native content (`target`: a path or an entity id, see `aiwsTarget`). */
150
+ read(workspace_id, target, selector) {
151
+ return this.call("doc.read", { workspace_id, ...aiwsTarget(target), ...selector ? { selector } : {} });
152
+ }
153
+ readMeta(workspace_id, target) {
154
+ return this.call("doc.read", { workspace_id, ...aiwsTarget(target), as: "meta" });
155
+ }
156
+ /** One page of the plain-text body; follow `next_cursor` (bound to `etag`) for the rest. */
157
+ readBody(workspace_id, target, params = {}) {
158
+ return this.call("doc.read", { workspace_id, ...aiwsTarget(target), as: "body", ...params });
159
+ }
160
+ /** `doc.list`: the readable direct children of `at` (default `/`), in tree order. */
161
+ listEntities(workspace_id, params = {}) {
162
+ return this.call("doc.list", { workspace_id, ...params });
163
+ }
164
+ /** `doc.find`: a pre-order walk under `at` by name / title, type and schema. */
165
+ findEntities(workspace_id, params = {}) {
166
+ return this.call("doc.find", { workspace_id, ...params });
167
+ }
168
+ /** `doc.query { text }`: a literal (1–256 characters) in names, titles and bodies. */
169
+ textQuery(workspace_id, text, params = {}) {
170
+ return this.call("doc.query", { workspace_id, text, ...params });
171
+ }
172
+ /** `doc.query { sql }`: one SELECT over the logical tables (`FROM "/data/销售"`, `"~<entity_id>"`, an alias of `tables`). */
173
+ sql(workspace_id, sql, params = {}) {
174
+ return this.call("doc.query", { workspace_id, sql, ...params });
175
+ }
176
+ /** `doc.source_query`: rows of a URL table from its remote source. */
177
+ sourceQuery(workspace_id, source_id, params) {
178
+ return this.call("doc.source_query", { workspace_id, source_id, ...params });
179
+ }
180
+ outline(workspace_id) {
181
+ return this.call("doc.outline", { workspace_id });
182
+ }
183
+ prepare(workspace_id, request) {
184
+ return commitWithParts(this.raw, { workspace_id, ...request }, { method: "doc.prepare" });
185
+ }
186
+ /** The three-state commit result (`status: accepted | conflict | rejected`), never thrown. One call per Commit
187
+ * whatever its size (up to `AIWS_COMMIT_MAX_BYTES` / `AIWS_COMMIT_MAX_OPERATIONS`): a large one is sent in parts. */
188
+ commit(workspace_id, request, options = {}) {
189
+ return commitWithParts(this.raw, { workspace_id, ...request }, options);
190
+ }
191
+ getSubmission(workspace_id, epoch, idempotency_key) {
192
+ return this.call("doc.get_submission", { workspace_id, epoch, idempotency_key });
193
+ }
194
+ /** Changes after `after_seq` (`filter.detail: "touched"` for the touched entities only). */
195
+ getChanges(workspace_id, epoch, after_seq, opts = {}) {
196
+ return this.call("doc.get_changes", { workspace_id, epoch, after_seq, ...opts.limit ? { limit: opts.limit } : {}, ...opts.touchedOnly ? { filter: { detail: "touched" } } : {} });
197
+ }
198
+ /** Long poll until the head passes `after_seq` (or `timeout_ms`). */
199
+ waitChanges(workspace_id, after_seq, opts = {}) {
200
+ return this.call("doc.wait_changes", { workspace_id, after_seq, ...opts });
201
+ }
202
+ /** A whole-Workspace package (`.bcanvas`): `download` names it in the owner's exports bucket. */
203
+ exportDoc(workspace_id, mode, self_contained, include_notes) {
204
+ return this.call("doc.export", { workspace_id, mode, self_contained, ...include_notes === void 0 ? {} : { include_notes } });
205
+ }
206
+ // ---- assets
207
+ /** Register a FileObject as a staged asset: `{ bucket_id, key }` (the uploader's binding) or `{ obj_id }`. */
208
+ assetImportObject(workspace_id, source) {
209
+ return this.call("asset.import_object", { workspace_id, ...source });
210
+ }
211
+ // ---- Block-controls (code-registered layouts such as the mind map)
212
+ controlsList() {
213
+ return this.call("control.list", {});
214
+ }
215
+ controlsDescribe(kind) {
216
+ return this.call("control.describe", { kind });
217
+ }
218
+ controlsImport(workspace_id, params) {
219
+ return this.call("control.import", { workspace_id, ...params });
220
+ }
221
+ controlsExport(workspace_id, entity_id, format) {
222
+ return this.call("control.export", { workspace_id, entity_id, ...format ? { format } : {} });
223
+ }
224
+ // ---- extension controls (README “Extension controls”; buckyos-websdk src/aiws_ext.ts drives them)
225
+ /** Build one control's source files into the Workspace; `BUILD_FAILED` carries `data.diagnostics`. */
226
+ extBuild(workspace_id, params) {
227
+ return this.call("ext.build", { workspace_id, ...params });
228
+ }
229
+ /** The bundle of definitions (`purpose: pull` needs read only and synthesizes the source of never-built ones). */
230
+ extExport(workspace_id, entity_ids, purpose = "package") {
231
+ return this.call("ext.export", { workspace_id, entity_ids, purpose });
232
+ }
233
+ /** Into the caller's library: a `.pikg` object or one bound into the caller's `exports` bucket (consumed), or
234
+ * definitions of a Workspace (`from` + `package`). */
235
+ extInstall(params) {
236
+ return this.call("ext.install", params);
237
+ }
238
+ /** Pack definitions (and what they build on, and templates of the Workspace) as an `aiws` `.pikg` into the caller's
239
+ * `exports` bucket (unsigned). */
240
+ extPack(workspace_id, entity_ids, pkg, templates) {
241
+ return this.call("ext.pack", { workspace_id, entity_ids, package: pkg, ...templates ? { templates } : {} });
242
+ }
243
+ /** Rebuild imported definitions from the caller's library (same Zone; across Zones `ext.build { provenance, upgrade }`):
244
+ * `EXT_LOCAL_CHANGES` when the snapshot was built locally since, unless `force`. */
245
+ extUpgrade(params) {
246
+ return this.call("ext.upgrade", { ...params });
247
+ }
248
+ /** Chosen Surfaces as a template snapshot: the manifest item, the definitions it needs and the files (base64) of
249
+ * `templates/<id>/`. */
250
+ extExportTemplate(params) {
251
+ return this.call("ext.export_template", { ...params });
252
+ }
253
+ /** A new Workspace from a template of the caller's library (installing a template never creates one). */
254
+ extCreateFromTemplate(params) {
255
+ return this.call("ext.create_from_template", params);
256
+ }
257
+ extListLibrary() {
258
+ return this.call("ext.list_library", {});
259
+ }
260
+ extUninstall(pkg_id) {
261
+ return this.call("ext.uninstall", { pkg_id });
262
+ }
263
+ /** A library package's controls with their bytes (base64): what a client relays into a Workspace of another Zone. */
264
+ extLibraryBundle(pkg_id, idents) {
265
+ return this.call("ext.library_bundle", { pkg_id, ...idents ? { idents } : {} });
266
+ }
267
+ /** Bring library controls into a Workspace of this Zone (one Commit). */
268
+ extImport(workspace_id, items, opts = {}) {
269
+ return this.call("ext.import", { workspace_id, items, ...opts });
270
+ }
271
+ // ---- runs (M3 executor protocol)
272
+ runStart(workspace_id, program, params, idempotency_key) {
273
+ return this.call("proc.start", { workspace_id, program, params, idempotency_key });
274
+ }
275
+ runGet(workspace_id, run_id, choices) {
276
+ return this.call("proc.get", { workspace_id, run_id, ...choices ? { choices } : {} });
277
+ }
278
+ runList(workspace_id, wish_id, limit) {
279
+ return this.call("proc.list", { workspace_id, ...wish_id ? { wish_id } : {}, ...limit ? { limit } : {} });
280
+ }
281
+ runClaim(workspace_id, run_id, claim_token, executor) {
282
+ return this.call("proc.claim", { workspace_id, run_id, claim_token, ...executor ? { executor } : {} });
283
+ }
284
+ runHeartbeat(workspace_id, run_id, attempt, progress) {
285
+ return this.call("proc.heartbeat", { workspace_id, run_id, attempt, ...progress ? { progress } : {} });
286
+ }
287
+ runReport(workspace_id, report) {
288
+ return this.call("proc.report", { workspace_id, ...report });
289
+ }
290
+ runApply(workspace_id, run_id, plan_digest, session_id) {
291
+ return this.call("proc.apply", { workspace_id, run_id, plan_digest, ...session_id ? { session_id } : {} });
292
+ }
293
+ runCancel(workspace_id, run_id) {
294
+ return this.call("proc.cancel", { workspace_id, run_id });
295
+ }
296
+ }
297
+ const WEEKDAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
298
+ class RRuleError extends Error {
299
+ constructor(message) {
300
+ super(message);
301
+ this.name = "RRuleError";
302
+ }
303
+ }
304
+ const FREQS = ["DAILY", "WEEKLY", "MONTHLY", "YEARLY"];
305
+ const MAX_COUNT = 1e3;
306
+ const MAX_INTERVAL = 999;
307
+ function intIn(part, value, lo, hi, zero = false) {
308
+ if (!/^[+-]?\d{1,3}$/.test(value))
309
+ throw new RRuleError(`${part}: ${value} is not a number`);
310
+ const n = Number(value);
311
+ if (n < lo || n > hi || !zero && n === 0)
312
+ throw new RRuleError(`${part}: ${value} is out of range`);
313
+ return n;
314
+ }
315
+ function list(part, value, max) {
316
+ const items = value.split(",");
317
+ if (items.length === 0 || items.length > max || items.some((x) => x === ""))
318
+ throw new RRuleError(`${part}: at most ${max} comma-separated values`);
319
+ return items;
320
+ }
321
+ function untilOf(value) {
322
+ let m = /^(\d{4})(\d{2})(\d{2})$/.exec(value);
323
+ if (m) {
324
+ const date = `${m[1]}-${m[2]}-${m[3]}`;
325
+ if (!isDate(date))
326
+ throw new RRuleError(`UNTIL: ${value} is not a date`);
327
+ return date;
328
+ }
329
+ m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(value);
330
+ if (m) {
331
+ const ms = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);
332
+ if (!isDate(`${m[1]}-${m[2]}-${m[3]}`) || +m[4] > 23 || +m[5] > 59 || +m[6] > 59)
333
+ throw new RRuleError(`UNTIL: ${value} is not a UTC time`);
334
+ return new Date(ms).toISOString();
335
+ }
336
+ throw new RRuleError(`UNTIL: ${value} must be YYYYMMDD or YYYYMMDDTHHMMSSZ`);
337
+ }
338
+ function parseRRule(text) {
339
+ const body = text.startsWith("RRULE:") ? text.slice(6) : text;
340
+ if (body.trim() === "")
341
+ throw new RRuleError("empty rule");
342
+ const seen = /* @__PURE__ */ new Set();
343
+ const raw = {};
344
+ for (const part of body.split(";")) {
345
+ const eq = part.indexOf("=");
346
+ if (eq <= 0)
347
+ throw new RRuleError(`${part || "(empty)"}: expected NAME=VALUE`);
348
+ const name = part.slice(0, eq);
349
+ const value = part.slice(eq + 1);
350
+ if (name !== name.toUpperCase() || value !== value.toUpperCase())
351
+ throw new RRuleError(`${part}: write the rule in upper case`);
352
+ if (seen.has(name))
353
+ throw new RRuleError(`${name}: given twice`);
354
+ seen.add(name);
355
+ if (!["FREQ", "INTERVAL", "COUNT", "UNTIL", "BYDAY", "BYMONTHDAY", "BYMONTH", "BYSETPOS", "WKST"].includes(name)) {
356
+ throw new RRuleError(`${name}: not supported (supported: FREQ, INTERVAL, COUNT, UNTIL, BYDAY, BYMONTHDAY, BYMONTH, BYSETPOS, WKST)`);
357
+ }
358
+ if (value === "")
359
+ throw new RRuleError(`${name}: empty value`);
360
+ raw[name] = value;
361
+ }
362
+ if (!raw.FREQ)
363
+ throw new RRuleError("FREQ is required");
364
+ if (!FREQS.includes(raw.FREQ))
365
+ throw new RRuleError(`FREQ: ${raw.FREQ} is not supported (DAILY, WEEKLY, MONTHLY, YEARLY)`);
366
+ const freq = raw.FREQ;
367
+ const rule = { freq, interval: 1, wkst: 0 };
368
+ if (raw.INTERVAL !== void 0)
369
+ rule.interval = intIn("INTERVAL", raw.INTERVAL, 1, MAX_INTERVAL);
370
+ if (raw.COUNT !== void 0 && raw.UNTIL !== void 0)
371
+ throw new RRuleError("COUNT and UNTIL cannot both be given");
372
+ if (raw.COUNT !== void 0)
373
+ rule.count = intIn("COUNT", raw.COUNT, 1, MAX_COUNT);
374
+ if (raw.UNTIL !== void 0)
375
+ rule.until = untilOf(raw.UNTIL);
376
+ if (raw.BYDAY !== void 0) {
377
+ rule.byDay = list("BYDAY", raw.BYDAY, 7).map((item) => {
378
+ const m = /^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/.exec(item);
379
+ if (!m)
380
+ throw new RRuleError(`BYDAY: ${item} is not a weekday`);
381
+ const weekday = WEEKDAYS.indexOf(m[2]);
382
+ if (m[1] === void 0)
383
+ return { weekday };
384
+ if (freq !== "MONTHLY" && freq !== "YEARLY")
385
+ throw new RRuleError(`BYDAY: ${item}: an ordinal needs FREQ=MONTHLY or YEARLY`);
386
+ return { weekday, ordinal: intIn("BYDAY", m[1], -5, 5) };
387
+ });
388
+ const keys = rule.byDay.map((d) => `${d.ordinal ?? ""}${d.weekday}`);
389
+ if (new Set(keys).size !== keys.length)
390
+ throw new RRuleError("BYDAY: repeated day");
391
+ }
392
+ if (raw.BYMONTHDAY !== void 0) {
393
+ if (freq !== "MONTHLY" && freq !== "YEARLY")
394
+ throw new RRuleError("BYMONTHDAY needs FREQ=MONTHLY or YEARLY");
395
+ rule.byMonthDay = list("BYMONTHDAY", raw.BYMONTHDAY, 31).map((v) => {
396
+ const n = intIn("BYMONTHDAY", v, -1, 31);
397
+ return n;
398
+ });
399
+ if (new Set(rule.byMonthDay).size !== rule.byMonthDay.length)
400
+ throw new RRuleError("BYMONTHDAY: repeated day");
401
+ }
402
+ if (raw.BYMONTH !== void 0) {
403
+ if (freq !== "YEARLY")
404
+ throw new RRuleError("BYMONTH needs FREQ=YEARLY");
405
+ rule.byMonth = list("BYMONTH", raw.BYMONTH, 12).map((v) => intIn("BYMONTH", v, 1, 12));
406
+ if (new Set(rule.byMonth).size !== rule.byMonth.length)
407
+ throw new RRuleError("BYMONTH: repeated month");
408
+ }
409
+ if (raw.BYSETPOS !== void 0) {
410
+ if (freq !== "MONTHLY" || !rule.byDay)
411
+ throw new RRuleError("BYSETPOS needs FREQ=MONTHLY and BYDAY");
412
+ rule.bySetPos = intIn("BYSETPOS", raw.BYSETPOS, -5, 5);
413
+ }
414
+ if (raw.WKST !== void 0) {
415
+ const w = WEEKDAYS.indexOf(raw.WKST);
416
+ if (w < 0)
417
+ throw new RRuleError(`WKST: ${raw.WKST} is not a weekday`);
418
+ rule.wkst = w;
419
+ }
420
+ return rule;
421
+ }
422
+ function formatRRule(rule) {
423
+ var _a, _b, _c;
424
+ const parts = [`FREQ=${rule.freq}`];
425
+ if (rule.interval > 1)
426
+ parts.push(`INTERVAL=${rule.interval}`);
427
+ if ((_a = rule.byMonth) == null ? void 0 : _a.length)
428
+ parts.push(`BYMONTH=${rule.byMonth.join(",")}`);
429
+ if ((_b = rule.byMonthDay) == null ? void 0 : _b.length)
430
+ parts.push(`BYMONTHDAY=${rule.byMonthDay.join(",")}`);
431
+ if ((_c = rule.byDay) == null ? void 0 : _c.length)
432
+ parts.push(`BYDAY=${rule.byDay.map((d) => `${d.ordinal ?? ""}${WEEKDAYS[d.weekday]}`).join(",")}`);
433
+ if (rule.bySetPos !== void 0)
434
+ parts.push(`BYSETPOS=${rule.bySetPos}`);
435
+ if (rule.count !== void 0)
436
+ parts.push(`COUNT=${rule.count}`);
437
+ if (rule.until !== void 0)
438
+ parts.push(`UNTIL=${rule.until.length === 10 ? rule.until.replace(/-/g, "") : rule.until.replace(/[-:]/g, "").replace(/\.\d{3}/, "")}`);
439
+ if (rule.wkst !== 0)
440
+ parts.push(`WKST=${WEEKDAYS[rule.wkst]}`);
441
+ return parts.join(";");
442
+ }
443
+ function isDate(s) {
444
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
445
+ if (!m)
446
+ return false;
447
+ const y = +m[1], mo = +m[2], d = +m[3];
448
+ return y >= 1 && mo >= 1 && mo <= 12 && d >= 1 && d <= daysInMonth(y, mo);
449
+ }
450
+ const isLeap = (y) => y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
451
+ function daysInMonth(y, m) {
452
+ return [31, isLeap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
453
+ }
454
+ const dayNumber = (y, m, d) => Math.floor(Date.UTC(y, m - 1, d) / 864e5);
455
+ function dayOf(date) {
456
+ return dayNumber(+date.slice(0, 4), +date.slice(5, 7), +date.slice(8, 10));
457
+ }
458
+ function dateOf(day) {
459
+ return new Date(day * 864e5).toISOString().slice(0, 10);
460
+ }
461
+ function ymdOf(day) {
462
+ const t = new Date(day * 864e5);
463
+ return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() };
464
+ }
465
+ const weekdayOf = (day) => ((day + 3) % 7 + 7) % 7;
466
+ const formatters = /* @__PURE__ */ new Map();
467
+ function formatter(tz) {
468
+ let f = formatters.get(tz);
469
+ if (!f) {
470
+ f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
471
+ formatters.set(tz, f);
472
+ }
473
+ return f;
474
+ }
475
+ function isTimeZone(tz) {
476
+ try {
477
+ formatter(tz);
478
+ return true;
479
+ } catch {
480
+ return false;
481
+ }
482
+ }
483
+ function zonedParts(ms, tz) {
484
+ const parts = {};
485
+ for (const p of formatter(tz).formatToParts(new Date(ms)))
486
+ if (p.type !== "literal")
487
+ parts[p.type] = Number(p.value);
488
+ return { y: parts.year, m: parts.month, d: parts.day, h: parts.hour === 24 ? 0 : parts.hour, mi: parts.minute, s: parts.second };
489
+ }
490
+ function offsetMs(ms, tz) {
491
+ const p = zonedParts(ms, tz);
492
+ return Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s) - Math.floor(ms / 1e3) * 1e3;
493
+ }
494
+ function zonedToUtc(day, minuteOfDay, secondOfMinute, tz) {
495
+ const local = day * 864e5 + minuteOfDay * 6e4 + secondOfMinute * 1e3;
496
+ const first = local - offsetMs(local, tz);
497
+ const second = local - offsetMs(first, tz);
498
+ return second;
499
+ }
500
+ function localDay(ms, tz) {
501
+ const p = zonedParts(ms, tz);
502
+ return dayNumber(p.y, p.m, p.d);
503
+ }
504
+ const MAX_PERIODS = 2e5;
505
+ function candidates(rule, period, startDay) {
506
+ const s = ymdOf(startDay);
507
+ const out = [];
508
+ const byDayAll = (day0, len, wanted) => {
509
+ for (let i = 0; i < len; i++)
510
+ if (wanted.some((w) => w.ordinal === void 0 && w.weekday === weekdayOf(day0 + i)))
511
+ out.push(day0 + i);
512
+ };
513
+ const nth = (day0, len, w) => {
514
+ const days = [];
515
+ for (let i = 0; i < len; i++)
516
+ if (weekdayOf(day0 + i) === w.weekday)
517
+ days.push(day0 + i);
518
+ const k = w.ordinal > 0 ? w.ordinal - 1 : days.length + w.ordinal;
519
+ if (k >= 0 && k < days.length)
520
+ out.push(days[k]);
521
+ };
522
+ const monthDays = (y, m, list2) => {
523
+ const n = daysInMonth(y, m);
524
+ for (const d of list2) {
525
+ const day = d > 0 ? d : n + d + 1;
526
+ if (day >= 1 && day <= n)
527
+ out.push(dayNumber(y, m, day));
528
+ }
529
+ };
530
+ switch (rule.freq) {
531
+ case "DAILY": {
532
+ const day = startDay + period * rule.interval;
533
+ const { m, d } = ymdOf(day);
534
+ if (rule.byMonth && !rule.byMonth.includes(m))
535
+ break;
536
+ if (rule.byMonthDay && !rule.byMonthDay.some((x) => x > 0 ? x === d : daysInMonth(ymdOf(day).y, m) + x + 1 === d))
537
+ break;
538
+ if (rule.byDay && !rule.byDay.some((w) => w.weekday === weekdayOf(day)))
539
+ break;
540
+ out.push(day);
541
+ break;
542
+ }
543
+ case "WEEKLY": {
544
+ const weekStart = startDay - (weekdayOf(startDay) - rule.wkst + 7) % 7 + period * rule.interval * 7;
545
+ const wanted = rule.byDay ?? [{ weekday: weekdayOf(startDay) }];
546
+ byDayAll(weekStart, 7, wanted);
547
+ if (rule.byMonth)
548
+ return out.filter((d) => rule.byMonth.includes(ymdOf(d).m)).sort((a, b) => a - b);
549
+ break;
550
+ }
551
+ case "MONTHLY": {
552
+ const index = s.y * 12 + (s.m - 1) + period * rule.interval;
553
+ const y = Math.floor(index / 12), m = index % 12 + 1;
554
+ const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m);
555
+ if (rule.byMonthDay) {
556
+ monthDays(y, m, rule.byMonthDay);
557
+ if (rule.byDay) {
558
+ const keep = out.filter((d) => rule.byDay.some((w) => w.weekday === weekdayOf(d)));
559
+ out.length = 0;
560
+ out.push(...keep);
561
+ }
562
+ } else if (rule.byDay) {
563
+ byDayAll(day0, len, rule.byDay);
564
+ for (const w of rule.byDay)
565
+ if (w.ordinal !== void 0)
566
+ nth(day0, len, w);
567
+ } else if (s.d <= len)
568
+ out.push(dayNumber(y, m, s.d));
569
+ break;
570
+ }
571
+ case "YEARLY": {
572
+ const y = s.y + period * rule.interval;
573
+ if (rule.byDay && !rule.byMonth && !rule.byMonthDay) {
574
+ const day0 = dayNumber(y, 1, 1), len = isLeap(y) ? 366 : 365;
575
+ byDayAll(day0, len, rule.byDay);
576
+ for (const w of rule.byDay)
577
+ if (w.ordinal !== void 0)
578
+ nth(day0, len, w);
579
+ break;
580
+ }
581
+ const months = rule.byMonth ?? [s.m];
582
+ for (const m of months) {
583
+ if (rule.byMonthDay)
584
+ monthDays(y, m, rule.byMonthDay);
585
+ else if (rule.byDay) {
586
+ const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m);
587
+ byDayAll(day0, len, rule.byDay);
588
+ for (const w of rule.byDay)
589
+ if (w.ordinal !== void 0)
590
+ nth(day0, len, w);
591
+ } else if (s.d <= daysInMonth(y, m))
592
+ out.push(dayNumber(y, m, s.d));
593
+ }
594
+ if (rule.byMonthDay && rule.byDay) {
595
+ const keep = out.filter((d) => rule.byDay.some((w) => w.weekday === weekdayOf(d)));
596
+ out.length = 0;
597
+ out.push(...keep);
598
+ }
599
+ break;
600
+ }
601
+ }
602
+ const sorted = [...new Set(out)].sort((a, b) => a - b);
603
+ if (rule.bySetPos !== void 0) {
604
+ const k = rule.bySetPos > 0 ? rule.bySetPos - 1 : sorted.length + rule.bySetPos;
605
+ return k >= 0 && k < sorted.length ? [sorted[k]] : [];
606
+ }
607
+ return sorted;
608
+ }
609
+ function periodStart(rule, p, startDay) {
610
+ const s = ymdOf(startDay);
611
+ switch (rule.freq) {
612
+ case "DAILY":
613
+ return startDay + p * rule.interval;
614
+ case "WEEKLY":
615
+ return startDay - (weekdayOf(startDay) - rule.wkst + 7) % 7 + p * rule.interval * 7;
616
+ case "MONTHLY": {
617
+ const index = s.y * 12 + (s.m - 1) + p * rule.interval;
618
+ return dayNumber(Math.floor(index / 12), index % 12 + 1, 1);
619
+ }
620
+ case "YEARLY":
621
+ return dayNumber(s.y + p * rule.interval, 1, 1);
622
+ }
623
+ }
624
+ function periodsBefore(rule, startDay, day) {
625
+ const s = ymdOf(startDay);
626
+ const t = ymdOf(day);
627
+ let p;
628
+ switch (rule.freq) {
629
+ case "DAILY":
630
+ p = Math.floor((day - startDay) / rule.interval);
631
+ break;
632
+ case "WEEKLY":
633
+ p = Math.floor((day - periodStart(rule, 0, startDay)) / (7 * rule.interval));
634
+ break;
635
+ case "MONTHLY":
636
+ p = Math.floor((t.y * 12 + t.m - (s.y * 12 + s.m)) / rule.interval);
637
+ break;
638
+ case "YEARLY":
639
+ p = Math.floor((t.y - s.y) / rule.interval);
640
+ break;
641
+ }
642
+ return Math.max(-1, p - 1);
643
+ }
644
+ function expandSeries(rule, start, window, opts = {}) {
645
+ var _a;
646
+ const limit = opts.limit ?? 2e3;
647
+ const excluded = new Set(opts.exdate ?? []);
648
+ const out = [];
649
+ let startDay;
650
+ let minute = 0, second = 0;
651
+ let tz = "UTC";
652
+ let fromDay, toDay;
653
+ const viewerTz = opts.viewerTz ?? "UTC";
654
+ if (start.kind === "date") {
655
+ startDay = dayOf(start.date);
656
+ fromDay = localDay(window.fromMs, viewerTz) - (opts.durationDays ?? 0);
657
+ toDay = localDay(window.toMs - 1, viewerTz);
658
+ } else {
659
+ tz = start.tz;
660
+ const ms = Date.parse(start.utc);
661
+ const p = zonedParts(ms, tz);
662
+ startDay = dayNumber(p.y, p.m, p.d);
663
+ minute = p.h * 60 + p.mi;
664
+ second = p.s;
665
+ fromDay = localDay(window.fromMs - (opts.durationMs ?? 0), tz) - 1;
666
+ toDay = localDay(window.toMs, tz) + 1;
667
+ }
668
+ const untilDay = ((_a = rule.until) == null ? void 0 : _a.length) === 10 ? dayOf(rule.until) : void 0;
669
+ const untilMs = rule.until && rule.until.length > 10 ? Date.parse(rule.until) : void 0;
670
+ let count = 0;
671
+ const emit = (day) => {
672
+ if (rule.count !== void 0 && count >= rule.count)
673
+ return false;
674
+ if (untilDay !== void 0 && day > untilDay)
675
+ return false;
676
+ let occ;
677
+ if (start.kind === "date") {
678
+ if (untilMs !== void 0 && day * 864e5 > untilMs)
679
+ return false;
680
+ const date = dateOf(day);
681
+ occ = { original: date, date };
682
+ } else {
683
+ const ms = zonedToUtc(day, minute, second, tz);
684
+ if (untilMs !== void 0 && ms > untilMs)
685
+ return false;
686
+ occ = { original: new Date(ms).toISOString(), startMs: ms };
687
+ }
688
+ count += 1;
689
+ if (excluded.has(occ.original))
690
+ return true;
691
+ if (start.kind === "date") {
692
+ if (day >= fromDay && day <= toDay)
693
+ out.push(occ);
694
+ } else if (occ.startMs + (opts.durationMs ?? 0) > window.fromMs && occ.startMs < window.toMs)
695
+ out.push(occ);
696
+ return true;
697
+ };
698
+ if (startDay > toDay || !emit(startDay))
699
+ return out;
700
+ let period = rule.count === void 0 ? periodsBefore(rule, startDay, fromDay) + 1 : 0;
701
+ for (let guard = 0; guard < MAX_PERIODS && out.length < limit; guard++, period++) {
702
+ if (periodStart(rule, period, startDay) > toDay)
703
+ break;
704
+ for (const day of candidates(rule, period, startDay)) {
705
+ if (day <= startDay)
706
+ continue;
707
+ if (day > toDay)
708
+ return out;
709
+ if (!emit(day) || out.length >= limit)
710
+ return out;
711
+ }
712
+ }
713
+ return out;
714
+ }
715
+ function seriesStartOf(values, tz, fallbackTz = "UTC") {
716
+ if (values.all_day === true)
717
+ return typeof values.start_date === "string" ? { kind: "date", date: values.start_date } : null;
718
+ return typeof values.start === "string" ? { kind: "datetime", utc: values.start, tz: tz && isTimeZone(tz) ? tz : fallbackTz } : null;
719
+ }
720
+ function originalOf(occ) {
721
+ return occ.date ?? new Date(occ.startMs).toISOString();
722
+ }
723
+ function occurrenceId(recordId, original) {
724
+ return `${recordId}@${original}`;
725
+ }
726
+ function parseOccurrenceId(id) {
727
+ const at = id.indexOf("@");
728
+ return at < 0 ? { recordId: id, original: null } : { recordId: id.slice(0, at), original: id.slice(at + 1) };
729
+ }
730
+ const ORD_ZH = { 1: "第一个", 2: "第二个", 3: "第三个", 4: "第四个", 5: "第五个", [-1]: "最后一个", [-2]: "倒数第二个", [-3]: "倒数第三个", [-4]: "倒数第四个", [-5]: "倒数第五个" };
731
+ const ORD_EN = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", [-1]: "last", [-2]: "second to last", [-3]: "third to last", [-4]: "fourth to last", [-5]: "fifth to last" };
732
+ const WD_ZH = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
733
+ const WD_EN = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
734
+ const MONTH_EN = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
735
+ const isWorkdays = (d) => !!d && d.length === 5 && d.every((x) => x.ordinal === void 0) && [0, 1, 2, 3, 4].every((w) => d.some((x) => x.weekday === w));
736
+ function describeRRule(rule, locale = "zh") {
737
+ var _a;
738
+ const zh = locale === "zh";
739
+ const n = rule.interval;
740
+ const days = (d) => d.map((x) => {
741
+ const wd = zh ? WD_ZH[x.weekday] : WD_EN[x.weekday];
742
+ if (x.ordinal === void 0)
743
+ return wd;
744
+ return zh ? `${ORD_ZH[x.ordinal]}${wd}` : `${ORD_EN[x.ordinal]} ${wd}`;
745
+ });
746
+ const join = (xs) => zh ? xs.join("、") : xs.length > 1 ? `${xs.slice(0, -1).join(", ")} and ${xs[xs.length - 1]}` : xs.join("");
747
+ const mday = (d) => zh ? d === -1 ? "最后一天" : `${d} 日` : d === -1 ? "the last day" : `day ${d}`;
748
+ let text;
749
+ switch (rule.freq) {
750
+ case "DAILY":
751
+ text = zh ? n === 1 ? "每天" : `每 ${n} 天` : n === 1 ? "every day" : `every ${n} days`;
752
+ break;
753
+ case "WEEKLY":
754
+ if (isWorkdays(rule.byDay) && n === 1)
755
+ text = zh ? "每个工作日" : "every weekday";
756
+ else {
757
+ const on = rule.byDay ? join(days(rule.byDay)) : "";
758
+ text = zh ? `${n === 1 ? "每周" : `每 ${n} 周的`}${on}` : `${n === 1 ? "every week" : `every ${n} weeks`}${on ? ` on ${on}` : ""}`;
759
+ }
760
+ break;
761
+ case "MONTHLY": {
762
+ let on = "";
763
+ if (rule.byMonthDay)
764
+ on = join(rule.byMonthDay.map(mday));
765
+ else if (rule.byDay && rule.bySetPos !== void 0) {
766
+ on = isWorkdays(rule.byDay) ? zh ? `${ORD_ZH[rule.bySetPos]}工作日` : `the ${ORD_EN[rule.bySetPos]} weekday` : zh ? `${ORD_ZH[rule.bySetPos]}${join(days(rule.byDay))}` : `the ${ORD_EN[rule.bySetPos]} of ${join(days(rule.byDay))}`;
767
+ } else if (rule.byDay)
768
+ on = zh ? join(days(rule.byDay)) : `the ${join(days(rule.byDay))}`;
769
+ text = zh ? `${n === 1 ? "每月" : `每 ${n} 个月的`}${on}` : `${n === 1 ? "every month" : `every ${n} months`}${on ? ` on ${on}` : ""}`;
770
+ break;
771
+ }
772
+ case "YEARLY": {
773
+ const months = (_a = rule.byMonth) == null ? void 0 : _a.map((m) => zh ? `${m} 月` : MONTH_EN[m - 1]);
774
+ let on = months ? join(months) : "";
775
+ if (rule.byMonthDay)
776
+ on += zh ? join(rule.byMonthDay.map(mday)) : ` ${join(rule.byMonthDay.map((d) => d === -1 ? "last day" : String(d)))}`;
777
+ else if (rule.byDay)
778
+ on += zh ? join(days(rule.byDay)) : ` on the ${join(days(rule.byDay))}`;
779
+ text = zh ? `${n === 1 ? "每年" : `每 ${n} 年的`}${on}` : `${n === 1 ? "every year" : `every ${n} years`}${on.trim() ? ` in ${on.trim()}` : ""}`;
780
+ break;
781
+ }
782
+ }
783
+ if (rule.count !== void 0)
784
+ text += zh ? `,共 ${rule.count} 次` : `, ${rule.count} times`;
785
+ if (rule.until !== void 0)
786
+ text += zh ? `,到 ${rule.until.slice(0, 10)} 为止` : `, until ${rule.until.slice(0, 10)}`;
787
+ return text;
788
+ }
789
+ function recurrencePresets(date, locale = "zh") {
790
+ const day = dayOf(date);
791
+ const { y, m, d } = ymdOf(day);
792
+ const wd = weekdayOf(day);
793
+ const nth = Math.floor((d - 1) / 7) + 1;
794
+ const last = d + 7 > daysInMonth(y, m);
795
+ const zh = locale === "zh";
796
+ const w = WEEKDAYS[wd];
797
+ const out = [
798
+ { id: "none", label: zh ? "不重复" : "Does not repeat", rrule: null },
799
+ { id: "daily", label: zh ? "每天" : "Daily", rrule: "FREQ=DAILY" },
800
+ { id: "weekdays", label: zh ? "每个工作日(周一至周五)" : "Every weekday (Monday to Friday)", rrule: "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR" },
801
+ { id: "weekly", label: zh ? `每周的${WD_ZH[wd]}` : `Weekly on ${WD_EN[wd]}`, rrule: `FREQ=WEEKLY;BYDAY=${w}` },
802
+ { id: "monthly_day", label: zh ? `每月 ${d} 日` : `Monthly on day ${d}`, rrule: `FREQ=MONTHLY;BYMONTHDAY=${d}` }
803
+ ];
804
+ if (nth <= 4)
805
+ out.push({ id: "monthly_nth", label: zh ? `每月${ORD_ZH[nth]}${WD_ZH[wd]}` : `Monthly on the ${ORD_EN[nth]} ${WD_EN[wd]}`, rrule: `FREQ=MONTHLY;BYDAY=${nth}${w}` });
806
+ if (last)
807
+ out.push({ id: "monthly_last", label: zh ? `每月最后一个${WD_ZH[wd]}` : `Monthly on the last ${WD_EN[wd]}`, rrule: `FREQ=MONTHLY;BYDAY=-1${w}` });
808
+ out.push({ id: "yearly", label: zh ? `每年 ${m} 月 ${d} 日` : `Annually on ${MONTH_EN[m - 1]} ${d}`, rrule: `FREQ=YEARLY;BYMONTH=${m};BYMONTHDAY=${d}` });
809
+ return out;
810
+ }
811
+ const TODO_SCHEMA_ID = "buckyos.todo@1";
812
+ const CALENDAR_SCHEMA_ID = "buckyos.calendar@1";
813
+ const SCHEDULE_WORKSPACE_NAME = "schedule";
814
+ const SCHEDULE_TODO_ID = "todo";
815
+ const SCHEDULE_CALENDAR_ID = "calendar";
816
+ const SCHEDULE_SURFACE_ID = "schedule-board";
817
+ const TODO_DONE = "done";
818
+ const AIWS_PROTOCOL_VERSION = "1.2";
819
+ const LABELS = {
820
+ zh: {
821
+ title: "标题",
822
+ status: "状态",
823
+ due: "截止",
824
+ order: "顺序",
825
+ done_at: "完成时间",
826
+ ext: "扩展",
827
+ todo: "待办",
828
+ doing: "进行中",
829
+ done: "已完成",
830
+ all_day: "全天",
831
+ start: "开始",
832
+ end: "结束",
833
+ start_date: "开始日期",
834
+ end_date: "结束日期",
835
+ confirmed: "已确认",
836
+ tentative: "暂定",
837
+ cancelled: "已取消",
838
+ todo_table: "待办",
839
+ calendar_table: "日程",
840
+ workspace: "我的日程",
841
+ board: "日程"
842
+ },
843
+ en: {
844
+ title: "Title",
845
+ status: "Status",
846
+ due: "Due",
847
+ order: "Order",
848
+ done_at: "Completed",
849
+ ext: "Extension",
850
+ todo: "To do",
851
+ doing: "In progress",
852
+ done: "Done",
853
+ all_day: "All day",
854
+ start: "Start",
855
+ end: "End",
856
+ start_date: "Start date",
857
+ end_date: "End date",
858
+ confirmed: "Confirmed",
859
+ tentative: "Tentative",
860
+ cancelled: "Cancelled",
861
+ todo_table: "To-do",
862
+ calendar_table: "Calendar",
863
+ workspace: "My schedule",
864
+ board: "Schedule"
865
+ }
866
+ };
867
+ function scheduleLabel(locale, key) {
868
+ return LABELS[locale][key] ?? LABELS.en[key] ?? key;
869
+ }
870
+ function todoFields(locale = "zh") {
871
+ const l = (k) => scheduleLabel(locale, k);
872
+ return [
873
+ { field_id: "title", name: l("title"), type: "text", required: true },
874
+ { field_id: "status", name: l("status"), type: "select", required: true, options: ["todo", "doing", "done"].map((id) => ({ option_id: id, label: l(id) })) },
875
+ { field_id: "due", name: l("due"), type: "date", nullable: true },
876
+ { field_id: "order", name: l("order"), type: "text", nullable: true },
877
+ { field_id: "done_at", name: l("done_at"), type: "datetime", nullable: true },
878
+ { field_id: "ext", name: l("ext"), type: "json", nullable: true }
879
+ ];
880
+ }
881
+ function calendarFields(locale = "zh") {
882
+ const l = (k) => scheduleLabel(locale, k);
883
+ return [
884
+ { field_id: "title", name: l("title"), type: "text", required: true },
885
+ { field_id: "all_day", name: l("all_day"), type: "boolean", nullable: true },
886
+ { field_id: "start", name: l("start"), type: "datetime", nullable: true },
887
+ { field_id: "end", name: l("end"), type: "datetime", nullable: true },
888
+ { field_id: "start_date", name: l("start_date"), type: "date", nullable: true },
889
+ { field_id: "end_date", name: l("end_date"), type: "date", nullable: true },
890
+ { field_id: "status", name: l("status"), type: "select", nullable: true, options: ["confirmed", "tentative", "cancelled"].map((id) => ({ option_id: id, label: l(id) })) },
891
+ { field_id: "ext", name: l("ext"), type: "json", nullable: true }
892
+ ];
893
+ }
894
+ function standardTableOp(kind, args) {
895
+ const locale = args.locale ?? "zh";
896
+ return {
897
+ op: "entity.create",
898
+ entity_id: args.entity_id,
899
+ type_id: "buckyos.table-source",
900
+ parent_id: args.parent_id,
901
+ order_key: args.order_key,
902
+ schema_id: kind === "todo" ? TODO_SCHEMA_ID : CALENDAR_SCHEMA_ID,
903
+ name: args.name ?? scheduleLabel(locale, kind === "todo" ? "todo_table" : "calendar_table"),
904
+ payload: { title_field_id: "title", fields: kind === "todo" ? todoFields(locale) : calendarFields(locale) }
905
+ };
906
+ }
907
+ const DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz";
908
+ const MAX_KEY_LEN = 64;
909
+ const APPEND_WIDTH = 8;
910
+ function isOrderKey(k) {
911
+ return typeof k === "string" && k.length > 0 && k.length <= MAX_KEY_LEN && /^[0-9a-z]+$/.test(k) && !k.endsWith("0");
912
+ }
913
+ function midpoint(a, b) {
914
+ if (b !== null) {
915
+ let n = 0;
916
+ while (n < b.length && (a[n] ?? "0") === b[n])
917
+ n++;
918
+ if (n > 0)
919
+ return b.slice(0, n) + midpoint(a.length > n ? a.slice(n) : "", b.slice(n));
920
+ }
921
+ const da = a.length ? DIGITS.indexOf(a[0]) : 0;
922
+ const db = b !== null ? DIGITS.indexOf(b[0]) : DIGITS.length;
923
+ if (db - da > 1)
924
+ return DIGITS[Math.floor((da + db + 1) / 2)];
925
+ if (b !== null && b.length > 1)
926
+ return b[0];
927
+ return DIGITS[da] + midpoint(a.length > 1 ? a.slice(1) : "", null);
928
+ }
929
+ function after(a) {
930
+ const out = a.padEnd(Math.max(a.length, APPEND_WIDTH), "0").split("");
931
+ let i = out.length - 1;
932
+ while (i >= 0 && out[i] === "z")
933
+ i--;
934
+ if (i >= 0) {
935
+ out[i] = DIGITS[DIGITS.indexOf(out[i]) + 1];
936
+ for (let j = i + 1; j < out.length; j++)
937
+ out[j] = "0";
938
+ if (out[out.length - 1] === "0")
939
+ out[out.length - 1] = "1";
940
+ return out.join("");
941
+ }
942
+ if (out.length >= MAX_KEY_LEN)
943
+ throw new Error("order key space exhausted; rebalance");
944
+ const longer = out.join("").padEnd(Math.min(out.length + APPEND_WIDTH, MAX_KEY_LEN), "0");
945
+ return longer.slice(0, -1) + "1";
946
+ }
947
+ function orderKeyBetween(a, b) {
948
+ const lo = a ?? null, hi = b ?? null;
949
+ if (lo !== null && hi !== null && lo >= hi)
950
+ throw new Error("orderKeyBetween requires a < b");
951
+ const key = lo !== null && hi === null ? after(lo) : midpoint(lo ?? "", hi);
952
+ if (!isOrderKey(key))
953
+ throw new Error("order key space exhausted; rebalance");
954
+ return key;
955
+ }
956
+ function orderKeysBetween(a, b, count) {
957
+ const out = [];
958
+ let lo = a;
959
+ for (let i = 0; i < count; i++) {
960
+ lo = orderKeyBetween(lo, b);
961
+ out.push(lo);
962
+ }
963
+ return out;
964
+ }
965
+ let counter = 0;
966
+ function newRecordId(prefix = "r") {
967
+ counter = (counter + 1) % 1296;
968
+ const rand = Math.floor(Math.random() * 36 ** 6).toString(36).padStart(6, "0");
969
+ return `${prefix}${Date.now().toString(36)}${counter.toString(36).padStart(2, "0")}${rand}`;
970
+ }
971
+ function setValuesOps(sourceId, row, changes) {
972
+ var _a;
973
+ const set = [];
974
+ const unset = [];
975
+ for (const [field, value] of Object.entries(changes)) {
976
+ const cell = { record_id: row.record_id, field_id: field, expect: { rev: ((_a = row.revs) == null ? void 0 : _a[field]) ?? 0 } };
977
+ if (value === null || value === void 0) {
978
+ if (row.values[field] !== void 0 && row.values[field] !== null)
979
+ unset.push(cell);
980
+ } else {
981
+ set.push({ ...cell, value });
982
+ }
983
+ }
984
+ const out = [];
985
+ if (set.length)
986
+ out.push({ op: "table.set_values", source_id: sourceId, values: set });
987
+ if (unset.length)
988
+ out.push({ op: "table.unset_values", source_id: sourceId, values: unset });
989
+ return out;
990
+ }
991
+ function insertRecordOp(sourceId, records) {
992
+ return {
993
+ op: "table.insert_records",
994
+ source_id: sourceId,
995
+ records: records.map((r) => ({ record_id: r.record_id, values: Object.fromEntries(Object.entries(r.values).filter(([, v]) => v !== void 0 && v !== null)) }))
996
+ };
997
+ }
998
+ function deleteRecordsOp(sourceId, rows) {
999
+ return { op: "table.delete_records", source_id: sourceId, records: rows.map((r) => ({ record_id: r.record_id, expect: { rev: r.rev ?? 0 } })) };
1000
+ }
1001
+ function canonicalOriginal(x) {
1002
+ if (isDate(x))
1003
+ return x;
1004
+ const t = Date.parse(x);
1005
+ return Number.isFinite(t) ? new Date(t).toISOString() : x;
1006
+ }
1007
+ const originals = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string").map(canonicalOriginal) : [];
1008
+ const extOf = (row) => {
1009
+ const e = row == null ? void 0 : row.values.ext;
1010
+ return e && typeof e === "object" && !Array.isArray(e) ? { ...e } : {};
1011
+ };
1012
+ function todoItem(row) {
1013
+ const v = row.values;
1014
+ const status = typeof v.status === "string" ? v.status : "todo";
1015
+ return {
1016
+ record_id: row.record_id,
1017
+ rev: row.rev,
1018
+ revs: row.revs,
1019
+ values: row.values,
1020
+ title: typeof v.title === "string" ? v.title : "",
1021
+ status,
1022
+ due: typeof v.due === "string" ? v.due : null,
1023
+ order: isOrderKey(v.order) ? v.order : null,
1024
+ done: status === TODO_DONE,
1025
+ done_at: typeof v.done_at === "string" ? v.done_at : null,
1026
+ ext: extOf(row)
1027
+ };
1028
+ }
1029
+ function sortTodos(items) {
1030
+ return [...items].sort((a, b) => a.order === b.order ? a.record_id.localeCompare(b.record_id) : a.order === null ? 1 : b.order === null ? -1 : a.order < b.order ? -1 : 1);
1031
+ }
1032
+ function todoAddOps(sourceId, input, place = {}) {
1033
+ const record_id = input.record_id ?? newRecordId("t");
1034
+ let order = input.order ?? null;
1035
+ if (!order) {
1036
+ if (place.after !== void 0 || place.before !== void 0)
1037
+ order = orderKeyBetween(place.after ?? null, place.before ?? null);
1038
+ else {
1039
+ const last = (place.items ?? []).map((i) => i.order).filter(isOrderKey).sort().pop() ?? null;
1040
+ order = orderKeyBetween(last, null);
1041
+ }
1042
+ }
1043
+ const status = input.status ?? "todo";
1044
+ const values = {
1045
+ title: input.title,
1046
+ status,
1047
+ order,
1048
+ due: input.due ?? void 0,
1049
+ ext: input.ext && Object.keys(input.ext).length ? input.ext : void 0,
1050
+ done_at: status === TODO_DONE ? input.done_at ?? (/* @__PURE__ */ new Date()).toISOString() : void 0
1051
+ };
1052
+ return { record_id, order, ops: [insertRecordOp(sourceId, [{ record_id, values }])] };
1053
+ }
1054
+ function todoCompleteOps(sourceId, row, done, opts = {}) {
1055
+ if (done)
1056
+ return setValuesOps(sourceId, row, { status: TODO_DONE, done_at: opts.now ?? (/* @__PURE__ */ new Date()).toISOString() });
1057
+ return setValuesOps(sourceId, row, { status: opts.reopenStatus ?? "todo", done_at: null });
1058
+ }
1059
+ function todoMoveOps(sourceId, row, to, opts = {}) {
1060
+ const changes = {};
1061
+ const was = typeof row.values.status === "string" ? row.values.status : void 0;
1062
+ if (to.status !== void 0 && to.status !== was) {
1063
+ changes.status = to.status;
1064
+ if (to.status === TODO_DONE)
1065
+ changes.done_at = opts.now ?? (/* @__PURE__ */ new Date()).toISOString();
1066
+ else if (was === TODO_DONE)
1067
+ changes.done_at = null;
1068
+ }
1069
+ if (to.order !== void 0 && to.order !== row.values.order)
1070
+ changes.order = to.order;
1071
+ return Object.keys(changes).length ? setValuesOps(sourceId, row, changes) : [];
1072
+ }
1073
+ function todoUpdateOps(sourceId, row, changes) {
1074
+ const out = {};
1075
+ for (const k of ["title", "status", "due", "order", "done_at"])
1076
+ if (changes[k] !== void 0)
1077
+ out[k] = changes[k];
1078
+ if (changes.ext !== void 0)
1079
+ out.ext = changes.ext && Object.keys(changes.ext).length ? changes.ext : null;
1080
+ if (changes.ext_merge) {
1081
+ const ext = extOf(row);
1082
+ for (const [k, v] of Object.entries(changes.ext_merge))
1083
+ if (v === null)
1084
+ delete ext[k];
1085
+ else
1086
+ ext[k] = v;
1087
+ out.ext = Object.keys(ext).length ? ext : null;
1088
+ }
1089
+ if (out.status !== void 0 && out.status !== row.values.status && out.done_at === void 0) {
1090
+ if (out.status === TODO_DONE)
1091
+ out.done_at = (/* @__PURE__ */ new Date()).toISOString();
1092
+ else if (row.values.status === TODO_DONE)
1093
+ out.done_at = null;
1094
+ }
1095
+ return setValuesOps(sourceId, row, out);
1096
+ }
1097
+ function orderAt(items, index) {
1098
+ const keys = items.map((i) => i.order);
1099
+ const before = index > 0 ? keys[index - 1] : null;
1100
+ const afterKey = index < keys.length ? keys[index] : null;
1101
+ if (before !== null && !isOrderKey(before))
1102
+ return orderKeyBetween(null, null);
1103
+ if (afterKey !== null && isOrderKey(afterKey) && (before === null || before < afterKey))
1104
+ return orderKeyBetween(before, afterKey);
1105
+ return orderKeyBetween(before, null);
1106
+ }
1107
+ const DEFAULT_EVENT_MS = 36e5;
1108
+ function rowTimes(row) {
1109
+ const v = row.values;
1110
+ if (v.all_day === true) {
1111
+ if (typeof v.start_date !== "string" || !isDate(v.start_date))
1112
+ return null;
1113
+ const endDate = typeof v.end_date === "string" && isDate(v.end_date) && v.end_date >= v.start_date ? v.end_date : v.start_date;
1114
+ return { allDay: true, startDate: v.start_date, endDate };
1115
+ }
1116
+ if (typeof v.start !== "string")
1117
+ return null;
1118
+ const startMs = Date.parse(v.start);
1119
+ if (!Number.isFinite(startMs))
1120
+ return null;
1121
+ const end = typeof v.end === "string" ? Date.parse(v.end) : NaN;
1122
+ return { allDay: false, startMs, endMs: Number.isFinite(end) && end >= startMs ? end : startMs + DEFAULT_EVENT_MS };
1123
+ }
1124
+ function addDays(date, n) {
1125
+ return dateOf(dayOf(date) + n);
1126
+ }
1127
+ const daysBetween = (a, b) => dayOf(b) - dayOf(a);
1128
+ function occurrenceOf(row, times, extra) {
1129
+ const ext = extOf(row);
1130
+ return {
1131
+ id: row.record_id,
1132
+ row,
1133
+ title: typeof row.values.title === "string" ? row.values.title : "",
1134
+ allDay: times.allDay,
1135
+ startMs: times.startMs,
1136
+ endMs: times.endMs,
1137
+ startDate: times.startDate,
1138
+ endDate: times.endDate,
1139
+ status: typeof row.values.status === "string" ? row.values.status : null,
1140
+ ext,
1141
+ recurring: false,
1142
+ override: false,
1143
+ agentWritten: false,
1144
+ ...extra
1145
+ };
1146
+ }
1147
+ function overlaps(o, window, viewerTz) {
1148
+ if (!o.allDay)
1149
+ return o.startMs < window.toMs && Math.max(o.endMs, o.startMs + 1) > window.fromMs;
1150
+ const from = localDate(window.fromMs, viewerTz), to = localDate(window.toMs - 1, viewerTz);
1151
+ return o.startDate <= to && o.endDate >= from;
1152
+ }
1153
+ function localDate(ms, tz) {
1154
+ const f = new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" });
1155
+ return f.format(new Date(ms));
1156
+ }
1157
+ function viewerTimeZone() {
1158
+ try {
1159
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
1160
+ } catch {
1161
+ return "UTC";
1162
+ }
1163
+ }
1164
+ function calendarOccurrences(rows, window, opts = {}) {
1165
+ const viewerTz = opts.viewerTz ?? viewerTimeZone();
1166
+ const out = [];
1167
+ const overrides = /* @__PURE__ */ new Map();
1168
+ for (const row of rows) {
1169
+ const rid = extOf(row).recurrence_id;
1170
+ if (rid && typeof rid === "object" && !Array.isArray(rid) && typeof rid.master === "string" && typeof rid.original === "string")
1171
+ overrides.set(`${rid.master}@${canonicalOriginal(rid.original)}`, row);
1172
+ }
1173
+ const byId = new Map(rows.map((r) => [r.record_id, r]));
1174
+ for (const row of rows) {
1175
+ const times = rowTimes(row);
1176
+ if (!times)
1177
+ continue;
1178
+ const ext = extOf(row);
1179
+ const rid = ext.recurrence_id;
1180
+ if (rid && typeof rid === "object") {
1181
+ const master = typeof rid.master === "string" ? byId.get(rid.master) : void 0;
1182
+ const original = typeof rid.original === "string" ? canonicalOriginal(rid.original) : void 0;
1183
+ const occ2 = occurrenceOf(row, times, { id: master && original ? occurrenceId(master.record_id, original) : row.record_id, master, original, recurring: Boolean(master), override: true });
1184
+ if (overlaps(occ2, window, viewerTz))
1185
+ out.push(occ2);
1186
+ continue;
1187
+ }
1188
+ const duration = times.allDay ? daysBetween(times.startDate, times.endDate) : times.endMs - times.startMs;
1189
+ const shift = (o) => {
1190
+ const key = `${row.record_id}@${o.original}`;
1191
+ if (overrides.has(key))
1192
+ return null;
1193
+ if (times.allDay)
1194
+ return occurrenceOf(row, { allDay: true, startDate: o.date, endDate: addDays(o.date, duration) }, { id: key, master: row, original: o.original, recurring: true });
1195
+ return occurrenceOf(row, { allDay: false, startMs: o.startMs, endMs: o.startMs + duration }, { id: key, master: row, original: o.original, recurring: true });
1196
+ };
1197
+ let rule = null;
1198
+ if (typeof ext.rrule === "string") {
1199
+ try {
1200
+ rule = parseRRule(ext.rrule);
1201
+ } catch {
1202
+ rule = null;
1203
+ }
1204
+ }
1205
+ if (rule) {
1206
+ const start = seriesStartOf(row.values, typeof ext.tz === "string" ? ext.tz : void 0, viewerTz);
1207
+ if (!start)
1208
+ continue;
1209
+ const exdate = originals(ext.exdate);
1210
+ const occs = expandSeries(rule, start, window, { exdate, viewerTz, durationMs: times.allDay ? void 0 : duration, durationDays: times.allDay ? duration : void 0, limit: opts.limit });
1211
+ for (const o of occs) {
1212
+ const s = shift(o);
1213
+ if (s)
1214
+ out.push(s);
1215
+ }
1216
+ continue;
1217
+ }
1218
+ if (Array.isArray(ext.occurrences) && ext.occurrences.length > 0) {
1219
+ const exdate = new Set(originals(ext.exdate));
1220
+ for (const raw of ext.occurrences) {
1221
+ if (typeof raw !== "string")
1222
+ continue;
1223
+ const x = canonicalOriginal(raw);
1224
+ if (exdate.has(x))
1225
+ continue;
1226
+ const o = times.allDay ? { original: x, date: x } : { original: x, startMs: Date.parse(x) };
1227
+ if (!times.allDay && !Number.isFinite(o.startMs))
1228
+ continue;
1229
+ if (times.allDay && !isDate(x))
1230
+ continue;
1231
+ const s = shift(o);
1232
+ if (s && overlaps(s, window, viewerTz))
1233
+ out.push({ ...s, agentWritten: true });
1234
+ }
1235
+ continue;
1236
+ }
1237
+ const occ = occurrenceOf(row, times, {});
1238
+ if (overlaps(occ, window, viewerTz))
1239
+ out.push(occ);
1240
+ }
1241
+ return out.sort((a, b) => sortKey(a) - sortKey(b) || a.id.localeCompare(b.id));
1242
+ }
1243
+ const sortKey = (o) => o.allDay ? Date.parse(`${o.startDate}T00:00:00Z`) : o.startMs;
1244
+ function eventAddOps(sourceId, input) {
1245
+ const record_id = input.record_id ?? newRecordId("e");
1246
+ const values = { title: input.title, status: input.status ?? void 0, ext: input.ext && Object.keys(input.ext).length ? input.ext : void 0 };
1247
+ if (input.all_day) {
1248
+ values.all_day = true;
1249
+ values.start_date = input.start_date ?? void 0;
1250
+ values.end_date = input.end_date && input.end_date !== input.start_date ? input.end_date : void 0;
1251
+ } else {
1252
+ values.start = input.start ?? void 0;
1253
+ values.end = input.end ?? void 0;
1254
+ }
1255
+ return { record_id, ops: [insertRecordOp(sourceId, [{ record_id, values }])] };
1256
+ }
1257
+ function timesChanges(times) {
1258
+ return times.allDay ? { all_day: true, start_date: times.startDate, end_date: times.endDate !== times.startDate ? times.endDate : null, start: null, end: null } : { all_day: null, start: times.start, end: times.end, start_date: null, end_date: null };
1259
+ }
1260
+ function overridesOf(rows, masterId) {
1261
+ return rows.filter((r) => {
1262
+ const rid = extOf(r).recurrence_id;
1263
+ return rid && typeof rid === "object" && rid.master === masterId;
1264
+ });
1265
+ }
1266
+ const isoShift = (iso, deltaMs) => new Date(Date.parse(iso) + deltaMs).toISOString();
1267
+ function shiftOriginal(original, allDay, deltaMs, deltaDays) {
1268
+ return allDay ? addDays(original, deltaDays) : isoShift(original, deltaMs);
1269
+ }
1270
+ function shiftRule(rule, deltaDays) {
1271
+ if (!deltaDays)
1272
+ return rule;
1273
+ const next = { ...rule };
1274
+ if (rule.byDay && rule.byDay.every((d) => d.ordinal === void 0) && (rule.freq === "WEEKLY" || rule.freq === "DAILY")) {
1275
+ next.byDay = rule.byDay.map((d) => ({ weekday: ((d.weekday + deltaDays) % 7 + 7) % 7 }));
1276
+ } else if (rule.byDay && rule.freq === "MONTHLY" && rule.byDay.length === 1 && rule.bySetPos === void 0 && Math.abs(deltaDays) < 7) {
1277
+ next.byDay = [{ ...rule.byDay[0], weekday: ((rule.byDay[0].weekday + deltaDays) % 7 + 7) % 7 }];
1278
+ } else if (rule.byMonthDay && rule.byMonthDay.length === 1 && rule.byMonthDay[0] > 0) {
1279
+ const d = rule.byMonthDay[0] + deltaDays;
1280
+ if (d >= 1 && d <= 28)
1281
+ next.byMonthDay = [d];
1282
+ }
1283
+ return next;
1284
+ }
1285
+ function eventEditOps(sourceId, occ, change, scope, ctx) {
1286
+ const newId = ctx.newRecordId ?? (() => newRecordId("e"));
1287
+ const fieldChanges = (row) => {
1288
+ const out = { ...change.values };
1289
+ if (change.ext_merge) {
1290
+ const ext = extOf(row);
1291
+ for (const [k, v] of Object.entries(change.ext_merge))
1292
+ if (v === null)
1293
+ delete ext[k];
1294
+ else
1295
+ ext[k] = v;
1296
+ out.ext = Object.keys(ext).length ? ext : null;
1297
+ }
1298
+ return out;
1299
+ };
1300
+ const master = occ.master;
1301
+ if (!master || occ.row !== master && scope === "one") {
1302
+ const row = occ.row;
1303
+ const changes = { ...fieldChanges(row), ...change.times ? timesChanges(change.times) : {} };
1304
+ if (change.rrule !== void 0 && !master) {
1305
+ const ext = changes.ext ?? extOf(row);
1306
+ const next = { ...ext ?? {} };
1307
+ if (change.rrule === null)
1308
+ delete next.rrule;
1309
+ else
1310
+ next.rrule = formatRRule(parseRRule(change.rrule));
1311
+ if (change.rrule === null)
1312
+ delete next.exdate;
1313
+ changes.ext = Object.keys(next).length ? next : null;
1314
+ }
1315
+ return { ops: setValuesOps(sourceId, row, changes), record_id: row.record_id };
1316
+ }
1317
+ const original = occ.original;
1318
+ const masterTimes = rowTimes(master);
1319
+ const masterExt = extOf(master);
1320
+ if (scope === "one") {
1321
+ const id2 = newId();
1322
+ const ext = { ...masterExt, recurrence_id: { master: master.record_id, original } };
1323
+ delete ext.rrule;
1324
+ delete ext.exdate;
1325
+ delete ext.occurrences;
1326
+ delete ext.rule_text;
1327
+ delete ext.covered_until;
1328
+ delete ext.maintenance;
1329
+ const base = { title: master.values.title, status: master.values.status, ext };
1330
+ const times2 = change.times ?? (occ.allDay ? { allDay: true, startDate: occ.startDate, endDate: addDays(occ.startDate, daysBetween(masterTimes.startDate, masterTimes.endDate)) } : { allDay: false, start: new Date(occ.startMs).toISOString(), end: new Date(occ.startMs + (masterTimes.endMs - masterTimes.startMs)).toISOString() });
1331
+ const values2 = { ...base, ...fieldChanges({ record_id: id2, values: { ext } }), ...timesChanges(times2) };
1332
+ if (!values2.ext)
1333
+ values2.ext = ext;
1334
+ return { ops: [insertRecordOp(sourceId, [{ record_id: id2, values: values2 }])], record_id: id2 };
1335
+ }
1336
+ let deltaMs = 0, deltaDays = 0;
1337
+ let durationMs = masterTimes.allDay ? 0 : masterTimes.endMs - masterTimes.startMs;
1338
+ let durationDays = masterTimes.allDay ? daysBetween(masterTimes.startDate, masterTimes.endDate) : 0;
1339
+ if (change.times) {
1340
+ if (change.times.allDay !== masterTimes.allDay)
1341
+ throw new Error("changing a series between all-day and timed: edit the series itself (scope all) with new times");
1342
+ if (change.times.allDay) {
1343
+ deltaDays = daysBetween(original, change.times.startDate);
1344
+ durationDays = daysBetween(change.times.startDate, change.times.endDate);
1345
+ } else {
1346
+ deltaMs = Date.parse(change.times.start) - Date.parse(original);
1347
+ deltaDays = Math.round(deltaMs / 864e5);
1348
+ durationMs = Date.parse(change.times.end) - Date.parse(change.times.start);
1349
+ }
1350
+ }
1351
+ const rule = typeof masterExt.rrule === "string" ? parseRRule(masterExt.rrule) : null;
1352
+ const overrides = overridesOf(ctx.rows, master.record_id);
1353
+ const exdate = originals(masterExt.exdate);
1354
+ const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs).toISOString();
1355
+ const seriesTimes = (startMs, startDate) => masterTimes.allDay ? { allDay: true, startDate: addDays(startDate, deltaDays), endDate: addDays(addDays(startDate, deltaDays), durationDays) } : { allDay: false, start: new Date(startMs + deltaMs).toISOString(), end: new Date(startMs + deltaMs + durationMs).toISOString() };
1356
+ const nextRule = (r) => {
1357
+ if (change.rrule !== void 0)
1358
+ return change.rrule === null ? null : formatRRule(parseRRule(change.rrule));
1359
+ return r ? formatRRule(shiftRule(r, deltaDays)) : null;
1360
+ };
1361
+ const ops = [];
1362
+ if (scope === "all" || isFirst) {
1363
+ const times2 = seriesTimes(masterTimes.startMs, masterTimes.startDate);
1364
+ const ext = { ...masterExt };
1365
+ const r = nextRule(rule);
1366
+ if (r)
1367
+ ext.rrule = r;
1368
+ else {
1369
+ delete ext.rrule;
1370
+ delete ext.exdate;
1371
+ }
1372
+ if (r && exdate.length)
1373
+ ext.exdate = exdate.map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays));
1374
+ const fc2 = fieldChanges({ record_id: master.record_id, values: { ext } });
1375
+ const extOut = fc2.ext !== void 0 ? fc2.ext : ext;
1376
+ ops.push(...setValuesOps(sourceId, master, { ...fc2, ...timesChanges(times2), ext: extOut && Object.keys(extOut).length ? extOut : null }));
1377
+ for (const o of overrides) {
1378
+ const oext = extOf(o);
1379
+ const rid = oext.recurrence_id;
1380
+ if (!r) {
1381
+ ops.push(deleteRecordsOp(sourceId, [o]));
1382
+ continue;
1383
+ }
1384
+ if (deltaMs || deltaDays)
1385
+ ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { ...rid, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }));
1386
+ }
1387
+ return { ops, record_id: master.record_id };
1388
+ }
1389
+ if (!rule)
1390
+ throw new Error("not a repeating event");
1391
+ const id = newId();
1392
+ const before = (x) => masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original);
1393
+ let headRule = { ...rule };
1394
+ let tailRule = { ...rule };
1395
+ if (rule.count !== void 0) {
1396
+ const start = seriesStartOf(master.values, typeof masterExt.tz === "string" ? masterExt.tz : void 0);
1397
+ const fromMs = masterTimes.allDay ? Date.parse(`${masterTimes.startDate}T00:00:00Z`) - 864e5 * 2 : masterTimes.startMs;
1398
+ const toMs = masterTimes.allDay ? Date.parse(`${original}T00:00:00Z`) : Date.parse(original);
1399
+ const done = expandSeries(rule, start, { fromMs, toMs }, { viewerTz: "UTC" }).filter((o) => before(o.original)).length;
1400
+ headRule = { ...rule, count: Math.max(1, done) };
1401
+ tailRule = { ...rule, count: Math.max(1, rule.count - done) };
1402
+ } else {
1403
+ headRule = { ...rule, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1e3).toISOString().replace(/\.\d{3}Z$/, ".000Z") };
1404
+ }
1405
+ const headExt = { ...masterExt, rrule: formatRRule(headRule) };
1406
+ const headEx = exdate.filter(before);
1407
+ if (headEx.length)
1408
+ headExt.exdate = headEx;
1409
+ else
1410
+ delete headExt.exdate;
1411
+ ops.push(...setValuesOps(sourceId, master, { ext: headExt }));
1412
+ const tailExt = { ...masterExt };
1413
+ const tr = nextRule(tailRule);
1414
+ if (tr)
1415
+ tailExt.rrule = tr;
1416
+ else
1417
+ delete tailExt.rrule;
1418
+ const tailEx = exdate.filter((x) => !before(x)).map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays));
1419
+ if (tailEx.length && tr)
1420
+ tailExt.exdate = tailEx;
1421
+ else
1422
+ delete tailExt.exdate;
1423
+ const times = seriesTimes(masterTimes.allDay ? void 0 : Date.parse(original), masterTimes.allDay ? original : void 0);
1424
+ const fc = fieldChanges({ record_id: id, values: { ext: tailExt } });
1425
+ const values = { title: master.values.title, status: master.values.status, ...fc, ...timesChanges(times) };
1426
+ values.ext = (fc.ext !== void 0 ? fc.ext : tailExt) ?? void 0;
1427
+ ops.push(insertRecordOp(sourceId, [{ record_id: id, values }]));
1428
+ for (const o of overrides) {
1429
+ const oext = extOf(o);
1430
+ const rid = oext.recurrence_id;
1431
+ if (before(String(rid.original)))
1432
+ continue;
1433
+ if (!tr) {
1434
+ ops.push(deleteRecordsOp(sourceId, [o]));
1435
+ continue;
1436
+ }
1437
+ ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { master: id, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }));
1438
+ }
1439
+ return { ops, record_id: id };
1440
+ }
1441
+ function eventDeleteOps(sourceId, occ, scope, ctx) {
1442
+ const master = occ.master;
1443
+ if (!master)
1444
+ return [deleteRecordsOp(sourceId, [occ.row])];
1445
+ const original = occ.original;
1446
+ const masterExt = extOf(master);
1447
+ const masterTimes = rowTimes(master);
1448
+ const overrides = overridesOf(ctx.rows, master.record_id);
1449
+ const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs).toISOString();
1450
+ if (scope === "all" || scope === "following" && isFirst)
1451
+ return [deleteRecordsOp(sourceId, [master, ...overrides])];
1452
+ const ops = [];
1453
+ if (scope === "one") {
1454
+ const exdate = originals(masterExt.exdate);
1455
+ if (!exdate.includes(original))
1456
+ ops.push(...setValuesOps(sourceId, master, { ext: { ...masterExt, exdate: [...exdate, original].sort() } }));
1457
+ const own = overrides.filter((o) => canonicalOriginal(String(extOf(o).recurrence_id.original)) === original);
1458
+ if (own.length)
1459
+ ops.push(deleteRecordsOp(sourceId, own));
1460
+ return ops;
1461
+ }
1462
+ const rule = typeof masterExt.rrule === "string" ? parseRRule(masterExt.rrule) : null;
1463
+ if (!rule)
1464
+ return [deleteRecordsOp(sourceId, [occ.row])];
1465
+ const before = (x) => masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original);
1466
+ const head = { ...rule, count: void 0, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1e3).toISOString() };
1467
+ const ext = { ...masterExt, rrule: formatRRule(head) };
1468
+ if (Array.isArray(masterExt.exdate)) {
1469
+ const keep = originals(masterExt.exdate).filter(before);
1470
+ if (keep.length)
1471
+ ext.exdate = keep;
1472
+ else
1473
+ delete ext.exdate;
1474
+ }
1475
+ ops.push(...setValuesOps(sourceId, master, { ext }));
1476
+ const gone = overrides.filter((o) => !before(String(extOf(o).recurrence_id.original)));
1477
+ if (gone.length)
1478
+ ops.push(deleteRecordsOp(sourceId, gone));
1479
+ return ops;
1480
+ }
1481
+ const eventSkipOps = (sourceId, occ, ctx) => eventDeleteOps(sourceId, occ, "one", ctx);
1482
+ function eventPostponeOps(sourceId, occ, minutes, ctx) {
1483
+ const times = occ.allDay ? { allDay: true, startDate: addDays(occ.startDate, Math.max(1, Math.round(minutes / 1440))), endDate: addDays(occ.endDate, Math.max(1, Math.round(minutes / 1440))) } : { allDay: false, start: new Date(occ.startMs + minutes * 6e4).toISOString(), end: new Date(occ.endMs + minutes * 6e4).toISOString() };
1484
+ return eventEditOps(sourceId, occ, { times }, "one", ctx);
1485
+ }
1486
+ const ROWS_PAGE = 1e3;
1487
+ class ScheduleClient {
1488
+ constructor(aiws, opts = {}) {
1489
+ this.aiws = aiws;
1490
+ this.handle = null;
1491
+ this.locale = opts.locale ?? "zh";
1492
+ }
1493
+ /** The schedule Workspace with its two tables (created when missing; concurrent first uses converge). */
1494
+ async ensure() {
1495
+ var _a, _b, _c;
1496
+ if (this.handle)
1497
+ return this.handle;
1498
+ const ws = await this.aiws.call("ws.ensure", { name: SCHEDULE_WORKSPACE_NAME, title: scheduleLabel(this.locale, "workspace") });
1499
+ const handle = { workspace_id: ws.workspace_id, epoch: ws.epoch, created: ws.created, todo: SCHEDULE_TODO_ID, calendar: SCHEDULE_CALENDAR_ID };
1500
+ const have = /* @__PURE__ */ new Set();
1501
+ for (const id of [SCHEDULE_TODO_ID, SCHEDULE_CALENDAR_ID, SCHEDULE_SURFACE_ID]) {
1502
+ try {
1503
+ const read = await this.aiws.call("doc.read", { workspace_id: ws.workspace_id, entity_id: id });
1504
+ if (!read.deleted)
1505
+ have.add(id);
1506
+ } catch (error) {
1507
+ const code = error == null ? void 0 : error.code;
1508
+ if (code !== "NOT_FOUND" && code !== "TARGET_DELETED")
1509
+ throw error;
1510
+ }
1511
+ }
1512
+ const ops = [];
1513
+ if (!have.has(SCHEDULE_TODO_ID))
1514
+ ops.push(standardTableOp("todo", { entity_id: SCHEDULE_TODO_ID, parent_id: "data", order_key: "u", locale: this.locale }));
1515
+ if (!have.has(SCHEDULE_CALENDAR_ID))
1516
+ ops.push(standardTableOp("calendar", { entity_id: SCHEDULE_CALENDAR_ID, parent_id: "data", order_key: "v", locale: this.locale }));
1517
+ if (!have.has(SCHEDULE_SURFACE_ID))
1518
+ ops.push(...scheduleBoardOps(this.locale));
1519
+ if (ops.length) {
1520
+ const result = await this.commitTo(handle, ops, "create the schedule", "system");
1521
+ const idConflict = (result.sub_code ?? ((_b = (_a = result.errors) == null ? void 0 : _a[0]) == null ? void 0 : _b.sub_code) ?? ((_c = result.error) == null ? void 0 : _c.sub_code)) === "ID_CONFLICT";
1522
+ if (result.status !== "accepted" && !(result.status === "rejected" && idConflict))
1523
+ throw failureOf(result);
1524
+ }
1525
+ this.handle = handle;
1526
+ return handle;
1527
+ }
1528
+ async commitTo(handle, operations, message, origin = "agent") {
1529
+ var _a;
1530
+ const key = `sched-${newRecordId("k")}`;
1531
+ const request = (epoch) => ({ protocol_version: AIWS_PROTOCOL_VERSION, workspace_id: handle.workspace_id, epoch, idempotency_key: key, origin, message, operations });
1532
+ let result = await this.aiws.call("doc.commit", request(handle.epoch));
1533
+ if (result.status === "rejected" && (result.code ?? ((_a = result.error) == null ? void 0 : _a.code)) === "EPOCH_MISMATCH") {
1534
+ const info = await this.aiws.call("ws.get_info", { workspace_id: handle.workspace_id });
1535
+ handle.epoch = info.epoch;
1536
+ result = await this.aiws.call("doc.commit", request(handle.epoch));
1537
+ }
1538
+ return result;
1539
+ }
1540
+ /** Commit operations into the schedule; a refusal or conflict throws with the service's reason. */
1541
+ async commit(operations, message) {
1542
+ const handle = await this.ensure();
1543
+ const result = await this.commitTo(handle, operations, message);
1544
+ if (result.status !== "accepted")
1545
+ throw failureOf(result);
1546
+ return result;
1547
+ }
1548
+ /** Every live record of a table, as `doc.read` answers one (the SQL `_record` column), by record id. */
1549
+ async rows(sourceId) {
1550
+ const handle = await this.ensure();
1551
+ const rows = [];
1552
+ for (let i = 0; i < 100; i++) {
1553
+ const page = await this.aiws.call("doc.query", {
1554
+ workspace_id: handle.workspace_id,
1555
+ sql: 'SELECT "_record" FROM t ORDER BY "_id" LIMIT ? OFFSET ?',
1556
+ params: [ROWS_PAGE, i * ROWS_PAGE],
1557
+ tables: { t: sourceId },
1558
+ max_rows: ROWS_PAGE
1559
+ });
1560
+ for (const [record] of page.rows)
1561
+ rows.push(typeof record === "string" ? JSON.parse(record) : record);
1562
+ if (page.rows.length < ROWS_PAGE)
1563
+ break;
1564
+ }
1565
+ return rows;
1566
+ }
1567
+ async row(sourceId, recordId) {
1568
+ const handle = await this.ensure();
1569
+ const r = await this.aiws.call("doc.read", { workspace_id: handle.workspace_id, entity_id: sourceId, selector: { kind: "table_record", record_id: recordId } });
1570
+ const row = r.content;
1571
+ if (!(row == null ? void 0 : row.record_id))
1572
+ throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `record ${recordId} not found` });
1573
+ return row;
1574
+ }
1575
+ // ---- to-do
1576
+ async todos(opts = {}) {
1577
+ const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
1578
+ return opts.includeDone ? items : items.filter((i) => !i.done);
1579
+ }
1580
+ async addTodo(input, place = {}) {
1581
+ var _a, _b, _c, _d;
1582
+ const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
1583
+ const at = (id) => items.find((i) => i.record_id === id);
1584
+ let pos = { items };
1585
+ if (place.after) {
1586
+ const i = items.findIndex((x) => x.record_id === place.after);
1587
+ pos = { after: ((_a = at(place.after)) == null ? void 0 : _a.order) ?? null, before: ((_b = items[i + 1]) == null ? void 0 : _b.order) ?? null };
1588
+ } else if (place.before) {
1589
+ const i = items.findIndex((x) => x.record_id === place.before);
1590
+ pos = { after: ((_c = items[i - 1]) == null ? void 0 : _c.order) ?? null, before: ((_d = at(place.before)) == null ? void 0 : _d.order) ?? null };
1591
+ }
1592
+ const { record_id, ops } = todoAddOps(SCHEDULE_TODO_ID, input, pos);
1593
+ await this.commit(ops, `add to-do: ${input.title}`);
1594
+ return todoItem(await this.row(SCHEDULE_TODO_ID, record_id));
1595
+ }
1596
+ async completeTodo(recordId, done = true) {
1597
+ const row = await this.row(SCHEDULE_TODO_ID, recordId);
1598
+ const ops = todoCompleteOps(SCHEDULE_TODO_ID, row, done);
1599
+ if (ops.length)
1600
+ await this.commit(ops, `${done ? "complete" : "reopen"} to-do ${recordId}`);
1601
+ }
1602
+ async updateTodo(recordId, changes) {
1603
+ const row = await this.row(SCHEDULE_TODO_ID, recordId);
1604
+ const ops = todoUpdateOps(SCHEDULE_TODO_ID, row, changes);
1605
+ if (ops.length)
1606
+ await this.commit(ops, `update to-do ${recordId}`);
1607
+ }
1608
+ /** Move a to-do before / after another one, and / or into another status. */
1609
+ async moveTodo(recordId, to) {
1610
+ const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
1611
+ const row = items.find((i) => i.record_id === recordId);
1612
+ if (!row)
1613
+ throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `to-do ${recordId} not found` });
1614
+ const others = items.filter((i) => i.record_id !== recordId);
1615
+ let order;
1616
+ if (to.before || to.after) {
1617
+ const anchor = others.findIndex((i) => i.record_id === (to.before ?? to.after));
1618
+ if (anchor < 0)
1619
+ throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `to-do ${to.before ?? to.after} not found` });
1620
+ order = orderAt(others, to.before ? anchor : anchor + 1);
1621
+ }
1622
+ const ops = todoMoveOps(SCHEDULE_TODO_ID, row, { status: to.status, order });
1623
+ if (ops.length)
1624
+ await this.commit(ops, `move to-do ${recordId}`);
1625
+ }
1626
+ async removeTodos(recordIds) {
1627
+ const rows = await Promise.all(recordIds.map((id) => this.row(SCHEDULE_TODO_ID, id)));
1628
+ await this.commit([deleteRecordsOp(SCHEDULE_TODO_ID, rows)], `delete to-do ${recordIds.join(", ")}`);
1629
+ }
1630
+ // ---- calendar
1631
+ async events(window, opts = {}) {
1632
+ return calendarOccurrences(await this.rows(SCHEDULE_CALENDAR_ID), window, opts);
1633
+ }
1634
+ async addEvent(input) {
1635
+ var _a;
1636
+ if (((_a = input.ext) == null ? void 0 : _a.rrule) !== void 0 && typeof input.ext.rrule === "string")
1637
+ input = { ...input, ext: { ...input.ext, rrule: formatRRule(parseRRule(input.ext.rrule)) } };
1638
+ const { record_id, ops } = eventAddOps(SCHEDULE_CALENDAR_ID, input);
1639
+ await this.commit(ops, `add event: ${input.title}`);
1640
+ return record_id;
1641
+ }
1642
+ /** The occurrence an id names (`record_id` or `<master>@<original>`), from all rows. */
1643
+ async occurrence(id) {
1644
+ const rows = await this.rows(SCHEDULE_CALENDAR_ID);
1645
+ return { occ: findOccurrence(rows, id), rows };
1646
+ }
1647
+ async editEvent(id, change, scope = "one") {
1648
+ const { occ, rows } = await this.occurrence(id);
1649
+ const { ops, record_id } = eventEditOps(SCHEDULE_CALENDAR_ID, occ, change, scope, { rows });
1650
+ if (ops.length)
1651
+ await this.commit(ops, `edit event ${id} (${scope})`);
1652
+ return record_id;
1653
+ }
1654
+ async deleteEvent(id, scope = "one") {
1655
+ const { occ, rows } = await this.occurrence(id);
1656
+ await this.commit(eventDeleteOps(SCHEDULE_CALENDAR_ID, occ, scope, { rows }), `delete event ${id} (${scope})`);
1657
+ }
1658
+ }
1659
+ function failureOf(result) {
1660
+ var _a, _b, _c, _d;
1661
+ const first = (_a = result.errors) == null ? void 0 : _a[0];
1662
+ if (result.status === "conflict") {
1663
+ const c = (_b = result.conflicts) == null ? void 0 : _b[0];
1664
+ return new AiwsFailure({ code: result.code ?? "REVISION_CONFLICT", retryable: true, detail: `changed meanwhile, read it again${c ? `: ${JSON.stringify(c.selector ?? c)}` : ""}` });
1665
+ }
1666
+ return new AiwsFailure({ code: result.code ?? ((_c = result.error) == null ? void 0 : _c.code) ?? "REJECTED", sub_code: result.sub_code ?? (first == null ? void 0 : first.sub_code), retryable: false, detail: (first == null ? void 0 : first.detail) ?? result.detail ?? ((_d = result.error) == null ? void 0 : _d.detail) ?? "refused" });
1667
+ }
1668
+ function findOccurrence(rows, id) {
1669
+ const at = id.indexOf("@");
1670
+ const recordId = at < 0 ? id : id.slice(0, at);
1671
+ const original = at < 0 ? null : canonicalOriginal(id.slice(at + 1));
1672
+ const row = rows.find((r) => r.record_id === recordId);
1673
+ if (!row)
1674
+ throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `event ${recordId} not found` });
1675
+ if (original === null) {
1676
+ const times2 = rowTimes(row);
1677
+ if (!times2)
1678
+ throw new AiwsFailure({ code: "INVALID_OPERATION", retryable: false, detail: `event ${recordId} has no time` });
1679
+ const ext = extOf(row);
1680
+ const rid = ext.recurrence_id;
1681
+ const master = rid && typeof rid.master === "string" ? rows.find((r) => r.record_id === rid.master) : void 0;
1682
+ return occurrenceOf(row, times2, master ? { master, original: String(rid.original), recurring: true, override: true } : { recurring: typeof ext.rrule === "string", master: typeof ext.rrule === "string" ? row : void 0, original: typeof ext.rrule === "string" ? times2.allDay ? times2.startDate : new Date(times2.startMs).toISOString() : void 0 });
1683
+ }
1684
+ const override = rows.find((r) => {
1685
+ const rid = extOf(r).recurrence_id;
1686
+ return rid && rid.master === recordId && typeof rid.original === "string" && canonicalOriginal(rid.original) === canonicalOriginal(original);
1687
+ });
1688
+ const times = rowTimes(row);
1689
+ if (!times)
1690
+ throw new AiwsFailure({ code: "INVALID_OPERATION", retryable: false, detail: `event ${recordId} has no time` });
1691
+ if (override)
1692
+ return occurrenceOf(override, rowTimes(override), { id, master: row, original, recurring: true, override: true });
1693
+ const allDay = times.allDay;
1694
+ const durationMs = allDay ? 0 : times.endMs - times.startMs;
1695
+ const durationDays = allDay ? daysBetween(times.startDate, times.endDate) : 0;
1696
+ const occTimes = allDay ? { allDay: true, startDate: original, endDate: addDays(original, durationDays) } : { allDay: false, startMs: Date.parse(original), endMs: Date.parse(original) + durationMs };
1697
+ return occurrenceOf(row, occTimes, { id, master: row, original, recurring: true });
1698
+ }
1699
+ function scheduleBoardOps(locale = "zh") {
1700
+ const folder = `${SCHEDULE_SURFACE_ID}-content`;
1701
+ const title = scheduleLabel(locale, "board");
1702
+ return [
1703
+ { op: "entity.create", entity_id: folder, type_id: "buckyos.container", parent_id: "canvas-content", order_key: "u", name: title, payload: { kind: "folder", title, system: "surface_content", surface_id: SCHEDULE_SURFACE_ID } },
1704
+ { op: "entity.create", entity_id: SCHEDULE_SURFACE_ID, type_id: "buckyos.container", parent_id: "surfaces", order_key: "a", name: title, payload: { kind: "surface", layout: { mode: "free" }, title, content_folder_id: folder } },
1705
+ {
1706
+ op: "entity.create",
1707
+ entity_id: `${SCHEDULE_SURFACE_ID}-calendar`,
1708
+ type_id: "buckyos.container",
1709
+ parent_id: SCHEDULE_SURFACE_ID,
1710
+ order_key: "a",
1711
+ placement: { x: 40, y: 40, w: 880, h: 640 },
1712
+ payload: { kind: "calendar", layout: { mode: "data" }, title: scheduleLabel(locale, "calendar_table"), bindings: { events: [{ entity_id: SCHEDULE_CALENDAR_ID }], todo: [{ entity_id: SCHEDULE_TODO_ID }] }, config: { view: "week" } }
1713
+ },
1714
+ {
1715
+ op: "entity.create",
1716
+ entity_id: `${SCHEDULE_SURFACE_ID}-todo`,
1717
+ type_id: "buckyos.container",
1718
+ parent_id: SCHEDULE_SURFACE_ID,
1719
+ order_key: "b",
1720
+ placement: { x: 960, y: 40, w: 420, h: 640 },
1721
+ payload: { kind: "todo", layout: { mode: "data" }, title: scheduleLabel(locale, "todo_table"), bindings: { items: { entity_id: SCHEDULE_TODO_ID } }, config: { mode: "list" } }
1722
+ }
1723
+ ];
1724
+ }
1725
+ class BindFailure extends Error {
1726
+ constructor(message, code, node, binding) {
1727
+ super(message);
1728
+ this.code = code;
1729
+ this.node = node;
1730
+ this.binding = binding;
1731
+ }
1732
+ }
1733
+ const STANDARD_SCHEMAS = [TODO_SCHEMA_ID, CALENDAR_SCHEMA_ID];
1734
+ const asList = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
1735
+ const label = (name, decl) => decl.title ?? name;
1736
+ function bindingAccepts(decl, data) {
1737
+ if (decl.accepts && decl.accepts.length > 0 && !decl.accepts.includes(data.type_id))
1738
+ return false;
1739
+ if (decl.schema_id && data.schema_id !== decl.schema_id)
1740
+ return false;
1741
+ return true;
1742
+ }
1743
+ const queryOf = (decl) => {
1744
+ var _a;
1745
+ return { ...((_a = decl.accepts) == null ? void 0 : _a.length) ? { accepts: decl.accepts } : {}, ...decl.schema_id ? { schema_id: decl.schema_id } : {} };
1746
+ };
1747
+ function noUiDialogs() {
1748
+ const fail = (title) => {
1749
+ throw new BindFailure(`needs a choice: ${title}`, "NEEDS_UI");
1750
+ };
1751
+ return { pickOne: async (o) => fail(o.title), pickMany: async (o) => fail(o.title), confirm: async (o) => fail(o.title) };
1752
+ }
1753
+ let refSeq = 0;
1754
+ const newRef = () => `ref:${++refSeq}`;
1755
+ const MAX_ITEMS = 32;
1756
+ const MAX_CREATE = 16;
1757
+ function checkBindResult(value, decls, node) {
1758
+ const bad = (message) => {
1759
+ throw new BindFailure(`on_bind result: ${message}`, "INVALID", node);
1760
+ };
1761
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1762
+ if (!isObject(value) || !isObject(value.bindings))
1763
+ return bad("{ bindings, create? } (or null to cancel)");
1764
+ const created = value.create === void 0 ? [] : value.create;
1765
+ if (!Array.isArray(created) || created.length > MAX_CREATE)
1766
+ return bad(`create: a list of at most ${MAX_CREATE}`);
1767
+ const refs = /* @__PURE__ */ new Map();
1768
+ const create = created.map((c, i) => {
1769
+ const at = `create[${i}]`;
1770
+ if (!isObject(c) || typeof c.ref !== "string" || !c.ref)
1771
+ return bad(`${at}: { ref, kind, … }`);
1772
+ if (refs.has(c.ref))
1773
+ return bad(`${at}: ref ${c.ref} twice`);
1774
+ const ref = newRef();
1775
+ refs.set(c.ref, ref);
1776
+ const name = typeof c.name === "string" && c.name.trim() && c.name.length <= 128 ? c.name.trim() : null;
1777
+ if (c.kind === "standard") {
1778
+ if (typeof c.schema_id !== "string")
1779
+ return bad(`${at}: a standard table names its schema_id`);
1780
+ return { ref, kind: "standard", schema_id: c.schema_id, name: name ?? c.schema_id };
1781
+ }
1782
+ if (!name)
1783
+ return bad(`${at}: a name (at most 128 characters)`);
1784
+ if (c.kind === "table") {
1785
+ if (!Array.isArray(c.fields) || c.fields.length === 0)
1786
+ return bad(`${at}: a table lists its fields`);
1787
+ if (c.title_field_id !== void 0 && typeof c.title_field_id !== "string")
1788
+ return bad(`${at}: title_field_id is a field id`);
1789
+ return { ref, kind: "table", name, fields: c.fields, ...c.title_field_id ? { title_field_id: c.title_field_id } : {} };
1790
+ }
1791
+ if (c.kind === "dir")
1792
+ return { ref, kind: "dir", name };
1793
+ return bad(`${at}: kind standard, table or dir`);
1794
+ });
1795
+ const bindings = {};
1796
+ const used = /* @__PURE__ */ new Set();
1797
+ for (const [name, v] of Object.entries(value.bindings)) {
1798
+ const decl = decls[name];
1799
+ if (!decl)
1800
+ return bad(`${name} is not a declared binding`);
1801
+ if (v === null || v === void 0)
1802
+ continue;
1803
+ const list2 = typeof v === "string" ? [v] : Array.isArray(v) && v.every((x) => typeof x === "string" && x) ? v : bad(`${name}: an id, or a list of ids`);
1804
+ if (!decl.many && (Array.isArray(v) || list2.length !== 1))
1805
+ return bad(`${name} takes one`);
1806
+ if (list2.length > MAX_ITEMS || new Set(list2).size !== list2.length)
1807
+ return bad(`${name}: at most ${MAX_ITEMS}, each once`);
1808
+ const ids = list2.map((id) => {
1809
+ if (refs.has(id))
1810
+ used.add(id);
1811
+ return refs.get(id) ?? id;
1812
+ });
1813
+ if (decl.many) {
1814
+ if (ids.length > 0)
1815
+ bindings[name] = ids;
1816
+ } else
1817
+ bindings[name] = ids[0];
1818
+ }
1819
+ const unused = [...refs.keys()].filter((r) => !used.has(r));
1820
+ if (unused.length > 0)
1821
+ return bad(`created but not bound: ${unused.join(", ")}`);
1822
+ return { bindings, create };
1823
+ }
1824
+ const defaultOnBind = async (ctx) => {
1825
+ const bindings = {};
1826
+ const create = [];
1827
+ const parentData = ctx.parent ? Object.values(ctx.parent.bound).flatMap(asList) : [];
1828
+ const known = new Map(ctx.find({}).map((d) => [d.entity_id, d]));
1829
+ for (const [name, decl] of Object.entries(ctx.decls)) {
1830
+ const failNamed = (message, code) => new BindFailure(message, code, ctx.node, name);
1831
+ if (ctx.reason === "rebind") {
1832
+ if (ctx.given[name] !== void 0 && ctx.no_ui) {
1833
+ bindings[name] = ctx.given[name];
1834
+ continue;
1835
+ }
1836
+ const current = asList(ctx.given[name]);
1837
+ if (decl.many) {
1838
+ const picked = await withName(name, () => ctx.dialogs.pickMany({ title: label(name, decl), query: queryOf(decl), preselect: current, allow_new: ctx.canCreate(decl) }));
1839
+ if (picked === null)
1840
+ return null;
1841
+ bindings[name] = picked.map((p) => {
1842
+ if (typeof p === "string")
1843
+ return p;
1844
+ const ref = newRef();
1845
+ create.push(standardSpec(ref, decl, ctx.title));
1846
+ return ref;
1847
+ });
1848
+ } else {
1849
+ const picked = await withName(name, () => ctx.dialogs.pickOne({ title: label(name, decl), query: queryOf(decl), allow_new: ctx.canCreate(decl), current: current[0] ?? null }));
1850
+ if (picked === null)
1851
+ return null;
1852
+ if (typeof picked === "string")
1853
+ bindings[name] = picked;
1854
+ else {
1855
+ const ref = newRef();
1856
+ create.push(standardSpec(ref, decl, ctx.title));
1857
+ bindings[name] = ref;
1858
+ }
1859
+ }
1860
+ continue;
1861
+ }
1862
+ if (ctx.given[name] !== void 0) {
1863
+ bindings[name] = decl.many ? asList(ctx.given[name]) : asList(ctx.given[name])[0];
1864
+ continue;
1865
+ }
1866
+ const fromParent = parentData.filter((id) => {
1867
+ const d = known.get(id);
1868
+ return d !== void 0 && bindingAccepts(decl, d);
1869
+ });
1870
+ if (decl.many && fromParent.length > 0) {
1871
+ bindings[name] = fromParent;
1872
+ continue;
1873
+ }
1874
+ if (!decl.many && fromParent.length === 1) {
1875
+ bindings[name] = fromParent[0];
1876
+ continue;
1877
+ }
1878
+ const found = ctx.find(queryOf(decl)).filter((d) => bindingAccepts(decl, d));
1879
+ if (found.length === 0) {
1880
+ if (!decl.required)
1881
+ continue;
1882
+ if (!ctx.canCreate(decl))
1883
+ throw failNamed(`no ${label(name, decl)} in this Workspace yet`, "NO_DATA");
1884
+ const ref = newRef();
1885
+ create.push(standardSpec(ref, decl, ctx.title));
1886
+ bindings[name] = decl.many ? [ref] : ref;
1887
+ } else if (decl.many) {
1888
+ bindings[name] = found.map((d) => d.entity_id);
1889
+ } else if (found.length === 1) {
1890
+ bindings[name] = found[0].entity_id;
1891
+ } else if (decl.required) {
1892
+ const picked = await withName(name, () => ctx.dialogs.pickOne({ title: label(name, decl), query: queryOf(decl), allow_new: ctx.canCreate(decl) }));
1893
+ if (picked === null)
1894
+ return null;
1895
+ if (typeof picked === "string")
1896
+ bindings[name] = picked;
1897
+ else {
1898
+ const ref = newRef();
1899
+ create.push(standardSpec(ref, decl, ctx.title));
1900
+ bindings[name] = ref;
1901
+ }
1902
+ }
1903
+ }
1904
+ return { bindings, create };
1905
+ };
1906
+ function standardSpec(ref, decl, title) {
1907
+ return { ref, kind: "standard", schema_id: decl.schema_id, name: title || decl.title || "Table" };
1908
+ }
1909
+ async function withName(binding, run) {
1910
+ try {
1911
+ return await run();
1912
+ } catch (error) {
1913
+ if (error instanceof BindFailure && error.code === "NEEDS_UI")
1914
+ throw new BindFailure(`binding ${binding} needs a choice: give it`, "NEEDS_UI", void 0, binding);
1915
+ throw error;
1916
+ }
1917
+ }
1918
+ function stepsOnBind(steps) {
1919
+ return async (ctx) => {
1920
+ var _a;
1921
+ const bindings = {};
1922
+ const create = [];
1923
+ for (const step of steps) {
1924
+ const decl = ctx.decls[step.binding] ?? {};
1925
+ if (ctx.given[step.binding] !== void 0 && ctx.reason === "insert") {
1926
+ bindings[step.binding] = ctx.given[step.binding];
1927
+ continue;
1928
+ }
1929
+ if ("from_parent" in step) {
1930
+ const v = (_a = ctx.parent) == null ? void 0 : _a.bound[step.from_parent];
1931
+ if (v !== void 0)
1932
+ bindings[step.binding] = decl.many ? asList(v) : asList(v)[0];
1933
+ } else if ("pick" in step) {
1934
+ const query = queryOf(decl);
1935
+ const title = step.title ?? label(step.binding, decl);
1936
+ const allowNew = step.allow_new !== false && ctx.canCreate(decl);
1937
+ const current = asList(ctx.given[step.binding]);
1938
+ if (step.pick === "all")
1939
+ bindings[step.binding] = ctx.find(query).filter((d) => bindingAccepts(decl, d)).map((d) => d.entity_id);
1940
+ else if (step.pick === "many") {
1941
+ const picked = await withName(step.binding, () => ctx.dialogs.pickMany({ title, query, preselect: current.length ? current : "none", allow_new: allowNew }));
1942
+ if (picked === null)
1943
+ return null;
1944
+ bindings[step.binding] = picked.map((p) => {
1945
+ if (typeof p === "string")
1946
+ return p;
1947
+ const ref = newRef();
1948
+ create.push(standardSpec(ref, decl, ctx.title));
1949
+ return ref;
1950
+ });
1951
+ } else {
1952
+ const picked = await withName(step.binding, () => ctx.dialogs.pickOne({ title, query, allow_new: allowNew, current: current[0] ?? null }));
1953
+ if (picked === null)
1954
+ return null;
1955
+ if (typeof picked === "string")
1956
+ bindings[step.binding] = decl.many ? [picked] : picked;
1957
+ else {
1958
+ const ref = newRef();
1959
+ create.push(standardSpec(ref, decl, ctx.title));
1960
+ bindings[step.binding] = decl.many ? [ref] : ref;
1961
+ }
1962
+ }
1963
+ } else {
1964
+ const missing = ctx.find(queryOf(decl)).filter((d) => bindingAccepts(decl, d)).length === 0;
1965
+ if ((step.when ?? "missing") === "missing" && !missing)
1966
+ continue;
1967
+ const ref = newRef();
1968
+ const c = step.create;
1969
+ create.push("standard" in c ? { ref, kind: "standard", schema_id: c.standard, name: label(step.binding, decl) } : "table" in c ? { ref, kind: "table", name: c.table.name, title_field_id: c.table.title_field_id, fields: c.table.fields } : { ref, kind: "dir", name: c.dir.name });
1970
+ bindings[step.binding] = decl.many ? [ref] : ref;
1971
+ }
1972
+ }
1973
+ const rest = Object.fromEntries(Object.entries(ctx.decls).filter(([name]) => bindings[name] === void 0));
1974
+ if (Object.keys(rest).length > 0) {
1975
+ const more = await defaultOnBind({ ...ctx, decls: rest });
1976
+ if (more === null)
1977
+ return null;
1978
+ Object.assign(bindings, more.bindings);
1979
+ create.push(...more.create);
1980
+ }
1981
+ return { bindings, create };
1982
+ };
1983
+ }
1984
+ const missingOf = (decls, bound) => Object.entries(decls).filter(([name, d]) => d.required && asList(bound[name]).length === 0).map(([name, d]) => label(name, d));
1985
+ const defaultOnInit = async (ctx) => {
1986
+ const own = missingOf(ctx.decls, ctx.bound);
1987
+ if (own.length > 0)
1988
+ return `${ctx.title}: ${own.join(", ")} not bound`;
1989
+ const waiting = ctx.children.filter((c) => !c.ready);
1990
+ return waiting.length > 0 ? `not ready: ${waiting.map((c) => `${c.title} (${c.missing.join(", ")})`).join("; ")}` : true;
1991
+ };
1992
+ async function resolveBindings(root, host) {
1993
+ const schemas = host.standardSchemas ?? STANDARD_SCHEMAS;
1994
+ const dialogs = host.no_ui ? noUiDialogs() : host.dialogs;
1995
+ const results = /* @__PURE__ */ new Map();
1996
+ const then = [];
1997
+ const visit = async (node, parent) => {
1998
+ const ctx = {
1999
+ reason: host.reason,
2000
+ no_ui: host.no_ui,
2001
+ node: node.id,
2002
+ title: node.title,
2003
+ decls: node.decls,
2004
+ given: node.given ?? {},
2005
+ parent,
2006
+ find: host.find,
2007
+ canCreate: (d) => Boolean(d.schema_id && schemas.includes(d.schema_id)),
2008
+ dialogs
2009
+ };
2010
+ const run = typeof node.onBind === "function" ? node.onBind : Array.isArray(node.onBind) ? stepsOnBind(node.onBind) : defaultOnBind;
2011
+ let result;
2012
+ try {
2013
+ result = await run(ctx);
2014
+ } catch (error) {
2015
+ if (error instanceof BindFailure)
2016
+ throw new BindFailure(error.message, error.code, error.node ?? node.id, error.binding);
2017
+ throw error;
2018
+ }
2019
+ if (result === null)
2020
+ throw new BindFailure(`${node.title}: cancelled`, "CANCELLED", node.id);
2021
+ result = checkBindResult(result, node.decls, node.id);
2022
+ results.set(node.id, result);
2023
+ const children = [];
2024
+ for (const child of node.children)
2025
+ children.push(await visit(child, { decls: node.decls, bound: result.bindings }));
2026
+ const init = typeof node.onInit === "function" ? node.onInit : defaultOnInit;
2027
+ const steps = Array.isArray(node.onInit) ? node.onInit : [];
2028
+ const verdict = await init({ reason: host.reason, no_ui: host.no_ui, node: node.id, title: node.title, decls: node.decls, bound: result.bindings, children, dialogs });
2029
+ if (verdict !== true)
2030
+ throw new BindFailure(verdict, "NOT_READY", node.id);
2031
+ for (const step of steps)
2032
+ if ("then" in step)
2033
+ then.push({ node: node.id, action: step.then.action });
2034
+ return { node: node.id, title: node.title, ready: true, missing: [] };
2035
+ };
2036
+ try {
2037
+ await visit(root, host.parent ?? null);
2038
+ return { ok: true, results, then };
2039
+ } catch (error) {
2040
+ if (error instanceof BindFailure)
2041
+ return { ok: false, error };
2042
+ throw error;
2043
+ }
2044
+ }
2045
+ function createOps(results, opts) {
2046
+ const ops = [];
2047
+ const ids = {};
2048
+ for (const result of results.values()) {
2049
+ for (const spec of result.create) {
2050
+ const entity_id = opts.newId();
2051
+ ids[spec.ref] = entity_id;
2052
+ const base = { entity_id, parent_id: opts.folderId, order_key: opts.orderKey(), name: opts.freeName(spec.name) };
2053
+ if (spec.kind === "standard") {
2054
+ const kind = spec.schema_id === TODO_SCHEMA_ID ? "todo" : spec.schema_id === CALENDAR_SCHEMA_ID ? "calendar" : null;
2055
+ if (!kind)
2056
+ throw new BindFailure(`cannot create a table of ${spec.schema_id}`, "INVALID");
2057
+ ops.push(standardTableOp(kind, { ...base, locale: opts.locale }));
2058
+ } else if (spec.kind === "table") {
2059
+ ops.push({ op: "entity.create", type_id: "buckyos.table-source", ...base, payload: { fields: spec.fields, ...spec.title_field_id ? { title_field_id: spec.title_field_id } : {} } });
2060
+ } else {
2061
+ ops.push({ op: "entity.create", type_id: "buckyos.dir", ...base, payload: { members: {} } });
2062
+ }
2063
+ }
2064
+ }
2065
+ return { ops, ids };
2066
+ }
2067
+ function bindingsPayload(bound, decls, ids) {
2068
+ var _a;
2069
+ const out = {};
2070
+ for (const [name, value] of Object.entries(bound)) {
2071
+ const list2 = asList(value).map((id) => ({ entity_id: ids[id] ?? id }));
2072
+ if (((_a = decls[name]) == null ? void 0 : _a.many) || Array.isArray(value)) {
2073
+ if (list2.length > 0)
2074
+ out[name] = list2;
2075
+ } else if (list2[0])
2076
+ out[name] = list2[0];
2077
+ }
2078
+ return out;
2079
+ }
2080
+ function boundIds(value) {
2081
+ return value === null || value === void 0 ? [] : Array.isArray(value) ? value : [value];
2082
+ }
2083
+ function checkBindSteps(onBind, onInit, decls, actions) {
2084
+ var _a, _b, _c, _d;
2085
+ const out = [];
2086
+ if (onBind !== void 0) {
2087
+ if (!Array.isArray(onBind) || onBind.length > 16)
2088
+ out.push("on_bind: at most 16 steps");
2089
+ else
2090
+ for (const [i, raw] of onBind.entries()) {
2091
+ const s = raw;
2092
+ const where = `on_bind[${i}]`;
2093
+ if (!s || typeof s !== "object" || typeof s.binding !== "string") {
2094
+ out.push(`${where}: names a binding`);
2095
+ continue;
2096
+ }
2097
+ const decl = decls[s.binding];
2098
+ if (!decl) {
2099
+ out.push(`${where}: ${s.binding} is not a declared binding`);
2100
+ continue;
2101
+ }
2102
+ const kinds = ["pick", "from_parent", "create"].filter((k) => k in s);
2103
+ if (kinds.length !== 1) {
2104
+ out.push(`${where}: one of pick, from_parent, create`);
2105
+ continue;
2106
+ }
2107
+ if ("pick" in s && !["one", "many", "all"].includes(String(s.pick)))
2108
+ out.push(`${where}: pick is one, many or all`);
2109
+ if ("pick" in s && s.pick !== "one" && !decl.many)
2110
+ out.push(`${where}: ${s.binding} takes one`);
2111
+ if ("from_parent" in s && typeof s.from_parent !== "string")
2112
+ out.push(`${where}: from_parent names a binding of the parent`);
2113
+ if ("create" in s) {
2114
+ const c = s.create;
2115
+ const which = c && typeof c === "object" ? ["standard", "table", "dir"].filter((k) => k in c) : [];
2116
+ if (which.length !== 1)
2117
+ out.push(`${where}: create one of standard, table, dir`);
2118
+ else if (which[0] === "standard" && !STANDARD_SCHEMAS.includes(String(c.standard)))
2119
+ out.push(`${where}: no standard table ${String(c.standard)}`);
2120
+ else if (which[0] === "table" && (!Array.isArray((_a = c.table) == null ? void 0 : _a.fields) || typeof ((_b = c.table) == null ? void 0 : _b.name) !== "string"))
2121
+ out.push(`${where}: create.table needs name and fields`);
2122
+ else if (which[0] === "dir" && typeof ((_c = c.dir) == null ? void 0 : _c.name) !== "string")
2123
+ out.push(`${where}: create.dir needs name`);
2124
+ if (s.when !== void 0 && s.when !== "missing" && s.when !== "always")
2125
+ out.push(`${where}: when is missing or always`);
2126
+ }
2127
+ }
2128
+ }
2129
+ if (onInit !== void 0) {
2130
+ if (!Array.isArray(onInit) || onInit.length > 16)
2131
+ out.push("on_init_control: at most 16 steps");
2132
+ else
2133
+ for (const [i, raw] of onInit.entries()) {
2134
+ const s = raw;
2135
+ const where = `on_init_control[${i}]`;
2136
+ if ((s == null ? void 0 : s.require) === "children")
2137
+ continue;
2138
+ const action = (_d = s == null ? void 0 : s.then) == null ? void 0 : _d.action;
2139
+ if (typeof action !== "string")
2140
+ out.push(`${where}: { require: "children" } or { then: { action } }`);
2141
+ else if (!actions.includes(action))
2142
+ out.push(`${where}: ${action} is not a declared action`);
2143
+ }
2144
+ }
2145
+ return out;
2146
+ }
2147
+ export {
2148
+ deleteRecordsOp as $,
2149
+ AIWORKSPACE_SERVICE_NAME as A,
2150
+ seriesStartOf as B,
2151
+ originalOf as C,
2152
+ occurrenceId as D,
2153
+ parseOccurrenceId as E,
2154
+ describeRRule as F,
2155
+ recurrencePresets as G,
2156
+ CALENDAR_SCHEMA_ID as H,
2157
+ SCHEDULE_TODO_ID as I,
2158
+ SCHEDULE_CALENDAR_ID as J,
2159
+ SCHEDULE_SURFACE_ID as K,
2160
+ TODO_DONE as L,
2161
+ AIWS_PROTOCOL_VERSION as M,
2162
+ scheduleLabel as N,
2163
+ todoFields as O,
2164
+ calendarFields as P,
2165
+ standardTableOp as Q,
2166
+ RRuleError as R,
2167
+ SCHEDULE_WORKSPACE_NAME as S,
2168
+ TODO_SCHEMA_ID as T,
2169
+ isOrderKey as U,
2170
+ orderKeyBetween as V,
2171
+ WEEKDAYS as W,
2172
+ orderKeysBetween as X,
2173
+ newRecordId as Y,
2174
+ setValuesOps as Z,
2175
+ insertRecordOp as _,
2176
+ AiwsFailure as a,
2177
+ canonicalOriginal as a0,
2178
+ todoItem as a1,
2179
+ sortTodos as a2,
2180
+ todoAddOps as a3,
2181
+ todoCompleteOps as a4,
2182
+ todoMoveOps as a5,
2183
+ todoUpdateOps as a6,
2184
+ orderAt as a7,
2185
+ localDate as a8,
2186
+ viewerTimeZone as a9,
2187
+ calendarOccurrences as aa,
2188
+ eventAddOps as ab,
2189
+ eventEditOps as ac,
2190
+ eventDeleteOps as ad,
2191
+ eventSkipOps as ae,
2192
+ eventPostponeOps as af,
2193
+ ScheduleClient as ag,
2194
+ findOccurrence as ah,
2195
+ scheduleBoardOps as ai,
2196
+ BindFailure as aj,
2197
+ STANDARD_SCHEMAS as ak,
2198
+ bindingAccepts as al,
2199
+ noUiDialogs as am,
2200
+ checkBindResult as an,
2201
+ defaultOnBind as ao,
2202
+ stepsOnBind as ap,
2203
+ defaultOnInit as aq,
2204
+ resolveBindings as ar,
2205
+ createOps as as,
2206
+ bindingsPayload as at,
2207
+ boundIds as au,
2208
+ checkBindSteps as av,
2209
+ aiwsReferenceUrl as b,
2210
+ aiwsTarget as c,
2211
+ AIWS_COMMIT_PART_BYTES as d,
2212
+ AIWS_COMMIT_MAX_BYTES as e,
2213
+ AIWS_COMMIT_MAX_OPERATIONS as f,
2214
+ commitOverLimit as g,
2215
+ commitWithParts as h,
2216
+ AiWorkspaceClient as i,
2217
+ parseRRule as j,
2218
+ formatRRule as k,
2219
+ isDate as l,
2220
+ isLeap as m,
2221
+ daysInMonth as n,
2222
+ dayNumber as o,
2223
+ parseAiwsReferenceUrl as p,
2224
+ dayOf as q,
2225
+ dateOf as r,
2226
+ splitCommitOperations as s,
2227
+ isTimeZone as t,
2228
+ zonedToUtc as u,
2229
+ localDay as v,
2230
+ weekdayOf as w,
2231
+ expandSeries as x,
2232
+ ymdOf as y,
2233
+ zonedParts as z
2234
+ };
2235
+ //# sourceMappingURL=aiws_bind-3b874f77.mjs.map