@composable-os/sdk 0.0.0-stage → 0.1.0-beta.10

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 (81) hide show
  1. package/LICENSE +109 -0
  2. package/dist/allowance.d.ts +198 -0
  3. package/dist/allowance.js +374 -0
  4. package/dist/automation-check.d.ts +38 -0
  5. package/dist/automation-check.js +454 -0
  6. package/dist/automation.d.ts +767 -0
  7. package/dist/automation.js +303 -0
  8. package/dist/behaviour.d.ts +3 -0
  9. package/dist/behaviour.js +153 -0
  10. package/dist/capacity.d.ts +77 -0
  11. package/dist/capacity.js +127 -0
  12. package/dist/contract.d.ts +819 -0
  13. package/dist/contract.js +42 -0
  14. package/dist/document.d.ts +211 -0
  15. package/dist/document.js +726 -0
  16. package/dist/field-types.d.ts +11 -0
  17. package/dist/field-types.js +98 -0
  18. package/dist/formula/ast.d.ts +67 -0
  19. package/dist/formula/ast.js +22 -0
  20. package/dist/formula/compile.d.ts +37 -0
  21. package/dist/formula/compile.js +379 -0
  22. package/dist/formula/index.d.ts +3 -0
  23. package/dist/formula/index.js +4 -0
  24. package/dist/formula/parser.d.ts +13 -0
  25. package/dist/formula/parser.js +365 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.js +24 -0
  28. package/dist/manifest.d.ts +1596 -0
  29. package/dist/manifest.js +1420 -0
  30. package/dist/media.d.ts +41 -0
  31. package/dist/media.js +90 -0
  32. package/dist/permissions.d.ts +17 -0
  33. package/dist/permissions.js +44 -0
  34. package/dist/recurring.d.ts +114 -0
  35. package/dist/recurring.js +173 -0
  36. package/dist/renamed.d.ts +16 -0
  37. package/dist/renamed.js +59 -0
  38. package/dist/rich-text-fixture.d.ts +121 -0
  39. package/dist/rich-text-fixture.js +67 -0
  40. package/dist/rich-text.d.ts +48 -0
  41. package/dist/rich-text.js +184 -0
  42. package/dist/runtime.d.ts +95 -0
  43. package/dist/runtime.js +312 -0
  44. package/dist/sellable.d.ts +253 -0
  45. package/dist/sellable.js +593 -0
  46. package/dist/slug.d.ts +11 -0
  47. package/dist/slug.js +23 -0
  48. package/dist/states.d.ts +238 -0
  49. package/dist/states.js +315 -0
  50. package/dist/testing.d.ts +151 -0
  51. package/dist/testing.js +679 -0
  52. package/dist/unique.d.ts +20 -0
  53. package/dist/unique.js +58 -0
  54. package/package.json +34 -4
  55. package/src/allowance.ts +522 -0
  56. package/src/automation-check.ts +534 -0
  57. package/src/automation.ts +743 -0
  58. package/src/behaviour.ts +215 -0
  59. package/src/capacity.ts +201 -0
  60. package/src/contract.ts +884 -0
  61. package/src/document.ts +935 -0
  62. package/src/field-types.ts +111 -0
  63. package/src/formula/ast.ts +72 -0
  64. package/src/formula/compile.ts +454 -0
  65. package/src/formula/index.ts +4 -0
  66. package/src/formula/parser.ts +417 -0
  67. package/src/index.ts +36 -0
  68. package/src/manifest.ts +1709 -0
  69. package/src/media.ts +108 -0
  70. package/src/permissions.ts +60 -0
  71. package/src/recurring.ts +321 -0
  72. package/src/renamed.ts +63 -0
  73. package/src/rich-text-fixture.ts +68 -0
  74. package/src/rich-text.ts +221 -0
  75. package/src/runtime.ts +410 -0
  76. package/src/sellable.ts +888 -0
  77. package/src/slug.ts +25 -0
  78. package/src/states.ts +484 -0
  79. package/src/testing.ts +847 -0
  80. package/src/unique.ts +81 -0
  81. package/README.md +0 -3
