@composable-os/sdk 0.1.0-beta.10 → 0.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/acknowledge.d.ts +38 -0
  2. package/dist/acknowledge.js +30 -0
  3. package/dist/agreements.d.ts +80 -0
  4. package/dist/agreements.js +109 -0
  5. package/dist/allowance.d.ts +47 -5
  6. package/dist/allowance.js +59 -4
  7. package/dist/automation-check.d.ts +6 -1
  8. package/dist/automation-check.js +93 -8
  9. package/dist/automation.d.ts +62 -4
  10. package/dist/automation.js +32 -9
  11. package/dist/behaviour.js +25 -6
  12. package/dist/calendar-entry.d.ts +97 -0
  13. package/dist/calendar-entry.js +180 -0
  14. package/dist/capacity.d.ts +69 -0
  15. package/dist/capacity.js +63 -2
  16. package/dist/checklists.d.ts +41 -0
  17. package/dist/checklists.js +75 -0
  18. package/dist/contract.d.ts +527 -26
  19. package/dist/contract.js +21 -3
  20. package/dist/discount.d.ts +135 -0
  21. package/dist/discount.js +281 -0
  22. package/dist/document.d.ts +2 -1
  23. package/dist/document.js +2 -1
  24. package/dist/field-types.d.ts +1 -1
  25. package/dist/field-types.js +5 -0
  26. package/dist/formula/compile.d.ts +15 -0
  27. package/dist/formula/compile.js +9 -0
  28. package/dist/index.d.ts +17 -0
  29. package/dist/index.js +17 -0
  30. package/dist/intake.d.ts +134 -0
  31. package/dist/intake.js +239 -0
  32. package/dist/journey-signals.d.ts +89 -0
  33. package/dist/journey-signals.js +151 -0
  34. package/dist/manifest.d.ts +1060 -60
  35. package/dist/manifest.js +1111 -61
  36. package/dist/mine.d.ts +45 -0
  37. package/dist/mine.js +119 -0
  38. package/dist/occupies.d.ts +64 -0
  39. package/dist/occupies.js +122 -0
  40. package/dist/questions.d.ts +179 -0
  41. package/dist/questions.js +514 -0
  42. package/dist/recurring.d.ts +33 -4
  43. package/dist/recurring.js +50 -3
  44. package/dist/restricted-fields.d.ts +15 -0
  45. package/dist/restricted-fields.js +97 -0
  46. package/dist/rich-text.d.ts +22 -0
  47. package/dist/rich-text.js +91 -0
  48. package/dist/routine-mail.d.ts +400 -0
  49. package/dist/routine-mail.js +955 -0
  50. package/dist/runtime.d.ts +5 -11
  51. package/dist/runtime.js +21 -11
  52. package/dist/screens.d.ts +3 -0
  53. package/dist/screens.js +74 -0
  54. package/dist/sellable.d.ts +231 -2
  55. package/dist/sellable.js +342 -1
  56. package/dist/slug.d.ts +2 -0
  57. package/dist/slug.js +6 -2
  58. package/dist/staffed.d.ts +178 -0
  59. package/dist/staffed.js +287 -0
  60. package/dist/states.d.ts +74 -4
  61. package/dist/states.js +154 -58
  62. package/dist/stock.d.ts +129 -0
  63. package/dist/stock.js +205 -0
  64. package/dist/team.d.ts +28 -0
  65. package/dist/team.js +52 -0
  66. package/dist/testing.d.ts +22 -1
  67. package/dist/testing.js +47 -5
  68. package/dist/worked-on.d.ts +42 -0
  69. package/dist/worked-on.js +79 -0
  70. package/package.json +9 -1
  71. package/src/acknowledge.ts +100 -0
  72. package/src/agreements.ts +185 -0
  73. package/src/allowance.ts +98 -8
  74. package/src/automation-check.ts +120 -9
  75. package/src/automation.ts +78 -10
  76. package/src/behaviour.ts +26 -6
  77. package/src/calendar-entry.ts +258 -0
  78. package/src/capacity.ts +103 -2
  79. package/src/checklists.ts +118 -0
  80. package/src/contract.ts +514 -27
  81. package/src/discount.ts +408 -0
  82. package/src/document.ts +4 -2
  83. package/src/field-types.ts +5 -0
  84. package/src/formula/compile.ts +10 -0
  85. package/src/index.ts +17 -0
  86. package/src/intake.ts +380 -0
  87. package/src/journey-signals.ts +215 -0
  88. package/src/manifest.ts +1313 -66
  89. package/src/mine.ts +161 -0
  90. package/src/occupies.ts +192 -0
  91. package/src/questions.ts +681 -0
  92. package/src/recurring.ts +90 -9
  93. package/src/restricted-fields.ts +129 -0
  94. package/src/rich-text.ts +112 -0
  95. package/src/routine-mail.ts +1272 -0
  96. package/src/runtime.ts +25 -12
  97. package/src/screens.ts +91 -0
  98. package/src/sellable.ts +595 -1
  99. package/src/slug.ts +7 -2
  100. package/src/staffed.ts +474 -0
  101. package/src/states.ts +220 -64
  102. package/src/stock.ts +332 -0
  103. package/src/team.ts +83 -0
  104. package/src/testing.ts +70 -6
  105. package/src/worked-on.ts +134 -0
