@composable-os/sdk 0.1.0-beta.10 → 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.
package/src/capacity.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // is packages/core/src/capacity/.
5
5
  import { z } from "zod";
6
6
  import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+ import { moveOrigins, type WindowBound, windowBoundSchema, windowChecks } from "./states.ts";
7
8
 
8
9
  /**
9
10
  * What customers and the public are told about a record's places (staff always see the real
@@ -128,13 +129,56 @@ export interface ClaimsSpec {
128
129
  on: string;
129
130
  held?: readonly string[];
130
131
  confirmed?: readonly string[];
132
+ waitlist?: WaitlistSpec;
131
133
  }
132
134
 
135
+ /**
136
+ * A waitlist on the claimed record's places (stage 31, ADR 0520). A record in `state` waits: it
137
+ * holds no place and spends nothing. It may be made only while the record it claims on is full
138
+ * and before `until`. Until then, a place given back while anyone waits is handed to the waitlist
139
+ * in the same statements that give it back, as a hold of its own that nobody booking directly
140
+ * can take. The host then promotes the first waiter (by when the record was made) from a current
141
+ * read: the move from `state` into `promote` takes the waitlist's hold, and whatever that move
142
+ * spends is spent then. A waiter who cannot be moved in (their spend is refused) is passed over
143
+ * and stays waiting; a hold nobody can take is given back to everyone. From `until`, nobody is
144
+ * promoted and a place given back goes to whoever claims first.
145
+ *
146
+ * - `state` is a state of the object that neither holds nor takes a place, and is not final.
147
+ * - `promote` is one of `confirmed`; a move from `state` to it must be declared for the host.
148
+ * Declared for a customer too (with a window), it lets a waiter take a free place themselves:
149
+ * only the host's promotion takes a place the waitlist holds, so nobody jumps the queue.
150
+ * - `until` is a moment, named as a window's end is (`{ at: "class.startsAt", minutesBefore:
151
+ * { field: "class.classType.promotionMinutes", setting: "promotionMinutes" } }`).
152
+ * - `promotedAt`, `passedOverAt` (read-only datetimes) and `passedOverReason` (read-only text)
153
+ * are what the host writes when it promotes a waiter or passes one over, for messages.
154
+ * - The claimed object has no pool.
155
+ */
156
+ export interface WaitlistSpec {
157
+ state: string;
158
+ promote: string;
159
+ until: string | WindowBound;
160
+ promotedAt?: string;
161
+ passedOverAt?: string;
162
+ passedOverReason?: string;
163
+ }
164
+
165
+ export const waitlistManifestSchema = z
166
+ .object({
167
+ state: z.string().min(1).max(100),
168
+ promote: z.string().min(1).max(100),
169
+ until: windowBoundSchema,
170
+ promotedAt: fieldName.optional(),
171
+ passedOverAt: fieldName.optional(),
172
+ passedOverReason: fieldName.optional(),
173
+ })
174
+ .strict();
175
+
133
176
  export const claimsManifestSchema = z
134
177
  .object({
135
178
  on: fieldName,
136
179
  held: z.array(z.string().min(1).max(100)).max(20).optional(),
137
180
  confirmed: z.array(z.string().min(1).max(100)).max(20).optional(),
181
+ waitlist: waitlistManifestSchema.optional(),
138
182
  })
139
183
  .strict();
140
184
  export type ClaimsManifest = z.infer<typeof claimsManifestSchema>;
@@ -198,4 +242,62 @@ export function checkObjectClaims(
198
242
  );
199
243
  }
200
244
  });
