@composable-os/cli 0.1.0-beta.11 → 0.1.0-beta.13

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 (166) hide show
  1. package/dist/{accounts-UHYLCLEY.js → accounts-GOCNY6WI.js} +17 -13
  2. package/dist/app-RPRZMLU5.js +43 -0
  3. package/dist/app-upload-YJVEKZC6.js +198 -0
  4. package/dist/{blocks-5IFU25J6.js → blocks-DE4RRWPJ.js} +207 -25
  5. package/dist/{chunk-XIDLW3EP.js → chunk-2B6YUYZV.js} +23499 -11766
  6. package/dist/{run-7P4RQALH.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/{chunk-DHS2CV2M.js → chunk-5D7BDF4Y.js} +15 -13
  9. package/dist/{chunk-ZAWES2UD.js → chunk-6CM3WZG5.js} +13 -2483
  10. package/dist/{chunk-7D4GKZOX.js → chunk-CIBJGB5H.js} +422 -75
  11. package/dist/chunk-EPDTPGZJ.js +330 -0
  12. package/dist/{chunk-LAAL4YGR.js → chunk-HAYF4G5V.js} +66 -23
  13. package/dist/chunk-HCG6T53D.js +61904 -0
  14. package/dist/{chunk-K34UKWEI.js → chunk-JX4IFWNT.js} +64 -32
  15. package/dist/{chunk-6XTU2MTP.js → chunk-KFHKNXGH.js} +632 -418
  16. package/dist/chunk-KMFMD52Z.js +13276 -0
  17. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  18. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  19. package/dist/{chunk-E64SG24J.js → chunk-Q6Y45DY6.js} +25 -2
  20. package/dist/{chunk-MBIKVRAC.js → chunk-QJZGYJVV.js} +823 -44
  21. package/dist/{chunk-PDD2ETVF.js → chunk-QQ3YSL5F.js} +172 -16
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-YFTLIEWU.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-LO6WGU5Y.js → chunk-U72NEGCT.js} +8089 -3464
  26. package/dist/{chunk-P6UWZ6QQ.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/{chunk-2IVEVPMY.js → chunk-Z7OVQ6BC.js} +105 -61
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-5UNY5G5L.js → cli-OKQHHSOE.js} +17 -25
  30. package/dist/{cli-UYZMVQMR.js → cli-VYSD2S4Z.js} +227 -81
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-SE4EKG6W.js → client-repo-NNUCHQ2Y.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-FTWWMD7N.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-U4KZLLSJ.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-UHLVBVLR.js → person-YOZTFV4Q.js} +11 -10
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  43. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  44. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  45. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  46. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  47. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  48. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  49. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  50. package/dist/platform/migrations/0815_checklists.sql +237 -0
  51. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  52. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  53. package/dist/platform/migrations/0850_agreements.sql +271 -0
  54. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  55. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  56. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  57. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  58. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  59. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  60. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  61. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  62. package/dist/platform/migrations/0911_texts.sql +60 -0
  63. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  64. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  65. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  66. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  67. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  68. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  69. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  70. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  71. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  72. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  73. package/dist/platform/migrations/0970_published_text.sql +59 -0
  74. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  75. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  76. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  77. package/dist/platform/migrations/1030_invoices.sql +747 -0
  78. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  79. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  80. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  81. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  82. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  83. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  84. package/dist/platform/migrations/1130_devices.sql +162 -0
  85. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  86. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  87. package/dist/platform/migrations/1151_payouts.sql +202 -0
  88. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  89. package/dist/platform/migrations/1170_journeys.sql +318 -0
  90. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  91. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  92. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  93. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  94. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  95. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  96. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  97. package/dist/platform/migrations/1271_leave.sql +249 -0
  98. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  99. package/dist/platform/migrations/1330_accounting.sql +260 -0
  100. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  101. package/dist/platform/migrations/1390_locations.sql +77 -0
  102. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  103. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  104. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  105. package/dist/platform/sdk/acknowledge.ts +100 -0
  106. package/dist/platform/sdk/agreements.ts +185 -0
  107. package/dist/platform/sdk/allowance.ts +98 -8
  108. package/dist/platform/sdk/automation-check.ts +120 -9
  109. package/dist/platform/sdk/automation.ts +78 -10
  110. package/dist/platform/sdk/behaviour.ts +26 -6
  111. package/dist/platform/sdk/calendar-entry.ts +258 -0
  112. package/dist/platform/sdk/capacity.ts +1 -2
  113. package/dist/platform/sdk/checklists.ts +118 -0
  114. package/dist/platform/sdk/contract.ts +489 -27
  115. package/dist/platform/sdk/discount.ts +408 -0
  116. package/dist/platform/sdk/document.ts +4 -2
  117. package/dist/platform/sdk/field-types.ts +5 -0
  118. package/dist/platform/sdk/formula/compile.ts +10 -0
  119. package/dist/platform/sdk/index.ts +17 -0
  120. package/dist/platform/sdk/intake.ts +380 -0
  121. package/dist/platform/sdk/journey-signals.ts +215 -0
  122. package/dist/platform/sdk/manifest.ts +1236 -65
  123. package/dist/platform/sdk/mine.ts +161 -0
  124. package/dist/platform/sdk/occupies.ts +192 -0
  125. package/dist/platform/sdk/questions.ts +681 -0
  126. package/dist/platform/sdk/recurring.ts +90 -9
  127. package/dist/platform/sdk/restricted-fields.ts +129 -0
  128. package/dist/platform/sdk/rich-text.ts +112 -0
  129. package/dist/platform/sdk/routine-mail.ts +1272 -0
  130. package/dist/platform/sdk/runtime.ts +25 -12
  131. package/dist/platform/sdk/screens.ts +91 -0
  132. package/dist/platform/sdk/sellable.ts +344 -0
  133. package/dist/platform/sdk/slug.ts +7 -2
  134. package/dist/platform/sdk/staffed.ts +474 -0
  135. package/dist/platform/sdk/states.ts +68 -26
  136. package/dist/platform/sdk/stock.ts +332 -0
  137. package/dist/platform/sdk/team.ts +83 -0
  138. package/dist/platform/sdk/testing.ts +70 -6
  139. package/dist/platform/sdk/worked-on.ts +134 -0
  140. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  141. package/dist/run-7ID64RA6.js +65 -0
  142. package/dist/run-FH7OGGTV.js +131 -0
  143. package/dist/run-OYZIAP6M.js +3363 -0
  144. package/dist/{run-ZCGFMEZF.js → run-QOFRRSZV.js} +41 -60
  145. package/dist/{run-PO3W5BFA.js → run-TJAEWR5U.js} +21 -51
  146. package/dist/{src-I3IJ4NKC.js → src-52VERUPK.js} +306 -4
  147. package/dist/src-PHRELWN5.js +40 -0
  148. package/dist/{visibility-TVXZ67FD.js → visibility-SZCINPP4.js} +21 -4
  149. package/package.json +2 -2
  150. package/dist/chunk-2TWV3SVB.js +0 -349
  151. package/dist/chunk-2XC5JLBO.js +0 -1931
  152. package/dist/chunk-324WJXNP.js +0 -320
  153. package/dist/chunk-6ELZRNUU.js +0 -116
  154. package/dist/chunk-6WGFA2IV.js +0 -643
  155. package/dist/chunk-7CQGMVDO.js +0 -63
  156. package/dist/chunk-7OGCMQXG.js +0 -284
  157. package/dist/chunk-FJIZGS5Q.js +0 -698
  158. package/dist/chunk-UB4I2QKR.js +0 -31575
  159. package/dist/chunk-WHKJGF36.js +0 -2418
  160. package/dist/chunk-YNUZRTPH.js +0 -182
  161. package/dist/chunk-ZZFWMVJO.js +0 -704
  162. package/dist/grants-LOW6TSWD.js +0 -32
  163. package/dist/invoke-6KVT6WJI.js +0 -41
  164. package/dist/moves-E2HKYCTK.js +0 -41
  165. package/dist/plan-on-sale-TJPFCNL7.js +0 -26
  166. package/dist/src-CRO35DYY.js +0 -46
