@composable-os/cli 0.0.0-stage → 0.1.0-beta.11

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 (184) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/accounts-UHYLCLEY.js +45 -0
  4. package/dist/blocks-5IFU25J6.js +233 -0
  5. package/dist/chunk-2ABSVMGB.js +13 -0
  6. package/dist/chunk-2IVEVPMY.js +669 -0
  7. package/dist/chunk-2TWV3SVB.js +349 -0
  8. package/dist/chunk-2XC5JLBO.js +1931 -0
  9. package/dist/chunk-324WJXNP.js +320 -0
  10. package/dist/chunk-5KSXSK7Y.js +47 -0
  11. package/dist/chunk-6ELZRNUU.js +116 -0
  12. package/dist/chunk-6UWRT4VM.js +220 -0
  13. package/dist/chunk-6WGFA2IV.js +643 -0
  14. package/dist/chunk-6XTU2MTP.js +11278 -0
  15. package/dist/chunk-7CQGMVDO.js +63 -0
  16. package/dist/chunk-7D4GKZOX.js +615 -0
  17. package/dist/chunk-7OGCMQXG.js +284 -0
  18. package/dist/chunk-DHS2CV2M.js +139 -0
  19. package/dist/chunk-DU6OIFOU.js +2358 -0
  20. package/dist/chunk-E4WCYTCT.js +347 -0
  21. package/dist/chunk-E64SG24J.js +88 -0
  22. package/dist/chunk-FJIZGS5Q.js +698 -0
  23. package/dist/chunk-GYTEW66E.js +50 -0
  24. package/dist/chunk-HDIOVFAZ.js +544 -0
  25. package/dist/chunk-K34UKWEI.js +298 -0
  26. package/dist/chunk-KGHA67HG.js +765 -0
  27. package/dist/chunk-LAAL4YGR.js +365 -0
  28. package/dist/chunk-LO6WGU5Y.js +26189 -0
  29. package/dist/chunk-MBIKVRAC.js +1425 -0
  30. package/dist/chunk-P6UWZ6QQ.js +426 -0
  31. package/dist/chunk-PDD2ETVF.js +1302 -0
  32. package/dist/chunk-UB4I2QKR.js +31575 -0
  33. package/dist/chunk-WHKJGF36.js +2418 -0
  34. package/dist/chunk-XIDLW3EP.js +15471 -0
  35. package/dist/chunk-YFTLIEWU.js +504 -0
  36. package/dist/chunk-YNUZRTPH.js +182 -0
  37. package/dist/chunk-ZAWES2UD.js +9364 -0
  38. package/dist/chunk-ZZFWMVJO.js +704 -0
  39. package/dist/cli-5UNY5G5L.js +136 -0
  40. package/dist/cli-UYZMVQMR.js +24534 -0
  41. package/dist/cli.js +25 -0
  42. package/dist/client-repo-SE4EKG6W.js +55 -0
  43. package/dist/create.js +25 -0
  44. package/dist/fields-FTWWMD7N.js +50 -0
  45. package/dist/grants-LOW6TSWD.js +32 -0
  46. package/dist/invoke-6KVT6WJI.js +41 -0
  47. package/dist/moves-E2HKYCTK.js +41 -0
  48. package/dist/order-U4KZLLSJ.js +19 -0
  49. package/dist/person-UHLVBVLR.js +67 -0
  50. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  51. package/dist/platform/migrations/0001_init.sql +59 -0
  52. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  53. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  54. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  55. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  56. package/dist/platform/migrations/0006_search.sql +223 -0
  57. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  58. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  59. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  60. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  61. package/dist/platform/migrations/0020_extensions.sql +373 -0
  62. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  63. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  64. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  65. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  66. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  67. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  68. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  69. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  70. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  71. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  72. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  73. package/dist/platform/migrations/0110_integrations.sql +103 -0
  74. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  75. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  76. package/dist/platform/migrations/0130_automations.sql +113 -0
  77. package/dist/platform/migrations/0131_notifications.sql +29 -0
  78. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  79. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  80. package/dist/platform/migrations/0160_releases.sql +41 -0
  81. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  82. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  83. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  84. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  85. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  86. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  87. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  88. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  89. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  90. package/dist/platform/migrations/0250_judge.sql +11 -0
  91. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  92. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  93. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  94. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  95. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  96. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  97. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  98. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  99. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  100. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  101. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  102. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  103. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  104. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  105. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  106. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  107. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  108. package/dist/platform/migrations/0365_routines.sql +38 -0
  109. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  110. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  111. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  112. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  113. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  114. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  115. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  116. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  117. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  118. package/dist/platform/migrations/0421_orders.sql +134 -0
  119. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  120. package/dist/platform/migrations/0440_capacity.sql +100 -0
  121. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  122. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  123. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  124. package/dist/platform/migrations/0460_content.sql +59 -0
  125. package/dist/platform/migrations/0461_media.sql +52 -0
  126. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  127. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  128. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  129. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  130. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  131. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  132. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  133. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  134. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  135. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  136. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  137. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  138. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  139. package/dist/platform/migrations/0533_allowances.sql +262 -0
  140. package/dist/platform/migrations/0560_recurring.sql +75 -0
  141. package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
  142. package/dist/platform/migrations/0581_once_per_person.sql +34 -0
  143. package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
  144. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  145. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  146. package/dist/platform/migrations/0650_person_links.sql +90 -0
  147. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  148. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  149. package/dist/platform/sdk/allowance.ts +522 -0
  150. package/dist/platform/sdk/automation-check.ts +534 -0
  151. package/dist/platform/sdk/automation.ts +743 -0
  152. package/dist/platform/sdk/behaviour.ts +215 -0
  153. package/dist/platform/sdk/capacity.ts +303 -0
  154. package/dist/platform/sdk/contract.ts +909 -0
  155. package/dist/platform/sdk/document.ts +935 -0
  156. package/dist/platform/sdk/field-types.ts +111 -0
  157. package/dist/platform/sdk/formula/ast.ts +72 -0
  158. package/dist/platform/sdk/formula/compile.ts +454 -0
  159. package/dist/platform/sdk/formula/index.ts +4 -0
  160. package/dist/platform/sdk/formula/parser.ts +417 -0
  161. package/dist/platform/sdk/index.ts +36 -0
  162. package/dist/platform/sdk/manifest.ts +1785 -0
  163. package/dist/platform/sdk/media.ts +108 -0
  164. package/dist/platform/sdk/permissions.ts +60 -0
  165. package/dist/platform/sdk/recurring.ts +321 -0
  166. package/dist/platform/sdk/renamed.ts +63 -0
  167. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  168. package/dist/platform/sdk/rich-text.ts +221 -0
  169. package/dist/platform/sdk/runtime.ts +410 -0
  170. package/dist/platform/sdk/sellable.ts +1138 -0
  171. package/dist/platform/sdk/slug.ts +25 -0
  172. package/dist/platform/sdk/states.ts +598 -0
  173. package/dist/platform/sdk/testing.ts +847 -0
  174. package/dist/platform/sdk/unique.ts +81 -0
  175. package/dist/products-2H5DR232.js +11 -0
  176. package/dist/run-7P4RQALH.js +648 -0
  177. package/dist/run-PO3W5BFA.js +508 -0
  178. package/dist/run-ZCGFMEZF.js +309 -0
  179. package/dist/src-CRO35DYY.js +46 -0
  180. package/dist/src-I3IJ4NKC.js +354 -0
  181. package/dist/token-MOJUA2U6.js +70 -0
  182. package/dist/token-util-TENRN4V7.js +6 -0
  183. package/dist/visibility-TVXZ67FD.js +41 -0
  184. package/package.json +33 -4