245
+ const waitlist = claims.waitlist;
246
+ if (!waitlist) return;
247
+ // A waitlist (ADR 0520).
248
+ const wp = `${path}.waitlist`;
249
+ if (!values.has(waitlist.state)) {
250
+ contract(`${wp}.state`, `"${waitlist.state}" is not a state of ${name}`);
251
+ } else if (held.includes(waitlist.state) || confirmed.includes(waitlist.state)) {
252
+ contract(`${wp}.state`, `"${waitlist.state}" waits: it can neither hold nor take a place`);
253
+ } else if (states.moves.some((move) => move.final && move.to === waitlist.state)) {
254
+ contract(`${wp}.state`, `"${waitlist.state}" is final: nobody waits in it`);
255
+ } else if (
256
+ states.initial !== waitlist.state &&
257
+ !Object.hasOwn(states.create?.in ?? {}, waitlist.state)
258
+ ) {
259
+ contract(
260
+ `${wp}.state`,
261
+ `"${waitlist.state}" must be a state ${name} may be created in (states.create.in): a waiter joins by being made waiting`,
262
+ );
263
+ }
264
+ if (!confirmed.includes(waitlist.promote)) {
265
+ contract(`${wp}.promote`, `"${waitlist.promote}" must be one of claims.confirmed`);
266
+ }
267
+ const promotions = states.moves.filter(
268
+ (move) => move.to === waitlist.promote && moveOrigins(move).includes(waitlist.state),
269
+ );
270
+ if (!promotions.some((move) => move.by.includes("host"))) {
271
+ contract(
272
+ `${wp}.promote`,
273
+ `Declare a move from "${waitlist.state}" to "${waitlist.promote}" by the host: promotion is the host's`,
274
+ );
275
+ }
276
+ // A customer may move their own waiting record in, but only onto a free place: the host's
277
+ // promotion alone takes a place the waitlist holds, so nobody moves themselves ahead of it.
278
+ // Their move needs the create's window, so they cannot claim a place booking would refuse.
279
+ promotions.forEach((move) => {
280
+ if (move.by.includes("customer") && !move.window) {
281
+ contract(
282
+ `${wp}.promote`,
283
+ `A customer's move from "${waitlist.state}" to "${waitlist.promote}" needs a window (the create's): it books them`,
284
+ );
285
+ }
286
+ });
287
+ windowChecks(m, object, name, contract).checkBound(waitlist.until, `${wp}.until`);
288
+ for (const [key, type] of [
289
+ ["promotedAt", "datetime"],
290
+ ["passedOverAt", "datetime"],
291
+ ["passedOverReason", "text"],
292
+ ] as const) {
293
+ const local = waitlist[key];
294
+ if (local === undefined) continue;
295
+ const field = Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
296
+ if (field?.type !== type || field.many || !field.readOnly) {
297
+ contract(`${wp}.${key}`, `"${local}" must be a read-only ${type} field of ${name}`);
298
+ }
299
+ }
300
+ if (targetObject?.capacity?.pool !== undefined) {
301
+ contract(`${wp}`, `A waitlist is on places with no pool; ${target} has one`);
302
+ }
201
303
  }
package/src/contract.ts CHANGED
@@ -608,6 +608,13 @@ export interface ToolSpec<In extends z.ZodType = z.ZodType, Out extends z.ZodTyp
608
608
  * any extension may declare it.
609
609
  */
610
610
  humanOnly?: boolean;
611
+ /**
612
+ * A person approves it (ADR 0552): a person on the staff calls it as any tool, and anyone else's
613
+ * call (the assistant, an MCP client, an automation) always waits in the approval queue for a
614
+ * person, whatever the approval policy or preset says, and runs when a person approves it. For
615
+ * what an AI may propose but a person decides (cancelling a class). Staff only, and not a read.
616
+ */
617
+ personApproves?: boolean;
611
618
  handler(input: z.output<In>, ctx: ExtensionContext): Promise<z.input<Out>> | z.input<Out>;
612
619
  }
613
620
 
