@composable-os/sdk 0.1.0-beta.7 → 0.1.0-beta.9

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/contract.ts CHANGED
@@ -2,12 +2,15 @@
2
2
  // `defineExtension({...})`. Everything here is plain data plus tool/automation handlers, so the host
3
3
  // can turn it into a JSON manifest, validate it, diff it and reconcile it to tables.
4
4
  import type { z } from "zod";
5
+ import type { AllowanceSpec } from "./allowance.ts";
5
6
  import type { AutomationSpec } from "./automation.ts";
6
- import type { CapacitySpec } from "./capacity.ts";
7
+ import type { CapacitySpec, ClaimsSpec } from "./capacity.ts";
7
8
  import type { DocumentPathSpec, DocumentSchema } from "./document.ts";
8
9
  import type { FieldTypeName } from "./field-types.ts";
10
+ import type { RecurringScheduleSpec } from "./recurring.ts";
9
11
  import type { SellableSpec } from "./sellable.ts";
10
12
  import type { StatesSpec } from "./states.ts";
13
+ import type { UniqueSpec } from "./unique.ts";
11
14
 
12
15
  /** The contract version this SDK writes. The host accepts this and the previous version. */
13
16
  export const CONTRACT_VERSION = 1;
@@ -173,6 +176,15 @@ export type FieldSpec =
173
176
  */
174
177
  type: "image";
175
178
  })