package/dist/states.js CHANGED
@@ -21,7 +21,7 @@ const windowNumber = (number) => z.union([
21
21
  .strict()
22
22
  .refine((n) => n.field !== undefined || n.setting !== undefined, "Name a field or a setting"),
23
23
  ]);
24
- const windowBound = z.union([
24
+ export const windowBoundSchema = z.union([
25
25
  fieldPath,
26
26
  z
27
27
  .object({
@@ -34,7 +34,7 @@ const windowBound = z.union([
34
34
  ]);
35
35
  const staffOnlyPaths = z.union([fieldPath, z.array(fieldPath).min(1).max(4)]);
36
36
  const moveWindow = z
37
- .object({ from: windowBound.optional(), until: windowBound.optional() })
37
+ .object({ from: windowBoundSchema.optional(), until: windowBoundSchema.optional() })
38
38
  .strict()
39
39
  .refine((w) => w.from !== undefined || w.until !== undefined, "A window needs from or until");
40
40
  export const statesManifestSchema = z.object({
@@ -62,6 +62,7 @@ export const statesManifestSchema = z.object({
62
62
  window: moveWindow.optional(),
63
63
  staffOnly: staffOnlyPaths.optional(),
64
64
  closed: staffOnlyPaths.optional(),
65
+ requires: z.array(fieldName).min(1).max(20).optional(),
65
66
  })
66
67
  .strict()
67
68
  .optional(),
@@ -79,6 +80,20 @@ export const statesManifestSchema = z.object({
79
80
  })
80
81
  .strict()
81
82
  .optional(),
83
+ after: z
84
+ .array(z
85
+ .object({
86
+ from: z.union([stateValue, z.array(stateValue).min(1).max(20)]),
87
+ to: stateValue,
88
+ at: fieldPath,
89
+ minutesAfter: z.number().int().min(0).max(10_080).optional(),
90
+ ifAnyIn: z.array(stateValue).min(1).max(20).optional(),
91
+ ifSet: z.array(fieldName).min(1).max(5).optional(),
92
+ })
93
+ .strict())
94
+ .min(1)
95
+ .max(4)
96
+ .optional(),
82
97
  });
83
98
  /** A staff-only rule's paths, as a list (ADR 0505). */
84
99
  export function staffOnlyPathsOf(value) {
@@ -158,49 +173,15 @@ export function checkObjectStates(m, name, object, contract) {
158
173
  }
159
174
  });
160
175
  // Windows, staff-only rules and requests (ADR 0503; two relations and settings, ADR 0505).
161
- const checkPath = (at, path, type) => {
162
- const field = resolveFieldPath(m, object, at);
163
- // A staff-only rule may read a formula: the host computes it in the view (a boolean one).
164
- const formulaOk = type === "boolean" && field?.type === "formula";
165
- if ((field?.type !== type && !formulaOk) || field?.many) {
166
- contract(path, `"${at}" must be a ${type} field of ${name}, or <relation>.<field> through up to two relations (one record each), every field on the way declared by this extension`);
167
- }
168
- };
169
- const checkNumber = (value, path) => {
170
- if (typeof value === "string")
171
- checkPath(value, path, "number");
172
- else if (typeof value === "object") {
173
- if (value.field !== undefined)
174
- checkPath(value.field, `${path}.field`, "number");
175
- if (value.setting !== undefined) {
176
- const settings = m.settings ?? {};
177
- const setting = Object.hasOwn(settings, value.setting)
178
- ? settings[value.setting]
179
- : undefined;
180
- if (setting?.type !== "number") {
181
- contract(`${path}.setting`, `"${value.setting}" must be a number setting of ${m.id}`);
182
- }
183
- }
184
- }
185
- };
186
- const checkWindow = (window, path) => {
187
- for (const end of ["from", "until"]) {
188
- const bound = window?.[end];
189
- if (bound === undefined)
190
- continue;
191
- const b = typeof bound === "string" ? { at: bound } : bound;
192
- checkPath(b.at, `${path}.${end}.at`, "datetime");
193
- for (const key of ["daysBefore", "minutesBefore"]) {
194
- checkNumber(b[key], `${path}.${end}.${key}`);
195
- }
196
- if (b.zone !== undefined)
197
- checkPath(b.zone, `${path}.${end}.zone`, "timezone");
198
- }
199
- };
176
+ const { checkPath, checkWindow } = windowChecks(m, object, name, contract);
200
177
  states.moves.forEach((move, i) => {
201
178
  const mp = `${sp}.moves.${i}`;
202
- if ((move.window || move.staffOnly) && !move.by.includes("customer")) {
203
- contract(mp, "A window or staffOnly binds customers: the move must list customer in by");
179
+ // A window binds customers, or staff too with bindsStaff (ADR 0551); staffOnly customers.
180
+ if (move.staffOnly && !move.by.includes("customer")) {
181
+ contract(mp, "staffOnly binds customers: the move must list customer in by");
182
+ }
183
+ if (move.window && !move.by.includes("customer") && !move.bindsStaff) {
184
+ contract(mp, "A window binds customers: the move must list customer in by, or bind staff (bindsStaff)");
204
185
  }
205
186
  checkWindow(move.window, `${mp}.window`);
206
187
  for (const p of staffOnlyPathsOf(move.staffOnly))
@@ -211,12 +192,12 @@ export function checkObjectStates(m, name, object, contract) {
211
192
  if (!spec) {
212
193
  contract(`${mp}.tools`, `"${tool}" is not a tool of this extension`);
213
194
  }
214
- else if (!spec.humanOnly || !spec.permission) {
215
- contract(`${mp}.tools`, `"${tool}" must be humanOnly and declare a permission: the move is a person's act with it`);
195
+ else if ((!spec.humanOnly && !spec.personApproves) || !spec.permission) {
196
+ contract(`${mp}.tools`, `"${tool}" must be humanOnly or personApproves and declare a permission: the move is a person's act with it`);
216
197
  }
217
198
  }
218
- if (move.bindsStaff && (!move.window || !move.by.includes("staff"))) {
219
- contract(`${mp}.bindsStaff`, "bindsStaff needs a window and staff in by");
199
+ if (move.bindsStaff && (!move.window || (!move.by.includes("staff") && !move.tools))) {
200
+ contract(`${mp}.bindsStaff`, "bindsStaff needs a window, and staff in by or named tools");
220
201
  }
221
202
  if (move.tools && move.by.includes("staff")) {
222
203
  contract(`${mp}.tools`, "A move named tools may make is not also open to all staff: drop staff from by");
@@ -236,33 +217,100 @@ export function checkObjectStates(m, name, object, contract) {
236
217
  for (const p of staffOnlyPathsOf(states.create.closed)) {
237
218
  checkPath(p, `${sp}.create.closed`, "boolean");
238
219
  }
220
+ for (const required of states.create.requires ?? []) {
221
+ if (!fieldOf(required)) {
222
+ contract(`${sp}.create.requires`, `"${required}" is not a field of ${name}`);
223
+ }
224
+ }
239
225
  }
240
226
  if (states.follows) {
241
227
  const fp = `${sp}.follows`;
242
228
  const f = states.follows;
243
229
  const rel = fieldOf(f.relation);
244
- const target = rel?.type === "relation" && !rel.many && rel.to?.startsWith(`${m.id}.`)
245
- ? m.objects[rel.to.slice(m.id.length + 1)]
246
- : undefined;
247
- if (!target?.states) {
248
- contract(`${fp}.relation`, `"${f.relation}" must be a relation (one record) of ${name} to another of this extension's objects that declares states`);
230
+ const to = rel?.type === "relation" && !rel.many ? rel.to : undefined;
231
+ const own = to?.startsWith(`${m.id}.`) ? to.slice(m.id.length + 1) : undefined;
232
+ const target = own !== undefined && Object.hasOwn(m.objects, own) ? m.objects[own] : undefined;
233
+ // A parent in another extension this one requires (ADR 0841): its states are the host's to
234
+ // check, at install and on every upgrade of either extension (core's checkManifest).
235
+ const otherExt = to && own === undefined && to.includes(".") ? to.split(".")[0] : undefined;
236
+ const required = otherExt !== undefined && (m.requires ?? []).includes(otherExt);
237
+ if (!target?.states && !required) {
238
+ contract(`${fp}.relation`, `"${f.relation}" must be a relation (one record) of ${name} to another of this extension's objects that declares states, or to an object of an extension this one requires`);
249
239
  }
250
240
  else {
251
- const parentStates = new Set((target.fields[target.states.field]?.options ?? []).map((o) => o.value));
252
- for (const [when, to] of Object.entries(f.when)) {
253
- if (!parentStates.has(when)) {
254
- contract(`${fp}.when`, `"${when}" is not a state of ${rel?.to ?? f.relation}`);
241
+ // A parent whose places other records draw on as a pool counts claims that are not its
242
+ // own, which the cascade's check at commit cannot read (ADR 0550). A child that draws on
243
+ // it (a member of the pool, or claiming places on the parent or on a member) is refused;
244
+ // one that draws nothing moves no places and may follow it (ADR 0841). A pool is always in
245
+ // the parent's own extension, so a parent in another extension is never drawn on from here.
246
+ if (target && own !== undefined) {
247
+ const localOf = (ref) => ref?.startsWith(`${m.id}.`) ? ref.slice(m.id.length + 1) : ref;
248
+ const poolOf = (other) => {
249
+ const poolField = other?.capacity?.pool;
250
+ return poolField ? localOf(other?.fields[poolField]?.to) : undefined;
251
+ };
252
+ const members = new Set(Object.entries(m.objects)
253
+ .filter(([, other]) => poolOf(other) === own)
254
+ .map(([key]) => key));
255
+ const claimsOn = object.claims ? localOf(object.fields[object.claims.on]?.to) : undefined;
256
+ const draws = members.has(name) ||
257
+ (claimsOn !== undefined && (claimsOn === own || members.has(claimsOn)));
258
+ if (members.size && draws) {
259
+ contract(`${fp}.relation`, `${to} is a pool other records draw places from, and ${name} draws places from it: a cascade cannot follow it`);
260
+ }
261
+ }
262
+ const parentStates = target?.states
263
+ ? new Set((target.fields[target.states.field]?.options ?? []).map((o) => o.value))
264
+ : null;
265
+ for (const [when, into] of Object.entries(f.when)) {
266
+ if (parentStates && !parentStates.has(when)) {
267
+ contract(`${fp}.when`, `"${when}" is not a state of ${to ?? f.relation}`);
255
268
  }
256
269
  for (const from of f.from) {
257
270
  if (!isState(from))
258
271
  contract(`${fp}.from`, `"${from}" is not an option of ${states.field}`);
259
- else if (!states.moves.some((move) => move.to === to && move.by.includes("host") && moveOrigins(move).includes(from))) {
260
- contract(`${fp}.when`, `${name} needs a host move from "${from}" to "${to}"`);
272
+ else if (!states.moves.some((move) => move.to === into && move.by.includes("host") && moveOrigins(move).includes(from))) {
273
+ contract(`${fp}.when`, `${name} needs a host move from "${from}" to "${into}"`);
261
274
  }
262
275
  }
263
276
  }
264
277
  }
265
278
  }
279
+ // Timed moves (ADR 0550): a declared host move each, and a moment the sweep reads in SQL.
280
+ (states.after ?? []).forEach((rule, i) => {
281
+ const tp = `${sp}.after.${i}`;
282
+ if (!isState(rule.to))
283
+ contract(`${tp}.to`, `"${rule.to}" is not an option of ${states.field}`);
284
+ for (const from of moveOrigins(rule)) {
285
+ if (!isState(from)) {
286
+ contract(`${tp}.from`, `"${from}" is not an option of ${states.field}`);
287
+ }
288
+ else if (!states.moves.some((move) => move.to === rule.to && move.by.includes("host") && moveOrigins(move).includes(from))) {
289
+ contract(`${tp}.from`, `${name} needs a host move from "${from}" to "${rule.to}"`);
290
+ }
291
+ }
292
+ const parts = rule.at.split(".");
293
+ const at = parts.length <= 2 ? resolveFieldPath(m, object, rule.at) : undefined;
294
+ const via = parts.length === 2 ? fieldOf(parts[0]) : undefined;
295
+ const ownTarget = via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`);
296
+ if (at?.type !== "datetime" || at.many || (parts.length === 2 && !ownTarget)) {
297
+ contract(`${tp}.at`, `"${rule.at}" must be a datetime field of ${name}, or <relation>.<field> on another of this extension's objects`);
298
+ }
299
+ for (const f of rule.ifSet ?? []) {
300
+ if (!fieldOf(f))
301
+ contract(`${tp}.ifSet`, `"${f}" is not a field of ${name}`);
302
+ }
303
+ if (rule.ifAnyIn) {
304
+ if (parts.length !== 2) {
305
+ contract(`${tp}.ifAnyIn`, "ifAnyIn needs at one relation away: the records it compares");
306
+ }
307
+ for (const state of rule.ifAnyIn) {
308
+ if (!isState(state)) {
309
+ contract(`${tp}.ifAnyIn`, `"${state}" is not an option of ${states.field}`);
310
+ }
311
+ }
312
+ }
313
+ });
266
314
  for (const [request, targets] of Object.entries(states.requests ?? {})) {
267
315
  const rp = `${sp}.requests.${request}`;
268
316
  if (isState(request))
@@ -278,6 +326,54 @@ export function checkObjectStates(m, name, object, contract) {
278
326
  }
279
327
  }
280
328
  }
329
+ /**
330
+ * The checks of window paths and numbers (ADRs 0503 and 0505): for a `states` declaration, and
331
+ * for any other declaration that names a moment the same way (a waitlist's cut-off, ADR 0520).
332
+ */
333
+ export function windowChecks(m, object, name, contract) {
334
+ const checkPath = (at, path, type) => {
335
+ const field = resolveFieldPath(m, object, at);
336
+ // A staff-only rule may read a formula: the host computes it in the view (a boolean one).
337
+ const formulaOk = type === "boolean" && field?.type === "formula";
338
+ if ((field?.type !== type && !formulaOk) || field?.many) {
339
+ contract(path, `"${at}" must be a ${type} field of ${name}, or <relation>.<field> through up to two relations (one record each), every field on the way declared by this extension`);
340
+ }
341
+ };
342
+ const checkNumber = (value, path) => {
343
+ if (typeof value === "string")
344
+ checkPath(value, path, "number");
345
+ else if (typeof value === "object") {
346
+ if (value.field !== undefined)
347
+ checkPath(value.field, `${path}.field`, "number");
348
+ if (value.setting !== undefined) {
349
+ const settings = m.settings ?? {};
350
+ const setting = Object.hasOwn(settings, value.setting)
351
+ ? settings[value.setting]
352
+ : undefined;
353
+ if (setting?.type !== "number") {
354
+ contract(`${path}.setting`, `"${value.setting}" must be a number setting of ${m.id}`);
355
+ }
356
+ }
357
+ }
358
+ };
359
+ const checkBound = (bound, path) => {
360
+ const b = typeof bound === "string" ? { at: bound } : bound;
361
+ checkPath(b.at, `${path}.at`, "datetime");
362
+ for (const key of ["daysBefore", "minutesBefore"]) {
363
+ checkNumber(b[key], `${path}.${key}`);
364
+ }
365
+ if (b.zone !== undefined)
366
+ checkPath(b.zone, `${path}.zone`, "timezone");
367
+ };
368
+ const checkWindow = (window, path) => {
369
+ for (const end of ["from", "until"]) {
370
+ const bound = window?.[end];
371
+ if (bound !== undefined)
372
+ checkBound(bound, `${path}.${end}`);
373
+ }
374
+ };
375
+ return { checkPath, checkNumber, checkBound, checkWindow };
376
+ }
281
377
  /**
282
378
  * The field a path names (ADR 0503; two relations from ADR 0505): `field` on the object, or
283
379
  * `relation.field` / `relation.relation.field` through relations of one record. Every field on
@@ -0,0 +1,129 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * What customers and the public are told about a record's stock (staff always see the numbers):
5
+ * `availability` (the default), "In stock" or "Sold out"; `low`, "only N left" at or below
6
+ * `lowAt`; `exact`, the number available.
7
+ */
8
+ export declare const STOCK_SHOW: readonly ["exact", "low", "availability"];
9
+ export type StockShow = (typeof STOCK_SHOW)[number];
10
+ /**
11
+ * The read-only values the host adds to every record of an object with stock: on hand (what is
12
+ * on the shelf, sold units gone), held (by orders being paid for) and available (on hand less
13
+ * held). An object with stock cannot have fields of these names.
14
+ */
15
+ export declare const STOCK_VALUES: readonly ["onHand", "held", "available"];
16
+ /**
17
+ * The kinds of movement in the ledger (ADR 0680). The host writes `opening`, `adjusted` and
18
+ * `sold`; a record's `stockMoves` writes `received`, `written_off`, `used` and `counted` (ADR
19
+ * 0681); a return (stage 37 step 4) writes `returned`.
20
+ */
21
+ export declare const STOCK_MOVEMENT_KINDS: readonly ["opening", "received", "sold", "returned", "written_off", "counted", "adjusted", "used"];
22
+ export type StockMovementKind = (typeof STOCK_MOVEMENT_KINDS)[number];
23
+ /**
24
+ * A number of things on hand (ADR 0680). The host keeps the count from a ledger of movements
25
+ * (opening stock, a correction, a sale) and nobody types it: an order line holds its quantity
26
+ * while the order is unpaid and sells it when it is paid, refused by the database past what is
27
+ * available, in the order's own batch. A refund changes nothing in stock; a return does.
28
+ *
29
+ * - `reorderAt` is this object's number field holding the reorder level (a record at or below it
30
+ * is low); `reorderQty` the number field holding how many to order then.
31
+ * - `show` is what customers and the public are told (default `availability`); `lowAt` is the
32
+ * threshold for `low`.
33
+ * - `notify` is one of this extension's tool permissions: when a write takes a record's on hand to
34
+ * or below its reorder level, the staff who hold it are told, once until it rises above again
35
+ * (ADR 0681). Without it, the admins are told. It needs `reorderAt`.
36
+ * - The object is sellable goods (`sellable.goods`, ADR 0682), or the object a `stockMoves` of
37
+ * this extension moves (a part nobody sells still has stock).
38
+ *
39
+ * An object with stock is not also a capacity (its counter is the stock's), and is not bought by
40
+ * deposit, by subscription or by moving a record (`sellable.deposit`, `recurring`, `moves`).
41
+ */
42
+ export interface StockSpec {
43
+ reorderAt?: string;
44
+ reorderQty?: string;
45
+ show?: StockShow;
46
+ lowAt?: number;
47
+ notify?: string;
48
+ }
49
+ export declare const stockManifestSchema: z.ZodObject<{
50
+ reorderAt: z.ZodOptional<z.ZodString>;
51
+ reorderQty: z.ZodOptional<z.ZodString>;
52
+ show: z.ZodOptional<z.ZodEnum<{
53
+ exact: "exact";
54
+ low: "low";
55
+ availability: "availability";
56
+ }>>;
57
+ lowAt: z.ZodOptional<z.ZodNumber>;
58
+ notify: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strict>;
60
+ export type StockManifest = z.infer<typeof stockManifestSchema>;
61
+ /** Reports problems with `objects.<name>.stock` through `contract`. */
62
+ export declare function checkObjectStock(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
63
+ /** How a record's move changes stock: units in, units out, or on hand set to a counted number. */
64
+ export declare const STOCK_MOVES: readonly ["add", "remove", "set"];
65
+ export type StockMove = (typeof STOCK_MOVES)[number];
66
+ /** The ledger kinds each move may write; the first is the default. */
67
+ export declare const STOCK_MOVE_KINDS: {
68
+ readonly add: readonly ["received"];
69
+ readonly remove: readonly ["written_off", "used"];
70
+ readonly set: readonly ["counted"];
71
+ };
72
+ /**
73
+ * A record's state moves stock (ADR 0681): when it enters `when`, the host writes a movement of
74
+ * `quantity` on the record `on` points to (an object of this extension with stock), in the batch
75
+ * of the write that makes the move, for every actor. A receipt `received` adds; a write-off
76
+ * removes; a count line `set`s on hand to the number counted, the difference worked out when the
77
+ * batch commits.
78
+ *
79
+ * - `when` is a state of this object, or with `through`, of the record `through` points to (a
80
+ * relation, one record, to another object of this extension with states): that record entering
81
+ * `when` moves the stock of every live record of this object pointing to it, in one batch (a
82
+ * count applied moves each of its lines). No declared move leaves `when`: stock moves once.
83
+ * - `kind` is the ledger's kind: `received` for add; `written_off` (default) or `used` for
84
+ * remove; `counted` for set.
85
+ * - `unitCost` (add only) is a number field of the cost of one, in minor units; `note` a text
86
+ * field the ledger keeps.
87
+ * - Every declared move into `when` is by `["host"]`, with the `tools` (humanOnly or
88
+ * personApproves, with a permission) a person makes it through; nothing is created in `when`
89
+ * but by the host. Moving stock is a person's act: an AI's call of the tool waits for a person.
90
+ * - A quantity is a whole number, above 0 (add, remove) or 0 and above (set). Once moved, `on`,
91
+ * `quantity`, `unitCost` and `note` cannot change, and a moved record's lines cannot be added to
92
+ * or changed: the ledger keeps what moved.
93
+ */
94
+ export interface StockMovesSpec {
95
+ move: StockMove;
96
+ on: string;
97
+ quantity: string;
98
+ when: string;
99
+ through?: string;
100
+ kind?: StockMovementKind;
101
+ unitCost?: string;
102
+ note?: string;
103
+ }
104
+ export declare const stockMovesManifestSchema: z.ZodObject<{
105
+ move: z.ZodEnum<{
106
+ set: "set";
107
+ add: "add";
108
+ remove: "remove";
109
+ }>;
110
+ on: z.ZodString;
111
+ quantity: z.ZodString;
112
+ when: z.ZodString;
113
+ through: z.ZodOptional<z.ZodString>;
114
+ kind: z.ZodOptional<z.ZodEnum<{
115
+ used: "used";
116
+ opening: "opening";
117
+ received: "received";
118
+ sold: "sold";
119
+ returned: "returned";
120
+ written_off: "written_off";
121
+ counted: "counted";
122
+ adjusted: "adjusted";
123
+ }>>;
124
+ unitCost: z.ZodOptional<z.ZodString>;
125
+ note: z.ZodOptional<z.ZodString>;
126
+ }, z.core.$strict>;
127
+ export type StockMovesManifest = z.infer<typeof stockMovesManifestSchema>;
128
+ /** Reports problems with `objects.<name>.stockMoves` through `contract`. */
129
+ export declare function checkObjectStockMoves(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
package/dist/stock.js ADDED
@@ -0,0 +1,205 @@
1
+ // The `stock` behaviour (stage 37, ADR 0680): an object declares that its records are things
2
+ // counted on a shelf (a variant of an item in a shop), and the host keeps how many there are, from
3
+ // a ledger nobody edits, never selling more than there is, for every actor. Its declaration, its
4
+ // manifest schema and its contract checks live here; the host's side is packages/core/src/stock/.
5
+ import { z } from "zod";
6
+ import { moveOrigins } from "./states.js";
7
+ /**
8
+ * What customers and the public are told about a record's stock (staff always see the numbers):
9
+ * `availability` (the default), "In stock" or "Sold out"; `low`, "only N left" at or below
10
+ * `lowAt`; `exact`, the number available.
11
+ */
12
+ export const STOCK_SHOW = ["exact", "low", "availability"];
13
+ /**
14
+ * The read-only values the host adds to every record of an object with stock: on hand (what is
15
+ * on the shelf, sold units gone), held (by orders being paid for) and available (on hand less
16
+ * held). An object with stock cannot have fields of these names.
17
+ */
18
+ export const STOCK_VALUES = ["onHand", "held", "available"];
19
+ /**
20
+ * The kinds of movement in the ledger (ADR 0680). The host writes `opening`, `adjusted` and
21
+ * `sold`; a record's `stockMoves` writes `received`, `written_off`, `used` and `counted` (ADR
22
+ * 0681); a return (stage 37 step 4) writes `returned`.
23
+ */
24
+ export const STOCK_MOVEMENT_KINDS = [
25
+ "opening",
26
+ "received",
27
+ "sold",
28
+ "returned",
29
+ "written_off",
30
+ "counted",
31
+ "adjusted",
32
+ "used",
33
+ ];
34
+ const fieldName = z.string().max(40);
35
+ export const stockManifestSchema = z
36
+ .object({
37
+ reorderAt: fieldName.optional(),
38
+ reorderQty: fieldName.optional(),
39
+ show: z.enum(STOCK_SHOW).optional(),
40
+ lowAt: z.number().int().min(1).max(1_000_000).optional(),
41
+ notify: z.string().max(80).optional(),
42
+ })
43
+ .strict();
44
+ /** Reports problems with `objects.<name>.stock` through `contract`. */
45
+ export function checkObjectStock(m, name, object, contract) {
46
+ const stock = object.stock;
47
+ if (!stock)
48
+ return;
49
+ const path = `objects.${name}.stock`;
50
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
51
+ for (const key of ["reorderAt", "reorderQty"]) {
52
+ const local = stock[key];
53
+ if (local === undefined)
54
+ continue;
55
+ const field = fieldOf(local);
56
+ if (field?.type !== "number" || field.many) {
57
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
58
+ }
59
+ }
60
+ for (const reserved of STOCK_VALUES) {
61
+ if (Object.hasOwn(object.fields, reserved)) {
62
+ contract(`objects.${name}.fields.${reserved}`, `"${reserved}" is a value the host adds to an object with stock; rename the field`);
63
+ }
64
+ }
65
+ if (object.capacity) {
66
+ contract(path, "An object has stock or a capacity, not both: stock keeps its own counter");
67
+ }
68
+ const sellable = object.sellable;
69
+ if (sellable) {
70
+ for (const key of ["deposit", "recurring", "moves"]) {
71
+ if (sellable[key] !== undefined) {
72
+ contract(`objects.${name}.sellable.${key}`, `A thing in stock is sold whole, on an order: it has no sellable.${key}`);
73
+ }
74
+ }
75
+ }
76
+ if (stock.lowAt !== undefined && stock.show !== "low") {
77
+ contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
78
+ }
79
+ if (stock.show === "low" && stock.lowAt === undefined) {
80
+ contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
81
+ }
82
+ if (stock.notify !== undefined) {
83
+ if (stock.reorderAt === undefined) {
84
+ contract(`${path}.notify`, "notify tells staff of a reorder level: declare reorderAt");
85
+ }
86
+ const permissions = Object.values(m.tools).flatMap((tool) => typeof tool.permission === "string" ? [tool.permission] : [...(tool.permission ?? [])]);
87
+ if (!permissions.includes(stock.notify)) {
88
+ contract(`${path}.notify`, `"${stock.notify}" is not the permission of any of this extension's tools (tools.<name>.permission)`);
89
+ }
90
+ }
91
+ const moved = Object.values(m.objects).some((other) => other.stockMoves && relationTarget(m, other, other.stockMoves.on) === name);
92
+ if (sellable && !sellable.goods) {
93
+ // A thing in stock that is sold is goods (ADR 0682): its orders have a channel and a delivery.
94
+ contract(`objects.${name}.sellable.goods`, `${name} has stock and is sold: declare sellable.goods (where it is sold)`);
95
+ }
96
+ if (!sellable && !moved) {
97
+ contract(path, `${name} has stock but is neither sellable goods nor moved by a stockMoves of this extension`);
98
+ }
99
+ }
100
+ // --- stockMoves (ADR 0681) ------------------------------------------------------------------------
101
+ /** How a record's move changes stock: units in, units out, or on hand set to a counted number. */
102
+ export const STOCK_MOVES = ["add", "remove", "set"];
103
+ /** The ledger kinds each move may write; the first is the default. */
104
+ export const STOCK_MOVE_KINDS = {
105
+ add: ["received"],
106
+ remove: ["written_off", "used"],
107
+ set: ["counted"],
108
+ };
109
+ export const stockMovesManifestSchema = z
110
+ .object({
111
+ move: z.enum(STOCK_MOVES),
112
+ on: fieldName,
113
+ quantity: fieldName,
114
+ when: z.string().min(1).max(100),
115
+ through: fieldName.optional(),
116
+ kind: z.enum(STOCK_MOVEMENT_KINDS).optional(),
117
+ unitCost: fieldName.optional(),
118
+ note: fieldName.optional(),
119
+ })
120
+ .strict();
121
+ /** The local name of the object of this extension a one-record relation field points to. */
122
+ function relationTarget(m, object, field) {
123
+ const f = Object.hasOwn(object.fields, field) ? object.fields[field] : undefined;
124
+ if (f?.type !== "relation" || f.many || !f.to?.startsWith(`${m.id}.`))
125
+ return undefined;
126
+ const local = f.to.slice(m.id.length + 1);
127
+ return Object.hasOwn(m.objects, local) ? local : undefined;
128
+ }
129
+ /** Reports problems with `objects.<name>.stockMoves` through `contract`. */
130
+ export function checkObjectStockMoves(m, name, object, contract) {
131
+ const moves = object.stockMoves;
132
+ if (!moves)
133
+ return;
134
+ const path = `objects.${name}.stockMoves`;
135
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
136
+ const target = relationTarget(m, object, moves.on);
137
+ if (!target) {
138
+ contract(`${path}.on`, `"${moves.on}" must be a relation field (one record) to an object of this extension with stock`);
139
+ }
140
+ else if (!m.objects[target]?.stock) {
141
+ contract(`${path}.on`, `${m.id}.${target} must declare stock for its stock to move`);
142
+ }
143
+ const number = (key) => {
144
+ const local = moves[key];
145
+ if (local === undefined)
146
+ return;
147
+ const field = fieldOf(local);
148
+ if (field?.type !== "number" || field.many) {
149
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
150
+ }
151
+ };
152
+ number("quantity");
153
+ number("unitCost");
154
+ if (moves.unitCost !== undefined && moves.move !== "add") {
155
+ contract(`${path}.unitCost`, "Only what comes in (add) has a unit cost");
156
+ }
157
+ if (moves.note !== undefined) {
158
+ const field = fieldOf(moves.note);
159
+ if (field?.type !== "text" || field.many) {
160
+ contract(`${path}.note`, `"${moves.note}" must be a text field of ${name}`);
161
+ }
162
+ }
163
+ const kinds = STOCK_MOVE_KINDS[moves.move];
164
+ if (moves.kind !== undefined && !kinds.includes(moves.kind)) {
165
+ contract(`${path}.kind`, `A ${moves.move} writes ${kinds.map((k) => `"${k}"`).join(" or ")}, not "${moves.kind}"`);
166
+ }
167
+ // Whose state moves it: this object's, or the record `through` points to.
168
+ let owner = name;
169
+ if (moves.through !== undefined) {
170
+ owner = relationTarget(m, object, moves.through);
171
+ if (!owner || owner === name) {
172
+ contract(`${path}.through`, `"${moves.through}" must be a relation field (one record) to another of this extension's objects`);
173
+ return;
174
+ }
175
+ }
176
+ const states = m.objects[owner]?.states;
177
+ if (!states) {
178
+ contract(moves.through === undefined ? path : `${path}.through`, `${owner} must declare states: entering "${moves.when}" moves the stock`);
179
+ return;
180
+ }
181
+ const stateField = Object.hasOwn(m.objects[owner]?.fields ?? {}, states.field)
182
+ ? m.objects[owner]?.fields[states.field]
183
+ : undefined;
184
+ if (!(stateField?.options ?? []).some((o) => o.value === moves.when)) {
185
+ contract(`${path}.when`, `"${moves.when}" is not a state of ${owner}`);
186
+ }
187
+ if (states.moves.some((move) => moveOrigins(move).includes(moves.when))) {
188
+ contract(`${path}.when`, `No move may leave "${moves.when}": stock moves once, when a record enters it`);
189
+ }
190
+ // Moving stock is a person's act with the pack's permission (ADR 0681, the review of #422):
191
+ // the host's alone, and the tools a person calls (ADR 0513), so an assistant's or an MCP
192
+ // client's call of them waits for a person, and no customer, member or automation moves stock
193
+ // by moving a record.
194
+ states.moves.forEach((move, i) => {
195
+ if (move.to !== moves.when)
196
+ return;
197
+ if (move.by.some((mover) => mover !== "host")) {
198
+ contract(`objects.${owner}.states.moves.${i}.by`, `Entering "${moves.when}" moves stock: declare it by ["host"] with the tools a person makes it through (states.moves.<n>.tools)`);
199
+ }
200
+ });
201
+ const created = states.create?.in?.[moves.when];
202
+ if (created?.some((mover) => mover !== "host")) {
203
+ contract(`objects.${owner}.states.create.in.${moves.when}`, `Creating a record in "${moves.when}" moves stock: only the host may; create it in another state and move it through a tool`);
204
+ }
205
+ }
package/dist/team.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * Who on the staff looks after the Person a record is about (ADR 0831): the accounts in its
5
+ * `staff` user fields, while the record is in one of the `live` states of the object's `states`
6
+ * (every record not in the Trash, when the object has no states). A client's program names their
7
+ * coach: `{ person: "person", staff: ["coach"], live: ["generating", "active"] }`.
8
+ *
9
+ * It gives nothing by itself. A pack role that declares `looksAfter` reaches its objects' records
10
+ * only for the People its holder looks after this way (ADR 0889). Only shipped packs and the
11
+ * org's own extensions declare it: who reaches whose records is access.
12
+ */
13
+ export interface TeamSpec {
14
+ /** A relation (one record) to `person`: whom the record is about. */
15
+ person: string;
16
+ /** `user` fields of this object (one account each, each `personApproves`): who looks after them. */
17
+ staff: readonly string[];
18
+ /** The states of the object's `states` in which the record counts. */
19
+ live?: readonly string[];
20
+ }
21
+ export declare const teamManifestSchema: z.ZodObject<{
22
+ person: z.ZodString;
23
+ staff: z.ZodArray<z.ZodString>;
24
+ live: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
+ }, z.core.$strict>;
26
+ export type TeamManifest = z.infer<typeof teamManifestSchema>;
27
+ /** Reports problems with `objects.<name>.team` through `contract`. */
28
+ export declare function checkObjectTeam(_m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;