@@ -627,6 +634,15 @@ export interface RoleSpec {
627
634
  permissions: readonly string[];
628
635
  /** Objects of this extension (`<id>.<object>`) whose records the role may read. */
629
636
  read: readonly string[];
637
+ /**
638
+ * Objects whose records the role reaches only when a datetime on them falls on the
639
+ * day it is on (ADR 0553), by object: the moment, and optionally its end and zone, read through
640
+ * one relation at most: `{ "bookings.class": { at: "startsAt", until: "endsAt", zone:
641
+ * "timezone" } }`. A record is today's when its start falls on today's date in its zone (the
642
+ * organisation's when empty), or it has started and not yet ended. The host holds it on every
643
+ * call the account makes and every call of a tool run it started. Other staff are not limited.
644
+ */
645
+ today?: Readonly<Record<string, string | { at: string; until?: string; zone?: string }>>;
630
646
  }
631
647
 
632
648
  /**
@@ -760,6 +776,15 @@ export interface CustomerSpec {
760
776
  * any tool.
761
777
  */
762
778
  createOnly?: readonly string[];
779
+ /**
780
+ * The family link (ADR 0540): a signed-in guardian also reads their live dependants' records of
781
+ * this object (a child's bookings), with the same `read` fields. With `write: true` they also
782
+ * make records for a dependant (`my.create`'s `forPersonId`) and change the dependant's, with
783
+ * the same `write` fields. `madeBy` names a relation to one person the host sets, on every
784
+ * record a customer makes, to the Person who made it. Staff link guardians to dependants; the
785
+ * seam checks the link in every read and write. A reviewed change, as `customer` is.
786
+ */
787
+ guardians?: { write?: boolean; madeBy?: string };
763
788
  }
764
789
 
765
790
  /** A tool shown as a button on a record page. */
package/src/manifest.ts CHANGED
@@ -34,7 +34,7 @@ import { checkFormula, type FormulaFieldRef } from "./formula/compile.ts";
34
34
  import { checkObjectRecurring, recurringManifestSchema } from "./recurring.ts";
35
35
  import { renamedMessage } from "./renamed.ts";
36
36
  import { checkObjectSellable, sellableManifestSchema } from "./sellable.ts";
37
- import { checkObjectStates, statesManifestSchema } from "./states.ts";
37
+ import { checkObjectStates, resolveFieldPath, statesManifestSchema } from "./states.ts";
38
38
  import { checkObjectUnique, uniqueManifestSchema } from "./unique.ts";
39
39
 
40
40
  export const EXTENSION_ID_RE = /^[a-z][a-z0-9]{1,29}$/;
@@ -214,6 +214,10 @@ export const objectManifestSchema = z.object({
214
214
  write: z.array(z.string().max(40)).max(100),
215
215
  requireAccess: z.array(z.string().max(40)).max(10).optional(),
216
216
  createOnly: z.array(z.string().max(40)).max(100).optional(),
217
+ guardians: z
218
+ .object({ write: z.boolean().optional(), madeBy: z.string().max(40).optional() })
219
+ .strict()
220
+ .optional(),
217
221
  })
218
222
  .strict()
219
223
  .optional(),
@@ -326,6 +330,8 @@ export const toolManifestSchema = z.object({
326
330
  permission: z.string().max(80).optional(),
327
331
  /** Only a person may call it (ADR 0512). */
328
332
  humanOnly: z.literal(true).optional(),
333
+ /** A person approves anyone else's call (ADR 0552). */
334
+ personApproves: z.literal(true).optional(),
329
335
  inputSchema: jsonSchemaObject,
330
336
  outputSchema: jsonSchemaObject,
331
337
  });
@@ -337,6 +343,22 @@ export const roleManifestSchema = z.object({
337
343
  description: z.string().min(10).max(500),
338
344
  permissions: z.array(z.string().max(80)).max(20).default([]),
339
345
  read: z.array(z.string().max(80)).max(20).default([]),
346
+ /** Objects whose records the role reaches only on the organisation's local today (ADR 0553). */
347
+ today: z
348
+ .record(
349
+ z.string().max(80),
350
+ z.union([
351
+ z.string().max(122),
352
+ z
353
+ .object({
354
+ at: z.string().max(122),
355
+ until: z.string().max(122).optional(),
356
+ zone: z.string().max(122).optional(),
357
+ })
358
+ .strict(),
359
+ ]),
360
+ )
361
+ .optional(),
340
362
  });
