@composable-os/cli 0.1.0-beta.7 → 0.1.0-beta.9

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 (64) hide show
  1. package/dist/accounts-D6N77JGP.js +44 -0
  2. package/dist/{blocks-HVTAQ5W2.js → blocks-4CA4PP3P.js} +4 -4
  3. package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
  4. package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
  5. package/dist/chunk-56A6RJIU.js +1040 -0
  6. package/dist/chunk-7CQGMVDO.js +63 -0
  7. package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
  8. package/dist/chunk-7U3OZLTK.js +1370 -0
  9. package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
  10. package/dist/chunk-E4WCYTCT.js +347 -0
  11. package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
  12. package/dist/chunk-LPD2VR5M.js +284 -0
  13. package/dist/chunk-NDKVIG23.js +2641 -0
  14. package/dist/chunk-NSSUOI3Z.js +333 -0
  15. package/dist/chunk-OV3OFYPI.js +746 -0
  16. package/dist/{chunk-2P4AZTFL.js → chunk-P6YZMS3F.js} +11 -5
  17. package/dist/{chunk-Y7PQ7NIL.js → chunk-RFJOPI42.js} +138 -14
  18. package/dist/{chunk-VL62IMBN.js → chunk-RXRD34QW.js} +10 -8
  19. package/dist/{chunk-BEKL3CA2.js → chunk-STBMGUTM.js} +7065 -4580
  20. package/dist/chunk-VTQNOQGA.js +150 -0
  21. package/dist/chunk-XSE37HK5.js +426 -0
  22. package/dist/{chunk-MINQ46RU.js → chunk-Z52IX5WL.js} +257 -844
  23. package/dist/chunk-ZSR5H4O7.js +552 -0
  24. package/dist/{cli-XHC6QBQW.js → cli-7A5XHYML.js} +16 -9
  25. package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
  26. package/dist/cli.js +4 -4
  27. package/dist/{client-repo-G55G4OLV.js → client-repo-PC4ISVEZ.js} +4 -4
  28. package/dist/create.js +4 -4
  29. package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
  30. package/dist/invoke-TLYT6CFI.js +33 -0
  31. package/dist/order-IKQBUFCV.js +19 -0
  32. package/dist/{person-AZFEPZOE.js → person-DXEOOH2A.js} +9 -5
  33. package/dist/plan-on-sale-LRCK5MJG.js +24 -0
  34. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  35. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  36. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  37. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  38. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  39. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  40. package/dist/platform/migrations/0533_allowances.sql +262 -0
  41. package/dist/platform/migrations/0560_recurring.sql +75 -0
  42. package/dist/platform/sdk/allowance.ts +508 -0
  43. package/dist/platform/sdk/capacity.ts +89 -0
  44. package/dist/platform/sdk/contract.ts +97 -1
  45. package/dist/platform/sdk/document.ts +161 -14
  46. package/dist/platform/sdk/field-types.ts +5 -0
  47. package/dist/platform/sdk/index.ts +3 -0
  48. package/dist/platform/sdk/manifest.ts +206 -5
  49. package/dist/platform/sdk/media.ts +62 -0
  50. package/dist/platform/sdk/recurring.ts +314 -0
  51. package/dist/platform/sdk/rich-text.ts +52 -4
  52. package/dist/platform/sdk/sellable.ts +120 -0
  53. package/dist/platform/sdk/states.ts +162 -1
  54. package/dist/platform/sdk/unique.ts +81 -0
  55. package/dist/run-BMSZKTN3.js +648 -0
  56. package/dist/run-GMQBAV6H.js +309 -0
  57. package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
  58. package/dist/src-7DXXGZG2.js +38 -0
  59. package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
  60. package/dist/visibility-XSBZTO66.js +33 -0
  61. package/package.json +2 -2
  62. package/dist/chunk-MAXLUQKB.js +0 -1287
  63. package/dist/invoke-5SR5ZWW7.js +0 -26
  64. package/dist/src-SSVOBH6L.js +0 -31