179
+ | (Omit<FieldBase, "default" | "defaultSetting" | "track"> & {
180
+ /**
181
+ * A video from the media library (stage 42, ADR 0475): `{ media, poster? }`, a video held in
182
+ * Cloudflare Stream (a ready one, checked on write) and a picture to show before it plays.
183
+ * Every video needs a token the host signs to play (`media.play`); the id alone plays
184
+ * nothing.
185
+ */
186
+ type: "video";
187
+ })
176
188
  | (Omit<FieldBase, "required"> & {
177
189
  type: "formula";
178
190
  /** An expression over fields of the same record. See the SDK README for the grammar. */
@@ -228,8 +240,28 @@ export interface ObjectSpec {
228
240
  capacity?: CapacitySpec;
229
241
  /** Something that can be bought, and what a paid line grants (see SellableSpec, ADR 0435). */
230
242
  sellable?: SellableSpec;
243
+ /**
244
+ * Uses a record holds (a pass, a membership), or a record that spends one (a booking): see
245
+ * AllowanceSpec, ADRs 0493 and 0494. The host counts and refuses a spend past the limit.
246
+ */
247
+ allowance?: AllowanceSpec;
231
248
  /** A fixed state machine (see StatesSpec, ADR 0425). An object has stages or states, not both. */
232
249
  states?: StatesSpec;
250
+ /**
251
+ * A capacity claimant (see ClaimsSpec, ADR 0501): the record's own states hold, take and give
252
+ * back one place on the record its relation `on` points to (a booking on its class).
253
+ */
254
+ claims?: ClaimsSpec;
255
+ /**
256
+ * Uniqueness among live records in some states (see UniqueSpec, ADR 0502): one active booking
257
+ * per Person per class. Refused by the database for every actor.
258
+ */
259
+ unique?: readonly UniqueSpec[];
260
+ /**
261
+ * A weekly schedule that generates dated records of another object (see RecurringScheduleSpec,
262
+ * ADR 0500): a timetable's series and its classes.
263
+ */
264
+ recurring?: RecurringScheduleSpec;
233
265
  /**
234
266
  * The record's owner: a `user` field of this object (ADR 0246, stage 14). Assignment rules set
235
267
  * it when a record is created without one, and stage 14's visibility policies read it.
@@ -273,6 +305,15 @@ export interface ObjectSpec {
273
305
  * may declare it.
274
306
  */
275
307
  customerVia?: CustomerViaSpec;
308
+ /**
309
+ * Who holds access to a record (stage 42, ADR 0477): a customer for whom one of `sources` is
310
+ * live (an enrolment of theirs pointing at it, or at a bundle that lists it). The parts of a
311
+ * document field this object's schema marks `holders` are read only by a holder; everyone
312
+ * else who may read the record reads it without them. The host asks one question for every
313
+ * read and for `media.play`; a block, a hook or a client app is only told the answer. Only
314
+ * shipped extensions and an org's own may declare it.
315
+ */
316
+ access?: AccessSpec;
276
317
  /**
277
318
  * A working copy staff edit and published versions (ADR 0446): `content` names the fields a
278
319
  * version keeps. `record.publish` snapshots them as the next version (a person with the
@@ -618,6 +659,49 @@ export interface CustomerViaSpec {
618
659
  read: readonly string[];
619
660
  }
620
661
 
662
+ /** Who holds access to a record: see `ObjectSpec.access` (ADR 0477). */
663
+ export interface AccessSpec {
664
+ /** Where access comes from. Any one live source is enough. */
665
+ sources: readonly AccessSourceSpec[];
666
+ }
667
+
668
+ /**
669
+ * One source of access. A record source (`via`) is a record of another of this extension's
670
+ * objects that declares a customer: the caller's own, in one of `states`, before its `until`,
671
+ * pointing at the record through `field` (an enrolment's `course`) or, with `through`, at a
672
+ * record whose field `through` lists it (an enrolment's `bundle`, whose `courses` name the
673
+ * course). A source of another `kind` is one the host provides (a subscription, stage 32).
674
+ */
675
+ export type AccessSourceSpec =
676
+ | {
677
+ /** `<extension>.<object>`: an object of this extension that declares a customer. */
678
+ via: string;
679
+ /** A relation of `via` to one record of this object, or of the object `through` is on. */
680
+ field: string;
681
+ /**
682
+ * A field of the record `field` points to that lists this object's records: a many
683
+ * relation, or a document whose refs name them. Read from its published version when the
684
+ * public reads it.
685
+ */
686
+ through?: string;
687
+ /** The states of `via` (its `states` behaviour) in which it gives access. */
688
+ states?: readonly string[];
689
+ /** A date or datetime field of `via`: access ends then. Empty is no end. */
690
+ until?: string;
691
+ kind?: undefined;
692
+ }
693
+ | {
694
+ /**
695
+ * A kind of source the host provides. `subscription` (stage 32a, ADR 0488): the caller
696
+ * holds a running subscription to a plan of `options.plans` (`<extension>.<object>`, an
697
+ * object of this extension whose `sellable` declares `recurring`), and `options.covers`
698
+ * is `"all"`: every live record. Access follows the subscription's holder.
699
+ */
700
+ kind: string;
701
+ options?: Readonly<Record<string, string | number | boolean | readonly string[]>>;
702
+ via?: undefined;
703
+ };
704
+
621
705
  /** What every signed-in customer may read: see `ObjectSpec.signedIn` (ADR 0447). */
622
706
  export interface SignedInSpec {
623
707
  read: readonly string[];
@@ -648,6 +732,12 @@ export interface CustomerSpec {
648
732
  field: string;
649
733
  read: readonly string[];
650
734
  write: readonly string[];
735
+ /**
736
+ * Relations whose record the customer must hold access to for any write of theirs (stage 42,
737
+ * ADR 0478): a lesson's progress is written only while its course is theirs. Checked by the host
738
+ * on create and on every update, against the record the row points to.
739
+ */
740
+ requireAccess?: readonly string[];
651
741
  }
652
742
 
653
743
  /** A tool shown as a button on a record page. */
@@ -722,6 +812,12 @@ export interface ExtensionSpec {
722
812
  contractVersion: number;
723
813
  label?: string;
724
814
  description?: string;
815
+ /**
816
+ * Extensions this one needs installed first, by id (stage 42, ADR 0478): Courses requires
817
+ * Programs. The host refuses to install it while one is missing, and installs shipped ones in
818
+ * that order.
819
+ */
820
+ requires?: readonly string[];
725
821
  permissions?: PermissionsSpec;
726
822
  objects?: Record<string, ObjectSpec>;
727
823
  /** Fields added to other objects, keyed by target object (`organisation`, `other.object`). */
package/src/document.ts CHANGED
@@ -23,6 +23,11 @@
23
23
  // An object node may be `private`: removed from what a customer or the public reads
24
24
  // (`redactDocument`), unless its `unless` key is true (a coach's note marked as shown to
25
25
  // members). The host does that at the visibility seam; staff read the whole document.
26
+ //
27
+ // An object node may also be for `holders` (stage 42, ADR 0477): removed, or some of its keys
28
+ // removed, from what an outsider reads unless they hold access to the record (the seam's one
29
+ // question, visibility/access.ts) or its `unless` key is true (a lesson marked as a free
30
+ // preview). A `ref` to `media` may name the kind of item it takes (`media: "video"`).
26
31
 
27
32
  /** The most a document may be, in bytes of its JSON, whatever a field declares. */
28
33
  export const DOCUMENT_MAX_BYTES = 524_288;
@@ -89,7 +94,24 @@ export interface DocumentObjectNode extends NodeBase {
89
94
  * that boolean key of the object is true (a note marked as shown to members).
90
95
  */
91
96
  private?: true | { unless: string };
97
+ /**
98
+ * For holders only (stage 42, ADR 0477): removed when someone outside the org who does not
99
+ * hold access to the record reads the document. `true` or `{ unless }` removes the whole object,
100
+ * as `private` does; `{ keys, unless? }` removes only those keys of it (a lesson's video and
101
+ * notes, while its title stays). `unless` names a boolean key of this object that keeps it (a
102
+ * free preview).
103
+ */
104
+ holders?: DocumentHolders;
92
105
  }
106
+
107
+ /** What of an object node is for holders only: see `DocumentObjectNode.holders`. */
108
+ export type DocumentHolders =
109
+ | true
110
+ | { unless: string; keys?: undefined }
111
+ | { keys: readonly string[]; unless?: string };
112
+
113
+ /** The kinds of media item (stage 42, ADR 0475). */
114
+ export type DocumentMediaKind = "image" | "video" | "file";
93
115
  export interface DocumentArrayNode extends NodeBase {
94
116
  type: "array";
95
117
  of: DocumentNode;
@@ -97,6 +119,12 @@ export interface DocumentArrayNode extends NodeBase {
97
119
  min?: number;
98
120
  /** A key of the listed objects whose values must differ (labels, level numbers). */
99
121
  unique?: string;
122
+ /**
123
+ * With `unique`: the key's values must differ across every list this node holds in the
124
+ * document, not only within one (stage 42: a lesson's key across all sections, since progress
125
+ * is kept by it).
126
+ */
127
+ uniqueAcross?: boolean;
100
128
  }
101
129
  export interface DocumentTextNode extends NodeBase {
102
130
  type: "text";
@@ -139,6 +167,11 @@ export interface DocumentChoiceNode extends NodeBase {
139
167
  export interface DocumentRefNode extends NodeBase {
140
168
  type: "ref";
141
169
  to: string;
170
+ /**
171
+ * For a ref to `media` (stage 42, ADR 0475): the kind of item it takes, checked by the host on
172
+ * write; a video must also be ready. Left out, any live item.
173
+ */
174
+ media?: DocumentMediaKind;
142
175
  }
143
176
  /** One of several object shapes, told apart by the value of `tag`. */
144
177
  export interface DocumentUnionNode extends NodeBase {
@@ -271,12 +304,15 @@ export function checkDocumentSchema(
271
304
  };
272
305
  switch (value.type) {
273
306
  case "object": {
274
- expect("fields", "private");
307
+ expect("fields", "private", "holders");
275
308
  object(path, value, depth);
276
309
  break;
277
310
  }
278
311
  case "array": {
279
- expect("of", "max", "min", "unique");
312
+ expect("of", "max", "min", "unique", "uniqueAcross");
313
+ if (value.uniqueAcross !== undefined && (value.uniqueAcross !== true || !value.unique)) {
314
+ add(`${path}.uniqueAcross`, "uniqueAcross is true, beside unique");
315
+ }
280
316
  const max = num("max", { int: true, min: 1, max: DOCUMENT_MAX_LIST });
281
317
  if (value.max === undefined) add(`${path}.max`, "A list declares its most entries (max)");
282
318
  const min = num("min", { int: true, min: 0 });
@@ -360,12 +396,18 @@ export function checkDocumentSchema(
360
396
  break;
361
397
  }
362
398
  case "ref": {
363
- expect("to");
399
+ expect("to", "media");
364
400
  if (typeof value.to !== "string" || !OBJECT_RE.test(value.to)) {
365
401
  add(`${path}.to`, "A ref names an object: `<extension>.<object>` or a core object");
366
402
  } else if (knownObjects && !knownObjects.has(value.to)) {
367
403
  add(`${path}.to`, `Unknown object "${value.to}"`);
368
404
  }
405
+ if (value.media !== undefined) {
406
+ if (value.to !== "media") add(`${path}.media`, "media is for a ref to media");
407
+ else if (!["image", "video", "file"].includes(String(value.media))) {
408
+ add(`${path}.media`, "media is image, video or file");
409
+ }
410
+ }
369
411
  break;
370
412
  }
371
413
  case "union": {
@@ -438,6 +480,33 @@ export function checkDocumentSchema(
438
480
  add(`${path}.private`, "private is true, or { unless: <a boolean key of this object> }");
439
481
  }
440
482
  }
483
+ const holders = value.holders;
484
+ if (holders !== undefined && holders !== true) {
485
+ const fields = value.fields as Record<string, unknown>;
486
+ const shape = isObject(holders) ? holders : null;
487
+ const unless = shape?.unless;
488
+ const keys = shape?.keys;
489
+ const flag = typeof unless === "string" ? fields[unless] : undefined;
490
+ const badUnless = unless !== undefined && (!isObject(flag) || flag.type !== "boolean");
491
+ const badKeys =
492
+ keys !== undefined &&
493
+ (!Array.isArray(keys) ||
494
+ !keys.length ||
495
+ keys.some((k) => typeof k !== "string" || !Object.hasOwn(fields, k) || k === unless));
496
+ const extra = shape ? Object.keys(shape).filter((k) => k !== "unless" && k !== "keys") : [];
497
+ if (
498
+ !shape ||
499
+ (unless === undefined && keys === undefined) ||
500
+ badUnless ||
501
+ badKeys ||
502
+ extra.length
503
+ ) {
504
+ add(
505
+ `${path}.holders`,
506
+ "holders is true, { unless: <a boolean key> } or { keys: [<keys of this object>], unless? }",
507
+ );
508
+ }
509
+ }
441
510
  };
442
511
 
443
512
  const resolve = (value: unknown, seen = new Set<string>()): DocumentNode | undefined => {
@@ -477,6 +546,10 @@ export function documentPathNode(
477
546
  const at = useOf(schema, current);
478
547
  if (at?.type !== "object")
479
548
  return `"${spec.path}" passes through something that is not an object`;
549
+ // A column of the view is read whole: a part for holders only cannot be one (ADR 0477).
550
+ if (at.holders && (at.holders === true || !at.holders.keys || at.holders.keys.includes(key))) {
551
+ return `"${spec.path}" is in a part for holders only, which a column cannot keep from others`;
552
+ }
480
553
  current = at.fields[key];
481
554
  if (!current) return `"${spec.path}" is not in the schema (no "${key}")`;
482
555
  }
@@ -541,6 +614,7 @@ export function validateDocument(
541
614
  };
542
615
  }
543
616
  const issues: DocumentIssue[] = [];
617
+ const acrossLists = new Map<DocumentArrayNode, Map<string, string>>();
544
618
  const fault = (path: (string | number)[], message: string) => {
545
619
  if (issues.length < DOCUMENT_MAX_ISSUES) issues.push({ path: [...path], message });
546
620
  };
@@ -587,17 +661,32 @@ export function validateDocument(
587
661
  fault(path, `At least ${node.min} ${node.min === 1 ? "entry" : "entries"}`);
588
662
  }
589
663
  const seen = new Map<string, number>();
664
+ // Across every list of this node in the document: the first place each key was used.
665
+ let across = node.uniqueAcross ? acrossLists.get(node) : undefined;
666
+ if (node.uniqueAcross && !across) {
667
+ across = new Map();
668
+ acrossLists.set(node, across);
669
+ }
590
670
  v.slice(0, node.max).forEach((item, i) => {
591
671
  walk(node.of, item, [...path, i], depth + 1);
592
672
  if (node.unique && isObject(item) && item[node.unique] !== undefined) {
593
673
  const key = JSON.stringify(item[node.unique]);
594
674
  const first = seen.get(key);
675
+ const elsewhere = across?.get(key);
595
676
  if (first !== undefined) {
596
677
  fault(
597
678
  [...path, i, node.unique],
598
679
  `${JSON.stringify(item[node.unique])} is there twice (also entry ${first})`,
599
680
  );
600
- } else seen.set(key, i);
681
+ } else if (elsewhere !== undefined) {
682
+ fault(
683
+ [...path, i, node.unique],
684
+ `${JSON.stringify(item[node.unique])} is used already (at ${elsewhere})`,
685
+ );
686
+ } else {
687
+ seen.set(key, i);
688
+ across?.set(key, [...path, i].join("."));
689
+ }
601
690
  }
602
691
  });
603
692
  return;
@@ -694,24 +783,70 @@ export function formatDocumentIssue(issue: DocumentIssue): string {
694
783
 
695
784
  // --- Reading a value -----------------------------------------------------------------------------
696
785
 
786
+ /** One `ref` of a value: the object it names, the id, where it is, and a media ref's kind. */
787
+ export interface DocumentRef {
788
+ to: string;
789
+ id: string;
790
+ path: (string | number)[];
791
+ media?: DocumentMediaKind;
792
+ }
793
+
697
794
  /** Every `ref` in a valid value: the object it names, the id, and where it is. */
698
- export function documentRefs(
699
- schema: DocumentSchema,
700
- value: unknown,
701
- ): { to: string; id: string; path: (string | number)[] }[] {
702
- const refs: { to: string; id: string; path: (string | number)[] }[] = [];
795
+ export function documentRefs(schema: DocumentSchema, value: unknown): DocumentRef[] {
796
+ const refs: DocumentRef[] = [];
703
797
  visit(schema, value, (node, v, path) => {
704
- if (node.type === "ref" && typeof v === "string") refs.push({ to: node.to, id: v, path });
798
+ if (node.type === "ref" && typeof v === "string") {
799
+ refs.push({ to: node.to, id: v, path, ...(node.media ? { media: node.media } : {}) });
800
+ }
705
801
  });
706
802
  return refs;
707
803
  }
708
804
 
805
+ /** Who outside the org may read a part of a document (ADR 0477). */
806
+ export type DocumentReach = "all" | "holders" | "private";
807
+
808
+ /**
809
+ * The media items a value names, each with who outside the org reads the part it is in: `all`
810
+ * (anyone who may read the field), `holders` (only a reader who holds access to the record) or
811
+ * `private` (no one outside the org). Read from `redactDocument` itself, so it is exactly what the
812
+ * seam shows. An item named in several parts has the widest reach of them.
813
+ */
814
+ export function documentMediaReach(
815
+ schema: DocumentSchema,
816
+ value: unknown,
817
+ mediaObject = "media",
818
+ ): Map<string, DocumentReach> {
819
+ const ids = (v: unknown) =>
820
+ new Set(
821
+ v === null || v === undefined
822
+ ? []
823
+ : documentRefs(schema, v)
824
+ .filter((r) => r.to === mediaObject)
825
+ .map((r) => r.id),
826
+ );
827
+ const everyone = ids(redactDocument(schema, value, { holder: false }));
828
+ const holders = ids(redactDocument(schema, value, { holder: true }));
829
+ const reach = new Map<string, DocumentReach>();
830
+ for (const id of ids(value)) {
831
+ reach.set(id, everyone.has(id) ? "all" : holders.has(id) ? "holders" : "private");
832
+ }
833
+ return reach;
834
+ }
835
+
709
836
  /**
710
837
  * The document as someone outside the org may read it: every `private` object removed (from a
711
- * list, its entry; from an object, its key), unless its `unless` key is true. A value that does
712
- * not fit the schema is returned as null: an outsider is never shown what was not checked.
838
+ * list, its entry; from an object, its key), unless its `unless` key is true. Unless `holder` is
839
+ * true (the reader holds access to the record, ADR 0477), every `holders` object is removed the
840
+ * same way and every `holders` key of an object dropped, unless its `unless` key is true. A value
841
+ * that does not fit the schema is returned as null: an outsider is never shown what was not
842
+ * checked.
713
843
  */
714
- export function redactDocument(schema: DocumentSchema, value: unknown): unknown {
844
+ export function redactDocument(
845
+ schema: DocumentSchema,
846
+ value: unknown,
847
+ options: { holder?: boolean } = {},
848
+ ): unknown {
849
+ const holder = options.holder === true;
715
850
  if (value === null || value === undefined) return value ?? null;
716
851
  const strip = (
717
852
  node: DocumentNode | undefined,
@@ -731,10 +866,22 @@ export function redactDocument(schema: DocumentSchema, value: unknown): unknown
731
866
  const unless = shape.private === true ? null : shape.private.unless;
732
867
  if (!unless || v[unless] !== true) return { keep: false, value: null };
733
868
  }
869
+ // Holders' parts (ADR 0477): for a reader without access, the object or its listed keys.
870
+ let dropped: ReadonlySet<string> | null = null;
871
+ const h = shape.holders;
872
+ if (h && !holder) {
873
+ const unless = h === true ? undefined : h.unless;
874
+ const open = unless !== undefined && v[unless] === true;
875
+ if (!open) {
876
+ const keys = h === true ? undefined : h.keys;
877
+ if (!keys) return { keep: false, value: null };
878
+ dropped = new Set(keys);
879
+ }
880
+ }
734
881
  const out: Record<string, unknown> = {};
735
882
  if (at.type === "union") out[at.tag] = v[at.tag];
736
883
  for (const [key, child] of Object.entries(shape.fields)) {
737
- if (!Object.hasOwn(v, key)) continue;
884
+ if (!Object.hasOwn(v, key) || dropped?.has(key)) continue;
738
885
  const kept = strip(child, v[key], depth + 1);
739
886
  if (kept.keep) out[key] = kept.value;
740
887
  }
@@ -33,6 +33,9 @@ export const FIELD_TYPES = [
33
33
  "slug",
34
34
  // A picture from the media library, with alt text and a focal point (stage 28, ADR 0444).
35
35
  "image",
36
+ // A video from the media library, held in Cloudflare Stream, played only with a token the host
37
+ // signs (stage 42, ADR 0475).
38
+ "video",
36
39
  ] as const;
37
40
  export type FieldTypeName = (typeof FIELD_TYPES)[number];
38
41
 
@@ -69,6 +72,7 @@ export function formulaTypeOf(
69
72
  case "document":
70
73
  case "richText":
71
74
  case "image":
75
+ case "video":
72
76
  return null;
73
77
  }
74
78
  }
@@ -99,6 +103,7 @@ export const LOSSLESS_TYPE_CHANGES: Readonly<Record<FieldTypeName, readonly Fiel
99
103
  richText: [],
100
104
  slug: ["text", "longText"],
101
105
  image: [],
106
+ video: [],
102
107
  };
103
108
 
104
109
  export function isLosslessChange(from: FieldTypeName, to: FieldTypeName): boolean {
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // import { defineExtension, defineTool, z } from "@composable-os/sdk";
4
4
  // export default defineExtension({ id: "example", version: "1.0.0", contractVersion: 1, ... });
5
5
  export { z } from "zod";
6
+ export * from "./allowance.ts";
6
7
  export * from "./automation.ts";
7
8
  export * from "./automation-check.ts";
8
9
  export * from "./capacity.ts";
@@ -12,6 +13,7 @@ export * from "./field-types.ts";
12
13
  export * from "./manifest.ts";
13
14
  export * from "./media.ts";
14
15
  export * from "./permissions.ts";
16
+ export * from "./recurring.ts";
15
17
  export * from "./renamed.ts";
16
18
  export * from "./rich-text.ts";
17
19
  export * from "./rich-text-fixture.ts";
@@ -31,3 +33,4 @@ export {
31
33
  export * from "./sellable.ts";
32
34
  export * from "./slug.ts";
33
35
  export * from "./states.ts";
36
+ export * from "./unique.ts";