341
363
  export type RoleManifest = z.infer<typeof roleManifestSchema>;
342
364
 
@@ -637,6 +659,7 @@ export function toManifest(extension: Extension): ExtensionManifest {
637
659
  ...(tool.audiences ? { audiences: [...tool.audiences] } : {}),
638
660
  ...(tool.permission ? { permission: tool.permission } : {}),
639
661
  ...(tool.humanOnly ? { humanOnly: true as const } : {}),
662
+ ...(tool.personApproves ? { personApproves: true as const } : {}),
640
663
  ...(tool.customerFields
641
664
  ? {
642
665
  customerFields: Object.fromEntries(
@@ -678,6 +701,7 @@ export function toManifest(extension: Extension): ExtensionManifest {
678
701
  description: role.description,
679
702
  permissions: [...role.permissions],
680
703
  read: [...role.read],
704
+ ...(role.today ? { today: { ...role.today } } : {}),
681
705
  },
682
706
  ]),
683
707
  ),
@@ -1295,6 +1319,24 @@ export function validateManifest(
1295
1319
  }
1296
1320
  }
1297
1321
 
1322
+ // The family link (ADR 0540): who made a record is a relation to one person the host sets, never
1323
+ // one the customer writes.
1324
+ for (const [name, object] of Object.entries(m.objects)) {
1325
+ const madeBy = object.customer?.guardians?.madeBy;
1326
+ if (madeBy === undefined) continue;
1327
+ const path = `objects.${name}.customer.guardians.madeBy`;
1328
+ const field = object.fields[madeBy];
1329
+ if (field?.type !== "relation" || field.to !== "person" || field.many) {
1330
+ contract(path, `"${madeBy}" must be a relation of ${name} to one person`);
1331
+ } else if (!field.readOnly) {
1332
+ contract(path, `"${madeBy}" must be readOnly: the host sets it, nobody edits it`);
1333
+ } else if (madeBy === object.customer?.field) {
1334
+ contract(path, "madeBy cannot be the customer field");
1335
+ } else if (object.customer?.write.includes(madeBy)) {
1336
+ contract(path, `"${madeBy}" is set by the host: customer.write may not list it`);
1337
+ }
1338
+ }
1339
+
1298
1340
  // A customer's write that needs access to what it points to (stage 42, ADR 0478): relations of
1299
1341
  // the object to one record of another of this extension's objects that declares `access`.
1300
1342
  for (const [name, object] of Object.entries(m.objects)) {
@@ -1466,6 +1508,12 @@ export function validateManifest(
1466
1508
  `A tool only a person on the staff may call cannot be open to ${open.join(" and ")} callers`,
1467
1509
  );
1468
1510
  }
1511
+ if (tool.personApproves && (open.length || tool.risk === "read")) {
1512
+ contract(
1513
+ `tools.${name}.personApproves`,
1514
+ "A tool a person approves is a staff tool that changes something: not open to customers or the public, and not a read",
1515
+ );
1516
+ }
1469
1517
  if (open.length && tool.risk !== "read" && tool.risk !== "write") {
1470
1518
  contract(
1471
1519
  `tools.${name}.risk`,
@@ -1586,6 +1634,34 @@ export function validateManifest(
1586
1634
  );
1587
1635
  }
1588
1636
  }
