@composable-os/sdk 0.1.0-beta.8 → 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/manifest.ts CHANGED
@@ -3,10 +3,16 @@
3
3
  // diffs and reconciles the manifest. `validateManifest` is the contract check `extension.check`
4
4
  // runs; it returns structured issues a model can act on.
5
5
  import { z } from "zod";
6
+ import { allowanceManifestSchema, checkObjectAllowance } from "./allowance.ts";
6
7
  import { automationManifestSchema } from "./automation.ts";
7
8
  import { checkAutomation } from "./automation-check.ts";
8
9
  import { checkObjectBehaviour } from "./behaviour.ts";
9
- import { capacityManifestSchema, checkObjectCapacity } from "./capacity.ts";
10
+ import {
11
+ capacityManifestSchema,
12
+ checkObjectCapacity,
13
+ checkObjectClaims,
14
+ claimsManifestSchema,
15
+ } from "./capacity.ts";
10
16
  import {
11
17
  type Extension,
12
18
  HOST_MODULES,
@@ -25,9 +31,11 @@ import {
25
31
  } from "./document.ts";
26
32
  import { FIELD_TYPES, type FieldTypeName, formulaTypeOf } from "./field-types.ts";
27
33
  import { checkFormula, type FormulaFieldRef } from "./formula/compile.ts";
34
+ import { checkObjectRecurring, recurringManifestSchema } from "./recurring.ts";
28
35
  import { renamedMessage } from "./renamed.ts";
29
36
  import { checkObjectSellable, sellableManifestSchema } from "./sellable.ts";
30
37
  import { checkObjectStates, statesManifestSchema } from "./states.ts";
38
+ import { checkObjectUnique, uniqueManifestSchema } from "./unique.ts";
31
39
 
32
40
  export const EXTENSION_ID_RE = /^[a-z][a-z0-9]{1,29}$/;
33
41
  export const OBJECT_NAME_RE = /^[a-z][a-z0-9]{0,29}$/;
@@ -192,13 +200,18 @@ export const objectManifestSchema = z.object({
192
200
  stages: stagesManifestSchema.optional(),
193
201
  capacity: capacityManifestSchema.optional(),
194
202
  sellable: sellableManifestSchema.optional(),
203
+ allowance: allowanceManifestSchema.optional(),
195
204
  states: statesManifestSchema.optional(),
205
+ claims: claimsManifestSchema.optional(),
206
+ unique: uniqueManifestSchema.optional(),
207
+ recurring: recurringManifestSchema.optional(),
196
208
  owner: z.string().max(40).optional(),
197
209
  customer: z
198
210
  .object({
199
211
  field: z.string().max(40),
200
212
  read: z.array(z.string().max(40)).max(100),
201
213
  write: z.array(z.string().max(40)).max(100),
214
+ requireAccess: z.array(z.string().max(40)).max(10).optional(),
202
215
  })
203
216
  .strict()
204
217
  .optional(),
@@ -212,6 +225,43 @@ export const objectManifestSchema = z.object({
212
225
  })
213
226
  .strict()
214
227
  .optional(),
228
+ access: z
229
+ .object({
230
+ sources: z
231
+ .array(
232
+ z.union([
233
+ z
234
+ .object({
235
+ via: z.string().max(81),
236
+ field: z.string().max(40),
237
+ through: z.string().max(40).optional(),
238
+ states: z.array(z.string().max(60)).min(1).max(20).optional(),
239
+ until: z.string().max(40).optional(),
240
+ })
241
+ .strict(),
242
+ z
243
+ .object({
244
+ kind: z.string().regex(/^[a-z][a-zA-Z0-9]{0,39}$/),
245
+ options: z
246
+ .record(
247
+ z.string().max(40),
248
+ z.union([
249
+ z.string().max(200),
250
+ z.number(),
251
+ z.boolean(),
252
+ z.array(z.string().max(200)).max(20),
253
+ ]),
254
+ )
255
+ .optional(),
256
+ })
257
+ .strict(),
258
+ ]),
259
+ )
260
+ .min(1)
261
+ .max(8),
262
+ })
263
+ .strict()
264
+ .optional(),
215
265
  publishable: z
216
266
  .object({
217
267
  content: z.array(z.string().max(40)).min(1).max(40),
@@ -383,6 +433,10 @@ export const manifestSchema = z.object({
383
433
  contractVersion: z.number().int(),
384
434
  label: z.string().max(100).optional(),
385
435
  description: z.string().max(2000).optional(),
436
+ requires: z
437
+ .array(z.string().regex(/^[a-z][a-z0-9]*$/))
438
+ .max(10)
439
+ .optional(),
386
440
  permissions: permissionsManifestSchema.default({
387
441
  read: [],
388
442
  write: [],
@@ -417,13 +471,16 @@ function checkDocumentField(
417
471
  known: ReadonlySet<string>,
418
472
  contract: (path: string, message: string) => void,
419
473
  ): void {
420
- if (field.type === "image") {
474
+ if (field.type === "image" || field.type === "video") {
421
475
  for (const key of ["schema", "maxBytes", "paths"] as const) {
422
476
  if (field[key] !== undefined) {
423
- contract(`${path}.${key}`, `An image field has the platform's schema and no ${key}`);
477
+ contract(
478
+ `${path}.${key}`,
479
+ `An ${field.type} field has the platform's schema and no ${key}`,
480
+ );
424
481
  }
425
482
  }
426
- if (field.track) contract(`${path}.track`, "An image is not tracked on the timeline");
483
+ if (field.track) contract(`${path}.track`, `An ${field.type} is not tracked on the timeline`);
427
484
  return;
428
485
  }
429
486
  if (field.type === "richText") {
@@ -455,7 +512,8 @@ function checkDocumentField(
455
512
  contract(`${path}.schema`, "A document field declares its schema");
456
513
  return;
457
514
  }
458
- const problems = checkDocumentSchema(field.schema, known);
515
+ // A document's refs may also name the media library (stage 42, ADR 0475): a lesson's video.
516
+ const problems = checkDocumentSchema(field.schema, new Set([...known, "media"]));
459
517
  for (const [at, message] of problems) contract(`${path}.schema${at ? `.${at}` : ""}`, message);
460
518
  if (
461
519
  field.maxBytes !== undefined &&
@@ -605,6 +663,7 @@ export function toManifest(extension: Extension): ExtensionManifest {
605
663
  ]),
606
664
  ),
607
665
  ...(extension.grantable ? { grantable: [...extension.grantable] } : {}),
666
+ ...(extension.requires?.length ? { requires: [...extension.requires] } : {}),
608
667
  roles: Object.fromEntries(
609
668
  Object.entries(extension.roles ?? {}).map(([name, role]) => [
610
669
  name,
@@ -925,7 +984,11 @@ export function validateManifest(
925
984
  checkObjectBehaviour(m, name, object, contract);
926
985
  checkObjectCapacity(m, name, object, contract);
927
986
  checkObjectSellable(m, name, object, contract);
987
+ checkObjectAllowance(m, name, object, contract);
928
988
  checkObjectStates(m, name, object, contract);
989
+ checkObjectClaims(m, name, object, contract);
990
+ checkObjectUnique(m, name, object, contract);
991
+ checkObjectRecurring(m, name, object, contract);
929
992
  object.requireOneOf?.forEach((group, i) => {
930
993
  for (const field of group) {
931
994
  if (!object.fields[field]) {
@@ -1206,6 +1269,144 @@ export function validateManifest(
1206
1269
  }
1207
1270
  }
1208
1271
 
1272
+ // The extensions this one needs installed first (stage 42): never itself, each once.
1273
+ for (const [i, required] of (m.requires ?? []).entries()) {
1274
+ if (required === m.id) contract(`requires.${i}`, "An extension does not require itself");
1275
+ if ((m.requires ?? []).indexOf(required) !== i) {
1276
+ contract(`requires.${i}`, `"${required}" is listed twice`);
1277
+ }
1278
+ }
1279
+
1280
+ // A customer's write that needs access to what it points to (stage 42, ADR 0478): relations of
1281
+ // the object to one record of another of this extension's objects that declares `access`.
1282
+ for (const [name, object] of Object.entries(m.objects)) {
1283
+ for (const fieldName of object.customer?.requireAccess ?? []) {
1284
+ const path = `objects.${name}.customer.requireAccess`;
1285
+ const field = object.fields[fieldName];
1286
+ const local = field?.to?.startsWith(`${m.id}.`) ? field.to.slice(m.id.length + 1) : null;
1287
+ const target = local ? m.objects[local] : undefined;
1288
+ if (field?.type !== "relation" || field.many || !target) {
1289
+ contract(
1290
+ path,
1291
+ `"${fieldName}" must be a relation of ${name} to one of this extension's objects`,
1292
+ );
1293
+ } else if (!target.access) {
1294
+ contract(path, `"${fieldName}" points to ${local}, which declares no access`);
1295
+ } else if (!object.customer?.read.includes(fieldName)) {
1296
+ contract(path, `"${fieldName}" must be one the customer reads (customer.read)`);
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ // Who holds access to a record (ADR 0477): sources of this extension's own records. A kind the
1302
+ // host provides is checked by the host, which knows its kinds; the subscription kind's options
1303
+ // (stage 32a, ADR 0488) are checked here too, as they name this extension's own plan object.
1304
+ for (const [name, object] of Object.entries(m.objects)) {
1305
+ const a = object.access;
1306
+ if (!a) continue;
1307
+ a.sources.forEach((given, i) => {
1308
+ const path = `objects.${name}.access.sources.${i}`;
1309
+ if ("kind" in given && given.kind === "subscription") {
1310
+ const options = (given.options ?? {}) as Record<string, unknown>;
1311
+ for (const key of Object.keys(options)) {
1312
+ if (key !== "plans" && key !== "covers") {
1313
+ contract(`${path}.options.${key}`, `a subscription source has no option "${key}"`);
1314
+ }
1315
+ }
1316
+ if (options.covers !== "all") {
1317
+ contract(`${path}.options.covers`, 'covers must be "all": every live record');
1318
+ }
1319
+ const plans = typeof options.plans === "string" ? options.plans : "";
1320
+ const planLocal = plans.startsWith(`${m.id}.`) ? plans.slice(m.id.length + 1) : null;
1321
+ const plan = planLocal && planLocal !== name ? m.objects[planLocal] : undefined;
1322
+ if (!plan) {
1323
+ contract(
1324
+ `${path}.options.plans`,
1325
+ `plans must name another of this extension's objects, as ${m.id}.<object>`,
1326
+ );
1327
+ } else if (!plan.sellable?.recurring) {
1328
+ contract(
1329
+ `${path}.options.plans`,
1330
+ "plans must name a plan: its sellable declares recurring",
1331
+ );
1332
+ }
1333
+ return;
1334
+ }
1335
+ if (!("via" in given)) return;
1336
+ const source = given;
1337
+ const local = source.via.startsWith(`${m.id}.`) ? source.via.slice(m.id.length + 1) : null;
1338
+ const via = local ? m.objects[local] : undefined;
1339
+ if (!via || local === name) {
1340
+ contract(
1341
+ `${path}.via`,
1342
+ `via must name another of this extension's objects, as ${m.id}.<object>`,
1343
+ );
1344
+ return;
1345
+ }
1346
+ if (!via.customer) {
1347
+ contract(`${path}.via`, "via must name an object that declares a customer");
1348
+ return;
1349
+ }
1350
+ const pointer = via.fields[source.field];
1351
+ if (pointer?.type !== "relation" || pointer.many || !pointer.to) {
1352
+ contract(`${path}.field`, `field must name a relation of ${local} to one record`);
1353
+ return;
1354
+ }
1355
+ if (source.through === undefined) {
1356
+ if (pointer.to !== `${m.id}.${name}`) {
1357
+ contract(`${path}.field`, `field must be a relation of ${local} to one ${name}`);
1358
+ }
1359
+ } else {
1360
+ const targetLocal = pointer.to.startsWith(`${m.id}.`)
1361
+ ? pointer.to.slice(m.id.length + 1)
1362
+ : null;
1363
+ const target = targetLocal ? m.objects[targetLocal] : undefined;
1364
+ const list = target?.fields[source.through];
1365
+ const lists =
1366
+ (list?.type === "relation" && list.many && list.to === `${m.id}.${name}`) ||
1367
+ list?.type === "document";
1368
+ if (!target || !lists) {
1369
+ contract(
1370
+ `${path}.through`,
1371
+ `through must name a many relation to ${name}, or a document whose refs name it, on the object field points to`,
1372
+ );
1373
+ }
1374
+ }
1375
+ if (via.states) {
1376
+ const stateField = via.fields[via.states.field];
1377
+ const known = new Set((stateField?.options ?? []).map((o) => o.value));
1378
+ // What a refund moves a grant of `via` to: never a state that gives access.
1379
+ const voids = new Set(
1380
+ Object.values(m.objects).flatMap((o) => {
1381
+ const g = o.sellable?.grants;
1382
+ return g && (g.object === local || g.object === source.via) ? [g.void] : [];
1383
+ }),
1384
+ );
1385
+ if (!source.states?.length) {
1386
+ contract(`${path}.states`, `${local} has states: name the ones that give access`);
1387
+ } else {
1388
+ for (const st of source.states) {
1389
+ if (!known.has(st)) contract(`${path}.states`, `"${st}" is not a state of ${local}`);
1390
+ if (voids.has(st)) {
1391
+ contract(
1392
+ `${path}.states`,
1393
+ `"${st}" is where a refund moves ${local}: it gives no access`,
1394
+ );
1395
+ }
1396
+ }
1397
+ }
1398
+ } else if (source.states !== undefined) {
1399
+ contract(`${path}.states`, `${local} has no states`);
1400
+ }
1401
+ if (source.until !== undefined) {
1402
+ const until = via.fields[source.until];
1403
+ if (until?.type !== "date" && until?.type !== "datetime") {
1404
+ contract(`${path}.until`, `until must name a date or datetime field of ${local}`);
1405
+ }
1406
+ }
1407
+ });
1408
+ }
1409
+
1209
1410
  for (const [target, fields] of Object.entries(m.fields)) {
1210
1411
  const path = `fields.${target}`;
1211
1412
  if (!known.has(target)) {
package/src/media.ts CHANGED
@@ -44,3 +44,65 @@ export function mediaProblem(bytes: Uint8Array): string | null {
44
44
  }
45
45
  return null;
46
46
  }
47
+
48
+ // --- Files and videos (stage 42, ADR 0475) ------------------------------------------------------
49
+ //
50
+ // A `file` item is a download (a PDF only, at first), kept in R2 like a picture and served by the
51
+ // same rule. Its type is read from its bytes too. A `video` item is held in Cloudflare Stream on
52
+ // the deployment's own account: the file goes from the staff browser straight to Stream, so the
53
+ // host only checks the size a person says it is, and Stream refuses what is not a video.
54
+
55
+ /** The kinds of item the media library holds. */
56
+ export const MEDIA_KINDS = ["image", "video", "file"] as const;
57
+ export type MediaKind = (typeof MEDIA_KINDS)[number];
58
+
59
+ /** The types a `file` item may be. */
60
+ export const MEDIA_FILE_TYPES = ["application/pdf"] as const;
61
+ export type MediaFileType = (typeof MEDIA_FILE_TYPES)[number];
62
+
63
+ /** The `type` the library records for a video (its bytes are Stream's, never the host's). */
64
+ export const MEDIA_VIDEO_TYPE = "video/stream" as const;
65
+
66
+ /** The most a downloadable file may be, in bytes. */
67
+ export const MEDIA_FILE_MAX_BYTES = 50 * 1024 * 1024;
68
+
69
+ /** The most a video may be, in bytes: under Stream's 30 GB. */
70
+ export const MEDIA_VIDEO_MAX_BYTES = 30 * 1000 * 1000 * 1000 - 1;
71
+
72
+ /** The longest a video may be, in seconds (Stream refuses an upload longer than it was told). */
73
+ export const MEDIA_VIDEO_MAX_SECONDS = 6 * 60 * 60;
74
+
75
+ /** The most a caption file may be (Stream's limit): WebVTT only. */
76
+ export const MEDIA_CAPTION_MAX_BYTES = 10 * 1024 * 1024;
77
+
78
+ /** The type a downloadable file's bytes are, or null when the library does not take it. */
79
+ export function sniffFileType(bytes: Uint8Array): MediaFileType | null {
80
+ return ascii(bytes, 0, "%PDF-") ? "application/pdf" : null;
81
+ }
82
+
83
+ /** The kind and type an uploaded file is, from its bytes: a picture or a download. */
84
+ export function sniffUpload(
85
+ bytes: Uint8Array,
86
+ ): { kind: "image"; type: MediaType } | { kind: "file"; type: MediaFileType } | null {
87
+ const image = sniffMediaType(bytes);
88
+ if (image) return { kind: "image", type: image };
89
+ const file = sniffFileType(bytes);
90
+ return file ? { kind: "file", type: file } : null;
91
+ }
92
+
93
+ /** The most an upload of this kind may be. */
94
+ export function maxBytesOf(kind: "image" | "file"): number {
95
+ return kind === "file" ? MEDIA_FILE_MAX_BYTES : MEDIA_MAX_BYTES;
96
+ }
97
+
98
+ /** Whether `bytes` are a WebVTT file (its header, after an optional byte order mark). */
99
+ export function isWebVtt(bytes: Uint8Array): boolean {
100
+ const at = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0;
101
+ if (!ascii(bytes, at, "WEBVTT")) return false;
102
+ const next = bytes[at + 6];
103
+ // "WEBVTT" alone on its line, or followed by a space or a tab and a header.
104
+ return next === undefined || next === 0x0a || next === 0x0d || next === 0x20 || next === 0x09;
105
+ }
106
+
107
+ /** A caption's language: a BCP 47 tag as Stream takes it (`en`, `pt-BR`). */
108
+ export const CAPTION_LANGUAGE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
@@ -0,0 +1,314 @@
1
+ // The `recurring` behaviour (stage 31, ADR 0500): a record (a series: one line of a timetable)
2
+ // declares a weekly rule in local wall-clock time, and the host makes the dated records it
3
+ // generates (its classes) ahead of time. Its declaration, its manifest schema and its contract
4
+ // checks live here; the host's side is packages/core/src/recurring/.
5
+ import { z } from "zod";
6
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+
8
+ /** The weekday values a rule's `weekdays` field must use (ISO order, Monday first). */
9
+ export const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
10
+ export type Weekday = (typeof WEEKDAYS)[number];
11
+
12
+ /** How far ahead the host makes records when a series does not say (days). */
13
+ export const RECURRING_HORIZON_DAYS = 56;
14
+ /** The most days ahead a series may ask for. */
15
+ export const RECURRING_HORIZON_MAX = 366;
16
+
17
+ /**
18
+ * A weekly schedule that generates dated records (ADR 0500). The rule is kept in local
19
+ * wall-clock time in the series' zone: 06:00 is 06:00 on both sides of a clock change. A local
20
+ * time that does not exist on a change day (02:30 when clocks go forward) moves forward by the
21
+ * gap; one that happens twice is the first of the two.
22
+ *
23
+ * - `generates` is another of this extension's objects, and `link` its relation field (one
24
+ * record, read-only) back to this object: the host sets it.
25
+ * - `rule` names this object's fields: `weekdays` (a multiSelect whose option values are
26
+ * `mon`…`sun`), `time` (a text field, `HH:MM`), `length` (a number field, minutes), `from` and
27
+ * `until` (date fields; `until` empty for ongoing) and `zone` (a timezone field; empty is the
28
+ * organisation's zone).
29
+ * - `into` names the generated object's fields the host fills: `starts` (datetime), `ends`
30
+ * (datetime, starts plus the length), `zone` (timezone) and `changed` (a read-only boolean the
31
+ * host sets when someone other than the host edits the record).
32
+ * - `copy` maps generated fields to this object's fields copied onto each record (`{ coach:
33
+ * "coach" }`).
34
+ * - `cancel` is the generated object's state the host moves a record to when a closure covers it
35
+ * or the series ends while places are claimed on it. The generated object declares `states`
36
+ * with a `host` move into it.
37
+ * - `ended` (optional) is this object's select field and the values that mean the series has
38
+ * ended: nothing more is made, and its future records go.
39
+ * - `closures` (optional) is another of this extension's objects whose records are date ranges
40
+ * (`from`, `until`, both date fields, inclusive) in which nothing is made and records already
41
+ * made are cancelled.
42
+ * - `horizonDays` (default 56): how far ahead records are made.
43
+ * - `horizonAtLeast` (optional): another of this extension's objects and a number field of it in
44
+ * days (a class type's booking window): the horizon is never less than the largest value any
45
+ * live record of it holds, so a class can be booked as soon as its window opens.
46
+ *
47
+ * Made records are never made twice (the host keys each on the series and its local date). A
48
+ * record edited by staff (its time, copied fields or state) is never overwritten or made again;
49
+ * a change of the series applies to the future records nobody edited.
50
+ */
51
+ export interface RecurringScheduleSpec {
52
+ generates: string;
53
+ link: string;
54
+ rule: {
55
+ weekdays: string;
56
+ time: string;
57
+ length?: string;
58
+ from: string;
59
+ until?: string;
60
+ zone?: string;
61
+ };
62
+ into: { starts: string; ends?: string; zone?: string; changed?: string };
63
+ copy?: Readonly<Record<string, string>>;
64
+ cancel: string;
65
+ ended?: { field: string; in: readonly string[] };
66
+ closures?: { object: string; from: string; until: string };
67
+ horizonDays?: number;
68
+ horizonAtLeast?: { object: string; field: string };
69
+ }
70
+
71
+ const fieldName = z.string().max(40);
72
+
73
+ export const recurringManifestSchema = z
74
+ .object({
75
+ generates: fieldName,
76
+ link: fieldName,
77
+ rule: z
78
+ .object({
79
+ weekdays: fieldName,
80
+ time: fieldName,
81
+ length: fieldName.optional(),
82
+ from: fieldName,
83
+ until: fieldName.optional(),
84
+ zone: fieldName.optional(),
85
+ })
86
+ .strict(),
87
+ into: z
88
+ .object({
89
+ starts: fieldName,
90
+ ends: fieldName.optional(),
91
+ zone: fieldName.optional(),
92
+ changed: fieldName.optional(),
93
+ })
94
+ .strict(),
95
+ copy: z
96
+ .record(fieldName, fieldName)
97
+ .refine((copy) => Object.keys(copy).length <= 20, "At most 20 copied fields")
98
+ .optional(),
99
+ cancel: z.string().min(1).max(100),
100
+ ended: z
101
+ .object({ field: fieldName, in: z.array(z.string().min(1).max(100)).min(1).max(20) })
102
+ .strict()
103
+ .optional(),
104
+ closures: z
105
+ .object({ object: fieldName, from: fieldName, until: fieldName })
106
+ .strict()
107
+ .optional(),
108
+ horizonDays: z.number().int().min(1).max(RECURRING_HORIZON_MAX).optional(),
109
+ horizonAtLeast: z.object({ object: fieldName, field: fieldName }).strict().optional(),
110
+ })
111
+ .strict();
112
+ export type RecurringScheduleManifest = z.infer<typeof recurringManifestSchema>;
113
+
114
+ /** Reports problems with `objects.<name>.recurring` through `contract`. */
115
+ export function checkObjectRecurring(
116
+ m: ExtensionManifest,
117
+ name: string,
118
+ object: ObjectManifest,
119
+ contract: (path: string, message: string) => void,
120
+ ): void {
121
+ const recurring = object.recurring;
122
+ if (!recurring) return;
123
+ const path = `objects.${name}.recurring`;
124
+ const own = (o: ObjectManifest, local: string): FieldManifest | undefined =>
125
+ Object.hasOwn(o.fields, local) ? o.fields[local] : undefined;
126
+ const expect = (
127
+ o: ObjectManifest,
128
+ oName: string,
129
+ at: string,
130
+ local: string | undefined,
131
+ types: readonly string[],
132
+ what: string,
133
+ ): FieldManifest | undefined => {
134
+ if (local === undefined) return undefined;
135
+ const field = own(o, local);
136
+ if (!field || !types.includes(field.type) || field.many) {
137
+ contract(at, `"${local}" must be ${what} of ${oName}`);
138
+ return undefined;
139
+ }
140
+ return field;
141
+ };
142
+
143
+ const rule = recurring.rule;
144
+ const weekdays = expect(
145
+ object,
146
+ name,
147
+ `${path}.rule.weekdays`,
148
+ rule.weekdays,
149
+ ["multiSelect"],
150
+ "a multiSelect field",
151
+ );
152
+ if (weekdays) {
153
+ const values = (weekdays.options ?? []).map((o) => o.value);
154
+ const wrong = values.filter((v) => !(WEEKDAYS as readonly string[]).includes(v));
155
+ if (wrong.length || !values.length) {
156
+ contract(
157
+ `${path}.rule.weekdays`,
158
+ `"${rule.weekdays}"'s options must be weekdays (${WEEKDAYS.join(", ")})`,
159
+ );
160
+ }
161
+ if (weekdays.editableOptions) {
162
+ contract(`${path}.rule.weekdays`, "The weekdays field cannot have editableOptions");
163
+ }
164
+ }
165
+ expect(object, name, `${path}.rule.time`, rule.time, ["text"], "a text field (HH:MM)");
166
+ expect(object, name, `${path}.rule.length`, rule.length, ["number"], "a number field (minutes)");
167
+ expect(object, name, `${path}.rule.from`, rule.from, ["date"], "a date field");
168
+ expect(object, name, `${path}.rule.until`, rule.until, ["date"], "a date field");
169
+ expect(object, name, `${path}.rule.zone`, rule.zone, ["timezone"], "a timezone field");
170
+ if (recurring.ended) {
171
+ const field = expect(
172
+ object,
173
+ name,
174
+ `${path}.ended.field`,
175
+ recurring.ended.field,
176
+ ["select"],
177
+ "a select field",
178
+ );
179
+ const values = new Set((field?.options ?? []).map((o) => o.value));
180
+ for (const value of recurring.ended.in) {
181
+ if (field && !values.has(value)) {
182
+ contract(`${path}.ended.in`, `"${value}" is not an option of ${recurring.ended.field}`);
183
+ }
184
+ }
185
+ }
186
+
187
+ const generatedName = recurring.generates;
188
+ const generated = Object.hasOwn(m.objects, generatedName) ? m.objects[generatedName] : undefined;
189
+ if (!generated || generatedName === name) {
190
+ contract(`${path}.generates`, `"${generatedName}" must be another of this extension's objects`);
191
+ return;
192
+ }
193
+ const link = own(generated, recurring.link);
194
+ if (link?.type !== "relation" || link.many || link.to !== `${m.id}.${name}`) {
195
+ contract(
196
+ `${path}.link`,
197
+ `"${recurring.link}" must be a relation field of ${generatedName} to ${m.id}.${name}`,
198
+ );
199
+ } else if (!link.readOnly) {
200
+ contract(`${path}.link`, `"${recurring.link}" must be read-only: the host sets it`);
201
+ }
202
+ expect(
203
+ generated,
204
+ generatedName,
205
+ `${path}.into.starts`,
206
+ recurring.into.starts,
207
+ ["datetime"],
208
+ "a datetime field",
209
+ );
210
+ expect(
211
+ generated,
212
+ generatedName,
213
+ `${path}.into.ends`,
214
+ recurring.into.ends,
215
+ ["datetime"],
216
+ "a datetime field",
217
+ );
218
+ expect(
219
+ generated,
220
+ generatedName,
221
+ `${path}.into.zone`,
222
+ recurring.into.zone,
223
+ ["timezone"],
224
+ "a timezone field",
225
+ );
226
+ const changed = expect(
227
+ generated,
228
+ generatedName,
229
+ `${path}.into.changed`,
230
+ recurring.into.changed,
231
+ ["boolean"],
232
+ "a boolean field",
233
+ );
234
+ if (changed && !changed.readOnly) {
235
+ contract(
236
+ `${path}.into.changed`,
237
+ `"${recurring.into.changed}" must be read-only: the host sets it`,
238
+ );
239
+ }
240
+ const into = new Set<string>(Object.values(recurring.into));
241
+ // The state is the host's to move and staff's to change; a series never copies one in.
242
+ if (generated.states) into.add(generated.states.field);
243
+ for (const [target, source] of Object.entries(recurring.copy ?? {})) {
244
+ const to = own(generated, target);
245
+ const from = own(object, source);
246
+ if (!to || to.type === "formula" || into.has(target) || target === recurring.link) {
247
+ contract(
248
+ `${path}.copy.${target}`,
249
+ `"${target}" must be a field of ${generatedName} the host does not already fill`,
250
+ );
251
+ } else if (
252
+ !from ||
253
+ from.type !== to.type ||
254
+ Boolean(from.many) !== Boolean(to.many) ||
255
+ from.to !== to.to
256
+ ) {
257
+ contract(
258
+ `${path}.copy.${target}`,
259
+ `"${source}" must be a field of ${name} of the same type as ${generatedName}.${target}`,
260
+ );
261
+ }
262
+ }
263
+ const states = generated.states;
264
+ if (!states) {
265
+ contract(
266
+ `${path}.cancel`,
267
+ `${generatedName} must declare states, with a host move into "${recurring.cancel}"`,
268
+ );
269
+ } else {
270
+ const field = own(generated, states.field);
271
+ if (!(field?.options ?? []).some((o) => o.value === recurring.cancel)) {
272
+ contract(`${path}.cancel`, `"${recurring.cancel}" is not a state of ${generatedName}`);
273
+ } else if (
274
+ !states.moves.some((move) => move.to === recurring.cancel && move.by.includes("host"))
275
+ ) {
276
+ contract(
277
+ `${path}.cancel`,
278
+ `${generatedName} needs a move into "${recurring.cancel}" that the host may make`,
279
+ );
280
+ }
281
+ }
282
+ if (recurring.horizonAtLeast) {
283
+ const h = recurring.horizonAtLeast;
284
+ const target = Object.hasOwn(m.objects, h.object) ? m.objects[h.object] : undefined;
285
+ if (!target) {
286
+ contract(
287
+ `${path}.horizonAtLeast.object`,
288
+ `"${h.object}" must be one of this extension's objects`,
289
+ );
290
+ } else {
291
+ expect(
292
+ target,
293
+ h.object,
294
+ `${path}.horizonAtLeast.field`,
295
+ h.field,
296
+ ["number"],
297
+ "a number field (days)",
298
+ );
299
+ }
300
+ }
301
+ if (recurring.closures) {
302
+ const c = recurring.closures;
303
+ const closure = Object.hasOwn(m.objects, c.object) ? m.objects[c.object] : undefined;
304
+ if (!closure || c.object === name || c.object === generatedName) {
305
+ contract(
306
+ `${path}.closures.object`,
307
+ `"${c.object}" must be another of this extension's objects`,
308
+ );
309
+ } else {
310
+ expect(closure, c.object, `${path}.closures.from`, c.from, ["date"], "a date field");
311
+ expect(closure, c.object, `${path}.closures.until`, c.until, ["date"], "a date field");
312
+ }
313
+ }
314
+ }