@@ -0,0 +1,1040 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ newId
4
+ } from "./chunk-OV3OFYPI.js";
5
+ import {
6
+ ValidationError,
7
+ liveViewOf,
8
+ sql,
9
+ viewColumnOf,
10
+ visibleObject,
11
+ visibleSource
12
+ } from "./chunk-7O4F3NU4.js";
13
+ import {
14
+ getObject
15
+ } from "./chunk-3MIEYXRY.js";
16
+ import {
17
+ getField
18
+ } from "./chunk-ZSR5H4O7.js";
19
+ import {
20
+ automationManifestSchema,
21
+ documentRefs,
22
+ external_exports
23
+ } from "./chunk-2MLAPQU7.js";
24
+
25
+ // ../core/src/records/common.ts
26
+ var TRASH_RETENTION_DAYS = 30;
27
+ var DAY_MS = 864e5;
28
+ function restorableUntil(deletedAt) {
29
+ return new Date(Date.parse(deletedAt) + TRASH_RETENTION_DAYS * DAY_MS).toISOString();
30
+ }
31
+ function purgeCutoff(now) {
32
+ return new Date(Date.parse(now) - TRASH_RETENTION_DAYS * DAY_MS).toISOString();
33
+ }
34
+ var BATCH_MAX = 100;
35
+ var IN_LIST_CHUNK = 50;
36
+ function jsonList(values) {
37
+ return sql`(SELECT value FROM json_each(${JSON.stringify(values)}))`;
38
+ }
39
+ function chunk(items, size = IN_LIST_CHUNK) {
40
+ const chunks = [];
41
+ for (let i = 0; i < items.length; i += size) chunks.push(items.slice(i, i + size));
42
+ return chunks;
43
+ }
44
+ var blankToNull = (value) => value === void 0 ? void 0 : value === null || value === "" ? null : value;
45
+ async function assertUserExists(db, id, field2 = "ownerId") {
46
+ if (!id) return;
47
+ const user = await db.selectFrom("core_user").select("id").where("id", "=", id).executeTakeFirst();
48
+ if (!user) throw new ValidationError(`No user with id ${id}`, { field: field2 });
49
+ }
50
+ function withPrimary(items, what) {
51
+ const flagged = items.filter((item) => item.primary).length;
52
+ if (flagged > 1) throw new ValidationError(`Only one ${what} can be primary`);
53
+ return items.map((item, i) => ({ ...item, primary: flagged ? Boolean(item.primary) : i === 0 }));
54
+ }
55
+ function uniqueIds(ids) {
56
+ const unique = [...new Set(ids)];
57
+ if (unique.length !== ids.length) throw new ValidationError("An id is listed twice");
58
+ return unique;
59
+ }
60
+
61
+ // ../core/src/notifications/send.ts
62
+ var CORE_USER_FIELDS = /* @__PURE__ */ new Set(["ownerId", "assigneeId", "authorUserId", "createdBy"]);
63
+ var NO_MANAGER_NOTE = "Users have no manager field: sent to the admins instead";
64
+ async function adminUserIds(db) {
65
+ const rows = await db.selectFrom("core_user").select("id").where("role", "=", "admin").where("kind", "=", "human").orderBy("id").execute();
66
+ return rows.map((row) => row.id);
67
+ }
68
+ async function recordUser(db, record, fieldName, options) {
69
+ const object = getObject(record.object);
70
+ if (!object) {
71
+ throw new ValidationError(`Unknown object "${record.object}"`, { field: "to" });
72
+ }
73
+ const field2 = getField(object, fieldName);
74
+ const isUserField = field2 && (field2.fieldType === "user" || !field2.extension && CORE_USER_FIELDS.has(field2.name));
75
+ if (!field2 || !isUserField) {
76
+ throw new ValidationError(
77
+ `${object.label} has no user field "${fieldName}" (recipients name a user field of the record)`,
78
+ { field: "to", object: record.object, recordField: fieldName }
79
+ );
80
+ }
81
+ const simulated = options.simulation?.record(record.object, record.id);
82
+ if (simulated) {
83
+ if (simulated.state === "deleted" || !simulated.record) {
84
+ return { userId: null, reason: `${object.label} ${record.id} is deleted` };
85
+ }
86
+ const values = simulated.record.values ?? simulated.record;
87
+ const value = values[field2.name];
88
+ return typeof value === "string" && value ? { userId: value } : {
89
+ userId: null,
90
+ reason: `${object.label} ${record.id} has no ${field2.label.toLowerCase()}`
91
+ };
92
+ }
93
+ const column = viewColumnOf(field2);
94
+ if (!column) throw new ValidationError(`${object.label}.${field2.name} cannot be read`);
95
+ const result = await sql`SELECT ${sql.ref(column)} AS v FROM ${sql.table(
96
+ object.source
97
+ )} WHERE id = ${record.id}`.execute(db);
98
+ const row = result.rows[0];
99
+ if (!row) return { userId: null, reason: `No ${object.label} with id ${record.id}` };
100
+ return typeof row.v === "string" && row.v ? { userId: row.v } : { userId: null, reason: `${object.label} ${record.id} has no ${field2.label.toLowerCase()}` };
101
+ }
102
+ async function resolveRecipients(db, to, options = {}) {
103
+ const ids = [];
104
+ const notes = [];
105
+ let admins = null;
106
+ const loadAdmins = async () => {
107
+ admins ??= await adminUserIds(db);
108
+ return admins;
109
+ };
110
+ for (const recipient of to) {
111
+ if ("userId" in recipient) {
112
+ ids.push(recipient.userId);
113
+ } else if ("role" in recipient) {
114
+ ids.push(...await loadAdmins());
115
+ } else if ("field" in recipient) {
116
+ const found = await recordUser(db, recipient.record, recipient.field, options);
117
+ if (found.userId) ids.push(found.userId);
118
+ else notes.push(`${found.reason}: nobody to notify`);
119
+ } else {
120
+ const found = await recordUser(db, recipient.record, recipient.managerOf, options);
121
+ if (!found.userId) notes.push(`${found.reason}`);
122
+ notes.push(NO_MANAGER_NOTE);
123
+ ids.push(...await loadAdmins());
124
+ }
125
+ }
126
+ const unique = [...new Set(ids)];
127
+ const people = unique.length ? await db.selectFrom("core_user").select("id").where("id", "in", jsonList(unique)).where("kind", "=", "human").execute() : [];
128
+ const known = new Set(people.map((p) => p.id));
129
+ const explicit = new Set(
130
+ to.flatMap((r) => "userId" in r ? [r.userId] : [])
131
+ );
132
+ for (const id of unique) {
133
+ if (known.has(id)) continue;
134
+ if (explicit.has(id)) {
135
+ throw new ValidationError(`No user with id ${id}`, { field: "to", userId: id });
136
+ }
137
+ notes.push(`User ${id} no longer exists: skipped`);
138
+ }
139
+ if (!to.length) notes.push("No recipients");
140
+ return { userIds: unique.filter((id) => known.has(id)), notes };
141
+ }
142
+ async function notifyStatements(db, input, now, options = {}) {
143
+ const { userIds, notes } = await resolveRecipients(db, input.to, options);
144
+ const source = JSON.stringify(
145
+ Object.fromEntries(Object.entries(input.source).filter(([, v]) => v !== void 0))
146
+ );
147
+ const link = input.link ? JSON.stringify(input.link) : null;
148
+ const statements = userIds.map(
149
+ (userId) => db.insertInto("core_notifications").orIgnore().values({
150
+ id: newId("notification"),
151
+ user_id: userId,
152
+ type: input.type,
153
+ title: input.title,
154
+ body: input.body ?? null,
155
+ link,
156
+ source,
157
+ dedupe_key: input.dedupeKey ?? null,
158
+ read_at: null,
159
+ created_at: now
160
+ })
161
+ );
162
+ return { statements, userIds, notes };
163
+ }
164
+
165
+ // ../core/src/filter.ts
166
+ var FILTER_OPS = [
167
+ "eq",
168
+ "neq",
169
+ "lt",
170
+ "lte",
171
+ "gt",
172
+ "gte",
173
+ "between",
174
+ "in",
175
+ "not_in",
176
+ "contains",
177
+ "not_contains",
178
+ "starts_with",
179
+ "ends_with",
180
+ "is_null",
181
+ "is_not_null"
182
+ ];
183
+ var FILTER_LIMITS = { maxDepth: 5, maxConditions: 100, maxListValues: 500 };
184
+ var conditionSchema = external_exports.object({
185
+ field: external_exports.string().min(1).max(64),
186
+ op: external_exports.enum(FILTER_OPS),
187
+ value: external_exports.unknown().optional()
188
+ }).strict();
189
+ var filterSchema = external_exports.lazy(
190
+ () => external_exports.union([
191
+ conditionSchema,
192
+ external_exports.object({ and: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict(),
193
+ external_exports.object({ or: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict()
194
+ ])
195
+ );
196
+ var COMPARABLE = ["eq", "neq", "lt", "lte", "gt", "gte", "between", "in", "not_in"];
197
+ var NULLS = ["is_null", "is_not_null"];
198
+ var TEXT = [
199
+ "eq",
200
+ "neq",
201
+ "in",
202
+ "not_in",
203
+ "contains",
204
+ "not_contains",
205
+ "starts_with",
206
+ "ends_with"
207
+ ];
208
+ var OPS_BY_TYPE = {
209
+ text: [...TEXT, ...NULLS],
210
+ number: [...COMPARABLE, ...NULLS],
211
+ date: [...COMPARABLE, ...NULLS],
212
+ datetime: [...COMPARABLE, ...NULLS],
213
+ boolean: ["eq", "neq", ...NULLS],
214
+ id: ["eq", "neq", "in", "not_in", ...NULLS],
215
+ enum: ["eq", "neq", "in", "not_in", ...NULLS],
216
+ json: []
217
+ };
218
+ var RELATED_OPS = [
219
+ "eq",
220
+ "neq",
221
+ "in",
222
+ "not_in",
223
+ "contains",
224
+ "not_contains",
225
+ "starts_with",
226
+ "ends_with",
227
+ ...NULLS
228
+ ];
229
+ var NEGATED = {
230
+ neq: "eq",
231
+ not_in: "in",
232
+ not_contains: "contains"
233
+ };
234
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
235
+ var DATETIME_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
236
+ function fail(path, reason) {
237
+ throw new ValidationError(`Invalid filter at ${path}: ${reason}`, { path, reason });
238
+ }
239
+ function scalar(field2, value, path) {
240
+ switch (field2.type) {
241
+ case "text":
242
+ if (typeof value !== "string") fail(path, `${field2.name} needs a string`);
243
+ if (value.length > 1e3) fail(path, "value is too long");
244
+ return value;
245
+ case "id":
246
+ if (typeof value !== "string" || value.length > 100) fail(path, `${field2.name} needs an id`);
247
+ return value;
248
+ case "number":
249
+ if (typeof value !== "number" || !Number.isFinite(value)) {
250
+ fail(path, `${field2.name} needs a number`);
251
+ }
252
+ return value;
253
+ case "boolean":
254
+ if (typeof value !== "boolean") fail(path, `${field2.name} needs true or false`);
255
+ return value ? 1 : 0;
256
+ case "date":
257
+ if (typeof value !== "string" || !DATE_RE.test(value)) {
258
+ fail(path, `${field2.name} needs a YYYY-MM-DD date`);
259
+ }
260
+ return value;
261
+ case "datetime":
262
+ if (typeof value !== "string" || !DATETIME_RE.test(value)) {
263
+ fail(path, `${field2.name} needs an ISO-8601 date or timestamp`);
264
+ }
265
+ return value;
266
+ case "enum":
267
+ if (typeof value !== "string" || !field2.enumValues?.includes(value)) {
268
+ fail(path, `${field2.name} must be one of ${field2.enumValues?.join(", ")}`);
269
+ }
270
+ return value;
271
+ case "json":
272
+ return fail(path, `${field2.name} cannot be filtered`);
273
+ }
274
+ }
275
+ function list(field2, value, path) {
276
+ if (!Array.isArray(value) || value.length === 0) fail(path, "needs a non-empty array");
277
+ if (value.length > FILTER_LIMITS.maxListValues) fail(path, "too many values");
278
+ return value.map((item, i) => scalar(field2, item, `${path}[${i}]`));
279
+ }
280
+ function escapeLike(value) {
281
+ return value.replace(/[\\%_]/g, (char) => `\\${char}`);
282
+ }
283
+ function comparison(field2, col, op, value, path) {
284
+ const nocase = field2.type === "text" ? sql` COLLATE NOCASE` : sql``;
285
+ switch (op) {
286
+ case "is_null":
287
+ return sql`${col} IS NULL`;
288
+ case "is_not_null":
289
+ return sql`${col} IS NOT NULL`;
290
+ case "eq":
291
+ return sql`${col} = ${scalar(field2, value, path)}${nocase}`;
292
+ case "neq":
293
+ return sql`(${col} IS NULL OR ${col} <> ${scalar(field2, value, path)}${nocase})`;
294
+ case "lt":
295
+ return sql`${col} < ${scalar(field2, value, path)}`;
296
+ case "lte":
297
+ return sql`${col} <= ${scalar(field2, value, path)}`;
298
+ case "gt":
299
+ return sql`${col} > ${scalar(field2, value, path)}`;
300
+ case "gte":
301
+ return sql`${col} >= ${scalar(field2, value, path)}`;
302
+ case "between": {
303
+ if (!Array.isArray(value) || value.length !== 2) fail(path, "between needs [low, high]");
304
+ const [low, high] = list(field2, value, path);
305
+ return sql`${col} BETWEEN ${low ?? null} AND ${high ?? null}`;
306
+ }
307
+ case "in":
308
+ return sql`${col}${nocase} IN (${sql.join(list(field2, value, path))})`;
309
+ case "not_in":
310
+ return sql`(${col} IS NULL OR ${col}${nocase} NOT IN (${sql.join(list(field2, value, path))}))`;
311
+ case "contains":
312
+ case "not_contains":
313
+ case "starts_with":
314
+ case "ends_with": {
315
+ const text = scalar(field2, value, path);
316
+ if (typeof text !== "string") fail(path, `${op} needs a string`);
317
+ const escaped = escapeLike(text);
318
+ const pattern = op === "starts_with" ? `${escaped}%` : op === "ends_with" ? `%${escaped}` : `%${escaped}%`;
319
+ const like = sql`${col} LIKE ${pattern} ESCAPE '\\'`;
320
+ return op === "not_contains" ? sql`(${col} IS NULL OR NOT (${like}))` : like;
321
+ }
322
+ }
323
+ }
324
+ function compileNode(object, node, alias, path, depth, state) {
325
+ if (depth > FILTER_LIMITS.maxDepth) fail(path, "filter is nested too deeply");
326
+ if ("and" in node || "or" in node) {
327
+ const isAnd = "and" in node;
328
+ const children = isAnd ? node.and : node.or;
329
+ const key = isAnd ? "and" : "or";
330
+ if (children.length === 0) return isAnd ? sql`1 = 1` : sql`1 = 0`;
331
+ const parts = children.map(
332
+ (child, i) => compileNode(object, child, alias, `${path}.${key}[${i}]`, depth + 1, state)
333
+ );
334
+ return sql`(${sql.join(parts, sql.raw(isAnd ? " AND " : " OR "))})`;
335
+ }
336
+ state.conditions += 1;
337
+ if (state.conditions > FILTER_LIMITS.maxConditions) fail(path, "too many conditions");
338
+ const { field: name, op, value } = node;
339
+ const field2 = object.fields.find((f) => f.name === name);
340
+ if (!field2) fail(path, `unknown field "${name}" on ${object.name}`);
341
+ if (!field2.filterable) fail(path, `${object.name}.${name} is not filterable`);
342
+ if (field2.related) {
343
+ if (!RELATED_OPS.includes(op) || !OPS_BY_TYPE[field2.type].includes(op)) {
344
+ fail(path, `${op} is not supported on ${object.name}.${name}`);
345
+ }
346
+ const r = field2.related;
347
+ const extra = r.where ? sql` AND ${sql.raw(r.where)}` : sql``;
348
+ const exists = (condition) => sql`EXISTS (SELECT 1 FROM ${sql.raw(r.from)} WHERE ${sql.raw(r.link)} = ${sql.ref(`${alias}.id`)}${extra}${condition ? sql` AND ${condition}` : sql``})`;
349
+ if (op === "is_not_null") return exists(null);
350
+ if (op === "is_null") return sql`NOT ${exists(null)}`;
351
+ const positive = NEGATED[op];
352
+ const col = sql.raw(r.column);
353
+ if (positive) {
354
+ return sql`NOT ${exists(comparison(field2, col, positive, value, path))}`;
355
+ }
356
+ return exists(comparison(field2, col, op, value, path));
357
+ }
358
+ if (!OPS_BY_TYPE[field2.type].includes(op)) {
359
+ fail(path, `${op} is not supported on ${field2.type} field ${object.name}.${name}`);
360
+ }
361
+ if (!field2.column) fail(path, `${object.name}.${name} has no column`);
362
+ if (!NULLS.includes(op) && value === void 0) fail(path, `${op} needs a value`);
363
+ return comparison(field2, sql.ref(`${alias}.${field2.column}`), op, value, path);
364
+ }
365
+ function compileFilter(object, filter, alias = object.source) {
366
+ const parsed = filterSchema.safeParse(filter);
367
+ if (!parsed.success) {
368
+ throw new ValidationError("Invalid filter", { issues: parsed.error.issues });
369
+ }
370
+ return compileNode(object, parsed.data, alias, "filter", 1, { conditions: 0 });
371
+ }
372
+
373
+ // ../core/src/list.ts
374
+ var sortSchema = external_exports.object({
375
+ field: external_exports.string().min(1).max(64),
376
+ direction: external_exports.enum(["asc", "desc"]).default("asc")
377
+ });
378
+ var LIST_MAX_LIMIT = 200;
379
+ var LIST_DEFAULT_LIMIT = 50;
380
+ var listInputSchema = external_exports.object({
381
+ filter: filterSchema.optional().describe("Structured filter: { and | or: [...] } of { field, op, value }."),
382
+ sort: sortSchema.optional().describe("Sort field and direction. Defaults per object."),
383
+ cursor: external_exports.string().max(1e3).optional().describe("nextCursor from the previous page."),
384
+ limit: external_exports.number().int().min(1).max(LIST_MAX_LIMIT).default(LIST_DEFAULT_LIMIT),
385
+ fields: external_exports.array(external_exports.string().min(1).max(64)).max(100).optional().describe("Return only these fields of each item (id is always included).")
386
+ });
387
+ function pageSchema(item) {
388
+ return external_exports.object({ items: external_exports.array(item), nextCursor: external_exports.string().nullable() });
389
+ }
390
+ function base64UrlEncode(text) {
391
+ const bytes = new TextEncoder().encode(text);
392
+ let binary = "";
393
+ for (const byte of bytes) binary += String.fromCharCode(byte);
394
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
395
+ }
396
+ function base64UrlDecode(text) {
397
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/");
398
+ const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
399
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
400
+ }
401
+ function encodeCursor(payload) {
402
+ return base64UrlEncode(JSON.stringify(payload));
403
+ }
404
+ var cursorSchema = external_exports.object({
405
+ f: external_exports.string(),
406
+ d: external_exports.enum(["asc", "desc"]),
407
+ v: external_exports.union([external_exports.string(), external_exports.number(), external_exports.null()]),
408
+ id: external_exports.string()
409
+ });
410
+ function decodeCursor(cursor, sort) {
411
+ let payload;
412
+ try {
413
+ payload = cursorSchema.parse(JSON.parse(base64UrlDecode(cursor)));
414
+ } catch {
415
+ throw new ValidationError("Invalid cursor");
416
+ }
417
+ if (payload.f !== sort.field || payload.d !== sort.direction) {
418
+ throw new ValidationError("Cursor was issued for a different sort; start from the first page");
419
+ }
420
+ return payload;
421
+ }
422
+ function resolveSort(object, sort) {
423
+ const resolved = sort ?? object.defaultSort;
424
+ const field2 = object.fields.find((f) => f.name === resolved.field);
425
+ if (!field2) throw new ValidationError(`Unknown sort field "${resolved.field}"`);
426
+ if (!field2.sortable || !field2.column) {
427
+ throw new ValidationError(`${object.name}.${resolved.field} is not sortable`);
428
+ }
429
+ return { sort: resolved, field: field2 };
430
+ }
431
+ function sortExpression(field2, alias) {
432
+ const ref = sql.ref(`${alias}.${field2.column}`);
433
+ return field2.type === "text" ? sql`${ref} COLLATE NOCASE` : ref;
434
+ }
435
+ function afterCursor(field2, alias, cursor) {
436
+ const col = sortExpression(field2, alias);
437
+ const raw = sql.ref(`${alias}.${field2.column}`);
438
+ const id = sql.ref(`${alias}.id`);
439
+ if (field2.name === "id") {
440
+ return cursor.d === "asc" ? sql`${id} > ${cursor.id}` : sql`${id} < ${cursor.id}`;
441
+ }
442
+ if (cursor.d === "asc") {
443
+ return cursor.v === null ? sql`((${raw} IS NULL AND ${id} > ${cursor.id}) OR ${raw} IS NOT NULL)` : sql`(${col} > ${cursor.v} OR (${col} = ${cursor.v} AND ${id} > ${cursor.id}))`;
444
+ }
445
+ return cursor.v === null ? sql`(${raw} IS NULL AND ${id} < ${cursor.id})` : sql`(${col} < ${cursor.v} OR ${raw} IS NULL OR (${col} = ${cursor.v} AND ${id} < ${cursor.id}))`;
446
+ }
447
+ function indexOrdered(object, field2) {
448
+ return field2.name === "id" || field2.name === object.defaultSort.field;
449
+ }
450
+ async function pageByIds(base, ordered, alias, column, take) {
451
+ const keys = await ordered.clearSelect().select([sql.ref(`${alias}.id`).as("id"), sql.ref(`${alias}.${column}`).as("sort_value")]).limit(take).execute();
452
+ if (!keys.length) return [];
453
+ const ids = keys.map((k) => k.id);
454
+ const rows = await base.where(
455
+ sql`${sql.ref(`${alias}.id`)} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`
456
+ ).execute();
457
+ const byId = new Map(rows.map((row) => [row.id, row]));
458
+ return ids.flatMap((id) => {
459
+ const row = byId.get(id);
460
+ return row ? [row] : [];
461
+ });
462
+ }
463
+ async function runListQuery(ctx, object, input) {
464
+ const query = ctx.db.selectFrom(visibleSource(ctx, object)).selectAll();
465
+ return pageQuery(query, visibleObject(ctx, object), input, object.source);
466
+ }
467
+ async function pageQuery(query, object, input, alias = object.source) {
468
+ const { sort, field: field2 } = resolveSort(object, input.sort);
469
+ let q = query;
470
+ if (input.filter) q = q.where(compileFilter(object, input.filter, alias));
471
+ if (input.cursor) q = q.where(afterCursor(field2, alias, decodeCursor(input.cursor, sort)));
472
+ const direction = sql.raw(sort.direction === "asc" ? "ASC" : "DESC");
473
+ if (field2.name !== "id") q = q.orderBy(sql`${sortExpression(field2, alias)} ${direction}`);
474
+ q = q.orderBy(sql`${sql.ref(`${alias}.id`)} ${direction}`);
475
+ const limit = input.limit ?? LIST_DEFAULT_LIMIT;
476
+ const rows = indexOrdered(object, field2) ? await q.limit(limit + 1).execute() : await pageByIds(query, q, alias, field2.column, limit + 1);
477
+ const page = rows.slice(0, limit);
478
+ const last = page.at(-1);
479
+ let nextCursor = null;
480
+ if (rows.length > limit && last) {
481
+ const value = last[field2.column];
482
+ nextCursor = encodeCursor({
483
+ f: sort.field,
484
+ d: sort.direction,
485
+ v: typeof value === "string" || typeof value === "number" ? value : null,
486
+ id: last.id
487
+ });
488
+ }
489
+ return { rows: page, nextCursor };
490
+ }
491
+ function selectFields(items, fields, allowed) {
492
+ if (!fields) return items;
493
+ const unknown = fields.filter((name) => !allowed.includes(name));
494
+ if (unknown.length) throw new ValidationError(`Unknown fields: ${unknown.join(", ")}`);
495
+ const keep = /* @__PURE__ */ new Set(["id", ...fields]);
496
+ return items.map(
497
+ (item) => Object.fromEntries(Object.entries(item).filter(([key]) => keep.has(key)))
498
+ );
499
+ }
500
+
501
+ // ../core/src/visibility/access.ts
502
+ var kinds = /* @__PURE__ */ new Map();
503
+ function registerAccessSource(kind, implementation) {
504
+ if (kind === "record") throw new Error("The record kind is the host's own");
505
+ kinds.set(kind, implementation);
506
+ }
507
+ function hasAccessSourceKind(kind) {
508
+ return kind === "record" || kinds.has(kind);
509
+ }
510
+ var kindOf = (source) => source.kind ?? "record";
511
+ function accessProblems(object) {
512
+ const declared = object.access;
513
+ if (!declared) return [];
514
+ if (!declared.sources.length) return ["access declares at least one source"];
515
+ const problems = [];
516
+ declared.sources.forEach((source, i) => {
517
+ const kind = kindOf(source);
518
+ const implementation = kind === "record" ? RECORD_KIND : kinds.get(kind);
519
+ if (!implementation) {
520
+ problems.push(`access.sources.${i}: the host has no source of kind "${kind}"`);
521
+ return;
522
+ }
523
+ for (const p of implementation.problems(object, source)) {
524
+ problems.push(`access.sources.${i}: ${p}`);
525
+ }
526
+ });
527
+ return problems;
528
+ }
529
+ async function holdsAccess(reader, object, ids, now = (/* @__PURE__ */ new Date()).toISOString()) {
530
+ const principal = reader.principal;
531
+ if (principal.kind === "staff") return new Set(ids);
532
+ const definition = getObject(object.name) ?? object;
533
+ const declared = definition.access;
534
+ if (principal.kind !== "customer" || !declared || !ids.length) return /* @__PURE__ */ new Set();
535
+ const problems = accessProblems(definition);
536
+ if (problems.length) {
537
+ throw new Error(`${definition.name}: invalid access declaration: ${problems.join("; ")}`);
538
+ }
539
+ const query = {
540
+ db: reader.db,
541
+ personId: principal.personId,
542
+ now,
543
+ object: definition,
544
+ ids: [...new Set(ids)]
545
+ };
546
+ const held = /* @__PURE__ */ new Set();
547
+ for (const source of declared.sources) {
548
+ const kind = kindOf(source);
549
+ const implementation = kind === "record" ? RECORD_KIND : kinds.get(kind);
550
+ if (!implementation) continue;
551
+ const left = query.ids.filter((id) => !held.has(id));
552
+ if (!left.length) break;
553
+ for (const id of await implementation.holders({ ...query, ids: left }, source)) {
554
+ if (left.includes(id)) held.add(id);
555
+ }
556
+ }
557
+ return held;
558
+ }
559
+ var field = (object, name) => object.fields.find((f) => f.name === name);
560
+ function resolveRecordSource(object, source) {
561
+ const via = getObject(source.via);
562
+ if (!via || via.name === object.name || !object.extension || via.extension !== object.extension) {
563
+ return `via "${source.via}" must be another object of the same extension`;
564
+ }
565
+ const ownerField = via.customer ? field(via, via.customer.field) : void 0;
566
+ const owner = ownerField ? viewColumnOf(ownerField) : null;
567
+ if (!via.customer || !owner) return `via "${source.via}" must declare a customer`;
568
+ const pointerField = field(via, source.field);
569
+ const pointer = pointerField ? viewColumnOf(pointerField) : null;
570
+ if (!pointer || pointerField?.fieldType !== "relation" || pointerField.options?.many) {
571
+ return `field "${source.field}" must be a relation of ${via.name} to one record`;
572
+ }
573
+ let through = null;
574
+ if (source.through === void 0) {
575
+ if (pointerField.options?.to !== object.name) {
576
+ return `field "${source.field}" must be a relation of ${via.name} to one ${object.name}`;
577
+ }
578
+ } else {
579
+ const target = getObject(String(pointerField.options?.to));
580
+ const list2 = target ? field(target, source.through) : void 0;
581
+ const column = list2 ? viewColumnOf(list2) : null;
582
+ const lists = list2?.fieldType === "relation" && list2.options?.many === true && list2.options?.to === object.name || list2?.fieldType === "document";
583
+ if (!target || !list2 || !column || !lists) {
584
+ return `through "${source.through}" must be a many relation to ${object.name}, or a document naming it, on the record ${source.field} points to`;
585
+ }
586
+ const published = Boolean(
587
+ target.publishable && target.public && target.publishable.content.includes(list2.name)
588
+ );
589
+ through = { view: published ? liveViewOf(target.name) : target.source, column, field: list2 };
590
+ }
591
+ let state = null;
592
+ if (via.states) {
593
+ const stateField = field(via, via.states.field);
594
+ const column = stateField ? viewColumnOf(stateField) : null;
595
+ if (!column) return `${via.name} has no state column`;
596
+ if (!source.states?.length) return `${via.name} has states: name the ones that give access`;
597
+ state = { column, values: source.states };
598
+ } else if (source.states?.length) {
599
+ return `${via.name} has no states`;
600
+ }
601
+ let until = null;
602
+ if (source.until !== void 0) {
603
+ const untilField = field(via, source.until);
604
+ const column = untilField ? viewColumnOf(untilField) : null;
605
+ if (!column || untilField?.fieldType !== "date" && untilField?.fieldType !== "datetime") {
606
+ return `until "${source.until}" must be a date or datetime field of ${via.name}`;
607
+ }
608
+ until = { column, date: untilField.fieldType === "date" };
609
+ }
610
+ return { view: via.source, owner, pointer, state, until, through };
611
+ }
612
+ function pointersSql(resolved, query) {
613
+ const conditions = [
614
+ sql`${sql.ref(resolved.owner)} = ${query.personId}`,
615
+ sql`${sql.ref(resolved.pointer)} IS NOT NULL`
616
+ ];
617
+ if (resolved.state) {
618
+ conditions.push(
619
+ sql`${sql.ref(resolved.state.column)} IN (${sql.join(resolved.state.values.map((v) => sql`${v}`))})`
620
+ );
621
+ }
622
+ if (resolved.until) {
623
+ const bound = resolved.until.date ? query.now.slice(0, 10) : query.now;
624
+ const op = resolved.until.date ? sql`>=` : sql`>`;
625
+ conditions.push(
626
+ sql`(${sql.ref(resolved.until.column)} IS NULL OR ${sql.ref(resolved.until.column)} = '' OR ${sql.ref(resolved.until.column)} ${op} ${bound})`
627
+ );
628
+ }
629
+ return sql`SELECT DISTINCT ${sql.ref(resolved.pointer)} AS id FROM ${sql.table(resolved.view)} WHERE ${sql.join(conditions, sql` AND `)}`;
630
+ }
631
+ var RECORD_KIND = {
632
+ problems(object, source) {
633
+ if (source.via === void 0) return ["a record source names via"];
634
+ const resolved = resolveRecordSource(object, source);
635
+ return typeof resolved === "string" ? [resolved] : [];
636
+ },
637
+ async holders(query, source) {
638
+ if (source.via === void 0) return /* @__PURE__ */ new Set();
639
+ const resolved = resolveRecordSource(query.object, source);
640
+ if (typeof resolved === "string") return /* @__PURE__ */ new Set();
641
+ const pointers = pointersSql(resolved, query);
642
+ if (!resolved.through) {
643
+ const rows2 = await sql`SELECT id FROM (${pointers}) WHERE id IN (${sql.join(
644
+ query.ids.map((id) => sql`${id}`)
645
+ )})`.execute(query.db);
646
+ return new Set(rows2.rows.map((r) => String(r.id)));
647
+ }
648
+ const { view, column, field: list2 } = resolved.through;
649
+ const rows = await sql`SELECT ${sql.ref(column)} AS value FROM ${sql.table(view)} WHERE id IN (${pointers})`.execute(
650
+ query.db
651
+ );
652
+ const wanted = new Set(query.ids);
653
+ const held = /* @__PURE__ */ new Set();
654
+ for (const { value } of rows.rows) {
655
+ for (const id of listed(list2, value, query.object.name)) if (wanted.has(id)) held.add(id);
656
+ }
657
+ return held;
658
+ }
659
+ };
660
+ function listed(list2, stored, object) {
661
+ let value = stored;
662
+ if (typeof stored === "string") {
663
+ try {
664
+ value = JSON.parse(stored);
665
+ } catch {
666
+ return [];
667
+ }
668
+ }
669
+ if (list2.fieldType === "relation") {
670
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
671
+ }
672
+ const schema = list2.options?.document?.schema;
673
+ if (!schema || value === null || value === void 0) return [];
674
+ return documentRefs(schema, value).filter((ref) => ref.to === object).map((ref) => ref.id);
675
+ }
676
+
677
+ // ../core/src/integrations/catalogue.ts
678
+ var CATALOGUE = [
679
+ {
680
+ vendor: "google",
681
+ title: "Google Workspace",
682
+ description: "Gmail, Google Calendar and Drive. Syncs mail and meetings onto timelines.",
683
+ connect: "oauth",
684
+ scopes: ["personal", "org"],
685
+ sync: {
686
+ mail: ["https://mail.google.com/"],
687
+ calendar: ["https://calendar.google.com/"]
688
+ }
689
+ },
690
+ {
691
+ vendor: "microsoft",
692
+ title: "Microsoft 365",
693
+ description: "Outlook mail, Outlook Calendar and SharePoint. Syncs mail and meetings.",
694
+ connect: "oauth",
695
+ scopes: ["personal", "org"],
696
+ sync: {
697
+ mail: ["https://outlook.office.com/"],
698
+ calendar: ["https://outlook.office.com/calendar"]
699
+ }
700
+ },
701
+ {
702
+ vendor: "slack",
703
+ title: "Slack",
704
+ description: "Read channels and threads, and post messages and DMs (with the Slack posting gatekeeper, through the same Slack app).",
705
+ connect: "oauth",
706
+ scopes: ["personal", "org"],
707
+ companion: "slack-post"
708
+ },
709
+ {
710
+ vendor: "slack-post",
711
+ title: "Slack (post messages)",
712
+ description: "Post to channels and send DMs as the CRM's Slack bot.",
713
+ connect: "oauth",
714
+ scopes: ["org"]
715
+ },
716
+ {
717
+ vendor: "mcp",
718
+ title: "MCP server",
719
+ description: "Connect any remote MCP server and use its tools through a gatekeeper.",
720
+ connect: "oauth",
721
+ scopes: ["personal", "org"]
722
+ },
723
+ {
724
+ vendor: "email",
725
+ title: "Inbound email",
726
+ description: "Receive mail at a CRM address (Cloudflare Email Routing).",
727
+ connect: "oauth",
728
+ scopes: ["org"]
729
+ },
730
+ {
731
+ vendor: "email-send",
732
+ title: "Email sending",
733
+ description: "Send email from the CRM's own addresses (Cloudflare Email Service).",
734
+ connect: "auto",
735
+ scopes: ["org"]
736
+ },
737
+ {
738
+ vendor: "zoominfo",
739
+ title: "ZoomInfo",
740
+ description: "Manual, approved 'Enrich now' on people and organisations. No polling.",
741
+ connect: "oauth",
742
+ scopes: ["org"]
743
+ },
744
+ {
745
+ vendor: "websearch",
746
+ title: "Web search",
747
+ description: "Search the public web (Cloudflare Web Search). Searches are observations.",
748
+ connect: "auto",
749
+ scopes: ["personal", "org"],
750
+ singleton: true
751
+ },
752
+ {
753
+ vendor: "webhook",
754
+ title: "Inbound webhooks",
755
+ description: "External systems post signed events to the CRM. Bad signatures are rejected; good ones become typed events for automations.",
756
+ connect: "auto",
757
+ scopes: ["org"]
758
+ },
759
+ {
760
+ vendor: "payments",
761
+ title: "Payments",
762
+ description: "Take payment for orders on the provider's own page (Stripe), into your own account. Keys stay in the gatekeeper; card details never reach the CRM.",
763
+ connect: "auto",
764
+ scopes: ["org"]
765
+ },
766
+ {
767
+ vendor: "fake",
768
+ title: "Fake provider (development)",
769
+ description: "A fake OAuth provider with a mailbox and calendar, for development and tests.",
770
+ connect: "oauth",
771
+ scopes: ["personal", "org"],
772
+ sync: { mail: ["fake://mailbox/"], calendar: ["fake://calendar/"] },
773
+ devOnly: true
774
+ }
775
+ ];
776
+ function catalogueEntry(vendor) {
777
+ return CATALOGUE.find((entry) => entry.vendor === vendor);
778
+ }
779
+ function syncKindOf(vendor, url) {
780
+ const entry = catalogueEntry(vendor);
781
+ for (const kind of ["calendar", "mail"]) {
782
+ if (entry?.sync?.[kind]?.some((prefix) => url.startsWith(prefix))) return kind;
783
+ }
784
+ return null;
785
+ }
786
+
787
+ // ../core/src/automations/bindings.ts
788
+ var WAITING_FOR_CONNECTIONS = "Waiting for connections";
789
+ var CONNECTION_REVOKED_PREFIX = "Connection revoked";
790
+ function toBinding(row) {
791
+ return {
792
+ automationId: row.automation_id,
793
+ slot: row.slot,
794
+ gatekeeper: row.gatekeeper,
795
+ purpose: row.purpose,
796
+ connectionId: row.connection_id,
797
+ boundBy: row.bound_by,
798
+ boundAt: row.bound_at,
799
+ revokedAt: row.revoked_at,
800
+ revokedBy: row.revoked_by,
801
+ revokeReason: row.revoke_reason
802
+ };
803
+ }
804
+ function declaredConnections(spec) {
805
+ return spec.connections ?? [];
806
+ }
807
+ function connectionServes(vendor, gatekeeper) {
808
+ return vendor === gatekeeper || catalogueEntry(vendor)?.companion === gatekeeper;
809
+ }
810
+ async function loadBindings(db, automationIds) {
811
+ if (!automationIds.length) return [];
812
+ const rows = await db.selectFrom("core_automation_binding").selectAll().where("automation_id", "in", jsonList([...new Set(automationIds)])).execute();
813
+ return rows.map(toBinding);
814
+ }
815
+ function unboundSlots(spec, bindings) {
816
+ return declaredConnections(spec).filter(
817
+ (c) => !bindings.some((b) => b.slot === c.id && b.revokedAt === null)
818
+ );
819
+ }
820
+ async function revokeBindingsPlan(db, target, input) {
821
+ let connectionIds;
822
+ if ("connectionId" in target) {
823
+ connectionIds = [target.connectionId];
824
+ } else {
825
+ const owned = await db.selectFrom("core_integration_connection").select("id").where("owner_user_id", "=", target.ownerUserId).execute();
826
+ connectionIds = owned.map((r) => r.id);
827
+ }
828
+ if (!connectionIds.length) return { statements: [], automationIds: [], revoked: 0 };
829
+ const live = await db.selectFrom("core_automation_binding as b").innerJoin("core_automations as a", "a.id", "b.automation_id").select(["b.automation_id", "b.slot", "a.label", "a.paused_reason"]).where("b.connection_id", "in", jsonList(connectionIds)).where("b.revoked_at", "is", null).execute();
830
+ if (!live.length) return { statements: [], automationIds: [], revoked: 0 };
831
+ const statements = [
832
+ db.updateTable("core_automation_binding").set({ revoked_at: input.now, revoked_by: input.by, revoke_reason: input.reason }).where("connection_id", "in", jsonList(connectionIds)).where("revoked_at", "is", null)
833
+ ];
834
+ const automations = /* @__PURE__ */ new Map();
835
+ for (const row of live) {
836
+ automations.set(row.automation_id, { label: row.label, paused: row.paused_reason !== null });
837
+ }
838
+ const pauseReason = `${CONNECTION_REVOKED_PREFIX}: ${input.reason}`;
839
+ statements.push(
840
+ db.updateTable("core_automations").set({ paused_reason: pauseReason, paused_at: input.now, updated_at: input.now }).where("id", "in", jsonList([...automations.keys()])).where(sql`(paused_reason IS NULL OR paused_reason = ${WAITING_FOR_CONNECTIONS})`)
841
+ );
842
+ for (const [id, a] of automations) {
843
+ const plan = await notifyStatements(
844
+ db,
845
+ {
846
+ to: [{ role: "admin" }],
847
+ type: "automation.paused",
848
+ title: `\u201C${a.label}\u201D was paused`,
849
+ body: `${input.reason}. Bind another connection on the automation page, then enable it again.`,
850
+ link: { kind: "automation", automationId: id },
851
+ dedupeKey: `revoked:${id}:${input.now}`,
852
+ source: { actor: "automation", automationId: id }
853
+ },
854
+ input.now
855
+ );
856
+ statements.push(...plan.statements);
857
+ }
858
+ return { statements, automationIds: [...automations.keys()], revoked: live.length };
859
+ }
860
+
861
+ // ../core/src/automations/types.ts
862
+ var MAX_CASCADE_DEPTH = 3;
863
+ var EVENT_CHANGES_PER_MESSAGE = 100;
864
+ var QUEUE_MESSAGE_MAX_BYTES = 12e4;
865
+ var AUTOMATION_SETTINGS = {
866
+ /** boolean. Human admins only (automation.killSwitch). Pauses every automation at once. */
867
+ killSwitch: "automations_kill_switch",
868
+ /** IANA timezone schedules and date-relative triggers are evaluated in. Default "UTC". */
869
+ timezone: "automation_timezone",
870
+ /** Seconds within which `updated` events for one record coalesce. Default 30. */
871
+ debounceSeconds: "automation_debounce_seconds"
872
+ };
873
+ var DEFAULT_RAILS = {
874
+ maxRunsPerMinute: 60,
875
+ maxWritesPerHour: 500,
876
+ debounceSeconds: 30
877
+ };
878
+ var RUN_STATUSES = [
879
+ /** Row written, Workflow not yet running. */
880
+ "queued",
881
+ "running",
882
+ /** In a step.sleep or step.waitForEvent. */
883
+ "waiting",
884
+ /** Paused on a pending action (review) until a person decides. */
885
+ "review",
886
+ "completed",
887
+ "failed",
888
+ /** Stopped: rejected (onRejected stop), cancelled by a person, or the kill switch. */
889
+ "cancelled",
890
+ /** Its pending action expired. */
891
+ "expired",
892
+ /** Not started: a rail dropped it (depth, cycle, budget, rate, paused, kill switch). */
893
+ "skipped"
894
+ ];
895
+ var DRAFT_TARGET_ERRORS = ["unknown_automation", "evaluate_failed"];
896
+
897
+ // ../core/src/automations/registry.ts
898
+ function triggerObject(spec) {
899
+ const t = spec.trigger;
900
+ return "object" in t && typeof t.object === "string" ? t.object : null;
901
+ }
902
+ function automationSyncStatements(db, input) {
903
+ const statements = [];
904
+ const ids = [];
905
+ for (const [key, spec] of Object.entries(input.automations)) {
906
+ const id = `${input.extensionId}.${key}`;
907
+ ids.push(id);
908
+ const values = {
909
+ label: spec.label,
910
+ trigger_type: spec.trigger.type,
911
+ trigger_object: triggerObject(spec),
912
+ spec: JSON.stringify(spec),
913
+ commit_oid: input.commit,
914
+ removed_at: null,
915
+ updated_at: input.now
916
+ };
917
+ statements.push(
918
+ db.insertInto("core_automations").values({
919
+ id,
920
+ extension_id: input.extensionId,
921
+ key,
922
+ ...values,
923
+ // Shipped turned off (ADR 0246) until a person turns it on.
924
+ enabled: spec.enabled === false ? 0 : 1,
925
+ // An automation that needs connections waits until a person binds them (ADR 0170).
926
+ paused_reason: spec.connections?.length ? WAITING_FOR_CONNECTIONS : null,
927
+ paused_at: spec.connections?.length ? input.now : null,
928
+ created_at: input.now
929
+ }).onConflict((oc) => oc.column("id").doUpdateSet(values))
930
+ );
931
+ }
932
+ let removed = db.updateTable("core_automations").set({ removed_at: input.now, updated_at: input.now }).where("extension_id", "=", input.extensionId).where("removed_at", "is", null);
933
+ if (ids.length) removed = removed.where("id", "not in", jsonList(ids));
934
+ statements.push(removed);
935
+ return statements;
936
+ }
937
+ function parseSpec(json) {
938
+ try {
939
+ const parsed = automationManifestSchema.safeParse(JSON.parse(json));
940
+ return parsed.success ? parsed.data : null;
941
+ } catch {
942
+ return null;
943
+ }
944
+ }
945
+ async function loadAutomationSettings(db) {
946
+ const rows = await db.selectFrom("core_settings").select(["key", "value"]).where("key", "in", [
947
+ AUTOMATION_SETTINGS.killSwitch,
948
+ AUTOMATION_SETTINGS.timezone,
949
+ AUTOMATION_SETTINGS.debounceSeconds
950
+ ]).execute();
951
+ const value = (key) => {
952
+ const row = rows.find((r) => r.key === key);
953
+ if (!row) return void 0;
954
+ try {
955
+ return JSON.parse(row.value);
956
+ } catch {
957
+ return void 0;
958
+ }
959
+ };
960
+ const tz = value(AUTOMATION_SETTINGS.timezone);
961
+ const debounce = value(AUTOMATION_SETTINGS.debounceSeconds);
962
+ return {
963
+ // Engaged only when the stored value is exactly true.
964
+ killSwitch: value(AUTOMATION_SETTINGS.killSwitch) === true,
965
+ timezone: typeof tz === "string" && isTimeZone(tz) ? tz : "UTC",
966
+ debounceSeconds: typeof debounce === "number" && debounce >= 0 ? debounce : DEFAULT_RAILS.debounceSeconds
967
+ };
968
+ }
969
+ function isTimeZone(tz) {
970
+ try {
971
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
972
+ return true;
973
+ } catch {
974
+ return false;
975
+ }
976
+ }
977
+ function effectiveRails(spec, settings) {
978
+ return {
979
+ maxRunsPerMinute: Math.min(
980
+ spec.rails?.maxRunsPerMinute ?? DEFAULT_RAILS.maxRunsPerMinute,
981
+ DEFAULT_RAILS.maxRunsPerMinute
982
+ ),
983
+ maxWritesPerHour: Math.min(
984
+ spec.rails?.maxWritesPerHour ?? DEFAULT_RAILS.maxWritesPerHour,
985
+ DEFAULT_RAILS.maxWritesPerHour
986
+ ),
987
+ debounceSeconds: spec.rails?.debounceSeconds ?? settings.debounceSeconds
988
+ };
989
+ }
990
+
991
+ export {
992
+ TRASH_RETENTION_DAYS,
993
+ restorableUntil,
994
+ purgeCutoff,
995
+ BATCH_MAX,
996
+ jsonList,
997
+ chunk,
998
+ blankToNull,
999
+ assertUserExists,
1000
+ withPrimary,
1001
+ uniqueIds,
1002
+ CATALOGUE,
1003
+ catalogueEntry,
1004
+ syncKindOf,
1005
+ notifyStatements,
1006
+ WAITING_FOR_CONNECTIONS,
1007
+ declaredConnections,
1008
+ connectionServes,
1009
+ loadBindings,
1010
+ unboundSlots,
1011
+ revokeBindingsPlan,
1012
+ MAX_CASCADE_DEPTH,
1013
+ EVENT_CHANGES_PER_MESSAGE,
1014
+ QUEUE_MESSAGE_MAX_BYTES,
1015
+ AUTOMATION_SETTINGS,
1016
+ RUN_STATUSES,
1017
+ DRAFT_TARGET_ERRORS,
1018
+ triggerObject,
1019
+ automationSyncStatements,
1020
+ parseSpec,
1021
+ loadAutomationSettings,
1022
+ isTimeZone,
1023
+ effectiveRails,
1024
+ filterSchema,
1025
+ OPS_BY_TYPE,
1026
+ compileFilter,
1027
+ registerAccessSource,
1028
+ hasAccessSourceKind,
1029
+ holdsAccess,
1030
+ sortSchema,
1031
+ LIST_MAX_LIMIT,
1032
+ listInputSchema,
1033
+ pageSchema,
1034
+ encodeCursor,
1035
+ decodeCursor,
1036
+ resolveSort,
1037
+ runListQuery,
1038
+ pageQuery,
1039
+ selectFields
1040
+ };