1637
+ // A role limited to today (ADR 0553): each object its own, each path a datetime on it (or
1638
+ // one relation away, through another of its objects).
1639
+ for (const [object, limit] of Object.entries(role.today ?? {})) {
1640
+ const tp = `${path}.today.${object}`;
1641
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1642
+ const target = local && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
1643
+ if (!target) {
1644
+ contract(tp, `"${object}" is not an object of this extension`);
1645
+ continue;
1646
+ }
1647
+ const spec = typeof limit === "string" ? { at: limit } : limit;
1648
+ const prefix = (p: string) => (p.includes(".") ? p.split(".")[0] : null);
1649
+ const paths: [string | undefined, string][] = [
1650
+ [spec.at, "datetime"],
1651
+ [spec.until, "datetime"],
1652
+ [spec.zone, "timezone"],
1653
+ ];
1654
+ for (const [p, type] of paths) {
1655
+ if (p === undefined) continue;
1656
+ const field = p.split(".").length <= 2 ? resolveFieldPath(m, target, p) : undefined;
1657
+ if (field?.type !== type || field.many) {
1658
+ contract(tp, `"${p}" must be a ${type} field of ${object}, or one relation away`);
1659
+ }
1660
+ if (prefix(p) !== prefix(spec.at)) {
1661
+ contract(tp, `"${p}" must be read through the same relation as "${spec.at}"`);
1662
+ }
1663
+ }
1664
+ }
1589
1665
  }
1590
1666
 
1591
1667
  for (const [name, view] of Object.entries(m.views)) {
package/src/sellable.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  import { z } from "zod";
7
7
  import { customerWritable, spendsOnList } from "./allowance.ts";
8
8
  import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
9
- import { moveOrigins } from "./states.ts";
9
+ import { moveOrigins, resolveFieldPath } from "./states.ts";
10
10
 
11
11
  /**
12
12
  * Where a granted record's field gets its value, when the host creates it:
@@ -107,6 +107,49 @@ export interface SellableSpec {
107
107
  * "sign_in"`). Such a line holds one, and an order at most one such line. Not on a plan.
108
108
  */
109
109
  onePerPerson?: string;
110
+ /**
111
+ * A paid line moves a record that already exists (stage 31a step 8, ADR 0560), see MovesSpec.
112
+ * A record of such an object is bought once, when it is made: `order.startHeld` makes it in
113
+ * `held` and starts its order in one batch. It is never put on `order.start`. Not with
114
+ * `grants`, `deposit`, `recurring`, `onePerPerson`, `maxPerOrder` or `saleWindow`.
115
+ */
116
+ moves?: MovesSpec;
117
+ }
118
+
119
+ /**
120
+ * What an order does to the record it was started for (ADR 0560): a drop-in booking held while
121
+ * its order is unpaid. The host makes every move, as the host, in the batch that moves the order.
122
+ *
123
+ * - `held`: the state `order.startHeld` makes the record in (`states.create.in` lets the host,
124
+ * and only the host, create it there). A capacity claimant holds its place in it.
125
+ * - `paid`: the order is paid: the record moves `held` -> `paid`.
126
+ * - `expired`: the order expired or was cancelled unpaid: `held` -> `expired`, a final state.
127
+ * A record that leaves `held` any other way (a class the gym cancels) cancels its unpaid order.
128
+ * - `refund`: states that give the money back. A record whose order is paid entering one of them
129
+ * queues the order's refund for a person with `orders:refund` to approve (never an AI).
130
+ * - `price`: where the price of one is read when the record is made: a number field through up
131
+ * to two relations (`class.classType.dropInPrice`), else the extension's number setting. The
132
+ * host writes it into the read-only `price` field, and the order's line is priced from it.
133
+ * - `title`: the order line's title, a text field through up to two relations (`class.title`).
134
+ * - `order`: a read-only text field the host writes the order's id into.
135
+ * - `guest`: a buyer who is not signed in is matched to no Person before payment: their record is
136
+ * held with its customer field empty (so it is no one's, blocks no one's own, and tells the
137
+ * buyer nothing about who has that address), and is given its Person when the payment is
138
+ * verified, by the rule a guest's order uses. The customer field must not be `required`; the
139
+ * host keeps it set in every state but `held`. Without it, a guest cannot buy the object.
140
+ * - `holdCap`: a number setting of the extension: the percent of the claimed record's places that
141
+ * unpaid guest holds may take at once (at least one). Over it a guest is told to try again soon.
142
+ */
143
+ export interface MovesSpec {
144
+ held: string;
145
+ paid: string;
146
+ expired: string;
147
+ refund?: readonly string[];
148
+ price?: { field?: string; setting?: string };
149
+ title?: string;
150
+ order?: string;
151
+ guest?: boolean;
152
+ holdCap?: { setting: string };
110
153
  }