@@ -0,0 +1,888 @@
1
+ // The `sellable` behaviour (stage 27, ADR 0435): an object's records can be put on an order. The
2
+ // host reads the price from the record, refuses a line outside the sale window or over the most
3
+ // one order may hold, and, when the order is first paid, creates what a paid line grants (a
4
+ // ticket per place) in the batch that marks it paid. Its declaration, its manifest schema and its
5
+ // contract checks live here; the host's side is packages/core/src/orders/ (sellable.ts, grants.ts).
6
+ import { z } from "zod";
7
+ import { customerWritable, spendsOnList } from "./allowance.ts";
8
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
9
+ import { moveOrigins } from "./states.ts";
10
+
11
+ /**
12
+ * Where a granted record's field gets its value, when the host creates it:
13
+ *
14
+ * - `item`: the record that was bought (a relation to this sellable object);
15
+ * - `item.<field>`: a field of the record that was bought (its event, its name);
16
+ * - `order`: the order's id (a text field);
17
+ * - `order.person`: the buyer, a relation to a person (empty when the order belongs to no one
18
+ * yet, so the field cannot be required);
19
+ * - `order.email`: the address the order was placed with;
20
+ * - `line`: the order line's id (a text field);
21
+ * - `line.title`: what the line was called when it was bought;
22
+ * - `line.unitPrice`: what one cost, in the currency's major unit;
23
+ * - `code`: a long, random, unguessable code the host makes (a ticket's). A read-only text field;
24
+ * at most one per grant. The host keeps it unique across every granted record.
25
+ */
26
+ export type GrantSource =
27
+ | "item"
28
+ | `item.${string}`
29
+ | "order"
30
+ | "order.person"
31
+ | "order.email"
32
+ | "line"
33
+ | "line.title"
34
+ | "line.unitPrice"
35
+ | "code";
36
+
37
+ /**
38
+ * What a paid line grants: one record of `object` for each unit bought (two tickets for a line
39
+ * of two), created by the host, as the host, when the order is first paid (the move to `paid`,
40
+ * or to `part_paid` for a deposit), in the same batch. No extension code runs.
41
+ *
42
+ * - `object` is another of this extension's objects. It declares `states`; its records start in
43
+ * the initial state.
44
+ * - `set` names, for each field of the granted record the host fills, where its value comes from
45
+ * (see GrantSource). Every required field of the granted object must be set from a source that
46
+ * always has a value.
47
+ * - `void` is the state the host moves what was granted to when the order is refunded in full, or
48
+ * cancelled after a deposit. Every state but `void` and the final ones needs a `host` move into
49
+ * it. A record already there, or in a final state, is left alone.
50
+ */
51
+ export interface GrantSpec {
52
+ object: string;
53
+ set: Readonly<Record<string, GrantSource>>;
54
+ void: string;
55
+ /**
56
+ * When what was granted is valid (stage 32b, ADR 0511): the host writes `from` (the moment it
57
+ * is granted) and `until` (that moment plus `days` local days in the organisation's zone; for a
58
+ * date field, the day before that, since a date includes its whole day), each a date or
59
+ * datetime field of the granted object. `days` is `item.<number field>` of the record bought (a
60
+ * class pack's "valid for 30 days"); empty there, `until` is left empty. A pass's expiry.
61
+ */
62
+ valid?: { from?: string; until?: string; days?: `item.${string}` };
63
+ }
64
+
65
+ /**
66
+ * Something that can be bought (ADR 0435). An order line may point only at a record of an object
67
+ * that declares it; the host prices the line from the record, so a caller never sends a price.
68
+ * Only a shipped pack or the org's own extension may declare it: selling to the public is a
69
+ * reviewed change, so a runtime extension that does is refused at check and install.
70
+ *
71
+ * - `price`: this object's currency (or number) field holding the price of one, in the currency's
72
+ * major unit. A record with no price cannot be bought.
73
+ * - `currency`: what the price is in (ISO 4217). Left out, the price field's own currency, and
74
+ * with neither, the deployment's. A line priced in another currency than the deployment's is
75
+ * refused.
76
+ * - `saleWindow`: the date or datetime fields saying when a record is on sale, from `from` and
77
+ * until `until` (a date: the whole day, in UTC). Empty values leave that end open. A line
78
+ * outside it is refused with `{ rule: "sale_window" }`.
79
+ * - `maxPerOrder`: a number field holding the most of one record one order may hold. Empty means
80
+ * no limit beyond the host's own: 10 when the object grants, and never more than 100 grants
81
+ * on one order (the paid batch has a size). More is refused with `{ rule: "max_per_order" }`.
82
+ * - `deposit`: paying by deposit (stage 25): the field holding the deposit for one, and the date
83
+ * field saying when the balance is due. A record offers a deposit when both have a value.
84
+ * - `grants`: what a paid line grants (see GrantSpec).
85
+ * - `tax`: tax at checkout (ADR 0479), see TaxSpec. A line is taxed only when this is declared and
86
+ * a human admin has turned tax on for the deployment.
87
+ * - `recurring`: a plan, paid for every period (stage 32a, ADR 0485), see RecurringSpec. Its records
88
+ * are subscribed to, never put on an order: `price` is the price of one period. Not with
89
+ * `deposit`, `maxPerOrder` or `grants` (32b adds what a subscription grants).
90
+ */
91
+ export interface SellableSpec {
92
+ price: string;
93
+ currency?: string;
94
+ saleWindow?: { from?: string; until?: string };
95
+ maxPerOrder?: string;
96
+ deposit?: { amount: string; balanceDue: string };
97
+ grants?: GrantSpec;
98
+ tax?: TaxSpec;
99
+ recurring?: RecurringSpec;
100
+ /**
101
+ * A boolean field: while it is true on a record, a Person may buy it once, across every record
102
+ * of this object with it true (an intro offer: one per Person, ADR 0512). The host holds it from
103
+ * the order's start, uses it when the order is paid, and gives it back only when the order
104
+ * expires or is cancelled unpaid; the database refuses a second hold, so two purchases at once
105
+ * give one. Only a buyer who proved who they are buys it (a signed-in customer, or staff for a
106
+ * Person): a guest who typed an address is refused (`rule: "once_per_person"`, `reason:
107
+ * "sign_in"`). Such a line holds one, and an order at most one such line. Not on a plan.
108
+ */
109
+ onePerPerson?: string;
110
+ }
111
+
112
+ /**
113
+ * How a plan recurs (ADR 0485). The payment provider charges every `interval` on its own schedule;
114
+ * the host learns of each paid period from its verified events and writes a paid order for it.
115
+ *
116
+ * - `interval`: `week`, `month` or `year`.
117
+ * - `trialDays`: a number field of the plan holding the days of a free first period (the card is
118
+ * taken at the start, the first charge is when it ends). Empty or zero: no trial.
119
+ */
120
+ export interface RecurringSpec {
121
+ interval: "week" | "month" | "year";
122
+ trialDays?: string;
123
+ /**
124
+ * What a subscription to the plan grants (stage 32b, ADR 0510): one record of `object` for the
125
+ * subscription's holder, made by the host when the provider first reports it running, then kept
126
+ * in step with it, as the host, in each verified event's batch: its state follows the
127
+ * subscription's (`states` maps each of the host's subscription states to one of the granted
128
+ * object's), and `until` is when it stops giving (the end of its last period when it is set to
129
+ * end, 30 days of failing while past due, the moment it ended). No extension code runs.
130
+ *
131
+ * - `object`: another of this extension's objects, declaring `states`.
132
+ * - `set`: fields filled once, when it is granted: `item` (a relation to the plan),
133
+ * `item.<field>` (the plan's terms as they are at the start: its uses, its class types),
134
+ * `subscription` (a text field, the subscription's id), `subscription.holder` and
135
+ * `subscription.payer` (relations to person). The holder always has a value.
136
+ * - `from`, `until`: datetime fields the host keeps.
137
+ * - `states`: the granted object's state for each subscription state that grants
138
+ * (`trialing`, `active`, `past_due`, `unpaid`, `paused`, `ended`); `ended`'s is final.
139
+ *
140
+ * Not the `recurring` behaviour (a weekly timetable rule, ADR 0500): this is the plan's own
141
+ * `sellable.recurring`, and its `grants` is what the subscription gives while it runs.
142
+ */
143
+ grants?: RecurringGrantSpec;
144
+ }
145
+
146
+ /** Where a field of what a subscription grants gets its value (see RecurringSpec.grants). */
147
+ export type RecurringGrantSource =
148
+ | "item"
149
+ | `item.${string}`
150
+ | "subscription"
151
+ | "subscription.holder"
152
+ | "subscription.payer";
153
+
154
+ /** The host's subscription states a grant follows (ADR 0485). */
155
+ export const SUBSCRIPTION_GRANT_STATES = [
156
+ "trialing",
157
+ "active",
158
+ "past_due",
159
+ "unpaid",
160
+ "paused",
161
+ "ended",
162
+ ] as const;
163
+ export type SubscriptionGrantState = (typeof SUBSCRIPTION_GRANT_STATES)[number];
164
+
165
+ export interface RecurringGrantSpec {
166
+ object: string;
167
+ set: Readonly<Record<string, RecurringGrantSource>>;
168
+ from?: string;
169
+ until?: string;
170
+ states: Readonly<Record<SubscriptionGrantState, string>>;
171
+ }
172
+
173
+ /**
174
+ * How the payment provider taxes a line of this object (ADR 0479). Prices stay what the buyer
175
+ * pays: the provider works the tax out inside them.
176
+ *
177
+ * - `code`: the provider's product tax code (Stripe's list: `txcd_` and eight digits). A human
178
+ * admin may override it per object in Settings → Orders.
179
+ * - `place`: for admission to an in-person event, where it is held, so the provider taxes it
180
+ * there and not where the buyer lives. Text fields of this object, or of the record its
181
+ * relation `via` points at (a ticket type's event): `country` (two letters, ISO 3166-1) and,
182
+ * when given, `region`, `postcode`, `city` and `line1`.
183
+ */
184
+ export interface TaxSpec {
185
+ code: string;
186
+ place?: {
187
+ via?: string;
188
+ country: string;
189
+ region?: string;
190
+ postcode?: string;
191
+ city?: string;
192
+ line1?: string;
193
+ };
194
+ }
195
+
196
+ /** A product tax code as Stripe's list has them. */
197
+ export const TAX_CODE_PATTERN = /^txcd_\d{8}$/;
198
+
199
+ const fieldName = z.string().max(40);
200
+
201
+ export const GRANT_SOURCES = [
202
+ "item",
203
+ "order",
204
+ "order.person",
205
+ "order.email",
206
+ "line",
207
+ "line.title",
208
+ "line.unitPrice",
209
+ "code",
210
+ ] as const;
211
+
212
+ const itemSource = z
213
+ .string()
214
+ .regex(/^item\.[a-z][a-zA-Z0-9]{0,39}$/, "item.<field>") as z.ZodType<`item.${string}`>;
215
+
216
+ const recurringGrantSource = z.union([
217
+ z.enum(["item", "subscription", "subscription.holder", "subscription.payer"]),
218
+ itemSource,
219
+ ]);
220
+
221
+ const grantSource = z.union([
222
+ z.enum(GRANT_SOURCES),
223
+ z.string().regex(/^item\.[a-z][a-zA-Z0-9]{0,39}$/, "Use item, item.<field>, order, line or code"),
224
+ ]);
225
+
226
+ export const sellableManifestSchema = z
227
+ .object({
228
+ price: fieldName,
229
+ currency: z
230
+ .string()
231
+ .regex(/^[A-Z]{3}$/)
232
+ .optional(),
233
+ saleWindow: z
234
+ .object({ from: fieldName.optional(), until: fieldName.optional() })
235
+ .strict()
236
+ .optional(),
237
+ maxPerOrder: fieldName.optional(),
238
+ deposit: z
239
+ .object({ amount: fieldName.optional(), balanceDue: fieldName.optional() })
240
+ .strict()
241
+ .optional(),
242
+ grants: z
243
+ .object({
244
+ object: z.string().max(40),
245
+ set: z.record(fieldName, grantSource),
246
+ void: z.string().min(1).max(100),
247
+ valid: z
248
+ .object({
249
+ from: fieldName.optional(),
250
+ until: fieldName.optional(),
251
+ days: itemSource.optional(),
252
+ })
253
+ .strict()
254
+ .optional(),
255
+ })
256
+ .strict()
257
+ .optional(),
258
+ onePerPerson: fieldName.optional(),
259
+ tax: z
260
+ .object({
261
+ code: z.string().regex(TAX_CODE_PATTERN, "A product tax code: txcd_ and eight digits"),
262
+ place: z
263
+ .object({
264
+ via: fieldName.optional(),
265
+ country: fieldName,
266
+ region: fieldName.optional(),
267
+ postcode: fieldName.optional(),
268
+ city: fieldName.optional(),
269
+ line1: fieldName.optional(),
270
+ })
271
+ .strict()
272
+ .optional(),
273
+ })
274
+ .strict()
275
+ .optional(),
276
+ recurring: z
277
+ .object({
278
+ interval: z.enum(["week", "month", "year"]),
279
+ trialDays: fieldName.optional(),
280
+ grants: z
281
+ .object({
282
+ object: z.string().max(40),
283
+ set: z.record(fieldName, recurringGrantSource),
284
+ from: fieldName.optional(),
285
+ until: fieldName.optional(),
286
+ states: z
287
+ .object({
288
+ trialing: z.string().min(1).max(100),
289
+ active: z.string().min(1).max(100),
290
+ past_due: z.string().min(1).max(100),
291
+ unpaid: z.string().min(1).max(100),
292
+ paused: z.string().min(1).max(100),
293
+ ended: z.string().min(1).max(100),
294
+ })
295
+ .strict(),
296
+ })
297
+ .strict()
298
+ .optional(),
299
+ })
300
+ .strict()
301
+ .optional(),
302
+ })
303
+ .strict();
304
+ export type SellableManifest = z.infer<typeof sellableManifestSchema>;
305
+
306
+ const NUMERIC = new Set(["number", "currency"]);
307
+ const DATES = new Set(["date", "datetime"]);
308
+ const TEXT = new Set(["text"]);
309
+
310
+ /** Reports problems with `objects.<name>.sellable` through `contract`. */
311
+ export function checkObjectSellable(
312
+ m: ExtensionManifest,
313
+ name: string,
314
+ object: ObjectManifest,
315
+ contract: (path: string, message: string) => void,
316
+ ): void {
317
+ const sellable = object.sellable;
318
+ if (!sellable) return;
319
+ const path = `objects.${name}.sellable`;
320
+ const fieldOf = (local: string): FieldManifest | undefined =>
321
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
322
+ const single = (local: string, types: Set<string>) => {
323
+ const field = fieldOf(local);
324
+ return field !== undefined && types.has(field.type) && !field.many;
325
+ };
326
+
327
+ if (!single(sellable.price, NUMERIC)) {
328
+ contract(`${path}.price`, `"${sellable.price}" must be a currency or number field of ${name}`);
329
+ } else {
330
+ const own = fieldOf(sellable.price)?.currency;
331
+ if (sellable.currency && own && own !== sellable.currency) {
332
+ contract(
333
+ `${path}.currency`,
334
+ `The price field is in ${own}; currency says ${sellable.currency}. Declare one`,
335
+ );
336
+ }
337
+ }
338
+ if (sellable.saleWindow) {
339
+ const { from, until } = sellable.saleWindow;
340
+ if (from === undefined && until === undefined) {
341
+ contract(`${path}.saleWindow`, "A sale window names its from field, its until field or both");
342
+ }
343
+ for (const [key, local] of [
344
+ ["from", from],
345
+ ["until", until],
346
+ ] as const) {
347
+ if (local !== undefined && !single(local, DATES)) {
348
+ contract(
349
+ `${path}.saleWindow.${key}`,
350
+ `"${local}" must be a date or datetime field of ${name}`,
351
+ );
352
+ }
353
+ }
354
+ }
355
+ if (sellable.recurring) {
356
+ // A plan is subscribed to, not put on an order (ADR 0485).
357
+ for (const key of ["deposit", "maxPerOrder", "grants"] as const) {
358
+ if (sellable[key] !== undefined) {
359
+ contract(
360
+ `${path}.${key}`,
361
+ `A recurring plan has no ${key}: it is subscribed to, one at a time`,
362
+ );
363
+ }
364
+ }
365
+ const trial = sellable.recurring.trialDays;
366
+ if (trial !== undefined && !single(trial, new Set(["number"]))) {
367
+ contract(`${path}.recurring.trialDays`, `"${trial}" must be a number field of ${name}`);
368
+ }
369
+ if (sellable.onePerPerson !== undefined) {
370
+ contract(
371
+ `${path}.onePerPerson`,
372
+ "A plan's trial is already one per person (ADR 0489); onePerPerson is for things bought once",
373
+ );
374
+ }
375
+ if (sellable.recurring.grants) {
376
+ checkRecurringGrants(
377
+ m,
378
+ name,
379
+ object,
380
+ sellable.recurring.grants,
381
+ `${path}.recurring.grants`,
382
+ contract,
383
+ );
384
+ }
385
+ }
386
+ if (sellable.onePerPerson !== undefined && !single(sellable.onePerPerson, new Set(["boolean"]))) {
387
+ contract(
388
+ `${path}.onePerPerson`,
389
+ `"${sellable.onePerPerson}" must be a boolean field of ${name}`,
390
+ );
391
+ }
392
+ if (sellable.maxPerOrder !== undefined && !single(sellable.maxPerOrder, new Set(["number"]))) {
393
+ contract(`${path}.maxPerOrder`, `"${sellable.maxPerOrder}" must be a number field of ${name}`);
394
+ }
395
+ if (sellable.deposit) {
396
+ const { amount, balanceDue } = sellable.deposit;
397
+ if (amount === undefined || balanceDue === undefined) {
398
+ contract(
399
+ `${path}.deposit`,
400
+ "A deposit names both fields: amount (the deposit for one) and balanceDue (when the rest is due)",
401
+ );
402
+ }
403
+ if (amount !== undefined && !single(amount, NUMERIC)) {
404
+ contract(
405
+ `${path}.deposit.amount`,
406
+ `"${amount}" must be a currency or number field of ${name}`,
407
+ );
408
+ }
409
+ if (balanceDue !== undefined && !single(balanceDue, DATES)) {
410
+ contract(
411
+ `${path}.deposit.balanceDue`,
412
+ `"${balanceDue}" must be a date or datetime field of ${name}`,
413
+ );
414
+ }
415
+ }
416
+ if (sellable.grants) checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
417
+ const place = sellable.tax?.place;
418
+ if (place) {
419
+ let holder: ObjectManifest | undefined = object;
420
+ let holderName = name;
421
+ if (place.via !== undefined) {
422
+ const via = fieldOf(place.via);
423
+ const local = via?.to?.startsWith(`${m.id}.`) ? via.to.slice(m.id.length + 1) : undefined;
424
+ if (
425
+ !via ||
426
+ via.type !== "relation" ||
427
+ via.many ||
428
+ !local ||
429
+ !Object.hasOwn(m.objects, local)
430
+ ) {
431
+ contract(
432
+ `${path}.tax.place.via`,
433
+ `"${place.via}" must be a relation of ${name} to one record of another of this extension's objects`,
434
+ );
435
+ holder = undefined;
436
+ } else {
437
+ holder = m.objects[local];
438
+ holderName = local;
439
+ }
440
+ }
441
+ if (holder) {
442
+ for (const key of ["country", "region", "postcode", "city", "line1"] as const) {
443
+ const local = place[key];
444
+ if (local === undefined) continue;
445
+ const field = Object.hasOwn(holder.fields, local) ? holder.fields[local] : undefined;
446
+ if (!field || field.type !== "text" || field.many) {
447
+ contract(`${path}.tax.place.${key}`, `"${local}" must be a text field of ${holderName}`);
448
+ }
449
+ }
450
+ }
451
+ }
452
+ }
453
+
454
+ function checkGrants(
455
+ m: ExtensionManifest,
456
+ name: string,
457
+ item: ObjectManifest,
458
+ grants: NonNullable<SellableManifest["grants"]>,
459
+ path: string,
460
+ contract: (path: string, message: string) => void,
461
+ ): void {
462
+ const local = grants.object.startsWith(`${m.id}.`)
463
+ ? grants.object.slice(m.id.length + 1)
464
+ : grants.object;
465
+ const granted = Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
466
+ if (!granted) {
467
+ contract(`${path}.object`, `"${grants.object}" must be another of this extension's objects`);
468
+ return;
469
+ }
470
+ if (local === name) {
471
+ contract(`${path}.object`, "An object cannot grant records of itself");
472
+ return;
473
+ }
474
+ if (granted.sellable) {
475
+ contract(
476
+ `${path}.object`,
477
+ `${local} is itself sellable; a grant is what was bought, not more for sale`,
478
+ );
479
+ }
480
+ const states = granted.states;
481
+ if (!states) {
482
+ contract(
483
+ `${path}.object`,
484
+ `${local} must declare states, so what was granted can be voided (to "${grants.void}")`,
485
+ );
486
+ } else {
487
+ const stateField = granted.fields[states.field];
488
+ const values = new Set((stateField?.options ?? []).map((o) => o.value));
489
+ const finals = new Set(states.moves.filter((mv) => mv.final).map((mv) => mv.to));
490
+ if (!values.has(grants.void)) {
491
+ contract(`${path}.void`, `"${grants.void}" is not a state of ${local}`);
492
+ } else if (grants.void === states.initial) {
493
+ contract(
494
+ `${path}.void`,
495
+ `"${grants.void}" is ${local}'s initial state; void is where a grant ends`,
496
+ );
497
+ } else {
498
+ for (const state of values) {
499
+ if (state === grants.void || finals.has(state)) continue;
500
+ const moves = states.moves.some(
501
+ (mv) =>
502
+ mv.to === grants.void && moveOrigins(mv).includes(state) && mv.by.includes("host"),
503
+ );
504
+ if (!moves) {
505
+ contract(
506
+ `${path}.void`,
507
+ `${local} needs a move from "${state}" to "${grants.void}" that the host may make (by: ["host", ...])`,
508
+ );
509
+ }
510
+ }
511
+ }
512
+ if (Object.hasOwn(grants.set, states.field)) {
513
+ contract(
514
+ `${path}.set.${states.field}`,
515
+ `${states.field} is ${local}'s state: a granted record starts in "${states.initial}"`,
516
+ );
517
+ }
518
+ }
519
+
520
+ const itemField = (f: string) => (Object.hasOwn(item.fields, f) ? item.fields[f] : undefined);
521
+ let codes = 0;
522
+ for (const [target, source] of Object.entries(grants.set)) {
523
+ const fp = `${path}.set.${target}`;
524
+ const field = Object.hasOwn(granted.fields, target) ? granted.fields[target] : undefined;
525
+ if (!field || field.type === "formula") {
526
+ contract(fp, `"${target}" must be a field of ${local} other than a formula`);
527
+ continue;
528
+ }
529
+ const want = (ok: boolean, what: string) => {
530
+ if (!ok) contract(fp, `${source} needs ${what}; "${target}" is a ${field.type} field`);
531
+ };
532
+ const one = !field.many;
533
+ if (source === "item") {
534
+ want(
535
+ field.type === "relation" && one && field.to === `${m.id}.${name}`,
536
+ `a relation (one record) to ${m.id}.${name}`,
537
+ );
538
+ } else if (source.startsWith("item.")) {
539
+ const from = source.slice("item.".length);
540
+ const own = itemField(from);
541
+ if (!own || own.type === "formula") {
542
+ contract(fp, `"${from}" is not a field of ${name}`);
543
+ continue;
544
+ }
545
+ want(
546
+ own.type === field.type &&
547
+ Boolean(own.many) === Boolean(field.many) &&
548
+ (own.type !== "relation" || own.to === field.to),
549
+ `a ${own.type} field${own.to ? ` to ${own.to}` : ""}, like ${name}.${from}`,
550
+ );
551
+ if (field.required && !own.required) {
552
+ contract(fp, `"${target}" is required and ${name}.${from} may be empty`);
553
+ }
554
+ } else if (source === "order.person") {
555
+ want(field.type === "relation" && one && field.to === "person", "a relation to one person");
556
+ if (field.required) {
557
+ contract(fp, `"${target}" cannot be required: an order may belong to no one yet`);
558
+ }
559
+ } else if (source === "order.email") {
560
+ want(field.type === "email" || field.type === "text", "an email or text field");
561
+ } else if (source === "order" || source === "line" || source === "line.title") {
562
+ want(TEXT.has(field.type), "a text field");
563
+ } else if (source === "line.unitPrice") {
564
+ want(NUMERIC.has(field.type), "a currency or number field");
565
+ } else if (source === "code") {
566
+ codes += 1;
567
+ want(TEXT.has(field.type), "a text field");
568
+ if (!field.readOnly) {
569
+ contract(
570
+ fp,
571
+ `"${target}" holds the host's code: make it readOnly, so nobody can change it`,
572
+ );
573
+ }
574
+ }
575
+ }
576
+ if (codes > 1) contract(`${path}.set`, "A grant has at most one code");
577
+ checkGrantedHolder(m, local, granted, contract);
578
+ if (grants.valid) {
579
+ const { from, until, days } = grants.valid;
580
+ if (from === undefined && until === undefined) {
581
+ contract(`${path}.valid`, "valid names the granted object's from field, until field or both");
582
+ }
583
+ for (const [key, target] of [
584
+ ["from", from],
585
+ ["until", until],
586
+ ] as const) {
587
+ if (target === undefined) continue;
588
+ const field = Object.hasOwn(granted.fields, target) ? granted.fields[target] : undefined;
589
+ if (!field || !DATES.has(field.type) || field.many) {
590
+ contract(
591
+ `${path}.valid.${key}`,
592
+ `"${target}" must be a date or datetime field of ${local}`,
593
+ );
594
+ } else if (Object.hasOwn(grants.set, target)) {
595
+ contract(
596
+ `${path}.valid.${key}`,
597
+ `"${target}" is in set too: the host writes it from valid`,
598
+ );
599
+ }
600
+ }
601
+ if (days !== undefined) {
602
+ const own = itemField(days.slice("item.".length));
603
+ if (own?.type !== "number" || own.many) {
604
+ contract(`${path}.valid.days`, `"${days}" must be item.<a number field of ${name}>`);
605
+ }
606
+ if (until === undefined) contract(`${path}.valid.days`, "days needs an until field to fill");
607
+ }
608
+ }
609
+
610
+ // The granted object's own rules must not be able to refuse the host's insert, since that
611
+ // would refuse the payment. What a grant always fills: its set fields whose source always has
612
+ // a value, and fields with a default.
613
+ const always = (source: string) =>
614
+ source === "order.person"
615
+ ? false
616
+ : source.startsWith("item.")
617
+ ? Boolean(itemField(source.slice("item.".length))?.required)
618
+ : true;
619
+ const filled = new Set([
620
+ ...Object.entries(grants.set)
621
+ .filter(([, source]) => always(source))
622
+ .map(([field]) => field),
623
+ ...Object.entries(granted.fields)
624
+ .filter(([, field]) => field.default !== undefined)
625
+ .map(([name]) => name),
626
+ ]);
627
+ if (granted.owner !== undefined) {
628
+ contract(
629
+ `objects.${local}.owner`,
630
+ `${local} is granted by ${name}: an owner would run assignment rules in the paid batch, which could refuse it. Remove owner`,
631
+ );
632
+ }
633
+ granted.requireOneOf?.forEach((group, i) => {
634
+ if (!group.some((field) => filled.has(field))) {
635
+ contract(
636
+ `objects.${local}.requireOneOf.${i}`,
637
+ `${local} is granted by ${name}: set one of ${group.join(", ")} in grants.set from a source that always has a value`,
638
+ );
639
+ }
640
+ });
641
+ for (const [fieldName, field] of Object.entries(granted.fields)) {
642
+ if (field.type !== "select") continue;
643
+ const source = grants.set[fieldName];
644
+ // The choices a granted record can hold when it is created.
645
+ const values =
646
+ source?.startsWith("item.") === true
647
+ ? (field.options ?? []).map((o) => o.value)
648
+ : states && fieldName === states.field
649
+ ? [states.initial]
650
+ : field.default !== undefined
651
+ ? [String(field.default)]
652
+ : [];
653
+ for (const option of field.options ?? []) {
654
+ if (!values.includes(option.value)) continue;
655
+ const missing = (option.requires ?? []).filter((required) => !filled.has(required));
656
+ if (missing.length) {
657
+ contract(
658
+ `objects.${local}.fields.${fieldName}.options`,
659
+ `${local} is granted by ${name}: "${option.value}" needs ${missing.join(", ")}, which grants.set does not always fill`,
660
+ );
661
+ }
662
+ }
663
+ }
664
+ for (const [fieldName, field] of Object.entries(granted.fields)) {
665
+ if (!field.required || field.type === "formula" || field.default !== undefined) continue;
666
+ if (states && fieldName === states.field) continue;
667
+ if (!Object.hasOwn(grants.set, fieldName)) {
668
+ contract(
669
+ `${path}.set`,
670
+ `${local}.${fieldName} is required: set it from the item, the order or the line`,
671
+ );
672
+ }
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Checks what a plan's subscription grants (ADR 0510), as `checkGrants` checks an order line's:
678
+ * each of these is a way the verified event's batch could otherwise fail, which would leave the
679
+ * provider's event unapplied.
680
+ */
681
+ function checkRecurringGrants(
682
+ m: ExtensionManifest,
683
+ name: string,
684
+ plan: ObjectManifest,
685
+ grants: NonNullable<NonNullable<SellableManifest["recurring"]>["grants"]>,
686
+ path: string,
687
+ contract: (path: string, message: string) => void,
688
+ ): void {
689
+ const local = grants.object.startsWith(`${m.id}.`)
690
+ ? grants.object.slice(m.id.length + 1)
691
+ : grants.object;
692
+ const granted = Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
693
+ if (!granted || local === name) {
694
+ contract(`${path}.object`, `"${grants.object}" must be another of this extension's objects`);
695
+ return;
696
+ }
697
+ if (granted.sellable) {
698
+ contract(`${path}.object`, `${local} is itself sellable; a grant is what was bought`);
699
+ }
700
+ if (granted.owner !== undefined) {
701
+ contract(
702
+ `objects.${local}.owner`,
703
+ `${local} is granted by ${name}'s subscriptions: an owner would run assignment rules in the provider's event batch. Remove owner`,
704
+ );
705
+ }
706
+ const states = granted.states;
707
+ if (!states) {
708
+ contract(
709
+ `${path}.object`,
710
+ `${local} must declare states: its state follows the subscription's`,
711
+ );
712
+ return;
713
+ }
714
+ const stateField = granted.fields[states.field];
715
+ const values = new Set((stateField?.options ?? []).map((o) => o.value));
716
+ const mapped = new Set(Object.values(grants.states));
717
+ for (const [from, to] of Object.entries(grants.states)) {
718
+ if (!values.has(to)) contract(`${path}.states.${from}`, `"${to}" is not a state of ${local}`);
719
+ }
720
+ if (!mapped.has(states.initial)) {
721
+ contract(
722
+ `${path}.states`,
723
+ `${local}'s initial state "${states.initial}" must be one the subscription's states map to`,
724
+ );
725
+ }
726
+ const ended = grants.states.ended;
727
+ const finals = new Set(states.moves.filter((mv) => mv.final).map((mv) => mv.to));
728
+ if (!finals.has(ended)) {
729
+ contract(`${path}.states.ended`, `"${ended}" must be a final state of ${local}`);
730
+ }
731
+ // The provider's reads move a subscription between its states in any order, so the granted
732
+ // record needs a host move from each mapped state to each other one (none out of the final).
733
+ for (const fromState of mapped) {
734
+ if (fromState === ended) continue;
735
+ for (const toState of mapped) {
736
+ if (toState === fromState) continue;
737
+ const ok = states.moves.some(
738
+ (mv) => mv.to === toState && moveOrigins(mv).includes(fromState) && mv.by.includes("host"),
739
+ );
740
+ if (!ok) {
741
+ contract(
742
+ `objects.${local}.states`,
743
+ `${local} needs a move from "${fromState}" to "${toState}" the host may make (by: ["host", ...]): it follows the subscription`,
744
+ );
745
+ }
746
+ }
747
+ }
748
+ if (Object.hasOwn(grants.set, states.field)) {
749
+ contract(
750
+ `${path}.set.${states.field}`,
751
+ `${states.field} is ${local}'s state: the host sets it`,
752
+ );
753
+ }
754
+ const filled = new Set<string>();
755
+ for (const [key, target] of [
756
+ ["from", grants.from],
757
+ ["until", grants.until],
758
+ ] as const) {
759
+ if (target === undefined) continue;
760
+ const field = Object.hasOwn(granted.fields, target) ? granted.fields[target] : undefined;
761
+ // A moment, not a day: access stops at the period's end and not a minute after (ADR 0488).
762
+ if (field?.type !== "datetime" || field.many) {
763
+ contract(`${path}.${key}`, `"${target}" must be a datetime field of ${local}`);
764
+ } else if (Object.hasOwn(grants.set, target)) {
765
+ contract(`${path}.${key}`, `"${target}" is in set too: the host keeps it`);
766
+ }
767
+ if (key === "from") filled.add(target);
768
+ }
769
+ for (const [target, source] of Object.entries(grants.set)) {
770
+ const fp = `${path}.set.${target}`;
771
+ const field = Object.hasOwn(granted.fields, target) ? granted.fields[target] : undefined;
772
+ if (!field || field.type === "formula") {
773
+ contract(fp, `"${target}" must be a field of ${local} other than a formula`);
774
+ continue;
775
+ }
776
+ const one = !field.many;
777
+ let always = true;
778
+ if (source === "item") {
779
+ if (!(field.type === "relation" && one && field.to === `${m.id}.${name}`)) {
780
+ contract(fp, `item needs a relation (one record) to ${m.id}.${name}`);
781
+ }
782
+ } else if (source.startsWith("item.")) {
783
+ const from = source.slice("item.".length);
784
+ const own = Object.hasOwn(plan.fields, from) ? plan.fields[from] : undefined;
785
+ if (!own || own.type === "formula") {
786
+ contract(fp, `"${from}" is not a field of ${name}`);
787
+ continue;
788
+ }
789
+ if (
790
+ own.type !== field.type ||
791
+ Boolean(own.many) !== Boolean(field.many) ||
792
+ (own.type === "relation" && own.to !== field.to)
793
+ ) {
794
+ contract(
795
+ fp,
796
+ `${source} needs a ${own.type} field like ${name}.${from}; "${target}" is a ${field.type} field`,
797
+ );
798
+ }
799
+ always = Boolean(own.required);
800
+ } else if (source === "subscription") {
801
+ if (field.type !== "text") {
802
+ contract(fp, `subscription needs a text field; "${target}" is a ${field.type} field`);
803
+ }
804
+ } else if (!(field.type === "relation" && one && field.to === "person")) {
805
+ contract(
806
+ fp,
807
+ `${source} needs a relation to one person; "${target}" is a ${field.type} field`,
808
+ );
809
+ } else if (source === "subscription.payer") {
810
+ // A payer erased later leaves the field empty; it never fills a required one.
811
+ always = false;
812
+ }
813
+ if (field.required && !always) {
814
+ contract(fp, `"${target}" is required and ${source} may be empty`);
815
+ }
816
+ if (always) filled.add(target);
817
+ }
818
+ for (const [fieldName, field] of Object.entries(granted.fields)) {
819
+ if (!field.required || field.type === "formula" || field.default !== undefined) continue;
820
+ if (fieldName === states.field || filled.has(fieldName)) continue;
821
+ contract(
822
+ `${path}.set`,
823
+ `${local}.${fieldName} is required: set it from the plan or the subscription`,
824
+ );
825
+ }
826
+ granted.requireOneOf?.forEach((group, i) => {
827
+ if (!group.some((f) => filled.has(f))) {
828
+ contract(
829
+ `objects.${local}.requireOneOf.${i}`,
830
+ `${local} is granted by ${name}'s subscriptions: set one of ${group.join(", ")}`,
831
+ );
832
+ }
833
+ });
834
+ checkGrantedHolder(m, local, granted, contract);
835
+ }
836
+
837
+ /**
838
+ * A granted holder (a pass a paid line grants, a membership a subscription grants) keeps the
839
+ * terms it was granted (ADR 0513): its Person, uses, period, dates, zone and the fields its
840
+ * conditions compare with are read-only and never a customer's to write, and nobody but the host
841
+ * (or a tool only a person with a permission may call) moves it into a state it can be spent in.
842
+ * Otherwise a staff write, an assistant or an automation could give someone uses nobody paid for.
843
+ */
844
+ export function checkGrantedHolder(
845
+ m: ExtensionManifest,
846
+ local: string,
847
+ granted: ObjectManifest,
848
+ contract: (path: string, message: string) => void,
849
+ ): void {
850
+ const allowance = granted.allowance;
851
+ if (!allowance || !("holds" in allowance)) return;
852
+ const h = allowance.holds;
853
+ const op = `objects.${local}`;
854
+ const terms = new Set<string>([h.person, h.uses]);
855
+ if (typeof h.per === "object") terms.add(h.per.field);
856
+ for (const f of [h.from, h.until, h.zone]) if (f) terms.add(f);
857
+ for (const target of spendsOnList(h)) {
858
+ for (const clause of target.when ?? []) {
859
+ for (const v of [clause.in, clause.atLeast, clause.below]) {
860
+ if (typeof v === "string") terms.add(v);
861
+ }
862
+ }
863
+ }
864
+ const customer = customerWritable(m, local);
865
+ for (const term of terms) {
866
+ const field = Object.hasOwn(granted.fields, term) ? granted.fields[term] : undefined;
867
+ if (field && !field.readOnly) {
868
+ contract(
869
+ `${op}.fields.${term}`,
870
+ `${local} is granted: "${term}" is one of its terms, so it must be readOnly (only the host writes it)`,
871
+ );
872
+ }
873
+ if (customer.has(term) && term !== granted.customer?.field) {
874
+ contract(`${op}.fields.${term}`, `${local} is granted: a customer cannot write "${term}"`);
875
+ }
876
+ }
877
+ const live = new Set(h.live ?? []);
878
+ for (const [i, move] of (granted.states?.moves ?? []).entries()) {
879
+ if (!live.has(move.to)) continue;
880
+ const open = move.by.filter((by) => by === "staff" || by === "customer");
881
+ if (open.length) {
882
+ contract(
883
+ `${op}.states.moves.${i}`,
884
+ `${local} is granted: only the host moves it into "${move.to}", where it can be spent (not ${open.join(" or ")})`,
885
+ );
886
+ }
887
+ }
888
+ }