@@ -16,6 +16,7 @@ import {
16
16
  durationMs,
17
17
  notificationInput,
18
18
  } from "./automation.ts";
19
+ import { DEFAULT_WAIT_TIMEOUT, NOTIFY_OPERATION } from "./automation-check.ts";
19
20
  import type {
20
21
  AiModule,
21
22
  Extension,
@@ -27,6 +28,7 @@ import type {
27
28
  StorageModule,
28
29
  } from "./contract.ts";
29
30
  import { toManifest } from "./manifest.ts";
31
+ import type { RoutineMailModule, RoutineSendResult } from "./routine-mail.ts";
30
32
 
31
33
  type HostFn = (...args: unknown[]) => Promise<unknown>;
32
34
 
@@ -36,6 +38,8 @@ export interface RawHostModules {
36
38
  storage?: { get: HostFn; set: HostFn; del: HostFn; list: HostFn };
37
39
  log?: { write: HostFn };
38
40
  ai?: { summarise: HostFn; extract: HostFn; classify: HostFn };
41
+ /** `codemode:routine-mail` (ADR 0590). */
42
+ "routine-mail"?: { send: HostFn };
39
43
  /** `codemode:<gatekeeper>` modules, by gatekeeper name. */
40
44
  [gatekeeper: string]: Record<string, HostFn> | undefined;
41
45
  }
@@ -56,9 +60,7 @@ export type RunResponse =
56
60
  | { ok: false; error: { code: string; message: string; details?: unknown } };
57
61
 
58
62
  /** What `codemode:ops`'s `call` returns. */
59
- export type OpsReply =
60
- | { ok: true; value: unknown }
61
- | { ok: false; error: { code: string; message: string; details?: unknown } };
63
+ export type OpsReply = RunResponse;
62
64
 
63
65
  /** Thrown by `ctx.ops.call` when the operation fails; `code` is the pipeline's error code. */
64
66
  export class OpsCallError extends Error {
@@ -72,6 +74,13 @@ export class OpsCallError extends Error {
72
74
  }
73
75
  }
74
76
 
77
+ // The host answers with an envelope so error codes survive the isolate boundary.
78
+ function unwrap(reply: unknown): unknown {
79
+ const r = reply as OpsReply;
80
+ if (r.ok) return r.value;
81
+ throw new OpsCallError(r.error.code, r.error.message, r.error.details);
82
+ }
83
+
75
84
  function missing(name: string): never {
76
85
  throw new Error(
77
86
  `Host module "${name}" is not declared. Add "${name}" to permissions.modules in defineExtension.`,
@@ -97,10 +106,7 @@ export function buildContext(
97
106
  const ops: OpsModule = raw.ops
98
107
  ? {
99
108
  call: async (operation, input) => {
100
- // The host answers with an envelope so error codes survive the isolate boundary.
101
- const reply = (await raw.ops?.call(operation, input ?? {})) as OpsReply;
102
- if (reply.ok) return reply.value as never;
103
- throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
109
+ return unwrap(await raw.ops?.call(operation, input ?? {})) as never;
104
110
  },
105
111
  }
106
112
  : absent("ops");
@@ -130,15 +136,21 @@ export function buildContext(
130
136
  classify: (text, labels) => raw.ai?.classify(text, labels) as Promise<never>,
131
137
  }
132
138
  : absent("ai");
139
+ const routine = raw["routine-mail"];
140
+ const routineMail: RoutineMailModule = routine?.send
141
+ ? {
142
+ send: async (input) => {
143
+ return unwrap(await routine.send?.(input)) as RoutineSendResult;
144
+ },
145
+ }
146
+ : absent("routine-mail");
133
147
  const gatekeeper = (name: string): GatekeeperModule => {
134
148
  const mod = raw[name] as Record<string, HostFn> | undefined;
135
149
  if (!mod?.call) return absent<GatekeeperModule>(name);
136
150
  return {
137
151
  connections: () => mod.connections?.() as Promise<never>,
138
152
  call: async (connectionId, resource, method, ...args) => {
139
- const reply = (await mod.call?.(connectionId, resource, method, args)) as OpsReply;
140
- if (reply.ok) return reply.value as never;
141
- throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
153
+ return unwrap(await mod.call?.(connectionId, resource, method, args)) as never;
142
154
  },
143
155
  types: (connectionId, resource) => mod.types?.(connectionId, resource) as Promise<string>,
144
156
  };
@@ -150,6 +162,7 @@ export function buildContext(
150
162
  log,
151
163
  ai,
152
164
  gatekeeper: gatekeeper as ExtensionContext["gatekeeper"],
165
+ routineMail,
153
166
  ...(caller ? { caller: Object.freeze({ ...caller }) as StartedBy } : {}),
154
167
  };
155
168
  }
@@ -262,7 +275,7 @@ export function buildAutomationContext(
262
275
  const n = (counts.get(step) ?? 0) + 1;
263
276
  counts.set(step, n);
264
277
  const input = notificationInput(event, to, message, `${step}:${n}`);
265
- const out = (await base.ops.call("notification.send" as never, input as never)) as {
278
+ const out = (await base.ops.call(NOTIFY_OPERATION as never, input as never)) as {
266
279
  sent?: number;
267
280
  } | null;
268
281
  return { sent: typeof out?.sent === "number" ? out.sent : 0 };
@@ -380,7 +393,7 @@ export async function runAutomation(
380
393
  };
381
394
  const r = replayed(name, "waitForEvent");
382
395
  if (r) return r.value ?? null;
383
- const timeoutMs = durationMs(declaredWait.timeout ?? "7 days");
396
+ const timeoutMs = durationMs(declaredWait.timeout ?? DEFAULT_WAIT_TIMEOUT);
384
397
  if (test) {
385
398
  testSteps.push({ name, kind: "waitForEvent", skippedMs: timeoutMs });
386
399
  return null;
@@ -0,0 +1,91 @@
1
+ // What decides a shipped pack's staff screens (stage 47, ADR 0660), as one string: the screens it
2
+ // declares and everything their gates are judged by (each gate tool's risk, audiences, permissions
3
+ // and `humanOnly`, the pack's restricted and grantable permissions and its roles). The admin's
4
+ // build computes it from each pack in the repository (screens-plugin.ts) and hands the host the
5
+ // list; `screens.mine` lists a pack's screens only when the installed row's manifest gives the same
6
+ // string. So a row that holds a pack's id with another manifest (an org's own extension taking an
7
+ // unlisted pack's id, a copy whose gate tools say less) borrows none of the pack's built screens.
8
+ import type { ExtensionManifest } from "./manifest.ts";
9
+
10
+ /** JSON with object keys sorted, so the same manifest gives the same string. */
11
+ function canonical(value: unknown): string {
12
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
13
+ if (value && typeof value === "object") {
14
+ const entries = Object.entries(value as Record<string, unknown>)
15
+ .filter(([, v]) => v !== undefined)
16
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
17
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
18
+ }
19
+ return JSON.stringify(value ?? null);
20
+ }
21
+
22
+ const sorted = (list: readonly string[] | undefined) => [...(list ?? [])].sort();
23
+
24
+ /** The gate fingerprint of a manifest's screens, or null when it declares none. */
25
+ export function screenGateFingerprint(m: Partial<ExtensionManifest>): string | null {
26
+ const screens = m.screens ?? {};
27
+ if (!Object.keys(screens).length) return null;
28
+ const toolNames = new Set(Object.values(screens).flatMap((s) => s.opens ?? []));
29
+ const tools = Object.fromEntries(
30
+ [...toolNames].sort().map((name) => {
31
+ const tool = m.tools?.[name];
32
+ return [
33
+ name,
34
+ tool
35
+ ? {
36
+ risk: tool.risk,
37
+ audiences: sorted(tool.audiences ?? ["staff"]),
38
+ permission: sorted(
39
+ tool.permission === undefined
40
+ ? []
41
+ : typeof tool.permission === "string"
42
+ ? [tool.permission]
43
+ : tool.permission,
44
+ ),
45
+ humanOnly: tool.humanOnly === true,
46
+ grantLiftsRoleLimits: tool.grantLiftsRoleLimits === true,
47
+ // ADR 0652: only when set, so a pack declaring neither keeps its fingerprint.
48
+ ...(tool.anyStaff ? { anyStaff: true } : {}),
49
+ ...(tool.corePermission ? { corePermission: tool.corePermission } : {}),
50
+ }
51
+ : null,
52
+ ];
53
+ }),
54
+ );
55
+ return canonical({
56
+ id: m.id,
57
+ screens: Object.fromEntries(
58
+ Object.entries(screens).map(([key, s]) => [
59
+ key,
60
+ {
61
+ label: s.label,
62
+ block: s.block,
63
+ export: s.export,
64
+ nav: s.nav ? { group: s.nav.group, order: s.nav.order ?? null } : null,
65
+ opens: [...(s.opens ?? [])],
66
+ writes: [...(s.writes ?? [])],
67
+ record: s.record ? { object: s.record.object, as: s.record.as } : null,
68
+ },
69
+ ]),
70
+ ),
71
+ tools,
72
+ restricted: sorted(m.restricted),
73
+ grantable: sorted(m.grantable),
74
+ roles: Object.fromEntries(
75
+ Object.entries(m.roles ?? {})
76
+ .sort(([a], [b]) => (a < b ? -1 : 1))
77
+ .map(([name, r]) => [
78
+ name,
79
+ {
80
+ permissions: sorted(r.permissions),
81
+ read: sorted(r.read),
82
+ today: r.today ?? null,
83
+ // Left out when absent, so a role without it keeps its fingerprint (ADR 0889).
84
+ looksAfter: r.looksAfter,
85
+ // Left out when absent too (ADR 0755).
86
+ mine: r.mine,
87
+ },
88
+ ]),
89
+ ),
90
+ });
91
+ }
@@ -114,6 +114,121 @@ export interface SellableSpec {
114
114
  * `grants`, `deposit`, `recurring`, `onePerPerson`, `maxPerOrder` or `saleWindow`.
115
115
  */
116
116
  moves?: MovesSpec;
117
+ /**
118
+ * What kind of sale this is in the finance reports, and when its money is earned (stage 52,
119
+ * ADR 0792), see FinanceSpec. Left out: category `other`, earned `at_sale`.
120
+ */
121
+ finance?: FinanceSpec;
122
+ /**
123
+ * The records are goods (stage 37, ADR 0682): things handed over or sent (a variant of an item
124
+ * in a shop), see GoodsSpec. An order with goods needs a delivery (`delivery`), and each goods
125
+ * line must be sold in the order's channel. Not with `deposit`, `recurring`, `moves` or
126
+ * `delivery`.
127
+ */
128
+ goods?: GoodsSpec;
129
+ /**
130
+ * The records are ways of getting goods to the buyer (stage 37, ADR 0682): a delivery option,
131
+ * see DeliverySpec. Never a line of `lines`: the buyer chooses one in `order.start`'s and
132
+ * `order.quote`'s `delivery`, and the host prices it (ADR 0685). Not with `goods`, `deposit`,
133
+ * `recurring`, `moves`, `onePerPerson` or `maxPerOrder` (one per order), nor beside `stock`.
134
+ */
135
+ delivery?: DeliverySpec;
136
+ }
137
+
138
+ /** Where goods are sold (stage 37 decision 3, ADR 0682): a select field holds one of these. */
139
+ export const SOLD_IN = ["online", "in_person", "both"] as const;
140
+ export type SoldIn = (typeof SOLD_IN)[number];
141
+
142
+ /** How a delivery option gets goods to the buyer (ADR 0682). */
143
+ export const DELIVERY_KINDS = ["post", "collect", "here"] as const;
144
+ export type DeliveryKind = (typeof DELIVERY_KINDS)[number];
145
+
146
+ /**
147
+ * Goods (ADR 0682). Every order with goods has a channel the host works out, never the caller's:
148
+ * a `post` or `collect` delivery is `online`, a `here` delivery ("take it now") is `in_person`.
149
+ *
150
+ * - `soldIn`: where a record is sold: a select field whose values are among `online`,
151
+ * `in_person` and `both`, of this object or through up to two relations (`item.whereSold`: a
152
+ * variant is sold where its item is). Left out or empty: both. A line not sold in the order's
153
+ * channel is refused (`rule: "not_sold_here"`), on every path.
154
+ */
155
+ export interface GoodsSpec {
156
+ soldIn?: string;
157
+ }
158
+
159
+ /**
160
+ * A delivery option (ADR 0682, priced by ADR 0685). A record is one way of getting an order's
161
+ * goods to the buyer; its object is sellable, so it has a price (which may be 0), a tax code and
162
+ * what a paid line grants (a shipment to pack, for `post` and `collect`; nothing is granted for a
163
+ * `here` record).
164
+ *
165
+ * - `kind`: a select field whose values are among `post` (an address is needed, in one of the
166
+ * option's countries), `collect` (at a place the record says; no address) and `here` (take it
167
+ * now, in person; no address).
168
+ * - `freeOver`: a currency or number field: when the goods on the order cost at least this
169
+ * (before the delivery), the delivery costs nothing. Empty: never free.
170
+ * - `countries`: a text field: the two-letter country codes (ISO 3166-1) a `post` record posts
171
+ * to, separated by commas or spaces; or `*`, everywhere no other post option of the object
172
+ * names. Empty: it posts nowhere yet.
173
+ * - `active`: a boolean field: a record with it off cannot be chosen.
174
+ */
175
+ export interface DeliverySpec {
176
+ kind: string;
177
+ freeOver?: string;
178
+ countries?: string;
179
+ active?: string;
180
+ }
181
+
182
+ /** How a sale's money is earned (ADR 0792), as the Unearned report reads it. */
183
+ export const EARNED = ["at_sale", "over_period", "per_use", "at_date"] as const;
184
+ export type Earned = (typeof EARNED)[number];
185
+
186
+ /**
187
+ * What kind of sale a sellable object is in the finance reports (stage 52, ADR 0792). It only
188
+ * labels the object's own sales: it prices nothing, grants nothing and moves no money. Which way
189
+ * the books treat a sale is the business's accountant's call; this says what the reports show.
190
+ *
191
+ * - `category`: the kind of sale its lines are counted under in Sales, Tax, Refunds and the book
192
+ * entries' `sales:<key>` and `refunds:<key>` headings. `key` is stable (lower case, digits and
193
+ * `_`); `label` is what the reports call it until an admin renames it. Two objects with the same
194
+ * key are one category, so this extension gives them one label.
195
+ * - `earned`: when the money is earned, for the Unearned report (cash is counted when it moved,
196
+ * whatever this says):
197
+ * - `at_sale`: when it is paid (a course, goods);
198
+ * - `over_period`: day by day over the order's period, from its start to its end (a plan's
199
+ * paid period); only on a plan (`recurring`);
200
+ * - `per_use`: as the uses of what a paid line grants are spent, the rest when it expires (a
201
+ * class pass); only when `grants` grants an object that holds uses (`allowance.holds`);
202
+ * - `at_date`: on the date in `at` (an event's start).
203
+ * - `at`: with `at_date`, a date or datetime field of this object, or `<relation>.<field>` through
204
+ * up to two relations (`event.startsAt`, `class.startsAt`).
205
+ *
206
+ * A line whose object issues stored value or a voucher (stage 34) is held for customers, not a
207
+ * sale, whatever it declares.
208
+ */
209
+ export interface FinanceSpec {
210
+ category?: { key: string; label: string };
211
+ earned?: Earned;
212
+ at?: string;
213
+ }
214
+
215
+ /** What `sellable.finance` comes to when it, or a part of it, is left out (ADR 0792). */
216
+ export const FINANCE_DEFAULTS = {
217
+ category: { key: "other", label: "Other" },
218
+ earned: "at_sale",
219
+ } as const satisfies Required<Omit<FinanceSpec, "at">>;
220
+
221
+ /** A sellable object's finance declaration with its defaults filled (ADR 0792). */
222
+ export function sellableFinance(finance: FinanceSpec | undefined): {
223
+ category: { key: string; label: string };
224
+ earned: Earned;
225
+ at?: string;
226
+ } {
227
+ return {
228
+ category: finance?.category ?? FINANCE_DEFAULTS.category,
229
+ earned: finance?.earned ?? FINANCE_DEFAULTS.earned,
230
+ ...(finance?.at !== undefined ? { at: finance.at } : {}),
231
+ };
117
232
  }
118
233
 
119
234
  /**
@@ -192,8 +307,23 @@ export interface RecurringSpec {
192
307
  * `subscriptions:manage`, as a person; while paused nothing is charged, granted or spent.
193
308
  */
194
309
  pause?: { minDays?: string; maxDays?: string };
310
+ /**
311
+ * A cooling-off period (stage 44 step 7, decision 11, ADR 0647): `setting` names a number setting
312
+ * of this extension holding whole days (0: off), which a person changes (`personApproves`),
313
+ * between 0 and `MAX_COOLING_OFF_DAYS`. A new member (a subscription started here without a
314
+ * continuation offer) may end their subscription within that many days of the provider-confirmed
315
+ * start, counted in the business's time zone to the end of the last day, for a full refund of
316
+ * what they paid; each refund waits for a person with `orders:refund` (ADR 0429). Once per
317
+ * holder. The days in force when a subscription started are kept with it: a setting shortened
318
+ * later never shortens that member's window. What any law requires is the business's to
319
+ * confirm; the platform only holds the number.
320
+ */
321
+ coolingOff?: { setting: string };
195
322
  }
196
323
 
324
+ /** The longest cooling-off period the host keeps (days); a longer setting reads as this. */
325
+ export const MAX_COOLING_OFF_DAYS = 90;
326
+
197
327
  /** Where a field of what a subscription grants gets its value (see RecurringSpec.grants). */
198
328
  export type RecurringGrantSource =
199
329
  | "item"
@@ -349,6 +479,7 @@ export const sellableManifestSchema = z
349
479
  .object({ minDays: fieldName.optional(), maxDays: fieldName.optional() })
350
480
  .strict()
351
481
  .optional(),
482
+ coolingOff: z.object({ setting: fieldName }).strict().optional(),
352
483
  grants: z
353
484
  .object({
354
485
  object: z.string().max(40),
@@ -371,6 +502,33 @@ export const sellableManifestSchema = z
371
502
  })
372
503
  .strict()
373
504
  .optional(),
505
+ finance: z
506
+ .object({
507
+ category: z
508
+ .object({
509
+ key: z.string().regex(/^[a-z][a-z0-9_]{0,39}$/, "Lower case letters, digits and _"),
510
+ label: z.string().min(1).max(60),
511
+ })
512
+ .strict()
513
+ .optional(),
514
+ earned: z.enum(EARNED).optional(),
515
+ at: z.string().max(130).optional(),
516
+ })
517
+ .strict()
518
+ .optional(),
519
+ goods: z
520
+ .object({ soldIn: z.string().max(130).optional() })
521
+ .strict()
522
+ .optional(),
523
+ delivery: z
524
+ .object({
525
+ kind: fieldName,
526
+ freeOver: fieldName.optional(),
527
+ countries: fieldName.optional(),
528
+ active: fieldName.optional(),
529
+ })
530
+ .strict()
531
+ .optional(),
374
532
  })
375
533
  .strict();
376
534
  export type SellableManifest = z.infer<typeof sellableManifestSchema>;
@@ -444,6 +602,34 @@ export function checkObjectSellable(
444
602
  contract(`${path}.recurring.pause.${key}`, `"${days}" must be a number field of ${name}`);
445
603
  }
446
604
  }
605
+ const coolingOff = sellable.recurring.coolingOff;
606
+ if (coolingOff) {
607
+ const settings = m.settings ?? {};
608
+ const setting = Object.hasOwn(settings, coolingOff.setting)
609
+ ? settings[coolingOff.setting]
610
+ : undefined;
611
+ const at = `${path}.recurring.coolingOff.setting`;
612
+ if (setting?.type !== "number") {
613
+ contract(at, `"${coolingOff.setting}" must be a number setting of ${m.id}`);
614
+ } else if (setting.personApproves !== true) {
615
+ // Refunds follow from it: a person's to change, never an AI's (decision 11).
616
+ contract(
617
+ at,
618
+ `"${coolingOff.setting}" must be a setting a person approves (personApproves): the cooling-off days are never an AI's to change`,
619
+ );
620
+ } else if (
621
+ setting.min === undefined ||
622
+ setting.min < 0 ||
623
+ setting.max === undefined ||
624
+ setting.max > MAX_COOLING_OFF_DAYS ||
625
+ (typeof setting.default === "number" && setting.default !== 0)
626
+ ) {
627
+ contract(
628
+ at,
629
+ `"${coolingOff.setting}" must be bounded from 0 to at most ${MAX_COOLING_OFF_DAYS} days, and off (0 or no default) until a person sets it`,
630
+ );
631
+ }
632
+ }
447
633
  if (sellable.onePerPerson !== undefined) {
448
634
  contract(
449
635
  `${path}.onePerPerson`,
@@ -493,6 +679,10 @@ export function checkObjectSellable(
493
679
  }
494
680
  if (sellable.grants) checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
495
681
  if (sellable.moves) checkMoves(m, name, object, sellable.moves, `${path}.moves`, contract);
682
+ if (sellable.goods || sellable.delivery) checkGoods(m, name, object, path, contract);
683
+ if (sellable.finance) {
684
+ checkFinance(m, name, object, sellable.finance, `${path}.finance`, contract);
685
+ }
496
686
  const place = sellable.tax?.place;
497
687
  if (place) {
498
688
  let holder: ObjectManifest | undefined = object;
@@ -530,6 +720,160 @@ export function checkObjectSellable(
530
720
  }
531
721
  }
532
722
 
723
+ /** A select field's option values (empty when it is not a select field). */
724
+ function selectValues(field: FieldManifest | undefined): string[] | null {
725
+ if (!field || field.type !== "select" || field.many) return null;
726
+ return (field.options ?? []).map((option) =>
727
+ typeof option === "string" ? option : (option as { value: string }).value,
728
+ );
729
+ }
730
+
731
+ /**
732
+ * Checks `sellable.goods` and `sellable.delivery` (ADR 0682): where goods are sold is a select of
733
+ * `online`, `in_person` and `both`; a delivery option's kind a select of `post`, `collect` and
734
+ * `here`, with its other fields of the right types; and neither is bought by deposit, by
735
+ * subscription or by moving a record. A delivery is one per order and has no stock.
736
+ */
737
+ function checkGoods(
738
+ m: ExtensionManifest,
739
+ name: string,
740
+ object: ObjectManifest,
741
+ path: string,
742
+ contract: (path: string, message: string) => void,
743
+ ): void {
744
+ const sellable = object.sellable as SellableManifest;
745
+ const fieldOf = (local: string): FieldManifest | undefined =>
746
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
747
+ if (sellable.goods && sellable.delivery) {
748
+ contract(`${path}.delivery`, "A record is goods or a delivery option, not both");
749
+ }
750
+ const what = sellable.goods ? "goods" : "a delivery option";
751
+ for (const key of ["deposit", "recurring", "moves"] as const) {
752
+ if (sellable[key] !== undefined) {
753
+ contract(`${path}.${key}`, `${name} is ${what}, sold whole on an order: it has no ${key}`);
754
+ }
755
+ }
756
+ const soldIn = sellable.goods?.soldIn;
757
+ if (soldIn !== undefined) {
758
+ const values = selectValues(resolveFieldPath(m, object, soldIn));
759
+ if (!values || values.some((v) => !(SOLD_IN as readonly string[]).includes(v))) {
760
+ contract(
761
+ `${path}.goods.soldIn`,
762
+ `"${soldIn}" must be a select field (of ${name}, or through its relations) whose values are among ${SOLD_IN.join(", ")}`,
763
+ );
764
+ }
765
+ }
766
+ const delivery = sellable.delivery;
767
+ if (!delivery) return;
768
+ for (const key of ["onePerPerson", "maxPerOrder"] as const) {
769
+ if (sellable[key] !== undefined) {
770
+ contract(`${path}.${key}`, `A delivery option is one per order: it has no ${key}`);
771
+ }
772
+ }
773
+ if (object.stock) {
774
+ contract(`objects.${name}.stock`, "A delivery option is not counted on a shelf: no stock");
775
+ }
776
+ const kinds = selectValues(fieldOf(delivery.kind));
777
+ if (!kinds?.length || kinds.some((v) => !(DELIVERY_KINDS as readonly string[]).includes(v))) {
778
+ contract(
779
+ `${path}.delivery.kind`,
780
+ `"${delivery.kind}" must be a select field of ${name} whose values are among ${DELIVERY_KINDS.join(", ")}`,
781
+ );
782
+ }
783
+ if (delivery.freeOver !== undefined) {
784
+ const field = fieldOf(delivery.freeOver);
785
+ if (!field || !NUMERIC.has(field.type) || field.many) {
786
+ contract(
787
+ `${path}.delivery.freeOver`,
788
+ `"${delivery.freeOver}" must be a currency or number field of ${name}`,
789
+ );
790
+ }
791
+ }
792
+ if (delivery.countries !== undefined) {
793
+ const field = fieldOf(delivery.countries);
794
+ if (!field || !TEXT.has(field.type) || field.many) {
795
+ contract(
796
+ `${path}.delivery.countries`,
797
+ `"${delivery.countries}" must be a text field of ${name}`,
798
+ );
799
+ }
800
+ }
801
+ if (delivery.active !== undefined) {
802
+ const field = fieldOf(delivery.active);
803
+ if (!field || field.type !== "boolean" || field.many) {
804
+ contract(
805
+ `${path}.delivery.active`,
806
+ `"${delivery.active}" must be a boolean field of ${name}`,
807
+ );
808
+ }
809
+ }
810
+ }
811
+
812
+ /**
813
+ * Checks `sellable.finance` (ADR 0792): each way of earning names what the host reads to work it
814
+ * out, and one category key has one label across this extension.
815
+ */
816
+ function checkFinance(
817
+ m: ExtensionManifest,
818
+ name: string,
819
+ object: ObjectManifest,
820
+ finance: NonNullable<SellableManifest["finance"]>,
821
+ path: string,
822
+ contract: (path: string, message: string) => void,
823
+ ): void {
824
+ const sellable = object.sellable as SellableManifest;
825
+ const earned = finance.earned ?? FINANCE_DEFAULTS.earned;
826
+ if (earned === "at_date") {
827
+ if (finance.at === undefined) {
828
+ contract(`${path}.at`, "at_date names its date: at, a date or datetime field");
829
+ } else {
830
+ const at = resolveFieldPath(m, object, finance.at);
831
+ if (!at || at.many || !DATES.has(at.type)) {
832
+ contract(
833
+ `${path}.at`,
834
+ `"${finance.at}" must be a date or datetime field of ${name}, or <relation>.<field> through up to two relations, every field on the way declared by this extension`,
835
+ );
836
+ }
837
+ }
838
+ } else if (finance.at !== undefined) {
839
+ contract(`${path}.at`, "at is the date of at_date: declare earned: at_date, or remove at");
840
+ }
841
+ if (earned === "over_period" && !sellable.recurring) {
842
+ contract(
843
+ `${path}.earned`,
844
+ "over_period is earned over a paid period: only a plan (recurring) has one",
845
+ );
846
+ }
847
+ if (earned === "per_use") {
848
+ const grants = sellable.grants;
849
+ const local = grants?.object.startsWith(`${m.id}.`)
850
+ ? grants.object.slice(m.id.length + 1)
851
+ : grants?.object;
852
+ const granted =
853
+ local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
854
+ if (!granted?.allowance || !("holds" in granted.allowance)) {
855
+ contract(
856
+ `${path}.earned`,
857
+ "per_use is earned as uses are spent: grants must grant an object that holds uses (allowance.holds)",
858
+ );
859
+ }
860
+ }
861
+ const category = finance.category;
862
+ if (category) {
863
+ for (const [other, o] of Object.entries(m.objects)) {
864
+ if (other === name) continue;
865
+ const theirs = o.sellable?.finance?.category;
866
+ if (theirs?.key === category.key && theirs.label !== category.label) {
867
+ contract(
868
+ `${path}.category.label`,
869
+ `${other} names category "${category.key}" "${theirs.label}": one category has one label`,
870
+ );
871
+ break;
872
+ }
873
+ }
874
+ }
875
+ }
876
+
533
877
  /**
534
878
  * Checks `sellable.moves` (ADR 0560): each of these is a way the order's batch could otherwise fail
535
879
  * (a payment the host could not apply), or a record someone could hold with no order.
@@ -15,11 +15,16 @@ export const SLUG_FROM_TITLE_MAX = 80;
15
15
  * a hyphen, at most SLUG_FROM_TITLE_MAX characters. Empty when nothing is left.
16
16
  */
17
17
  export function slugify(title: string): string {
18
- const plain = title
18
+ return hyphenate(title, SLUG_FROM_TITLE_MAX);
19
+ }
20
+
21
+ /** Text as words of lowercase letters and digits joined by hyphens, accents dropped, at most `max`. */
22
+ export function hyphenate(text: string, max: number): string {
23
+ const plain = text
19
24
  .normalize("NFKD")
20
25
  .replace(/[̀-ͯ]/g, "")
21
26
  .toLowerCase()
22
27
  .replace(/[^a-z0-9]+/g, "-")
23
28
  .replace(/^-+|-+$/g, "");
24
- return plain.slice(0, SLUG_FROM_TITLE_MAX).replace(/-+$/g, "");
29
+ return plain.slice(0, max).replace(/-+$/g, "");
25
30
  }