111
154
 
112
155
  /**
@@ -141,6 +184,14 @@ export interface RecurringSpec {
141
184
  * `sellable.recurring`, and its `grants` is what the subscription gives while it runs.
142
185
  */
143
186
  grants?: RecurringGrantSpec;
187
+ /**
188
+ * Whether staff may pause a subscription to the plan (stage 32b, decision 10, ADR 0531), and
189
+ * for how long: `minDays` and `maxDays` name number fields of the plan holding the shortest and
190
+ * longest pause the company allows (empty: 1 day, and 366 days, the most the host asks the
191
+ * provider for). Left out, a subscription to the plan is never paused. Only staff pause, with
192
+ * `subscriptions:manage`, as a person; while paused nothing is charged, granted or spent.
193
+ */
194
+ pause?: { minDays?: string; maxDays?: string };
144
195
  }
145
196
 
146
197
  /** Where a field of what a subscription grants gets its value (see RecurringSpec.grants). */
@@ -256,6 +307,23 @@ export const sellableManifestSchema = z
256
307
  .strict()
257
308
  .optional(),
258
309
  onePerPerson: fieldName.optional(),
310
+ moves: z
311
+ .object({
312
+ held: z.string().min(1).max(100),
313
+ paid: z.string().min(1).max(100),
314
+ expired: z.string().min(1).max(100),
315
+ refund: z.array(z.string().min(1).max(100)).max(20).optional(),
316
+ price: z
317
+ .object({ field: z.string().max(130).optional(), setting: fieldName.optional() })
318
+ .strict()
319
+ .optional(),
320
+ title: z.string().max(130).optional(),
321
+ order: fieldName.optional(),
322
+ guest: z.boolean().optional(),
323
+ holdCap: z.object({ setting: fieldName }).strict().optional(),
324
+ })
325
+ .strict()
326
+ .optional(),
259
327
  tax: z