@@ -0,0 +1,1931 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ PROVIDERS,
4
+ parseRoleLayer
5
+ } from "./chunk-KGHA67HG.js";
6
+ import {
7
+ ACTORS,
8
+ CompiledQuery,
9
+ ConflictError,
10
+ PERMISSIONS,
11
+ RISK_CLASSES,
12
+ ValidationError,
13
+ registryFieldName,
14
+ sql,
15
+ visibleSource
16
+ } from "./chunk-6XTU2MTP.js";
17
+ import {
18
+ getObject
19
+ } from "./chunk-YFTLIEWU.js";
20
+ import {
21
+ external_exports,
22
+ moveOrigins
23
+ } from "./chunk-LO6WGU5Y.js";
24
+
25
+ // ../core/src/ids.ts
26
+ var ID_PREFIXES = {
27
+ person: "per",
28
+ organisation: "org",
29
+ affiliation: "aff",
30
+ activity: "act",
31
+ task: "tsk",
32
+ user: "usr",
33
+ view: "vw",
34
+ audit: "aud",
35
+ tag: "tag",
36
+ email: "eml",
37
+ phone: "phn",
38
+ domain: "dom",
39
+ address: "adr",
40
+ /** Records of extension objects (stage 3). */
41
+ record: "rec",
42
+ /** Extension run history rows. */
43
+ extensionRun: "xrn",
44
+ changeSet: "chs",
45
+ pendingAction: "pac",
46
+ connectedApp: "cap",
47
+ /** Integration connections (stage 6, ADR 0050). */
48
+ connection: "con",
49
+ integrationEvent: "iev",
50
+ jobChange: "jcs",
51
+ /** Stage history rows (ADR 0100). */
52
+ stageHistory: "sth",
53
+ dashboard: "dsh",
54
+ /** Automation runs (ADR 0130). */
55
+ automationRun: "arn",
56
+ /** Notifications (ADR 0132). */
57
+ notification: "ntf",
58
+ /** Automation events outbox rows (ADR 0171). */
59
+ outbox: "obx",
60
+ /** Admin notification channel routes (ADR 0172). */
61
+ notificationRoute: "nrt",
62
+ /** In-app assistant conversations (ADR 0200). */
63
+ assistantConversation: "asc",
64
+ /** A person's one assistant thread (ADR 0340). */
65
+ assistantThread: "ath",
66
+ /** A memory line (ADR 0342). */
67
+ memory: "mem",
68
+ /** A personal routine (ADR 0343). */
69
+ routine: "rtn",
70
+ /** Policy adjudicator verdicts (ADR 0204). */
71
+ adjudication: "adj",
72
+ /** Assignment rules (ADR 0246). */
73
+ assignmentRule: "asr",
74
+ /** An agent (ADR 0344). */
75
+ agentJob: "job",
76
+ /** One approval's claim on the actions it applies (ADR 0345). */
77
+ execution: "exe",
78
+ /** A customer account (stage 22, ADR 0402): a Person who can sign in. Never a core_user. */
79
+ customer: "cus",
80
+ /** A request to erase a Person, made when a customer deletes their account (stage 22). */
81
+ eraseRequest: "erq",
82
+ /** An order and one of its lines (stage 25, ADR 0426). */
83
+ order: "ord",
84
+ orderLine: "orl",
85
+ /** A refund of an order's payment (stage 25, ADR 0429). */
86
+ refund: "rfd",
87
+ /** A subscription the payment provider runs (stage 32a, ADR 0485). */
88
+ subscription: "sbs",
89
+ /** A continuation offer: free until a date for a subscriber moving from elsewhere (ADR 0491). */
90
+ subscriptionOffer: "sof",
91
+ /** A plan change or a pause the host asked a subscription's provider for (ADRs 0530, 0531). */
92
+ subscriptionChange: "sbc",
93
+ /** A native app's signed-in session on the HTTP surface (stage 23, ADR 0419). */
94
+ deviceSession: "dvs",
95
+ /** Places claimed from a record's capacity (stage 26, ADR 0430). */
96
+ capacityClaim: "clm",
97
+ /** A use spent from an allowance holder by a spender (stage 32b, ADR 0493). */
98
+ allowanceUse: "alu",
99
+ /** A Person's one purchase of something sold once per Person (stage 32b, ADR 0512). */
100
+ sellableOnce: "sbo",
101
+ /** An invite for a staff account (ADR 0455). */
102
+ userInvite: "uin",
103
+ // Stage 28 (ADR 0444): a picture of the media library.
104
+ media: "med",
105
+ /** A family link: a guardian and a dependant (stage 31a, ADR 0540). */
106
+ personLink: "pln",
107
+ refundDue: "rdu"
108
+ };
109
+ var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
110
+ var lastTime = -1;
111
+ var lastRandom = [];
112
+ function randomDigits() {
113
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
114
+ return Array.from(bytes, (byte) => byte & 31);
115
+ }
116
+ function increment(digits) {
117
+ const next = [...digits];
118
+ for (let i = next.length - 1; i >= 0; i--) {
119
+ const digit = next[i] ?? 0;
120
+ if (digit < 31) {
121
+ next[i] = digit + 1;
122
+ return next;
123
+ }
124
+ next[i] = 0;
125
+ }
126
+ throw new Error("ULID random component overflowed within one millisecond");
127
+ }
128
+ function ulid(now = Date.now()) {
129
+ let random;
130
+ if (now <= lastTime) {
131
+ random = increment(lastRandom);
132
+ now = lastTime;
133
+ } else {
134
+ random = randomDigits();
135
+ lastTime = now;
136
+ }
137
+ lastRandom = random;
138
+ let time = "";
139
+ let t = now;
140
+ for (let i = 0; i < 10; i++) {
141
+ time = ALPHABET[t % 32] + time;
142
+ t = Math.floor(t / 32);
143
+ }
144
+ return time + random.map((digit) => ALPHABET[digit]).join("");
145
+ }
146
+ function newId(kind, now) {
147
+ return `${ID_PREFIXES[kind]}_${ulid(now)}`;
148
+ }
149
+ var PROVISIONAL_ID_RE = /^[a-z]{2,4}_pending_[0-9A-HJKMNP-TV-Z]{26}$/;
150
+ var PROVISIONAL_ANYWHERE_RE = /[a-z]{2,4}_pending_[0-9A-HJKMNP-TV-Z]{26}/g;
151
+ var ANY_ID_RE = /[a-z]{2,4}_(?:pending_)?[0-9A-HJKMNP-TV-Z]{26}/g;
152
+ function toProvisionalId(id) {
153
+ const at = id.indexOf("_");
154
+ return at < 0 ? id : `${id.slice(0, at)}_pending_${id.slice(at + 1)}`;
155
+ }
156
+ function isProvisionalId(value) {
157
+ return typeof value === "string" && PROVISIONAL_ID_RE.test(value);
158
+ }
159
+ function findProvisionalIds(value) {
160
+ const text = JSON.stringify(value ?? null);
161
+ return [...new Set(text.match(PROVISIONAL_ANYWHERE_RE) ?? [])];
162
+ }
163
+ function findIds(value) {
164
+ const text = JSON.stringify(value ?? null);
165
+ return [...new Set(text.match(ANY_ID_RE) ?? [])];
166
+ }
167
+ function replaceIds(value, map) {
168
+ if (!map.size) return value;
169
+ const inString = (text) => text.replace(ANY_ID_RE, (id) => map.get(id) ?? id);
170
+ const walk = (v) => {
171
+ if (typeof v === "string") return inString(v);
172
+ if (Array.isArray(v)) return v.map(walk);
173
+ if (v && typeof v === "object") {
174
+ return Object.fromEntries(
175
+ Object.entries(v).map(([k, x]) => [inString(k), walk(x)])
176
+ );
177
+ }
178
+ return v;
179
+ };
180
+ return walk(value);
181
+ }
182
+
183
+ // ../core/src/gate.ts
184
+ var GATE_DECISIONS = ["auto", "review", "deny"];
185
+ var POLICY_PRESETS = ["cautious", "balanced", "autonomous"];
186
+ var approvalPolicySchema = external_exports.object({ preset: external_exports.enum(POLICY_PRESETS) });
187
+ var APPROVAL_POLICY_SETTING = "approval_policy";
188
+ var HUMAN_ALL_AUTO = {
189
+ read: "auto",
190
+ write: "auto",
191
+ "bulk-write": "auto",
192
+ destructive: "auto",
193
+ schema: "auto",
194
+ extension: "auto",
195
+ outbound: "auto"
196
+ };
197
+ var cautiousAi = {
198
+ read: "auto",
199
+ write: "review",
200
+ "bulk-write": "review",
201
+ destructive: "review",
202
+ schema: "review",
203
+ extension: "review",
204
+ outbound: "review"
205
+ };
206
+ var balancedAi = {
207
+ read: "auto",
208
+ write: "auto",
209
+ "bulk-write": { autoUpTo: 25, above: "review" },
210
+ destructive: "review",
211
+ schema: "review",
212
+ extension: "review",
213
+ outbound: "review"
214
+ };
215
+ var balancedMcp = { ...balancedAi, "bulk-write": "review" };
216
+ var autonomousAi = {
217
+ read: "auto",
218
+ write: "auto",
219
+ "bulk-write": "auto",
220
+ destructive: { autoUpTo: 10, above: "review" },
221
+ schema: "review",
222
+ extension: "review",
223
+ outbound: "auto"
224
+ };
225
+ var extensionRow = (bulk, destructive) => ({
226
+ read: "auto",
227
+ write: "auto",
228
+ "bulk-write": bulk,
229
+ destructive,
230
+ schema: "deny",
231
+ extension: "deny",
232
+ outbound: "review"
233
+ });
234
+ var PRESET_MATRICES = {
235
+ cautious: {
236
+ human: HUMAN_ALL_AUTO,
237
+ assistant: cautiousAi,
238
+ mcp: cautiousAi,
239
+ automation: {
240
+ read: "auto",
241
+ write: "auto",
242
+ "bulk-write": "review",
243
+ destructive: "review",
244
+ schema: "deny",
245
+ extension: "deny",
246
+ outbound: "review"
247
+ },
248
+ extension: extensionRow("review", "review")
249
+ },
250
+ balanced: {
251
+ human: HUMAN_ALL_AUTO,
252
+ assistant: balancedAi,
253
+ mcp: balancedMcp,
254
+ automation: {
255
+ read: "auto",
256
+ write: "auto",
257
+ "bulk-write": { autoUpTo: 100, above: "review" },
258
+ destructive: "review",
259
+ schema: "deny",
260
+ extension: "deny",
261
+ outbound: "review"
262
+ },
263
+ extension: extensionRow({ autoUpTo: 100, above: "review" }, "review")
264
+ },
265
+ autonomous: {
266
+ human: HUMAN_ALL_AUTO,
267
+ assistant: autonomousAi,
268
+ mcp: autonomousAi,
269
+ automation: { ...autonomousAi, schema: "deny", extension: "deny" },
270
+ extension: extensionRow("auto", { autoUpTo: 10, above: "review" })
271
+ }
272
+ };
273
+ var ruleSchema = external_exports.union([
274
+ external_exports.enum(GATE_DECISIONS),
275
+ external_exports.object({ autoUpTo: external_exports.number().int().min(0), above: external_exports.enum(["review", "deny"]) }).strict()
276
+ ]);
277
+ var floorSchema = external_exports.partialRecord(
278
+ external_exports.enum([...ACTORS, "*"]),
279
+ external_exports.partialRecord(external_exports.enum([...RISK_CLASSES, "*"]), ruleSchema)
280
+ );
281
+ var STRICTNESS = { auto: 0, review: 1, deny: 2 };
282
+ function stricter(a, b) {
283
+ return STRICTNESS[a] >= STRICTNESS[b] ? a : b;
284
+ }
285
+ function applyRule(rule, bulkSize) {
286
+ if (typeof rule === "string") return rule;
287
+ return bulkSize <= rule.autoUpTo ? "auto" : rule.above;
288
+ }
289
+ function evaluateGate(request, policy, floor = {}) {
290
+ const bulkSize = Math.max(1, request.bulkSize ?? 1);
291
+ let policyDecision = applyRule(
292
+ PRESET_MATRICES[policy.preset][request.actor][request.risk],
293
+ bulkSize
294
+ );
295
+ if (request.risk === "outbound" && policyDecision === "review" && policy.preset === "balanced" && request.outbound?.autoApprovable && request.outbound.enabled) {
296
+ policyDecision = "auto";
297
+ }
298
+ const floorRules = [
299
+ floor[request.actor]?.[request.risk],
300
+ floor[request.actor]?.["*"],
301
+ floor["*"]?.[request.risk],
302
+ floor["*"]?.["*"]
303
+ ].filter((rule) => rule !== void 0);
304
+ let decision = policyDecision;
305
+ let floorDecision;
306
+ for (const rule of floorRules) {
307
+ const fromFloor = applyRule(rule, bulkSize);
308
+ floorDecision = floorDecision ? stricter(floorDecision, fromFloor) : fromFloor;
309
+ decision = stricter(decision, fromFloor);
310
+ }
311
+ return {
312
+ decision,
313
+ policyDecision,
314
+ ...floorDecision ? { floorDecision } : {},
315
+ preset: policy.preset
316
+ };
317
+ }
318
+ function evaluateOutsideGate(risk, floor = {}) {
319
+ if (risk !== "read" && risk !== "write") return "deny";
320
+ const rules = [floor["*"]?.[risk], floor["*"]?.["*"]].filter(
321
+ (rule) => rule !== void 0
322
+ );
323
+ return rules.some((rule) => applyRule(rule, 1) === "deny") ? "deny" : "auto";
324
+ }
325
+ function isLoosening(from, to) {
326
+ const a = PRESET_MATRICES[from];
327
+ const b = PRESET_MATRICES[to];
328
+ for (const actor of ACTORS) {
329
+ for (const risk of RISK_CLASSES) {
330
+ for (const size of [1, 10, 11, 25, 26, 100, 101, 1e4]) {
331
+ if (STRICTNESS[applyRule(b[actor][risk], size)] < STRICTNESS[applyRule(a[actor][risk], size)])
332
+ return true;
333
+ }
334
+ }
335
+ }
336
+ return false;
337
+ }
338
+
339
+ // ../core/src/settings.ts
340
+ async function loadApprovalPolicy(db) {
341
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", APPROVAL_POLICY_SETTING).executeTakeFirst();
342
+ if (!row) return { preset: "cautious" };
343
+ try {
344
+ const parsed = approvalPolicySchema.safeParse(JSON.parse(row.value));
345
+ return parsed.success ? parsed.data : { preset: "cautious" };
346
+ } catch {
347
+ return { preset: "cautious" };
348
+ }
349
+ }
350
+ var BASE_CURRENCY_SETTING = "base_currency";
351
+ var ORG_NAME_SETTING = "org_name";
352
+ var ORG_LOGO_SETTING = "org_logo";
353
+ var ORG_TIMEZONE_SETTING = "org_timezone";
354
+ var ASSISTANT_NAME_SETTING = "assistant_name";
355
+ var DEFAULT_ASSISTANT_NAME = "Assistant";
356
+ function parseJson(value) {
357
+ if (value === void 0) return null;
358
+ try {
359
+ return JSON.parse(value);
360
+ } catch {
361
+ return null;
362
+ }
363
+ }
364
+ function isTimezone(tz) {
365
+ try {
366
+ new Intl.DateTimeFormat("en", { timeZone: tz });
367
+ return true;
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+ async function loadGeneralSettings(db) {
373
+ const rows = await db.selectFrom("core_settings").select(["key", "value"]).where("key", "in", [
374
+ BASE_CURRENCY_SETTING,
375
+ ORG_NAME_SETTING,
376
+ ORG_LOGO_SETTING,
377
+ ORG_TIMEZONE_SETTING,
378
+ ASSISTANT_NAME_SETTING
379
+ ]).execute();
380
+ const get = (key) => parseJson(rows.find((r) => r.key === key)?.value);
381
+ const currency = get(BASE_CURRENCY_SETTING);
382
+ const name = get(ORG_NAME_SETTING);
383
+ const logo = get(ORG_LOGO_SETTING);
384
+ const timezone = get(ORG_TIMEZONE_SETTING);
385
+ const assistantName = get(ASSISTANT_NAME_SETTING);
386
+ return {
387
+ baseCurrency: typeof currency === "string" && /^[A-Z]{3}$/.test(currency) ? currency : "USD",
388
+ orgName: typeof name === "string" && name.trim() ? name : null,
389
+ logo: typeof logo === "string" && logo.startsWith("data:image/") ? logo : null,
390
+ timezone: typeof timezone === "string" && isTimezone(timezone) ? timezone : "UTC",
391
+ assistantName: typeof assistantName === "string" && assistantName.trim() ? assistantName.trim() : DEFAULT_ASSISTANT_NAME
392
+ };
393
+ }
394
+ var AI_SETTINGS = "ai_settings";
395
+ async function loadAiSettings(db) {
396
+ const row = await db.selectFrom("core_settings").select("value").where("key", "=", AI_SETTINGS).executeTakeFirst();
397
+ if (!row) return { roles: {}, byok: [] };
398
+ try {
399
+ const value = JSON.parse(row.value);
400
+ return {
401
+ roles: parseRoleLayer(JSON.stringify(value.roles ?? {}), "Settings \u2192 AI (ai_settings)"),
402
+ byok: Array.isArray(value.byok) ? value.byok.filter((p) => PROVIDERS.includes(p)) : []
403
+ };
404
+ } catch {
405
+ return { roles: {}, byok: [] };
406
+ }
407
+ }
408
+
409
+ // ../core/src/time/local.ts
410
+ function zoneOffset(at, timeZone) {
411
+ const parts = new Intl.DateTimeFormat("en-US", {
412
+ timeZone,
413
+ hourCycle: "h23",
414
+ year: "numeric",
415
+ month: "2-digit",
416
+ day: "2-digit",
417
+ hour: "2-digit",
418
+ minute: "2-digit",
419
+ second: "2-digit"
420
+ }).formatToParts(new Date(at));
421
+ const n = (type) => Number(parts.find((p) => p.type === type)?.value);
422
+ return Date.UTC(n("year"), n("month") - 1, n("day"), n("hour"), n("minute"), n("second")) - at;
423
+ }
424
+ function realWallClock(y, m, d, h = 0, mi = 0, s = 0) {
425
+ const at = new Date(Date.UTC(y, m - 1, d, h, mi, s));
426
+ return at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d && at.getUTCHours() === h && at.getUTCMinutes() === mi && at.getUTCSeconds() === s;
427
+ }
428
+ var offsetFormatters = /* @__PURE__ */ new Map();
429
+ function offsetFormatter(timeZone) {
430
+ let f = offsetFormatters.get(timeZone);
431
+ if (!f) {
432
+ f = new Intl.DateTimeFormat("en-US", {
433
+ timeZone,
434
+ hourCycle: "h23",
435
+ year: "numeric",
436
+ month: "2-digit",
437
+ day: "2-digit",
438
+ hour: "2-digit",
439
+ minute: "2-digit",
440
+ second: "2-digit",
441
+ weekday: "short"
442
+ });
443
+ offsetFormatters.set(timeZone, f);
444
+ }
445
+ return f;
446
+ }
447
+ var WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
448
+ var pad = (n) => String(n).padStart(2, "0");
449
+ function localParts(at, timeZone) {
450
+ const ms = typeof at === "number" ? at : new Date(at).getTime();
451
+ const parts = Object.fromEntries(
452
+ offsetFormatter(timeZone).formatToParts(new Date(ms)).map((p) => [p.type, p.value])
453
+ );
454
+ const year = Number(parts.year);
455
+ const month = Number(parts.month);
456
+ const day = Number(parts.day);
457
+ const hour = Number(parts.hour) % 24;
458
+ const minute = Number(parts.minute);
459
+ const second = Number(parts.second);
460
+ return {
461
+ year,
462
+ month,
463
+ day,
464
+ hour,
465
+ minute,
466
+ second,
467
+ weekday: WEEKDAYS.indexOf(String(parts.weekday)) + 1,
468
+ date: `${year}-${pad(month)}-${pad(day)}`,
469
+ minuteOfDay: hour * 60 + minute
470
+ };
471
+ }
472
+ var HOUR = 36e5;
473
+ function wallClockToInstant(wall, timeZone) {
474
+ const asUtc = Date.UTC(
475
+ wall.year,
476
+ wall.month - 1,
477
+ wall.day,
478
+ wall.hour ?? 0,
479
+ wall.minute ?? 0,
480
+ wall.second ?? 0
481
+ );
482
+ const before = zoneOffset(asUtc - 14 * HOUR, timeZone);
483
+ const after = zoneOffset(asUtc + 14 * HOUR, timeZone);
484
+ const reads = (at) => {
485
+ const p = localParts(at, timeZone);
486
+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) === asUtc - (asUtc % 1e3 + 1e3) % 1e3;
487
+ };
488
+ const candidates = [asUtc - before, asUtc - after].filter(reads).sort((a, b) => a - b);
489
+ return candidates[0] ?? asUtc - before;
490
+ }
491
+ function wallClockToIso(wall, timeZone) {
492
+ return new Date(wallClockToInstant(wall, timeZone)).toISOString();
493
+ }
494
+ function addLocalDays(date, days) {
495
+ const at = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
496
+ return { year: at.getUTCFullYear(), month: at.getUTCMonth() + 1, day: at.getUTCDate() };
497
+ }
498
+ function parseLocalDate(date) {
499
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
500
+ if (!match) return null;
501
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
502
+ return realWallClock(year, month, day) ? { year, month, day } : null;
503
+ }
504
+ function requireDate(date) {
505
+ const parts = parseLocalDate(date);
506
+ if (!parts) throw new RangeError(`Not a date: ${date}`);
507
+ return parts;
508
+ }
509
+ function parseLocalTime(time) {
510
+ const match = /^(\d{2}):(\d{2})$/.exec(time.trim());
511
+ if (!match) return null;
512
+ const [h, mi] = [Number(match[1]), Number(match[2])];
513
+ return h < 24 && mi < 60 ? h * 60 + mi : null;
514
+ }
515
+ function wallClockOf(date, minutes) {
516
+ return { ...requireDate(date), hour: Math.floor(minutes / 60), minute: minutes % 60 };
517
+ }
518
+ function isoWeekday(date) {
519
+ const d = requireDate(date);
520
+ const day = new Date(Date.UTC(d.year, d.month - 1, d.day)).getUTCDay();
521
+ return day === 0 ? 7 : day;
522
+ }
523
+ function localDaysBefore(at, days, timeZone) {
524
+ const p = localParts(at, timeZone);
525
+ const date = addLocalDays(p, -days);
526
+ const ms = (at % 1e3 + 1e3) % 1e3;
527
+ const wall = { ...date, hour: p.hour, minute: p.minute, second: p.second };
528
+ return wallClockToInstant(wall, timeZone) + ms;
529
+ }
530
+
531
+ // ../core/src/audiences.ts
532
+ var AUDIENCES = ["staff", "customer", "public"];
533
+ var DEFAULT_AUDIENCES = Object.freeze(["staff"]);
534
+ var OUTSIDE_RISK_CLASSES = Object.freeze(["read", "write"]);
535
+ function audiencesOf(op) {
536
+ return op.audiences ?? DEFAULT_AUDIENCES;
537
+ }
538
+ function isOpenOutside(op) {
539
+ return audiencesOf(op).some((audience) => audience !== "staff");
540
+ }
541
+ function audienceOf(principal) {
542
+ return principal.kind;
543
+ }
544
+ function allowsAudience(op, principal) {
545
+ return audiencesOf(op).includes(audienceOf(principal));
546
+ }
547
+ function audienceProblems(op) {
548
+ const problems = [];
549
+ const declared = op.audiences;
550
+ if (declared !== void 0) {
551
+ if (!Array.isArray(declared) || declared.length === 0) {
552
+ problems.push("audiences must list at least one of staff, customer, public");
553
+ return problems;
554
+ }
555
+ if (declared.some((a) => !AUDIENCES.includes(a))) {
556
+ problems.push("audiences must be a subset of staff, customer, public");
557
+ return problems;
558
+ }
559
+ if (new Set(declared).size !== declared.length) problems.push("audiences lists one twice");
560
+ }
561
+ if (isOpenOutside(op) && !OUTSIDE_RISK_CLASSES.includes(op.risk)) {
562
+ const who = audiencesOf(op).filter((a) => a !== "staff");
563
+ problems.push(
564
+ `an operation open to ${who.join(" and ")} callers must have risk class read or write, not ${op.risk} (ADR 0402)`
565
+ );
566
+ }
567
+ return problems;
568
+ }
569
+ function packOf(name) {
570
+ const [first, id] = name.split(".");
571
+ return first === "x" && id ? id : void 0;
572
+ }
573
+ function forPacks(file, installed) {
574
+ return {
575
+ ...file,
576
+ operations: file.operations.filter((op) => {
577
+ const pack = op.pack ?? packOf(op.name);
578
+ return pack === void 0 || installed.includes(pack);
579
+ }).map(({ pack: _pack, ...op }) => op)
580
+ };
581
+ }
582
+
583
+ // ../core/src/operation.ts
584
+ var AFTER_COMMIT = /* @__PURE__ */ Symbol("afterCommit");
585
+ function afterCommit(read) {
586
+ return { [AFTER_COMMIT]: read };
587
+ }
588
+ function isAfterCommit(value) {
589
+ return typeof value === "object" && value !== null && AFTER_COMMIT in value;
590
+ }
591
+ function runAfterCommit(value) {
592
+ return value[AFTER_COMMIT]();
593
+ }
594
+ function recordHostChange(ctx, change) {
595
+ (ctx.recordHostChange ?? ctx.recordChange)(change);
596
+ }
597
+ function personsTool(ctx, extensionId) {
598
+ const caller = ctx.extension;
599
+ if (!caller || !extensionId || caller.id !== extensionId) return null;
600
+ const tool = caller.tool;
601
+ return (tool?.humanOnly || tool?.personApproves) && tool.permission ? tool.name : null;
602
+ }
603
+ var HOST_TOOLS = /* @__PURE__ */ new WeakSet();
604
+ function markHostTool(op) {
605
+ HOST_TOOLS.add(op);
606
+ }
607
+ function isHostTool(op) {
608
+ return HOST_TOOLS.has(op);
609
+ }
610
+ var OPERATION_NAME_RE = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
611
+ function defineOperation(definition) {
612
+ const problems = operationProblems(definition);
613
+ if (problems.length) {
614
+ throw new Error(`Operation ${definition.name}: ${problems.join("; ")}`);
615
+ }
616
+ return Object.freeze({ ...definition });
617
+ }
618
+ function operationProblems(op) {
619
+ const problems = [];
620
+ if (!OPERATION_NAME_RE.test(op.name ?? "")) problems.push("name must be <object>.<verb>");
621
+ if (typeof op.description !== "string" || op.description.trim().length < 20) {
622
+ problems.push("description must explain what it does, when to use it and side effects");
623
+ }
624
+ if (!op.input || typeof op.input.safeParse !== "function") problems.push("input schema missing");
625
+ if (!op.output || typeof op.output.safeParse !== "function") {
626
+ problems.push("output schema missing");
627
+ }
628
+ if (!PERMISSIONS.includes(op.permission)) problems.push("permission missing or unknown");
629
+ if (op.packPermission !== void 0) {
630
+ const extension = /^x\.([a-z][a-z0-9]{1,29})\./.exec(op.name ?? "")?.[1];
631
+ if (!extension) problems.push("packPermission is for extension tools only");
632
+ else if (!op.packPermission.startsWith(`${extension}:`)) {
633
+ problems.push(`packPermission is named ${extension}:<word>`);
634
+ }
635
+ }
636
+ if (!RISK_CLASSES.includes(op.risk)) problems.push("risk class missing or unknown");
637
+ if (op.actors && (op.actors.length === 0 || op.actors.some((a) => !ACTORS.includes(a)))) {
638
+ problems.push("actors must list known actor types");
639
+ }
640
+ if (typeof op.handler !== "function") problems.push("handler missing");
641
+ problems.push(...audienceProblems(op));
642
+ if (op.hostInternal !== void 0) {
643
+ if (op.hostInternal !== true) problems.push("hostInternal is true or left out");
644
+ if (op.name?.startsWith("x.")) problems.push("an extension tool can never be hostInternal");
645
+ if (!isOpenOutside(op)) {
646
+ problems.push("hostInternal is only for an operation open to customer or public callers");
647
+ }
648
+ }
649
+ if (op.toolOnly !== void 0) {
650
+ if (op.toolOnly !== true) problems.push("toolOnly is true or left out");
651
+ if (op.name?.startsWith("x.")) problems.push("an extension tool cannot be toolOnly");
652
+ if (!audiencesOf(op).includes("customer")) {
653
+ problems.push("toolOnly is only for an operation open to customer callers");
654
+ }
655
+ }
656
+ if (isOpenOutside(op) && op.alwaysReview) {
657
+ problems.push("an operation open to customer or public callers is never queued for review");
658
+ }
659
+ if ((op.risk === "bulk-write" || op.risk === "destructive") && op.name.endsWith("Many")) {
660
+ if (typeof op.bulkSize !== "function") problems.push("batch operations need bulkSize");
661
+ }
662
+ return problems;
663
+ }
664
+
665
+ // ../core/src/recurring/bookkeeping.ts
666
+ function armSeriesStatement(object, id, at, now) {
667
+ return CompiledQuery.raw(
668
+ "INSERT INTO core_recurrence_series (object_type, record_id, next_run_at, version, updated_at) VALUES (?, ?, ?, 1, ?) ON CONFLICT (object_type, record_id) DO UPDATE SET next_run_at = excluded.next_run_at, version = core_recurrence_series.version + 1, updated_at = excluded.updated_at",
669
+ [object, id, at, now]
670
+ );
671
+ }
672
+ async function seriesVersion(db, object, id) {
673
+ const row = await db.selectFrom("core_recurrence_series").select("version").where("object_type", "=", object).where("record_id", "=", id).executeTakeFirst();
674
+ return row?.version ?? 0;
675
+ }
676
+ function guardStatement(kind, object, record, expected) {
677
+ return CompiledQuery.raw(
678
+ "INSERT INTO core_write_guard (kind, object_type, record_id, expected) VALUES (?, ?, ?, ?)",
679
+ [kind, object, record, expected]
680
+ );
681
+ }
682
+ function occurrenceStatement(input) {
683
+ return CompiledQuery.raw(
684
+ "INSERT INTO core_recurrence_occurrence (series_object, series_id, local_date, object_type, record_id, created_at) VALUES (?, ?, ?, ?, ?, ?)",
685
+ [input.seriesObject, input.seriesId, input.date, input.object, input.record, input.now]
686
+ );
687
+ }
688
+ function markEditedStatement(object, record, now) {
689
+ return CompiledQuery.raw(
690
+ "UPDATE core_recurrence_occurrence SET edited_at = ? WHERE object_type = ? AND record_id = ? AND edited_at IS NULL",
691
+ [now, object, record]
692
+ );
693
+ }
694
+ function dropRecurringStatements(object) {
695
+ return [
696
+ CompiledQuery.raw(
697
+ "DELETE FROM core_recurrence_occurrence WHERE series_object = ? OR object_type = ?",
698
+ [object, object]
699
+ ),
700
+ CompiledQuery.raw("DELETE FROM core_recurrence_series WHERE object_type = ?", [object])
701
+ ];
702
+ }
703
+
704
+ // ../core/src/records/windows.ts
705
+ function pathReader(ctx, object, after) {
706
+ const ext = object.extension;
707
+ const records = /* @__PURE__ */ new Map();
708
+ const load = (target, id) => {
709
+ const key = `${target.name}:${id}`;
710
+ const cached = records.get(key);
711
+ if (cached) return cached;
712
+ const promise = (async () => {
713
+ const stored = await ctx.db.selectFrom(visibleSource(ctx, target)).selectAll().where("id", "=", id).executeTakeFirst();
714
+ if (!stored) return null;
715
+ const values = {};
716
+ for (const field of target.fields) {
717
+ if (field.column && Object.hasOwn(stored, field.column)) {
718
+ values[field.name] = stored[field.column];
719
+ }
720
+ }
721
+ return values;
722
+ })();
723
+ records.set(key, promise);
724
+ return promise;
725
+ };
726
+ const nameOn = (on, local) => ext ? registryFieldName(ext, on.name, local) : local;
727
+ let settings;
728
+ const loadSettings = () => {
729
+ settings ??= (async () => {
730
+ if (!ext) return {};
731
+ const [stored, declared] = await Promise.all([
732
+ ctx.db.selectFrom("core_extension_settings").select("value").where("extension_id", "=", ext).executeTakeFirst(),
733
+ ctx.db.selectFrom("core_extensions").select("manifest").where("id", "=", ext).executeTakeFirst()
734
+ ]);
735
+ const defaults = Object.fromEntries(
736
+ Object.entries(
737
+ (declared ? JSON.parse(declared.manifest) : {}).settings ?? {}
738
+ ).map(([name, s]) => [name, s.default ?? null])
739
+ );
740
+ return {
741
+ ...defaults,
742
+ ...stored ? JSON.parse(stored.value) : {}
743
+ };
744
+ })();
745
+ return settings;
746
+ };
747
+ return {
748
+ async read(path) {
749
+ const parts = path.split(".");
750
+ let values = after;
751
+ let on = object;
752
+ for (const [i, part] of parts.entries()) {
753
+ if (!values) return null;
754
+ const name = i === 0 ? part : nameOn(on, part);
755
+ const value = values[name] ?? null;
756
+ if (i === parts.length - 1) return value;
757
+ const to = on.fields.find((f) => f.name === name)?.options?.to;
758
+ const target = to ? getObject(to) : void 0;
759
+ if (typeof value !== "string" || !value || !target) return null;
760
+ values = await load(target, value);
761
+ if (!values) return UNREADABLE;
762
+ on = target;
763
+ }
764
+ return null;
765
+ },
766
+ async setting(name) {
767
+ return (await loadSettings())[name] ?? null;
768
+ }
769
+ };
770
+ }
771
+ var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
772
+ function asNumber(value) {
773
+ if (typeof value === "number" && Number.isFinite(value)) return value;
774
+ if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {
775
+ return Number(value);
776
+ }
777
+ return null;
778
+ }
779
+ async function boundMoment(ctx, reader, bound) {
780
+ const b = typeof bound === "string" ? { at: bound } : bound;
781
+ const at = await reader.read(b.at);
782
+ const instant = typeof at === "string" ? Date.parse(at) : Number.NaN;
783
+ if (Number.isNaN(instant)) return null;
784
+ const part = async (value) => {
785
+ if (value === void 0) return 0;
786
+ if (typeof value === "number") return value;
787
+ if (typeof value === "string") return asNumber(await reader.read(value));
788
+ const raw = value.field === void 0 ? null : await reader.read(value.field);
789
+ if (raw === UNREADABLE) return null;
790
+ const own = asNumber(raw);
791
+ if (own !== null || value.setting === void 0) return own;
792
+ return asNumber(await reader.setting(value.setting));
793
+ };
794
+ const days = await part(b.daysBefore);
795
+ const minutes = await part(b.minutesBefore);
796
+ if (days === null || minutes === null) return null;
797
+ let moment = instant;
798
+ if (days !== 0) {
799
+ const zoneValue = b.zone ? await reader.read(b.zone) : null;
800
+ if (zoneValue === UNREADABLE) return null;
801
+ const zone = typeof zoneValue === "string" && zoneValue ? zoneValue : (await loadGeneralSettings(ctx.db)).timezone;
802
+ moment = localDaysBefore(instant, Math.trunc(days), zone);
803
+ }
804
+ return moment - Math.round(minutes * 6e4);
805
+ }
806
+ async function windowRefusal(ctx, reader, window, what) {
807
+ if (!window) return null;
808
+ const now = Date.parse(ctx.now);
809
+ const from = window.from === void 0 ? void 0 : await boundMoment(ctx, reader, window.from);
810
+ const until = window.until === void 0 ? void 0 : await boundMoment(ctx, reader, window.until);
811
+ if (from === null || until === null) {
812
+ return {
813
+ rule: "window_unknown",
814
+ message: `${what} cannot be done now: when it is allowed cannot be worked out`
815
+ };
816
+ }
817
+ const iso = (ms) => new Date(ms).toISOString();
818
+ const times = {
819
+ ...from !== void 0 ? { opensAt: iso(from) } : {},
820
+ ...until !== void 0 ? { closesAt: iso(until) } : {}
821
+ };
822
+ if (from !== void 0 && now < from) {
823
+ return { rule: "window_not_open", message: `${what} opens at ${iso(from)}`, ...times };
824
+ }
825
+ if (until !== void 0 && now >= until) {
826
+ return { rule: "window_closed", message: `${what} closed at ${iso(until)}`, ...times };
827
+ }
828
+ return null;
829
+ }
830
+ async function staffOnlySet(reader, paths) {
831
+ for (const path of paths === void 0 ? [] : typeof paths === "string" ? [paths] : paths) {
832
+ const value = await reader.read(path);
833
+ if (value === UNREADABLE) return true;
834
+ if (value === true || value === 1 || value === "1" || value === "true") return true;
835
+ }
836
+ return false;
837
+ }
838
+ function staffOnlyMessage(what) {
839
+ return `${what} is made by staff only`;
840
+ }
841
+
842
+ // ../core/src/records/transitions.ts
843
+ function callerOf(ctx) {
844
+ return ctx.onBehalfOf ?? ctx.principal;
845
+ }
846
+ function enteredBy(ctx) {
847
+ return callerOf(ctx).kind === "staff" ? ctx.user.id : null;
848
+ }
849
+ var ALL_MOVERS = ["staff", "customer", "host"];
850
+ var TransitionRuleError = class extends ValidationError {
851
+ name = "TransitionRuleError";
852
+ };
853
+ var NO_TRANSITION = {
854
+ values: {},
855
+ history: [],
856
+ moved: null,
857
+ left: null,
858
+ field: null
859
+ };
860
+ function isEmptyValue(value) {
861
+ return value === null || value === void 0 || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0;
862
+ }
863
+ function ruleBase(write, rule, fields) {
864
+ return {
865
+ rule,
866
+ object: write.object.name,
867
+ field: fields[0],
868
+ fields,
869
+ labels: fields.map(write.labelOf)
870
+ };
871
+ }
872
+ async function runTransition(lifecycle, ctx, object, id, before, written, by) {
873
+ const values = {};
874
+ const after = { ...before ?? {}, ...written };
875
+ const has = (field) => Object.hasOwn(written, field);
876
+ const write = {
877
+ ctx,
878
+ object,
879
+ id,
880
+ before,
881
+ written,
882
+ after,
883
+ by,
884
+ has,
885
+ changed: (field) => has(field) && JSON.stringify(written[field] ?? null) !== JSON.stringify(before?.[field] ?? null),
886
+ set: (field, value) => {
887
+ if (!field) return;
888
+ values[field] = value;
889
+ after[field] = value;
890
+ },
891
+ labelOf: (field) => object.fields.find((f) => f.name === field)?.label ?? field
892
+ };
893
+ const placement = await lifecycle.place(write);
894
+ if (!placement) return NO_TRANSITION;
895
+ const { to } = placement;
896
+ const moved = to.id !== placement.fromId;
897
+ if (moved && !placement.by.includes(by)) {
898
+ throw lifecycle.refusal(
899
+ write,
900
+ {
901
+ rule: "move_not_permitted",
902
+ message: notPermittedMessage(object, to, placement.by),
903
+ fields: [lifecycle.field]
904
+ },
905
+ placement
906
+ );
907
+ }
908
+ lifecycle.follow?.(write, placement, moved);
909
+ const required = [...new Set(placement.requires)].filter(
910
+ (field) => object.fields.some((f) => f.name === field)
911
+ );
912
+ const checked = moved || before === null ? required : required.filter(write.changed);
913
+ const missing = checked.filter((field) => isEmptyValue(after[field]));
914
+ if (missing.length) {
915
+ throw lifecycle.refusal(
916
+ write,
917
+ {
918
+ rule: "required_fields",
919
+ message: `${to.title} needs ${missing.map(write.labelOf).join(", ")}`,
920
+ fields: missing
921
+ },
922
+ placement
923
+ );
924
+ }
925
+ const history = [];
926
+ if (moved) {
927
+ if (before !== null) {
928
+ const column = object.fields.find((f) => f.name === lifecycle.field)?.column;
929
+ if (!column) {
930
+ throw new ValidationError(`${object.label} has no column for ${lifecycle.field}`);
931
+ }
932
+ ctx.write(
933
+ CompiledQuery.raw(
934
+ `UPDATE core_transition_history SET left_at = ? WHERE object_type = ? AND record_id = ? AND left_at IS NULL AND EXISTS (SELECT 1 FROM ${object.source} WHERE id = ? AND ${column} IS ?)`,
935
+ [ctx.now, object.name, id, id, storedPosition(before[lifecycle.field])]
936
+ )
937
+ );
938
+ }
939
+ history.push(
940
+ CompiledQuery.raw(
941
+ "INSERT INTO core_transition_history (id, object_type, record_id, form, position_id, group_id, position_type, entered_at, left_at, entered_by, entered_as) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)",
942
+ [
943
+ newId("stageHistory"),
944
+ object.name,
945
+ id,
946
+ lifecycle.form,
947
+ to.id,
948
+ placement.group(),
949
+ to.type,
950
+ ctx.now,
951
+ enteredBy(ctx),
952
+ by
953
+ ]
954
+ )
955
+ );
956
+ }
957
+ return {
958
+ values,
959
+ history,
960
+ moved: moved ? to : null,
961
+ left: moved ? placement.from : null,
962
+ field: lifecycle.field
963
+ };
964
+ }
965
+ function storedPosition(value) {
966
+ if (value === null || value === void 0) return null;
967
+ if (typeof value === "object" && value && "id" in value)
968
+ return String(value.id);
969
+ return String(value);
970
+ }
971
+ function notPermittedMessage(object, to, by) {
972
+ if (by.length === 1 && by[0] === "host") {
973
+ return `${object.label} becomes ${to.title} when the platform confirms it; it cannot be set`;
974
+ }
975
+ const who = by.map((mover) => mover === "host" ? "the platform" : mover).join(" or ");
976
+ return `Only ${who} can move ${object.label.toLowerCase()} to ${to.title}`;
977
+ }
978
+ function transitionTimeline(outcome) {
979
+ if (!outcome.moved || !outcome.field) return void 0;
980
+ return {
981
+ subject: `Moved to ${outcome.moved.title}`,
982
+ field: outcome.field,
983
+ labels: { before: outcome.left?.title ?? null, after: outcome.moved.title }
984
+ };
985
+ }
986
+
987
+ // ../core/src/records/states.ts
988
+ var StateRuleError = class extends TransitionRuleError {
989
+ name = "StateRuleError";
990
+ constructor(message, details) {
991
+ super(message, details);
992
+ }
993
+ };
994
+ var ref = (position) => position ? { id: position.id, title: position.title, final: position.type === "final" } : null;
995
+ function statesLifecycle(object, states) {
996
+ const field = states.field;
997
+ const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
998
+ const finals = new Set(states.moves.filter((move) => move.final).map((move) => move.to));
999
+ const position = (value) => ({
1000
+ id: value,
1001
+ title: choices.find((choice) => choice.value === value)?.label ?? value,
1002
+ type: finals.has(value) ? "final" : "open"
1003
+ });
1004
+ const moveBetween = (from, to) => states.moves.find((move) => move.to === to && moveOrigins(move).includes(from));
1005
+ const reachable = (from) => [
1006
+ ...new Set(
1007
+ states.moves.filter((move) => moveOrigins(move).includes(from)).map((move) => move.to)
1008
+ )
1009
+ ];
1010
+ const held = (state) => {
1011
+ const into = states.moves.filter((move) => move.to === state);
1012
+ const [first, ...rest] = into.map((move) => move.requires ?? []);
1013
+ return (first ?? []).filter((name) => rest.every((list) => list.includes(name)));
1014
+ };
1015
+ const refuse = (write, rule, message, fields, to, from, extra = {}) => new StateRuleError(message, {
1016
+ ...ruleBase(write, rule, fields),
1017
+ rule,
1018
+ state: ref(to),
1019
+ from: ref(from),
1020
+ ...extra
1021
+ });
1022
+ const customerRules = async (write, rules, what, to, from) => {
1023
+ const refusal = await customerRefusal(write.ctx, write.object, write.after, rules, what);
1024
+ if (refusal) {
1025
+ throw refuse(write, refusal.rule, refusal.message, [field], to, from, refusal.times);
1026
+ }
1027
+ };
1028
+ return {
1029
+ form: "states",
1030
+ field,
1031
+ async place(write) {
1032
+ const { before, after, object: o } = write;
1033
+ const stored = before?.[field];
1034
+ const fromId = typeof stored === "string" && stored !== "" ? stored : null;
1035
+ const from = fromId ? position(fromId) : null;
1036
+ const wanted = after[field];
1037
+ let toId = typeof wanted === "string" && wanted !== "" ? wanted : null;
1038
+ if (toId === null) {
1039
+ if (fromId !== null) {
1040
+ throw refuse(write, "no_state", `${o.label} must have a state`, [field], null, from);
1041
+ }
1042
+ toId = states.initial;
1043
+ write.set(field, toId);
1044
+ }
1045
+ const to = position(toId);
1046
+ const base = { fromId, from, to, group: () => null };
1047
+ const closedPaths = states.create?.closed;
1048
+ if (closedPaths && write.by !== "host" && (before === null || ruleSources({ staffOnly: closedPaths }).some((f) => write.changed(f)))) {
1049
+ const reader = pathReader(write.ctx, o, after);
1050
+ if (await staffOnlySet(reader, closedPaths)) {
1051
+ throw refuse(
1052
+ write,
1053
+ "state_closed",
1054
+ `${o.label} cannot be made now: what it is for is closed`,
1055
+ [field],
1056
+ to,
1057
+ from
1058
+ );
1059
+ }
1060
+ await queueUnmovedGuards(write.ctx, o, after, closedPaths);
1061
+ }
1062
+ const claims = o.claims;
1063
+ if (closedPaths && claims && before !== null && toId !== fromId) {
1064
+ const holds = (state) => state !== null && (claims.held.includes(state) || claims.confirmed.includes(state));
1065
+ if (holds(toId) && !holds(fromId)) {
1066
+ if (await staffOnlySet(pathReader(write.ctx, o, after), closedPaths)) {
1067
+ throw refuse(
1068
+ write,
1069
+ "state_closed",
1070
+ `${o.label} cannot take a place now: what it is for is closed`,
1071
+ [field],
1072
+ to,
1073
+ from
1074
+ );
1075
+ }
1076
+ await queueUnmovedGuards(write.ctx, o, after, closedPaths);
1077
+ }
1078
+ }
1079
+ if (before === null && write.by === "customer" && toId !== states.initial && !states.create?.in?.[toId]?.includes("customer")) {
1080
+ throw refuse(
1081
+ write,
1082
+ "state_move_not_permitted",
1083
+ `A customer creates ${o.label.toLowerCase()} in ${position(states.initial).title} only`,
1084
+ [field],
1085
+ to,
1086
+ null,
1087
+ { by: [] }
1088
+ );
1089
+ }
1090
+ if (before === null && write.by === "customer" && states.create) {
1091
+ await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, null);
1092
+ }
1093
+ if (before !== null && write.by === "customer" && states.create && ruleSources(states.create).some((f) => write.changed(f))) {
1094
+ await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, from);
1095
+ }
1096
+ const createdIn = before === null && toId !== states.initial ? states.create?.in?.[toId] : void 0;
1097
+ if (createdIn) {
1098
+ return { ...base, by: createdIn, requires: held(toId) };
1099
+ }
1100
+ if (toId === fromId) return { ...base, by: ALL_MOVERS, requires: held(toId) };
1101
+ const origin = fromId ?? states.initial;
1102
+ if (toId === origin) return { ...base, by: ALL_MOVERS, requires: [] };
1103
+ const originPosition = position(origin);
1104
+ if (finals.has(origin)) {
1105
+ throw refuse(
1106
+ write,
1107
+ "state_final",
1108
+ `${o.label} is ${originPosition.title}, which is final: it cannot move to ${to.title}`,
1109
+ [field],
1110
+ to,
1111
+ originPosition,
1112
+ { allowed: [] }
1113
+ );
1114
+ }
1115
+ const move = moveBetween(origin, toId);
1116
+ if (!move) {
1117
+ throw refuse(
1118
+ write,
1119
+ "state_move_not_declared",
1120
+ `${o.label} cannot move from ${originPosition.title} to ${to.title}`,
1121
+ [field],
1122
+ to,
1123
+ originPosition,
1124
+ { allowed: reachable(origin) }
1125
+ );
1126
+ }
1127
+ if (write.by === "customer" && move.by.includes("customer")) {
1128
+ await customerRules(
1129
+ write,
1130
+ move,
1131
+ `Moving ${o.label.toLowerCase()} to ${to.title}`,
1132
+ to,
1133
+ originPosition
1134
+ );
1135
+ }
1136
+ const tool = write.by === "staff" ? personsTool(write.ctx, o.extension) : null;
1137
+ const byTool = tool !== null && (move.tools ?? []).includes(tool);
1138
+ if (write.by === "staff" && move.bindsStaff && (move.by.includes("staff") || byTool)) {
1139
+ await customerRules(
1140
+ write,
1141
+ { window: move.window },
1142
+ `Moving ${o.label.toLowerCase()} to ${to.title}`,
1143
+ to,
1144
+ originPosition
1145
+ );
1146
+ }
1147
+ return {
1148
+ ...base,
1149
+ from: originPosition,
1150
+ by: byTool ? [...move.by, "staff"] : move.by,
1151
+ requires: move.requires ?? []
1152
+ };
1153
+ },
1154
+ refusal(write, refusal, placement) {
1155
+ const rule = `state_${refusal.rule}`;
1156
+ return refuse(
1157
+ write,
1158
+ rule,
1159
+ refusal.message,
1160
+ refusal.fields,
1161
+ placement.to,
1162
+ placement.from,
1163
+ refusal.rule === "move_not_permitted" ? { by: [...placement.by] } : {}
1164
+ );
1165
+ }
1166
+ };
1167
+ }
1168
+ async function queueUnmovedGuards(ctx, object, after, paths) {
1169
+ if (ctx.simulation) return;
1170
+ const relations = new Set(
1171
+ (typeof paths === "string" ? [paths] : paths).filter((p) => p.includes(".")).map((p) => p.split(".")[0])
1172
+ );
1173
+ for (const relation of relations) {
1174
+ const id = after[relation];
1175
+ const to = object.fields.find((f) => f.name === relation)?.options?.to;
1176
+ if (typeof id !== "string" || !id || !to) continue;
1177
+ const row = await ctx.db.selectFrom("core_transition_history").select((eb) => eb.fn.countAll().as("n")).where("object_type", "=", to).where("record_id", "=", id).executeTakeFirst();
1178
+ ctx.write(guardStatement("unmoved", to, id, Number(row?.n ?? 0)));
1179
+ }
1180
+ }
1181
+ function ruleSources(rules) {
1182
+ const paths = [];
1183
+ if (typeof rules.staffOnly === "string") paths.push(rules.staffOnly);
1184
+ else if (rules.staffOnly) paths.push(...rules.staffOnly);
1185
+ for (const bound of [rules.window?.from, rules.window?.until]) {
1186
+ if (bound === void 0) continue;
1187
+ if (typeof bound === "string") {
1188
+ paths.push(bound);
1189
+ continue;
1190
+ }
1191
+ paths.push(bound.at);
1192
+ for (const part of [bound.daysBefore, bound.minutesBefore, bound.zone]) {
1193
+ if (typeof part === "string") paths.push(part);
1194
+ else if (typeof part === "object" && part.field) paths.push(part.field);
1195
+ }
1196
+ }
1197
+ return [...new Set(paths.map((p) => p.split(".")[0]))];
1198
+ }
1199
+ async function customerRefusal(ctx, object, after, rules, what) {
1200
+ if (!rules.window && !rules.staffOnly) return null;
1201
+ const reader = pathReader(ctx, object, after);
1202
+ if (await staffOnlySet(reader, rules.staffOnly)) {
1203
+ return { rule: "state_staff_only", message: staffOnlyMessage(what), times: {} };
1204
+ }
1205
+ const refusal = await windowRefusal(ctx, reader, rules.window, what);
1206
+ if (!refusal) return null;
1207
+ return {
1208
+ rule: `state_${refusal.rule}`,
1209
+ message: refusal.message,
1210
+ times: {
1211
+ ...refusal.opensAt ? { opensAt: refusal.opensAt } : {},
1212
+ ...refusal.closesAt ? { closesAt: refusal.closesAt } : {}
1213
+ }
1214
+ };
1215
+ }
1216
+ function isPerson(ctx) {
1217
+ try {
1218
+ return ctx.actor === "human";
1219
+ } catch {
1220
+ return false;
1221
+ }
1222
+ }
1223
+ async function resolveStateRequest(ctx, object, before, values, by) {
1224
+ const states = object.states;
1225
+ const field = states?.field;
1226
+ const requests = states?.requests;
1227
+ if (!states || !field || !requests) return values;
1228
+ const asked = values[field];
1229
+ if (typeof asked !== "string" || !Object.hasOwn(requests, asked)) return values;
1230
+ const stored = before?.[field];
1231
+ const origin = typeof stored === "string" && stored !== "" ? stored : states.initial;
1232
+ const after = { ...before ?? {}, ...values };
1233
+ const labelOf = (name) => object.fields.find((f) => f.name === name)?.label ?? name;
1234
+ const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
1235
+ const title = (value) => choices.find((c) => c.value === value)?.label ?? value;
1236
+ let refused = null;
1237
+ for (const to of requests[asked] ?? []) {
1238
+ const move = states.moves.find((m) => m.to === to && moveOrigins(m).includes(origin));
1239
+ if (!move?.by.includes(by)) continue;
1240
+ if (by === "customer" || by === "staff" && (!isPerson(ctx) || move.bindsStaff)) {
1241
+ const refusal = await customerRefusal(
1242
+ ctx,
1243
+ object,
1244
+ { ...after, [field]: to },
1245
+ move,
1246
+ `Moving ${object.label.toLowerCase()} to ${title(to)}`
1247
+ );
1248
+ if (refusal) {
1249
+ refused ??= refusal;
1250
+ continue;
1251
+ }
1252
+ }
1253
+ return { ...values, [field]: to };
1254
+ }
1255
+ const state = { id: origin, title: title(origin), final: false };
1256
+ throw new StateRuleError(
1257
+ refused?.message ?? `${object.label} cannot be moved by "${asked}" from ${title(origin)}`,
1258
+ {
1259
+ ...ruleBase({ object, labelOf }, refused?.rule ?? "state_request_refused", [field]),
1260
+ rule: refused?.rule ?? "state_request_refused",
1261
+ state: null,
1262
+ from: state,
1263
+ ...refused?.times ?? {}
1264
+ }
1265
+ );
1266
+ }
1267
+ async function assertCreateRules(ctx, object, after, by) {
1268
+ const states = object.states;
1269
+ if (!states?.create) return;
1270
+ const labelOf = (name) => object.fields.find((f) => f.name === name)?.label ?? name;
1271
+ const choices = object.fields.find((f) => f.name === states.field)?.options?.choices ?? [];
1272
+ const wanted = after[states.field];
1273
+ const toId = typeof wanted === "string" && wanted ? wanted : states.initial;
1274
+ const state = {
1275
+ id: toId,
1276
+ title: choices.find((c) => c.value === toId)?.label ?? toId,
1277
+ final: states.moves.some((m) => m.final && m.to === toId)
1278
+ };
1279
+ const fail = (rule, message, times = {}) => new StateRuleError(message, {
1280
+ ...ruleBase({ object, labelOf }, rule, [states.field]),
1281
+ rule,
1282
+ state,
1283
+ from: null,
1284
+ ...times
1285
+ });
1286
+ const reader = pathReader(ctx, object, after);
1287
+ if (states.create.closed) {
1288
+ if (await staffOnlySet(reader, states.create.closed)) {
1289
+ throw fail("state_closed", `${object.label} cannot be made now: what it is for is closed`);
1290
+ }
1291
+ await queueUnmovedGuards(ctx, object, after, states.create.closed);
1292
+ }
1293
+ if (by === "staff") return;
1294
+ const refusal = await customerRefusal(
1295
+ ctx,
1296
+ object,
1297
+ after,
1298
+ states.create,
1299
+ `Creating ${object.label.toLowerCase()}`
1300
+ );
1301
+ if (refusal) throw fail(refusal.rule, refusal.message, refusal.times);
1302
+ }
1303
+
1304
+ // ../core/src/capacity/index.ts
1305
+ function claimStatements(db, request, now) {
1306
+ const quantity = request.quantity;
1307
+ if (!Number.isInteger(quantity) || quantity < 1) {
1308
+ throw new ValidationError("A claim is for a whole number of places, at least 1", {
1309
+ rule: "capacity",
1310
+ object: request.object,
1311
+ record: request.record,
1312
+ asked: quantity
1313
+ });
1314
+ }
1315
+ const id = request.id ?? newId("capacityClaim");
1316
+ const counter = () => db.selectFrom("core_capacity").where("object_type", "=", request.object).where("record_id", "=", request.record);
1317
+ const statements = [
1318
+ db.updateTable("core_capacity").set({ held: sql`held + ${quantity}`, updated_at: now }).where("object_type", "=", request.object).where("record_id", "=", request.record),
1319
+ // The pool named on the record's counter, if any: no row matches when there is none.
1320
+ db.updateTable("core_capacity").set({ held: sql`held + ${quantity}`, updated_at: now }).where("object_type", "=", counter().select("pool_object_type")).where("record_id", "=", counter().select("pool_record_id")),
1321
+ db.insertInto("core_capacity_claim").values({
1322
+ id,
1323
+ object_type: request.object,
1324
+ record_id: request.record,
1325
+ pool_object_type: counter().select("pool_object_type"),
1326
+ pool_record_id: counter().select("pool_record_id"),
1327
+ quantity,
1328
+ state: "held",
1329
+ for_type: request.for.type,
1330
+ for_id: request.for.id,
1331
+ created_at: now,
1332
+ updated_at: now
1333
+ })
1334
+ ];
1335
+ return { id, statements };
1336
+ }
1337
+
1338
+ // ../core/src/capacity/records.ts
1339
+ async function readCounter(db, object, record) {
1340
+ return db.selectFrom("core_capacity as c").leftJoin(
1341
+ "core_capacity as p",
1342
+ (join) => join.onRef("p.object_type", "=", "c.pool_object_type").onRef("p.record_id", "=", "c.pool_record_id")
1343
+ ).select([
1344
+ "c.places",
1345
+ "c.held",
1346
+ "c.taken",
1347
+ "c.pool_object_type",
1348
+ "c.pool_record_id",
1349
+ "p.places as pool_places",
1350
+ "p.held as pool_held",
1351
+ "p.taken as pool_taken"
1352
+ ]).where("c.object_type", "=", object).where("c.record_id", "=", record).executeTakeFirst();
1353
+ }
1354
+ function left(places, held, taken) {
1355
+ return places === null ? null : Math.max(places - held - taken, 0);
1356
+ }
1357
+ var simulated = /* @__PURE__ */ new WeakMap();
1358
+ async function queueClaim(ctx, request) {
1359
+ const { id, statements } = claimStatements(ctx.db, request, ctx.now);
1360
+ if (ctx.simulation) {
1361
+ await simulateClaim(ctx, request);
1362
+ return id;
1363
+ }
1364
+ ctx.write(...statements);
1365
+ return id;
1366
+ }
1367
+ function creditSimulatedClaim(ctx, object, record, quantity) {
1368
+ if (!ctx.simulation) return;
1369
+ const seen = simulated.get(ctx) ?? /* @__PURE__ */ new Map();
1370
+ simulated.set(ctx, seen);
1371
+ const key = `${object}|${record}`;
1372
+ seen.set(key, (seen.get(key) ?? 0) - quantity);
1373
+ }
1374
+ async function simulateClaim(ctx, request) {
1375
+ const row = await readCounter(ctx.db, request.object, request.record);
1376
+ if (!row) throw new ValidationError("A referenced record does not exist");
1377
+ const seen = simulated.get(ctx) ?? /* @__PURE__ */ new Map();
1378
+ simulated.set(ctx, seen);
1379
+ const levels = [
1380
+ {
1381
+ object: request.object,
1382
+ record: request.record,
1383
+ left: left(row.places, row.held, row.taken)
1384
+ },
1385
+ ...row.pool_object_type && row.pool_record_id ? [
1386
+ {
1387
+ object: row.pool_object_type,
1388
+ record: row.pool_record_id,
1389
+ left: left(row.pool_places, row.pool_held ?? 0, row.pool_taken ?? 0)
1390
+ }
1391
+ ] : []
1392
+ ];
1393
+ for (const level of levels) {
1394
+ const key = `${level.object}|${level.record}`;
1395
+ const already = seen.get(key) ?? 0;
1396
+ const available = level.left === null ? null : Math.max(level.left - already, 0);
1397
+ if (available !== null && request.quantity > available) {
1398
+ throw new ValidationError(
1399
+ `Not enough places: asked for ${request.quantity}, ${available} left`,
1400
+ {
1401
+ rule: "capacity",
1402
+ object: level.object,
1403
+ record: level.record,
1404
+ asked: request.quantity,
1405
+ available
1406
+ }
1407
+ );
1408
+ }
1409
+ }
1410
+ for (const level of levels) {
1411
+ const key = `${level.object}|${level.record}`;
1412
+ seen.set(key, (seen.get(key) ?? 0) + request.quantity);
1413
+ }
1414
+ }
1415
+ function placesOf(object, capacity, value) {
1416
+ if (value === null || value === void 0 || value === "") return null;
1417
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1418
+ throw new ValidationError(
1419
+ `${object.label}: places must be a whole number from 0, or empty for unlimited`,
1420
+ { field: capacity.places, rule: "capacity" }
1421
+ );
1422
+ }
1423
+ return value;
1424
+ }
1425
+ async function counterWrite(ctx, object, id, after, changed) {
1426
+ const capacity = object.capacity;
1427
+ if (!capacity) return null;
1428
+ const touches = changed === "create" || changed.includes(capacity.places) || capacity.pool !== void 0 && changed.includes(capacity.pool.field);
1429
+ if (!touches) return null;
1430
+ const places = placesOf(object, capacity, after[capacity.places]);
1431
+ const poolId = capacity.pool ? after[capacity.pool.field] : null;
1432
+ const pool = capacity.pool && typeof poolId === "string" && poolId ? { object: capacity.pool.object, record: poolId } : null;
1433
+ if (changed !== "create" && ctx.simulation) {
1434
+ const row = await readCounter(ctx.db, object.name, id);
1435
+ if (row && places !== null && row.held + row.taken > places) {
1436
+ throw new ValidationError(
1437
+ `Places cannot be fewer than are claimed: ${row.held} held and ${row.taken} taken`,
1438
+ {
1439
+ rule: "capacity",
1440
+ object: object.name,
1441
+ record: id,
1442
+ places,
1443
+ held: row.held,
1444
+ taken: row.taken
1445
+ }
1446
+ );
1447
+ }
1448
+ }
1449
+ return CompiledQuery.raw(
1450
+ "INSERT INTO core_capacity (object_type, record_id, places, pool_object_type, pool_record_id, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (object_type, record_id) DO UPDATE SET places = excluded.places, pool_object_type = excluded.pool_object_type, pool_record_id = excluded.pool_record_id, updated_at = excluded.updated_at",
1451
+ [object.name, id, places, pool?.object ?? null, pool?.record ?? null, ctx.now]
1452
+ );
1453
+ }
1454
+ async function assertNoConfirmedClaims(ctx, object, id) {
1455
+ if (!object.capacity) return;
1456
+ const row = await ctx.db.selectFrom("core_capacity").select("taken").where("object_type", "=", object.name).where("record_id", "=", id).executeTakeFirst();
1457
+ if (row && row.taken > 0) {
1458
+ throw new ValidationError(
1459
+ `${object.label} has ${row.taken} places taken by paid orders and cannot be deleted`,
1460
+ { rule: "capacity", object: object.name, record: id, taken: row.taken }
1461
+ );
1462
+ }
1463
+ }
1464
+ function dropCapacityStatements(object) {
1465
+ return [
1466
+ CompiledQuery.raw("DELETE FROM core_capacity_claim WHERE object_type = ?", [object]),
1467
+ CompiledQuery.raw("DELETE FROM core_capacity WHERE object_type = ?", [object])
1468
+ ];
1469
+ }
1470
+ function backfillCounters(input) {
1471
+ const places = `CASE WHEN typeof(t.${input.placesColumn}) IN ('integer', 'real') AND t.${input.placesColumn} >= 0 THEN CAST(t.${input.placesColumn} AS INTEGER) END`;
1472
+ const poolRecord = input.pool ? `(SELECT p.record_id FROM core_capacity p WHERE p.object_type = ? AND p.record_id = t.${input.pool.column})` : "NULL";
1473
+ const poolObject = input.pool ? `CASE WHEN ${poolRecord} IS NULL THEN NULL ELSE ? END` : "NULL";
1474
+ const params = input.pool ? [input.object, input.pool.object, input.pool.object, input.pool.object, input.now] : [input.object, input.now];
1475
+ return CompiledQuery.raw(
1476
+ `INSERT INTO core_capacity (object_type, record_id, places, pool_object_type, pool_record_id, updated_at) SELECT ?, t.id, ${places}, ${poolObject}, ${poolRecord}, ? FROM ${input.table} t WHERE true ON CONFLICT (object_type, record_id) DO NOTHING`,
1477
+ params
1478
+ );
1479
+ }
1480
+
1481
+ // ../core/src/capacity/waitlist.ts
1482
+ async function liveClaimIds(db, object, id) {
1483
+ const rows = await db.selectFrom("core_capacity_claim").select("id").where("for_type", "=", object).where("for_id", "=", id).where("state", "in", ["held", "confirmed"]).execute();
1484
+ return rows.map((r) => r.id);
1485
+ }
1486
+ async function holdsOn(db, t, on) {
1487
+ const row = await db.selectFrom("core_capacity_claim").select((eb) => eb.fn.countAll().as("n")).where("object_type", "=", t.claims.object).where("record_id", "=", on).where("for_type", "=", WAITLIST_FOR).where("for_id", "=", t.object.name).where("state", "=", "held").executeTakeFirst();
1488
+ return Number(row?.n ?? 0);
1489
+ }
1490
+ var WAITLIST_FOR = "waitlist";
1491
+ function waitlistOf(object) {
1492
+ const claims = object.claims;
1493
+ const waitlist = claims?.waitlist;
1494
+ const stateField = object.states?.field;
1495
+ if (!claims || !waitlist || !stateField) return null;
1496
+ const onColumn = object.fields.find((f) => f.name === claims.on)?.column;
1497
+ const stateColumn = object.fields.find((f) => f.name === stateField)?.column;
1498
+ if (!onColumn || !stateColumn) return null;
1499
+ const passedOverColumn = waitlist.passedOverAt ? object.fields.find((f) => f.name === waitlist.passedOverAt)?.column : void 0;
1500
+ return {
1501
+ object,
1502
+ claims,
1503
+ waitlist,
1504
+ source: object.source,
1505
+ onColumn,
1506
+ stateColumn,
1507
+ ...passedOverColumn ? { passedOverColumn } : {}
1508
+ };
1509
+ }
1510
+ function requireWaitlist(objectName) {
1511
+ const object = getObject(objectName);
1512
+ const target = object ? waitlistOf(object) : null;
1513
+ if (!target) {
1514
+ throw new ValidationError(`${objectName} has no waitlist`, { field: "object" });
1515
+ }
1516
+ return target;
1517
+ }
1518
+ var ident = (name) => `"${name.replaceAll('"', '""')}"`;
1519
+ function waitersSql(t) {
1520
+ return `EXISTS (SELECT 1 FROM ${ident(t.source)} w WHERE w.${ident(t.onColumn)} = ? AND w.${ident(t.stateColumn)} = ? AND w.id != ?)`;
1521
+ }
1522
+ async function cutoffOf(ctx, t, values) {
1523
+ return boundMoment(ctx, pathReader(ctx, t.object, values), t.waitlist.until);
1524
+ }
1525
+ async function beforeCutoff(ctx, t, values) {
1526
+ const cutoff = await cutoffOf(ctx, t, values);
1527
+ return cutoff !== null && Date.parse(ctx.now) < cutoff;
1528
+ }
1529
+ function handOnStatements(t, on, claimant, claims, id, now) {
1530
+ const released = `EXISTS (SELECT 1 FROM core_capacity_claim r WHERE r.id IN (SELECT value FROM json_each(?)) AND r.object_type = ? AND r.record_id = ? AND r.state = 'released' AND r.released_at = ?)`;
1531
+ const conditions = `${released} AND ${waitersSql(t)}`;
1532
+ const params = [JSON.stringify(claims), t.claims.object, on, now, on, t.waitlist.state, claimant];
1533
+ return [
1534
+ CompiledQuery.raw(
1535
+ `UPDATE core_capacity SET held = held + 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND ${conditions}`,
1536
+ [now, t.claims.object, on, ...params]
1537
+ ),
1538
+ CompiledQuery.raw(
1539
+ `INSERT INTO core_capacity_claim (id, object_type, record_id, pool_object_type, pool_record_id, quantity, state, for_type, for_id, created_at, updated_at) SELECT ?, ?, ?, NULL, NULL, 1, 'held', ?, ?, ?, ? WHERE ${conditions}`,
1540
+ [id, t.claims.object, on, WAITLIST_FOR, t.object.name, now, now, ...params]
1541
+ )
1542
+ ];
1543
+ }
1544
+ async function handOnAfterRelease(ctx, object, id) {
1545
+ const t = waitlistOf(object);
1546
+ if (!t) return;
1547
+ const row = await ctx.db.selectFrom(t.source).select(t.onColumn).where("id", "=", id).executeTakeFirst();
1548
+ const on = row?.[t.onColumn];
1549
+ if (typeof on !== "string" || !on) return;
1550
+ const claims = await liveClaimIds(ctx.db, object.name, id);
1551
+ if (!claims.length) return;
1552
+ if (!await beforeCutoff(ctx, t, { [t.claims.on]: on })) return;
1553
+ ctx.write(...handOnStatements(t, on, id, claims, newId("capacityClaim"), ctx.now));
1554
+ }
1555
+ async function erasedWaiter(ctx, object, id) {
1556
+ const t = waitlistOf(object);
1557
+ if (!t) return null;
1558
+ const row = await ctx.db.selectFrom(t.source).select([t.onColumn, t.stateColumn]).where("id", "=", id).executeTakeFirst();
1559
+ if (!row || row[t.stateColumn] !== t.waitlist.state) return null;
1560
+ const on = row[t.onColumn];
1561
+ if (typeof on !== "string" || !on) return [];
1562
+ return releaseHoldsStatements(t, on, ctx.now, { unlessWaiting: { except: id } });
1563
+ }
1564
+ function takeHoldStatements(t, on, now) {
1565
+ const holds = `SELECT id FROM core_capacity_claim WHERE object_type = ? AND record_id = ? AND for_type = ? AND for_id = ? AND state = 'held'`;
1566
+ const params = [t.claims.object, on, WAITLIST_FOR, t.object.name];
1567
+ return [
1568
+ CompiledQuery.raw(
1569
+ `UPDATE core_capacity SET held = held - 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND EXISTS (${holds})`,
1570
+ [now, t.claims.object, on, ...params]
1571
+ ),
1572
+ CompiledQuery.raw(
1573
+ `UPDATE core_capacity_claim SET state = 'released', released_at = ?, updated_at = ? WHERE id = (${holds} ORDER BY created_at, id LIMIT 1)`,
1574
+ [now, now, ...params]
1575
+ )
1576
+ ];
1577
+ }
1578
+ function releaseHoldsStatements(t, on, now, options = {}) {
1579
+ const where = [
1580
+ "c.object_type = ?",
1581
+ "c.record_id = ?",
1582
+ "c.for_type = ?",
1583
+ "c.for_id = ?",
1584
+ "c.state = 'held'",
1585
+ ...options.before !== void 0 ? ["c.created_at <= ?"] : []
1586
+ ].join(" AND ");
1587
+ const params = [
1588
+ t.claims.object,
1589
+ on,
1590
+ WAITLIST_FOR,
1591
+ t.object.name,
1592
+ ...options.before !== void 0 ? [options.before] : []
1593
+ ];
1594
+ const unless = options.unlessWaiting ? {
1595
+ sql: ` AND NOT ${waitersSql(t)}`,
1596
+ params: [on, t.waitlist.state, options.unlessWaiting.except]
1597
+ } : { sql: "", params: [] };
1598
+ return [
1599
+ CompiledQuery.raw(
1600
+ `UPDATE core_capacity SET held = held - (SELECT coalesce(sum(c.quantity), 0) FROM core_capacity_claim c WHERE ${where}), updated_at = ? WHERE object_type = ? AND record_id = ?${unless.sql}`,
1601
+ [...params, now, t.claims.object, on, ...unless.params]
1602
+ ),
1603
+ CompiledQuery.raw(
1604
+ `UPDATE core_capacity_claim SET state = 'released', released_at = ?, updated_at = ? WHERE id IN (SELECT c.id FROM core_capacity_claim c WHERE ${where})${unless.sql}`,
1605
+ [now, now, ...params, ...unless.params]
1606
+ )
1607
+ ];
1608
+ }
1609
+ function releaseAllWaitlistHoldsStatements(object, now) {
1610
+ return [
1611
+ CompiledQuery.raw(
1612
+ "UPDATE core_capacity SET held = held - (SELECT coalesce(sum(c.quantity), 0) FROM core_capacity_claim c WHERE c.for_type = ? AND c.for_id = ? AND c.state = 'held' AND c.object_type = core_capacity.object_type AND c.record_id = core_capacity.record_id), updated_at = ? WHERE (object_type, record_id) IN (SELECT c.object_type, c.record_id FROM core_capacity_claim c WHERE c.for_type = ? AND c.for_id = ? AND c.state = 'held')",
1613
+ [WAITLIST_FOR, object, now, WAITLIST_FOR, object]
1614
+ ),
1615
+ CompiledQuery.raw(
1616
+ "UPDATE core_capacity_claim SET state = 'released', released_at = ?, updated_at = ? WHERE for_type = ? AND for_id = ? AND state = 'held'",
1617
+ [now, now, WAITLIST_FOR, object]
1618
+ )
1619
+ ];
1620
+ }
1621
+ async function assertJoin(ctx, t, on, after) {
1622
+ if (!await beforeCutoff(ctx, t, after)) {
1623
+ throw new ValidationError(
1624
+ `The waitlist has closed: nobody is moved in from it this close to the start`,
1625
+ { rule: "waitlist", reason: "closed", field: t.object.states?.field }
1626
+ );
1627
+ }
1628
+ const counter = await readCounter(ctx.db, t.claims.object, on);
1629
+ if (!counter) throw new ValidationError("A referenced record does not exist");
1630
+ if (counter.places === null || counter.held + counter.taken < counter.places) {
1631
+ throw new ConflictError("A place is free: claim it instead of waiting.", {
1632
+ rule: "waitlist",
1633
+ reason: "not_full"
1634
+ });
1635
+ }
1636
+ if (!ctx.simulation) ctx.write(guardStatement("full", t.claims.object, on, 0));
1637
+ }
1638
+ function placeKind(claims, state) {
1639
+ if (typeof state !== "string") return null;
1640
+ if (claims.held.includes(state)) return "held";
1641
+ if (claims.confirmed.includes(state)) return "confirmed";
1642
+ return null;
1643
+ }
1644
+ async function waitlistMove(ctx, object, id, before, after, by, phase) {
1645
+ const t = waitlistOf(object);
1646
+ const field = object.states?.field;
1647
+ if (!t || !field) return;
1648
+ const waiting = t.waitlist.state;
1649
+ const was = before === null ? null : before[field];
1650
+ const is = after[field];
1651
+ const onBefore = before === null ? null : before[t.claims.on];
1652
+ const onAfter = after[t.claims.on];
1653
+ if (phase === "before") {
1654
+ if (was === waiting && is === t.waitlist.promote) {
1655
+ const closed = object.states?.create?.closed;
1656
+ if (closed && await staffOnlySet(pathReader(ctx, object, after), closed)) {
1657
+ throw new ValidationError(`${object.label} cannot move in now: what it is for is closed`, {
1658
+ rule: "state_closed",
1659
+ field
1660
+ });
1661
+ }
1662
+ if (closed) await queueUnmovedGuards(ctx, object, after, closed);
1663
+ }
1664
+ if (was === waiting && is === t.waitlist.promote && by === "host") {
1665
+ if (typeof onAfter === "string" && onAfter) {
1666
+ ctx.write(...takeHoldStatements(t, onAfter, ctx.now));
1667
+ if (ctx.simulation && await holdsOn(ctx.db, t, onAfter) > 0) {
1668
+ creditSimulatedClaim(ctx, t.claims.object, onAfter, 1);
1669
+ }
1670
+ }
1671
+ }
1672
+ return;
1673
+ }
1674
+ if (is === waiting && by !== "host" && was !== waiting) {
1675
+ if (typeof onAfter !== "string" || !onAfter) {
1676
+ const label = object.fields.find((f) => f.name === t.claims.on)?.label ?? t.claims.on;
1677
+ throw new ValidationError(`${object.label} needs ${label} to wait for a place`, {
1678
+ field: t.claims.on,
1679
+ rule: "waitlist"
1680
+ });
1681
+ }
1682
+ await assertJoin(ctx, t, onAfter, after);
1683
+ }
1684
+ if (was === waiting && is !== waiting && is !== t.waitlist.promote) {
1685
+ if (typeof onBefore === "string" && onBefore) {
1686
+ ctx.write(...releaseHoldsStatements(t, onBefore, ctx.now, { unlessWaiting: { except: id } }));
1687
+ }
1688
+ }
1689
+ const from = before === null ? null : placeKind(t.claims, was);
1690
+ const to = placeKind(t.claims, is);
1691
+ if (from !== null && to === null && typeof onBefore === "string" && onBefore) {
1692
+ const claims = await liveClaimIds(ctx.db, object.name, id);
1693
+ if (claims.length && await beforeCutoff(ctx, t, before ?? after)) {
1694
+ ctx.write(...handOnStatements(t, onBefore, id, claims, newId("capacityClaim"), ctx.now));
1695
+ }
1696
+ }
1697
+ }
1698
+ async function waitlistPosition(db, t, id) {
1699
+ const k = db;
1700
+ const mine = await k.selectFrom(t.source).select(["id", "created_at", t.onColumn, t.stateColumn]).where("id", "=", id).executeTakeFirst();
1701
+ if (!mine || mine[t.stateColumn] !== t.waitlist.state) return null;
1702
+ const on = mine[t.onColumn];
1703
+ const rows = await k.selectFrom(t.source).select(["id", "created_at"]).where(t.onColumn, "=", on).where(t.stateColumn, "=", t.waitlist.state).execute();
1704
+ const key = (r) => `${r.created_at}|${r.id}`;
1705
+ const own = key({ id, created_at: String(mine.created_at) });
1706
+ return {
1707
+ position: rows.filter((r) => key(r) < own).length + 1,
1708
+ waiting: rows.length
1709
+ };
1710
+ }
1711
+
1712
+ // ../core/src/capacity/holds.ts
1713
+ function targetWhere(target, alias) {
1714
+ if ("claim" in target) return { sql: `${alias}.id = ?`, params: [target.claim] };
1715
+ if ("forType" in target) return { sql: `${alias}.for_type = ?`, params: [target.forType] };
1716
+ return {
1717
+ sql: `${alias}.for_type = ? AND ${alias}.for_id = ?`,
1718
+ params: [target.for.type, target.for.id]
1719
+ };
1720
+ }
1721
+ function counterMoves(target, state, sets, now) {
1722
+ const where = targetWhere(target, "c");
1723
+ return ["record", "pool"].map((level) => {
1724
+ const [object, record] = level === "record" ? ["object_type", "record_id"] : ["pool_object_type", "pool_record_id"];
1725
+ const sum = `(SELECT coalesce(sum(c.quantity), 0) FROM core_capacity_claim c WHERE ${where.sql} AND c.state = '${state}' AND c.${object} = core_capacity.object_type AND c.${record} = core_capacity.record_id)`;
1726
+ const assignments = [
1727
+ `${sets.minus} = ${sets.minus} - ${sum}`,
1728
+ ...sets.plus ? [`${sets.plus} = ${sets.plus} + ${sum}`] : [],
1729
+ "updated_at = ?"
1730
+ ];
1731
+ const params = [...where.params, ...sets.plus ? where.params : [], now, ...where.params];
1732
+ return CompiledQuery.raw(
1733
+ `UPDATE core_capacity SET ${assignments.join(", ")} WHERE (object_type, record_id) IN (SELECT c.${object}, c.${record} FROM core_capacity_claim c WHERE ${where.sql} AND c.state = '${state}' AND c.${object} IS NOT NULL)`,
1734
+ params
1735
+ );
1736
+ });
1737
+ }
1738
+ function claimMove(target, from, to, now) {
1739
+ const where = targetWhere(target, "core_capacity_claim");
1740
+ const stamp = to === "confirmed" ? "confirmed_at" : "released_at";
1741
+ return CompiledQuery.raw(
1742
+ `UPDATE core_capacity_claim SET state = '${to}', ${stamp} = ?, updated_at = ? WHERE ${where.sql} AND state = '${from}'`,
1743
+ [now, now, ...where.params]
1744
+ );
1745
+ }
1746
+ function confirmStatements(target, now) {
1747
+ return [
1748
+ ...counterMoves(target, "held", { minus: "held", plus: "taken" }, now),
1749
+ claimMove(target, "held", "confirmed", now)
1750
+ ];
1751
+ }
1752
+ function releaseStatements(target, now, options = {}) {
1753
+ const from = options.confirmed ? "confirmed" : "held";
1754
+ return [
1755
+ ...counterMoves(target, from, { minus: from === "held" ? "held" : "taken" }, now),
1756
+ claimMove(target, from, "released", now)
1757
+ ];
1758
+ }
1759
+
1760
+ // ../core/src/capacity/claimants.ts
1761
+ function kindOf(claims, state) {
1762
+ if (typeof state !== "string") return null;
1763
+ if (claims.held.includes(state)) return "held";
1764
+ if (claims.confirmed.includes(state)) return "confirmed";
1765
+ return null;
1766
+ }
1767
+ function claimKind(object, values) {
1768
+ if (!object.claims || !object.states || !values) return null;
1769
+ return kindOf(object.claims, values[object.states.field]);
1770
+ }
1771
+ async function claimantMove(ctx, object, id, before, after) {
1772
+ const claims = object.claims;
1773
+ const field = object.states?.field;
1774
+ if (!claims || !field) return;
1775
+ const from = before === null ? null : kindOf(claims, before[field]);
1776
+ const to = kindOf(claims, after[field]);
1777
+ if (from === to) return;
1778
+ const target = { for: { type: object.name, id } };
1779
+ if (from === "held") {
1780
+ ctx.write(
1781
+ ...to === "confirmed" ? confirmStatements(target, ctx.now) : releaseStatements(target, ctx.now)
1782
+ );
1783
+ return;
1784
+ }
1785
+ if (from === "confirmed") {
1786
+ ctx.write(...releaseStatements(target, ctx.now, { confirmed: true }));
1787
+ if (to === null) return;
1788
+ }
1789
+ const on = after[claims.on];
1790
+ if (typeof on !== "string" || on === "") {
1791
+ const label = object.fields.find((f) => f.name === claims.on)?.label ?? claims.on;
1792
+ throw new ValidationError(`${object.label} needs ${label} to hold a place`, {
1793
+ field: claims.on,
1794
+ rule: "capacity"
1795
+ });
1796
+ }
1797
+ const claim = await queueClaim(ctx, {
1798
+ object: claims.object,
1799
+ record: on,
1800
+ quantity: 1,
1801
+ for: { type: object.name, id }
1802
+ });
1803
+ if (to === "confirmed") ctx.write(...confirmStatements({ claim }, ctx.now));
1804
+ }
1805
+ function assertClaimRelationKept(object, before, written) {
1806
+ const claims = object.claims;
1807
+ if (!claims || before === null || !Object.hasOwn(written, claims.on)) return;
1808
+ if ((written[claims.on] ?? null) === (before[claims.on] ?? null)) return;
1809
+ const waiting = claims.waitlist !== void 0 && object.states !== void 0 && before[object.states.field] === claims.waitlist.state;
1810
+ if (claimKind(object, before) === null && !waiting) return;
1811
+ const label = object.fields.find((f) => f.name === claims.on)?.label ?? claims.on;
1812
+ throw new ValidationError(
1813
+ waiting ? `${object.label} is waiting for a place on its ${label.toLowerCase()}, so its ${label.toLowerCase()} cannot change: leave the waitlist and join another` : `${object.label} holds a place on its ${label.toLowerCase()}, so its ${label.toLowerCase()} cannot change`,
1814
+ { field: claims.on, rule: "claim_relation_kept" }
1815
+ );
1816
+ }
1817
+ async function assertNoLiveClaim(ctx, object, id) {
1818
+ if (!object.claims) return;
1819
+ const row = await ctx.db.selectFrom("core_capacity_claim").select("state").where("for_type", "=", object.name).where("for_id", "=", id).where("state", "in", ["held", "confirmed"]).executeTakeFirst();
1820
+ if (row) {
1821
+ throw new ConflictError(
1822
+ `${object.label} holds a place; move it to a state that gives the place back before deleting it`,
1823
+ { rule: "capacity", reason: "claim_live", object: object.name, record: id }
1824
+ );
1825
+ }
1826
+ }
1827
+ function releaseAllClaimsStatements(object, now) {
1828
+ const target = { forType: object };
1829
+ return [
1830
+ ...releaseStatements(target, now),
1831
+ ...releaseStatements(target, now, { confirmed: true }),
1832
+ // And the places its waitlist held for its waiters (ADR 0520).
1833
+ ...releaseAllWaitlistHoldsStatements(object, now)
1834
+ ];
1835
+ }
1836
+ function releaseAllClaimsOfStatements(object, id, now) {
1837
+ const target = { for: { type: object, id } };
1838
+ return [
1839
+ ...releaseStatements(target, now),
1840
+ ...releaseStatements(target, now, { confirmed: true })
1841
+ ];
1842
+ }
1843
+
1844
+ export {
1845
+ ID_PREFIXES,
1846
+ newId,
1847
+ toProvisionalId,
1848
+ isProvisionalId,
1849
+ findProvisionalIds,
1850
+ findIds,
1851
+ replaceIds,
1852
+ POLICY_PRESETS,
1853
+ approvalPolicySchema,
1854
+ APPROVAL_POLICY_SETTING,
1855
+ PRESET_MATRICES,
1856
+ evaluateGate,
1857
+ evaluateOutsideGate,
1858
+ isLoosening,
1859
+ loadApprovalPolicy,
1860
+ BASE_CURRENCY_SETTING,
1861
+ ORG_NAME_SETTING,
1862
+ ORG_LOGO_SETTING,
1863
+ ORG_TIMEZONE_SETTING,
1864
+ ASSISTANT_NAME_SETTING,
1865
+ isTimezone,
1866
+ loadGeneralSettings,
1867
+ AI_SETTINGS,
1868
+ loadAiSettings,
1869
+ zoneOffset,
1870
+ realWallClock,
1871
+ localParts,
1872
+ wallClockToInstant,
1873
+ wallClockToIso,
1874
+ addLocalDays,
1875
+ parseLocalDate,
1876
+ parseLocalTime,
1877
+ wallClockOf,
1878
+ isoWeekday,
1879
+ AUDIENCES,
1880
+ OUTSIDE_RISK_CLASSES,
1881
+ audiencesOf,
1882
+ allowsAudience,
1883
+ forPacks,
1884
+ afterCommit,
1885
+ isAfterCommit,
1886
+ runAfterCommit,
1887
+ recordHostChange,
1888
+ personsTool,
1889
+ markHostTool,
1890
+ isHostTool,
1891
+ defineOperation,
1892
+ operationProblems,
1893
+ confirmStatements,
1894
+ releaseStatements,
1895
+ queueClaim,
1896
+ counterWrite,
1897
+ assertNoConfirmedClaims,
1898
+ dropCapacityStatements,
1899
+ backfillCounters,
1900
+ armSeriesStatement,
1901
+ seriesVersion,
1902
+ guardStatement,
1903
+ occurrenceStatement,
1904
+ markEditedStatement,
1905
+ dropRecurringStatements,
1906
+ callerOf,
1907
+ TransitionRuleError,
1908
+ NO_TRANSITION,
1909
+ ruleBase,
1910
+ runTransition,
1911
+ transitionTimeline,
1912
+ pathReader,
1913
+ UNREADABLE,
1914
+ boundMoment,
1915
+ statesLifecycle,
1916
+ resolveStateRequest,
1917
+ assertCreateRules,
1918
+ WAITLIST_FOR,
1919
+ requireWaitlist,
1920
+ beforeCutoff,
1921
+ handOnAfterRelease,
1922
+ erasedWaiter,
1923
+ releaseHoldsStatements,
1924
+ waitlistMove,
1925
+ waitlistPosition,
1926
+ claimantMove,
1927
+ assertClaimRelationKept,
1928
+ assertNoLiveClaim,
1929
+ releaseAllClaimsStatements,
1930
+ releaseAllClaimsOfStatements
1931
+ };