260
328
  .object({
261
329
  code: z.string().regex(TAX_CODE_PATTERN, "A product tax code: txcd_ and eight digits"),
@@ -277,6 +345,10 @@ export const sellableManifestSchema = z
277
345
  .object({
278
346
  interval: z.enum(["week", "month", "year"]),
279
347
  trialDays: fieldName.optional(),
348
+ pause: z
349
+ .object({ minDays: fieldName.optional(), maxDays: fieldName.optional() })
350
+ .strict()
351
+ .optional(),
280
352
  grants: z
281
353
  .object({
282
354
  object: z.string().max(40),
@@ -366,6 +438,12 @@ export function checkObjectSellable(
366
438
  if (trial !== undefined && !single(trial, new Set(["number"]))) {
367
439
  contract(`${path}.recurring.trialDays`, `"${trial}" must be a number field of ${name}`);
368
440
  }
441
+ for (const key of ["minDays", "maxDays"] as const) {
442
+ const days = sellable.recurring.pause?.[key];
443
+ if (days !== undefined && !single(days, new Set(["number"]))) {
444
+ contract(`${path}.recurring.pause.${key}`, `"${days}" must be a number field of ${name}`);
445
+ }
446
+ }
369
447
  if (sellable.onePerPerson !== undefined) {
370
448
  contract(
371
449
  `${path}.onePerPerson`,
@@ -414,6 +492,7 @@ export function checkObjectSellable(
414
492
  }
415
493
  }
416
494
  if (sellable.grants) checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
495
+ if (sellable.moves) checkMoves(m, name, object, sellable.moves, `${path}.moves`, contract);
417
496
  const place = sellable.tax?.place;
418
497
  if (place) {
419
498
  let holder: ObjectManifest | undefined = object;
@@ -451,6 +530,177 @@ export function checkObjectSellable(
451
530
  }
452
531
  }
453
532
 
533
+ /**
534
+ * Checks `sellable.moves` (ADR 0560): each of these is a way the order's batch could otherwise fail
535
+ * (a payment the host could not apply), or a record someone could hold with no order.
536
+ */
537
+ function checkMoves(
538
+ m: ExtensionManifest,
539
+ name: string,
540
+ object: ObjectManifest,
541
+ moves: NonNullable<SellableManifest["moves"]>,
542
+ path: string,
543
+ contract: (path: string, message: string) => void,
544
+ ): void {
545
+ const sellable = object.sellable as SellableManifest;
546
+ for (const key of [
547
+ "grants",
548
+ "deposit",
549
+ "recurring",
550
+ "onePerPerson",
551
+ "maxPerOrder",
552
+ "saleWindow",
553
+ ] as const) {
554
+ if (sellable[key] !== undefined) {
555
+ contract(
556
+ `objects.${name}.sellable.${key}`,
557
+ `A record bought with moves is one record on one order: it has no ${key}`,
558
+ );
559
+ }
560
+ }
561
+ const field = (local: string) =>
562
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
563
+ const price = field(sellable.price);
564
+ if (price && !price.readOnly) {
565
+ contract(
566
+ `objects.${name}.fields.${sellable.price}`,
567
+ `"${sellable.price}" holds what the host priced it at: make it readOnly`,
568
+ );
569
+ }
570
+ if (moves.order !== undefined) {
571
+ const order = field(moves.order);
572
+ if (order?.type !== "text" || order.many || !order.readOnly) {
573
+ contract(`${path}.order`, `"${moves.order}" must be a readOnly text field of ${name}`);
574
+ }
575
+ }
576
+ if (moves.price) {
577
+ if (moves.price.field === undefined && moves.price.setting === undefined) {
578
+ contract(`${path}.price`, "price names a field, a setting or both");
579
+ }
580
+ if (moves.price.field !== undefined) {
581
+ const at = resolveFieldPath(m, object, moves.price.field);
582
+ if (!at || at.many || (at.type !== "number" && at.type !== "currency")) {
583
+ contract(
584
+ `${path}.price.field`,
585
+ `"${moves.price.field}" must be a number field of ${name}, or <relation>.<field> through up to two relations, every field on the way declared by this extension`,
586
+ );
587
+ }
588
+ }
589
+ if (moves.price.setting !== undefined) {
590
+ const settings = m.settings ?? {};
591
+ const setting = Object.hasOwn(settings, moves.price.setting)
592
+ ? settings[moves.price.setting]
593
+ : undefined;
594
+ if (setting?.type !== "number") {
595
+ contract(
596
+ `${path}.price.setting`,
597
+ `"${moves.price.setting}" must be a number setting of ${m.id}`,
598
+ );
599
+ }
600
+ }
601
+ }
602
+ if (moves.title !== undefined) {
603
+ const at = resolveFieldPath(m, object, moves.title);
604
+ if (!at || at.many || at.type !== "text") {
605
+ contract(
606
+ `${path}.title`,
607
+ `"${moves.title}" must be a text field of ${name}, or through up to two relations`,
608
+ );
609
+ }
610
+ }
611
+ if (!object.customer) contract(path, `${name} must declare customer: whose record it is`);
612
+ if (moves.guest && object.customer) {
613
+ const owner = field(object.customer.field);
614
+ if (owner?.required) {
615
+ contract(
616
+ `objects.${name}.fields.${object.customer.field}`,
617
+ `A guest's ${name} is held with no ${object.customer.field} until it is paid: it cannot be required (the host keeps it set outside "${moves.held}")`,
618
+ );
619
+ }
620
+ }
621
+ if (moves.holdCap) {
622
+ const settings = m.settings ?? {};
623
+ const setting = Object.hasOwn(settings, moves.holdCap.setting)
624
+ ? settings[moves.holdCap.setting]
625
+ : undefined;
626
+ if (setting?.type !== "number") {
627
+ contract(
628
+ `${path}.holdCap.setting`,
629
+ `"${moves.holdCap.setting}" must be a number setting of ${m.id}`,
630
+ );
631
+ }
632
+ if (!moves.guest) contract(`${path}.holdCap`, "holdCap limits guests' holds: declare guest");
633
+ if (!object.claims) contract(`${path}.holdCap`, `${name} must claim places (claims)`);
634
+ }
635
+ const states = object.states;
636
+ if (!states) {
637
+ contract(path, `${name} must declare states: the order moves it`);
638
+ return;
639
+ }
640
+ const values = new Set((object.fields[states.field]?.options ?? []).map((o) => o.value));
641
+ const finals = new Set(states.moves.filter((mv) => mv.final).map((mv) => mv.to));
642
+ for (const key of ["held", "paid", "expired"] as const) {
643
+ if (!values.has(moves[key])) {
644
+ contract(`${path}.${key}`, `"${moves[key]}" is not a state of ${name}`);
645
+ }
646
+ }
647
+ if (new Set([moves.held, moves.paid, moves.expired]).size !== 3) {
648
+ contract(path, "held, paid and expired are three different states");
649
+ }
650
+ const creators = states.create?.in?.[moves.held] ?? [];
651
+ if (!creators.includes("host")) {
652
+ contract(
653
+ `${path}.held`,
654
+ `states.create.in must let the host create ${name} in "${moves.held}"`,
655
+ );
656
+ }
657
+ if (creators.some((by) => by !== "host")) {
658
+ contract(
659
+ `${path}.held`,
660
+ `Only the host creates ${name} in "${moves.held}": anyone else would hold it with no order`,
661
+ );
662
+ }
663
+ const hostMove = (to: string) =>
664
+ states.moves.some(
665
+ (mv) => mv.to === to && moveOrigins(mv).includes(moves.held) && mv.by.includes("host"),
666
+ );
667
+ for (const key of ["paid", "expired"] as const) {
668
+ if (!hostMove(moves[key])) {
669
+ contract(
670
+ `${path}.${key}`,
671
+ `${name} needs a move from "${moves.held}" to "${moves[key]}" the host may make`,
672
+ );
673
+ }
674
+ }
675
+ if (!finals.has(moves.expired)) {
676
+ contract(`${path}.expired`, `"${moves.expired}" must be a final state of ${name}`);
677
+ }
678
+ for (const mv of states.moves) {
679
+ if (!moveOrigins(mv).includes(moves.held)) continue;
680
+ if (mv.by.some((by) => by !== "host")) {
681
+ contract(
682
+ `${path}.held`,
683
+ `Only the host moves ${name} out of "${moves.held}" (to "${mv.to}"): its order says where it goes`,
684
+ );
685
+ }
686
+ }
687
+ for (const [i, state] of (moves.refund ?? []).entries()) {
688
+ if (!values.has(state) || state === moves.held || state === moves.expired) {
689
+ contract(
690
+ `${path}.refund.${i}`,
691
+ `"${state}" must be a state of ${name} other than held and expired`,
692
+ );
693
+ }
694
+ }
695
+ const allowance = object.allowance;
696
+ if (allowance && "spends" in allowance && !allowance.spends.waived) {
697
+ contract(
698
+ path,
699
+ `${name} spends uses: declare allowance.spends.waived, which the host sets on a record its order pays for`,
700
+ );
701
+ }
702
+ }
703
+
454
704
  function checkGrants(
455
705
  m: ExtensionManifest,
456
706
  name: string,