@orthograph/compiler 0.0.0-stage → 0.1.0-next.1

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 (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +4 -2
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +9 -0
  5. package/dist/main.d.ts +2 -0
  6. package/dist/main.js +18 -0
  7. package/dist/modules/app/internal/checks.d.ts +30 -0
  8. package/dist/modules/app/internal/checks.js +99 -0
  9. package/dist/modules/app/internal/describe.d.ts +6 -0
  10. package/dist/modules/app/internal/describe.js +59 -0
  11. package/dist/modules/app/internal/hash.d.ts +1 -0
  12. package/dist/modules/app/internal/hash.js +7 -0
  13. package/dist/modules/app/internal/known.d.ts +19 -0
  14. package/dist/modules/app/internal/known.js +45 -0
  15. package/dist/modules/app/internal/read.d.ts +6 -0
  16. package/dist/modules/app/internal/read.js +45 -0
  17. package/dist/modules/app/service.d.ts +2 -0
  18. package/dist/modules/app/service.js +3 -0
  19. package/dist/modules/app/types.d.ts +87 -0
  20. package/dist/modules/app/types.js +1 -0
  21. package/dist/modules/compare/internal/assets.d.ts +4 -0
  22. package/dist/modules/compare/internal/assets.js +40 -0
  23. package/dist/modules/compare/internal/chain.d.ts +4 -0
  24. package/dist/modules/compare/internal/chain.js +37 -0
  25. package/dist/modules/compare/internal/diff.d.ts +3 -0
  26. package/dist/modules/compare/internal/diff.js +27 -0
  27. package/dist/modules/compare/internal/versions.d.ts +9 -0
  28. package/dist/modules/compare/internal/versions.js +75 -0
  29. package/dist/modules/compare/service.d.ts +2 -0
  30. package/dist/modules/compare/service.js +43 -0
  31. package/dist/modules/compare/types.d.ts +47 -0
  32. package/dist/modules/compare/types.js +1 -0
  33. package/dist/modules/lock/internal/evolve.d.ts +7 -0
  34. package/dist/modules/lock/internal/evolve.js +52 -0
  35. package/dist/modules/lock/internal/runtime.d.ts +3 -0
  36. package/dist/modules/lock/internal/runtime.js +12 -0
  37. package/dist/modules/lock/service.d.ts +4 -0
  38. package/dist/modules/lock/service.js +20 -0
  39. package/dist/modules/lock/types.d.ts +101 -0
  40. package/dist/modules/lock/types.js +6 -0
  41. package/dist/modules/model/internal/allowed.d.ts +26 -0
  42. package/dist/modules/model/internal/allowed.js +78 -0
  43. package/dist/modules/model/internal/approval.d.ts +4 -0
  44. package/dist/modules/model/internal/approval.js +10 -0
  45. package/dist/modules/model/internal/assets.d.ts +5 -0
  46. package/dist/modules/model/internal/assets.js +31 -0
  47. package/dist/modules/model/internal/bits.d.ts +6 -0
  48. package/dist/modules/model/internal/bits.js +9 -0
  49. package/dist/modules/model/internal/chain.d.ts +9 -0
  50. package/dist/modules/model/internal/chain.js +47 -0
  51. package/dist/modules/model/internal/codes.d.ts +59 -0
  52. package/dist/modules/model/internal/codes.js +80 -0
  53. package/dist/modules/model/internal/derive.d.ts +11 -0
  54. package/dist/modules/model/internal/derive.js +31 -0
  55. package/dist/modules/model/internal/describe.d.ts +8 -0
  56. package/dist/modules/model/internal/describe.js +248 -0
  57. package/dist/modules/model/internal/device.d.ts +5 -0
  58. package/dist/modules/model/internal/device.js +12 -0
  59. package/dist/modules/model/internal/environments.d.ts +7 -0
  60. package/dist/modules/model/internal/environments.js +90 -0
  61. package/dist/modules/model/internal/exits.d.ts +49 -0
  62. package/dist/modules/model/internal/exits.js +85 -0
  63. package/dist/modules/model/internal/fields.d.ts +23 -0
  64. package/dist/modules/model/internal/fields.js +50 -0
  65. package/dist/modules/model/internal/fillable.d.ts +3 -0
  66. package/dist/modules/model/internal/fillable.js +9 -0
  67. package/dist/modules/model/internal/forms.d.ts +47 -0
  68. package/dist/modules/model/internal/forms.js +75 -0
  69. package/dist/modules/model/internal/found.d.ts +40 -0
  70. package/dist/modules/model/internal/found.js +60 -0
  71. package/dist/modules/model/internal/handler-files.d.ts +18 -0
  72. package/dist/modules/model/internal/handler-files.js +23 -0
  73. package/dist/modules/model/internal/hash.d.ts +4 -0
  74. package/dist/modules/model/internal/hash.js +7 -0
  75. package/dist/modules/model/internal/holds.d.ts +19 -0
  76. package/dist/modules/model/internal/holds.js +65 -0
  77. package/dist/modules/model/internal/invariants.d.ts +38 -0
  78. package/dist/modules/model/internal/invariants.js +134 -0
  79. package/dist/modules/model/internal/journeys.d.ts +15 -0
  80. package/dist/modules/model/internal/journeys.js +135 -0
  81. package/dist/modules/model/internal/layout.d.ts +143 -0
  82. package/dist/modules/model/internal/layout.js +203 -0
  83. package/dist/modules/model/internal/lock-fields.d.ts +3 -0
  84. package/dist/modules/model/internal/lock-fields.js +17 -0
  85. package/dist/modules/model/internal/money.d.ts +17 -0
  86. package/dist/modules/model/internal/money.js +49 -0
  87. package/dist/modules/model/internal/nullable.d.ts +7 -0
  88. package/dist/modules/model/internal/nullable.js +21 -0
  89. package/dist/modules/model/internal/operations.d.ts +27 -0
  90. package/dist/modules/model/internal/operations.js +81 -0
  91. package/dist/modules/model/internal/reads.d.ts +16 -0
  92. package/dist/modules/model/internal/reads.js +58 -0
  93. package/dist/modules/model/internal/rules.d.ts +2 -0
  94. package/dist/modules/model/internal/rules.js +33 -0
  95. package/dist/modules/model/internal/same-value.d.ts +10 -0
  96. package/dist/modules/model/internal/same-value.js +50 -0
  97. package/dist/modules/model/internal/secrets.d.ts +4 -0
  98. package/dist/modules/model/internal/secrets.js +35 -0
  99. package/dist/modules/model/internal/source-refusals.d.ts +7 -0
  100. package/dist/modules/model/internal/source-refusals.js +52 -0
  101. package/dist/modules/model/internal/sources.d.ts +12 -0
  102. package/dist/modules/model/internal/sources.js +65 -0
  103. package/dist/modules/model/internal/stores.d.ts +20 -0
  104. package/dist/modules/model/internal/stores.js +44 -0
  105. package/dist/modules/model/internal/things.d.ts +33 -0
  106. package/dist/modules/model/internal/things.js +99 -0
  107. package/dist/modules/model/service.d.ts +4 -0
  108. package/dist/modules/model/service.js +105 -0
  109. package/dist/modules/model/types.d.ts +485 -0
  110. package/dist/modules/model/types.js +5 -0
  111. package/dist/modules/mounts/fixtures/both/things/echo/thing.d.ts +1 -0
  112. package/dist/modules/mounts/fixtures/both/things/echo/thing.js +1 -0
  113. package/dist/modules/mounts/fixtures/both/things/echo/verbs/only.d.ts +1 -0
  114. package/dist/modules/mounts/fixtures/both/things/echo/verbs/only.js +1 -0
  115. package/dist/modules/mounts/internal/attribute.d.ts +2 -0
  116. package/dist/modules/mounts/internal/attribute.js +4 -0
  117. package/dist/modules/mounts/internal/calls.d.ts +12 -0
  118. package/dist/modules/mounts/internal/calls.js +42 -0
  119. package/dist/modules/mounts/internal/choices.d.ts +11 -0
  120. package/dist/modules/mounts/internal/choices.js +34 -0
  121. package/dist/modules/mounts/internal/fold.d.ts +6 -0
  122. package/dist/modules/mounts/internal/fold.js +8 -0
  123. package/dist/modules/mounts/internal/needs.d.ts +14 -0
  124. package/dist/modules/mounts/internal/needs.js +26 -0
  125. package/dist/modules/mounts/internal/verbs.d.ts +11 -0
  126. package/dist/modules/mounts/internal/verbs.js +44 -0
  127. package/dist/modules/mounts/service.d.ts +2 -0
  128. package/dist/modules/mounts/service.js +165 -0
  129. package/dist/modules/mounts/types.d.ts +78 -0
  130. package/dist/modules/mounts/types.js +1 -0
  131. package/dist/modules/source/internal/plugins.d.ts +25 -0
  132. package/dist/modules/source/internal/plugins.js +49 -0
  133. package/dist/modules/source/service.d.ts +6 -0
  134. package/dist/modules/source/service.js +86 -0
  135. package/dist/modules/source/types.d.ts +55 -0
  136. package/dist/modules/source/types.js +6 -0
  137. package/dist/modules/time/internal/anchor.d.ts +2 -0
  138. package/dist/modules/time/internal/anchor.js +48 -0
  139. package/dist/modules/time/internal/keeper.d.ts +13 -0
  140. package/dist/modules/time/internal/keeper.js +19 -0
  141. package/dist/modules/time/internal/zones.d.ts +1 -0
  142. package/dist/modules/time/internal/zones.js +3 -0
  143. package/dist/modules/time/service.d.ts +2 -0
  144. package/dist/modules/time/service.js +56 -0
  145. package/dist/modules/time/types.d.ts +89 -0
  146. package/dist/modules/time/types.js +1 -0
  147. package/package.json +30 -3
@@ -0,0 +1,47 @@
1
+ import type { Event, Thing } from "orthograph";
2
+ import type { MountModel, ThingModel } from "../types.ts";
3
+ import type { Layout } from "./layout.ts";
4
+ export interface FormContext {
5
+ readonly layout: Layout;
6
+ readonly thingNames: ReadonlyMap<Thing, string>;
7
+ readonly problems: Array<string>;
8
+ }
9
+ /** `agents.<name>`: its file, and its slots as `{ size, reserve, held }` when it holds a seat. */
10
+ export declare const agentsModel: (ctx: FormContext) => {
11
+ [k: string]: {
12
+ file: string;
13
+ slots?: {
14
+ size: string;
15
+ reserve: number;
16
+ held: string;
17
+ };
18
+ };
19
+ };
20
+ /** `declared.<things>`: every `Blueprint.declare` file of the app, by its thing's plural. */
21
+ export declare const declaredModel: (ctx: FormContext) => Record<string, unknown[]>;
22
+ /** `problems`: each `Blueprint.problem`, the fields it names by name, and when it shows. */
23
+ export declare const problemsModel: (ctx: FormContext) => {
24
+ kind: string;
25
+ thing: string;
26
+ of: string;
27
+ name: string;
28
+ failures: string;
29
+ after: string | number;
30
+ }[];
31
+ export interface FormsContext extends FormContext {
32
+ readonly mounts: Readonly<Record<string, MountModel>>;
33
+ readonly things: Readonly<Record<string, ThingModel>>;
34
+ readonly eventNames: ReadonlyMap<Event, string>;
35
+ readonly opName: (declaration: unknown) => string | undefined;
36
+ }
37
+ /** What the new forms add to the model, each key only when the blueprint uses it: agents, sources, holds, problems and declared. */
38
+ export declare const formsOf: (c: FormsContext) => {
39
+ problems?: {
40
+ kind: string;
41
+ thing: string;
42
+ of: string;
43
+ name: string;
44
+ failures: string;
45
+ after: string | number;
46
+ }[];
47
+ };
@@ -0,0 +1,75 @@
1
+ import { holdsModel } from "./holds.js";
2
+ import { refuseConnection } from "./source-refusals.js";
3
+ import { kindsOf, sourceNameOf, sourcesModel } from "./sources.js";
4
+ const fieldName = (ctx, f) => `${ctx.thingNames.get(f.of) ?? "?"}.${f.key}`;
5
+ /** The thing whose rows hold the seats: named by the thing, or by the id prefix it owns. */
6
+ const heldName = (ctx, file, held) => {
7
+ if (held.kind === "thing")
8
+ return ctx.thingNames.get(held) ?? "?";
9
+ if (held.meta.type !== "id") {
10
+ ctx.problems.push(`${file}: slots.held must be a thing, or the id of one (Blueprint.id("asg")), and it is a ${held.meta.type}`);
11
+ return "?";
12
+ }
13
+ const prefix = held.meta.prefix;
14
+ // Every thing that owns the prefix: a plugin mounted twice, under two names, brings two, and the pool must not bind to either by luck.
15
+ const owners = [...ctx.thingNames].filter(([t]) => t.fields["id"]?.value.meta?.prefix === prefix).map(([, name]) => name).sort();
16
+ if (owners.length !== 1) {
17
+ ctx.problems.push(owners.length === 0
18
+ ? `${file}: slots.held names the id prefix "${prefix}", which no thing owns`
19
+ : `${file}: slots.held names the id prefix "${prefix}", which ${owners.length} things own (${owners.join(", ")}): name the thing itself, so the seats are held by the one you mean`);
20
+ return "?";
21
+ }
22
+ return owners[0];
23
+ };
24
+ /** `agents.<name>`: its file, and its slots as `{ size, reserve, held }` when it holds a seat. */
25
+ export const agentsModel = (ctx) => Object.fromEntries([...ctx.layout.agents].sort(([a], [b]) => a.localeCompare(b)).map(([name, { file, declaration: a }]) => {
26
+ const slots = a.slots;
27
+ if (slots !== undefined && !(slots.size.key in slots.size.of.fields))
28
+ ctx.problems.push(`${file}: slots.size is not a field of its thing`);
29
+ if (slots !== undefined && (!Number.isInteger(slots.reserve) || slots.reserve < 0))
30
+ ctx.problems.push(`${file}: slots.reserve must be a whole number, 0 or more`);
31
+ return [name, {
32
+ file,
33
+ ...(slots === undefined ? {} : { slots: { size: fieldName(ctx, slots.size), reserve: slots.reserve, held: heldName(ctx, file, slots.held) } }),
34
+ }];
35
+ }));
36
+ /** What a declared value is in the model: plain data, a connection by the name of its source. */
37
+ const plain = (ctx, file, x) => {
38
+ if (Array.isArray(x))
39
+ return x.map((i) => plain(ctx, file, i));
40
+ if (typeof x === "object" && x !== null) {
41
+ const o = x;
42
+ if (o.kind === "connection") {
43
+ const source = sourceNameOf(ctx.layout, o.source);
44
+ if (source === undefined)
45
+ ctx.problems.push(`${file}: lists a connection of a source that is not a file of a plugin's blueprint/sources/`);
46
+ refuseConnection(ctx.problems, file, ctx.layout, o.source, o.config, kindsOf);
47
+ return { source: source ?? "?", config: plain(ctx, file, o.config) };
48
+ }
49
+ return Object.fromEntries(Object.entries(x).filter(([, v]) => typeof v !== "function").map(([k, v]) => [k, plain(ctx, file, v)]));
50
+ }
51
+ return typeof x === "bigint" ? x.toString() : x;
52
+ };
53
+ /** `declared.<things>`: every `Blueprint.declare` file of the app, by its thing's plural. */
54
+ export const declaredModel = (ctx) => {
55
+ const out = {};
56
+ for (const [, { file, declaration }] of [...ctx.layout.declared].sort(([a], [b]) => a.localeCompare(b))) {
57
+ const key = `${ctx.thingNames.get(declaration.thing) ?? "?"}s`;
58
+ (out[key] ??= []).push({ file, ...plain(ctx, file, declaration.values) });
59
+ }
60
+ return out;
61
+ };
62
+ /** `problems`: each `Blueprint.problem`, the fields it names by name, and when it shows. */
63
+ export const problemsModel = (ctx) => [...ctx.layout.things].flatMap(([thing, t]) => (t.problem === undefined ? [] : [(() => {
64
+ const p = t.problem.declaration;
65
+ return { kind: p.of, thing, of: p.points.key, name: p.name.key, failures: p.failures.key, after: typeof p.after === "number" ? p.after : p.after.key };
66
+ })()])).sort((a, b) => a.kind.localeCompare(b.kind));
67
+ /** What the new forms add to the model, each key only when the blueprint uses it: agents, sources, holds, problems and declared. */
68
+ export const formsOf = (c) => {
69
+ const some = (key, value) => (Object.keys(value).length > 0 ? { [key]: value } : {});
70
+ const problems = problemsModel(c);
71
+ return {
72
+ ...some("agents", agentsModel(c)), ...some("sources", sourcesModel(c)), ...some("holds", holdsModel(c)),
73
+ ...(problems.length > 0 ? { problems } : {}), ...some("declared", declaredModel(c)),
74
+ };
75
+ };
@@ -0,0 +1,40 @@
1
+ import type { Operation, Thing } from "orthograph";
2
+ /** A generated not-found refusal: after the machine's (900) in a thing's codes. */
3
+ export declare const NOT_FOUND_NUMBER = 901;
4
+ /** Its exit: the CLI's "not found", beside `NotAllowed`'s 3. */
5
+ export declare const NOT_FOUND_EXIT = 4;
6
+ /** The thing whose id a field holds: followed back to the `id` it was taken from, as the runtime's role check does. */
7
+ export declare const referenced: (field: unknown) => Thing | undefined;
8
+ export interface Found {
9
+ /** Each payload field holding a thing's id, and that thing. */
10
+ readonly refs: ReadonlyMap<string, Thing>;
11
+ /** The fields whose missing instance is refused `<Thing>NotFound`: no role check reads them on every way in. */
12
+ readonly notFound: ReadonlyMap<string, Thing>;
13
+ }
14
+ export declare const foundOf: (op: Operation) => Found;
15
+ /** A thing's not-found refusal: the one it declares under that name, else generated at `<XX>-901` (`generated` is that code, from the lock), exit 4. */
16
+ export declare const notFoundOf: (identifier: string, generated: string, errors: Readonly<Record<string, {
17
+ readonly exit: number;
18
+ readonly code: string;
19
+ }>>) => {
20
+ readonly error: string;
21
+ readonly exit: number;
22
+ readonly code: string;
23
+ };
24
+ /** An operation's part of the model: `refs` and `notFound` by payload field, each present only when it has any. */
25
+ export declare const foundModel: (op: Operation, nameOf: (t: Thing) => string | undefined, errorOf: (thing: string) => string | undefined) => {
26
+ refs?: {
27
+ [k: string]: string;
28
+ };
29
+ notFound?: {
30
+ [k: string]: string;
31
+ };
32
+ };
33
+ /** An operation the runtime can serve: none of the parts the read needs is still `Blueprint.todo`. */
34
+ export declare const missedBy: (d: Operation | {
35
+ readonly kind: "read";
36
+ }, blank: (x: unknown) => boolean) => ReadonlyArray<Thing>;
37
+ /** A creating move's field that carries the new id: the answer's, else the payload's, holding the thing's own `id`. */
38
+ export declare const mintsOf: (creating: boolean, own: string, ...fields: ReadonlyArray<Readonly<Record<string, {
39
+ readonly ref?: string;
40
+ }>>>) => string | undefined;
@@ -0,0 +1,60 @@
1
+ /** A generated not-found refusal: after the machine's (900) in a thing's codes. */
2
+ export const NOT_FOUND_NUMBER = 901;
3
+ /** Its exit: the CLI's "not found", beside `NotAllowed`'s 3. */
4
+ export const NOT_FOUND_EXIT = 4;
5
+ const isField = (x) => typeof x === "object" && x !== null && x.kind === "field";
6
+ /** The thing whose id a field holds: followed back to the `id` it was taken from, as the runtime's role check does. */
7
+ export const referenced = (field) => {
8
+ let f = isField(field) ? field : undefined;
9
+ while (f) {
10
+ if (f.key === "id")
11
+ return f.of;
12
+ f = f.from;
13
+ }
14
+ return undefined;
15
+ };
16
+ /** The payload field naming an instance of `thing`. */
17
+ const keyOf = (payload, thing) => Object.keys(payload).find((k) => referenced(payload[k]) === thing);
18
+ /** The payload field a role check starts its walk from, and so reads: undefined for `anyone` and `signedIn`. */
19
+ const readBy = (entry, payload, own) => {
20
+ const a = entry.kind === "narrowed" ? entry.entry : entry;
21
+ if (a.kind === "anyone" || a.kind === "signed-in" || a.kind === "system" || a.kind === "keeper")
22
+ return undefined;
23
+ // A service role reads nothing: the mount the call came in by decides.
24
+ if ((a.kind === "role-of" ? a.role : a).service !== undefined)
25
+ return undefined;
26
+ if (a.kind === "role-of") {
27
+ const first = a.path.split(".")[0] ?? "";
28
+ return first in payload ? first : keyOf(payload, own);
29
+ }
30
+ return keyOf(payload, own) ?? keyOf(payload, a.thing);
31
+ };
32
+ export const foundOf = (op) => {
33
+ const refs = new Map();
34
+ for (const [key, field] of Object.entries(op.payload)) {
35
+ const thing = referenced(field);
36
+ if (thing)
37
+ refs.set(key, thing);
38
+ }
39
+ const creating = op.move !== undefined && op.move.from.length === 0;
40
+ const notFound = new Map([...refs].filter(([key, thing]) => !(creating && thing === op.thing) && !op.allowed.every((a) => readBy(a, op.payload, op.thing) === key)));
41
+ return { refs, notFound };
42
+ };
43
+ /** A thing's not-found refusal: the one it declares under that name, else generated at `<XX>-901` (`generated` is that code, from the lock), exit 4. */
44
+ export const notFoundOf = (identifier, generated, errors) => {
45
+ const error = `${identifier}NotFound`;
46
+ const declared = errors[error];
47
+ return declared ? { error, exit: declared.exit, code: declared.code } : { error, exit: NOT_FOUND_EXIT, code: generated };
48
+ };
49
+ /** An operation's part of the model: `refs` and `notFound` by payload field, each present only when it has any. */
50
+ export const foundModel = (op, nameOf, errorOf) => {
51
+ const found = foundOf(op);
52
+ const refs = Object.fromEntries([...found.refs].map(([k, t]) => [k, nameOf(t) ?? "?"]));
53
+ const notFound = Object.fromEntries([...found.notFound].map(([k, t]) => [k, errorOf(nameOf(t) ?? "") ?? "?"]));
54
+ return { ...(Object.keys(refs).length > 0 ? { refs } : {}), ...(Object.keys(notFound).length > 0 ? { notFound } : {}) };
55
+ };
56
+ /** An operation the runtime can serve: none of the parts the read needs is still `Blueprint.todo`. */
57
+ export const missedBy = (d, blank) => d.kind !== "operation" || [d.payload, d.allowed, d.move].some(blank) || Object.values(d.payload).some(blank) || d.allowed.some(blank)
58
+ ? [] : [...foundOf(d).notFound.values()];
59
+ /** A creating move's field that carries the new id: the answer's, else the payload's, holding the thing's own `id`. */
60
+ export const mintsOf = (creating, own, ...fields) => creating ? fields.flatMap((f) => Object.keys(f).filter((k) => f[k].ref === `${own}.id`))[0] : undefined;
@@ -0,0 +1,18 @@
1
+ import type { OperationModel } from "../types.ts";
2
+ /** The hosts a client operation needs an entry for. `worker` is never one: nothing of it runs on the server. */
3
+ export declare const DEVICE_HOSTS: readonly ["node", "browser", "world"];
4
+ export interface HandlerFile {
5
+ readonly host: "worker" | (typeof DEVICE_HOSTS)[number];
6
+ /** The module's path inside its package (`src/<thing>/<verb>[.<host>].js`), for a plugin's; the project's path for the app's. */
7
+ readonly module: string;
8
+ /** What a reader opens: relative to the project root for the app's own, `<package>/<module>` for a plugin's. */
9
+ readonly file: string;
10
+ }
11
+ /**
12
+ * Is this operation one of the four the framework serves for a thing with `versions:`: its verb is one of them, and the thing's key
13
+ * is a field of its payload? It has no handler file: the generated server serves it from the thing's declaration.
14
+ */
15
+ export declare const isVersioned: (op: Pick<OperationModel, "kind" | "verb" | "payload">, versions: {
16
+ readonly key: string;
17
+ } | undefined) => boolean;
18
+ export declare const handlerFiles: (op: Pick<OperationModel, "kind" | "thing" | "verb" | "runs" | "from">) => ReadonlyArray<HandlerFile>;
@@ -0,0 +1,23 @@
1
+ /** The hosts a client operation needs an entry for. `worker` is never one: nothing of it runs on the server. */
2
+ export const DEVICE_HOSTS = ["node", "browser", "world"];
3
+ /** The verbs of the four operations a thing with versions has (K40 fix 2). */
4
+ const VERSION_VERBS = ["save", "get", "history", "restore"];
5
+ /**
6
+ * Is this operation one of the four the framework serves for a thing with `versions:`: its verb is one of them, and the thing's key
7
+ * is a field of its payload? It has no handler file: the generated server serves it from the thing's declaration.
8
+ */
9
+ export const isVersioned = (op, versions) => op.kind === "operation" && versions !== undefined && VERSION_VERBS.includes(op.verb) && versions.key in op.payload;
10
+ export const handlerFiles = (op) => {
11
+ if (op.kind !== "operation")
12
+ return [];
13
+ if (op.from.kind === "app") {
14
+ const module = `src/${op.thing}/${op.verb}.ts`;
15
+ return [{ host: "worker", module, file: module }];
16
+ }
17
+ const { thing, package: pkg } = op.from;
18
+ const one = (host, suffix) => {
19
+ const module = `src/${thing}/${op.verb}${suffix}.js`;
20
+ return { host, module, file: `${pkg}/${module}` };
21
+ };
22
+ return op.runs === "client" ? DEVICE_HOSTS.map((host) => one(host, `.${host}`)) : [one("worker", "")];
23
+ };
@@ -0,0 +1,4 @@
1
+ /** JSON with keys sorted at every level, so the same declaration always gives the same text. */
2
+ export declare const canonical: (x: unknown) => string;
3
+ /** A declaration's hash: from what it means, never from how its file is formatted. */
4
+ export declare const hashOf: (entry: unknown) => string;
@@ -0,0 +1,7 @@
1
+ import { createHash } from "node:crypto";
2
+ /** JSON with keys sorted at every level, so the same declaration always gives the same text. */
3
+ export const canonical = (x) => JSON.stringify(x, (_, v) => v && typeof v === "object" && !Array.isArray(v)
4
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
5
+ : v);
6
+ /** A declaration's hash: from what it means, never from how its file is formatted. */
7
+ export const hashOf = (entry) => createHash("sha256").update(canonical(entry)).digest("hex").slice(0, 16);
@@ -0,0 +1,19 @@
1
+ import type { Event, Operation, Read, Thing } from "orthograph";
2
+ import type { ThingModel } from "../types.ts";
3
+ import type { Layout } from "./layout.ts";
4
+ /** One delivery the blueprint declares: an event, and the operation an outbox hop calls for it. */
5
+ export interface Delivery {
6
+ readonly event: Event;
7
+ readonly to: Operation | Read;
8
+ }
9
+ /** Every `on:` of an operation, and every `on` verb of a feature mount. */
10
+ export declare const deliveriesOf: (layout: Layout) => ReadonlyArray<Delivery>;
11
+ export interface HoldContext {
12
+ readonly layout: Layout;
13
+ readonly things: Readonly<Record<string, ThingModel>>;
14
+ readonly thingNames: ReadonlyMap<Thing, string>;
15
+ readonly eventNames: ReadonlyMap<Event, string>;
16
+ readonly opName: (declaration: unknown) => string | undefined;
17
+ readonly problems: Array<string>;
18
+ }
19
+ export declare const holdsModel: (ctx: HoldContext) => Record<string, unknown>;
@@ -0,0 +1,65 @@
1
+ /** Every `on:` of an operation, and every `on` verb of a feature mount. */
2
+ export const deliveriesOf = (layout) => [
3
+ ...[...layout.things.values()].flatMap((t) => [...t.verbs.values()].flatMap(({ declaration: d }) => (d.kind === "operation" ? d.on.map((h) => ({ event: h.event, to: d })) : []))),
4
+ ...[...layout.mounts.values()].flatMap((m) => m.mount.verbs.flatMap((v) => (v.verb === "on" ? [{ event: v.hop.event, to: v.operation }] : []))),
5
+ ];
6
+ const idPrefix = (input) => {
7
+ const meta = (input.kind === "field" ? input.value : input).meta;
8
+ return meta.type === "id" ? meta.prefix : undefined;
9
+ };
10
+ /** Whether an event has a field holding the id the hold keys on: `superagent`, whichever thing declares the event. */
11
+ const carries = (event, prefix) => prefix !== undefined && Object.values(event.fields).some((f) => idPrefix(f) === prefix);
12
+ const where = (ctx, thing) => ctx.things[thing];
13
+ const placeOf = (t) => (t === undefined ? "?" : t.store ? `store ${t.store}` : t.lives === "actor" ? "the actor store" : "the default store");
14
+ export const holdsModel = (ctx) => {
15
+ const out = {};
16
+ const declaredIn = new Map();
17
+ const deliveries = deliveriesOf(ctx.layout);
18
+ const eventOwner = new Map([...ctx.layout.things].flatMap(([n, t]) => [...t.events.values()].map((e) => [e, n])));
19
+ for (const [thingName, t] of ctx.layout.things) {
20
+ for (const [name, { declaration: hold }] of t.holds) {
21
+ const prefix = idPrefix(hold.key);
22
+ const lists = ctx.layout.holdLists.filter((l) => l.declaration.hold === hold);
23
+ const file = lists[0]?.file ?? `${t.base}/holds.ts`;
24
+ const named = (event, to) => ({ event: ctx.eventNames.get(event) ?? "?", to: ctx.opName(to) ?? "?" });
25
+ const held = lists.flatMap((l) => l.declaration.held.map((d) => named(d.event, d.to)));
26
+ const unheld = lists.flatMap((l) => l.declaration.unheld.map((d) => ({ ...named(d.event, d.to), reason: d.reason })));
27
+ const ownMoves = new Set(Object.values(t.machine?.moves ?? {}).map((m) => m.emits));
28
+ const row = (r) => `${r.event} to ${r.to}`;
29
+ const listed = (r, rows) => rows.some((x) => x.event === r.event && x.to === r.to);
30
+ for (const d of deliveries.filter((x) => carries(x.event, prefix))) {
31
+ const r = named(d.event, d.to);
32
+ if (!listed(r, held) && !listed(r, unheld))
33
+ ctx.problems.push(`${file}: ${row(r)} is in neither the held nor the unheld list of ${name}: say whether the switch holds it, so new work cannot slip past a pause`);
34
+ }
35
+ const both = new Set(held.map((r) => r.event).filter((e) => unheld.some((u) => u.event === e)));
36
+ for (const e of both)
37
+ ctx.problems.push(`${file}: ${e} has deliveries on both the held and the unheld list of ${name}: the unheld work needs an event of its own`);
38
+ for (const l of lists)
39
+ for (const d of l.declaration.held)
40
+ if (ownMoves.has(d.event)) {
41
+ ctx.problems.push(`${l.file}: ${ctx.eventNames.get(d.event) ?? "?"} is held by ${name}, and it is the ${thingName}'s own move: holding it would deadlock the resume`);
42
+ }
43
+ for (const l of lists)
44
+ for (const d of [...l.declaration.held, ...l.declaration.unheld]) {
45
+ const owner = eventOwner.get(d.event);
46
+ if (owner !== undefined && carries(d.event, prefix) && placeOf(where(ctx, owner)) !== placeOf(where(ctx, thingName))) {
47
+ ctx.problems.push(`${l.file}: the hold ${name} is on ${thingName}, which lives in ${placeOf(where(ctx, thingName))}, and ${ctx.eventNames.get(d.event) ?? "?"} is made in ${owner}, in ${placeOf(where(ctx, owner))}: a hold and the events it holds are in one store`);
48
+ break;
49
+ }
50
+ }
51
+ // A hold is named by its export, for the whole project: two things may not export one name.
52
+ const first = declaredIn.get(name);
53
+ if (first !== undefined) {
54
+ ctx.problems.push(`${t.holds.get(name).file}: the hold ${name} is already declared in ${first}: a hold is named for the whole project, so give one another name`);
55
+ continue;
56
+ }
57
+ declaredIn.set(name, t.holds.get(name).file);
58
+ out[name] = {
59
+ thing: thingName, key: hold.key.key, while: hold.while.map((s) => s.key),
60
+ held: held.sort((a, b) => row(a).localeCompare(row(b))), unheld: unheld.sort((a, b) => row(a).localeCompare(row(b))),
61
+ };
62
+ }
63
+ }
64
+ return out;
65
+ };
@@ -0,0 +1,38 @@
1
+ import type { AnyErrorClass, Thing } from "orthograph";
2
+ import type { StepModel, ThingModel } from "../types.ts";
3
+ import { type ThingFiles } from "./layout.ts";
4
+ /** What `invariantsOf` needs to know about the rest of the blueprint. */
5
+ export interface RuleContext {
6
+ readonly thingNames: ReadonlyMap<Thing, string>;
7
+ readonly errorNames: ReadonlyMap<AnyErrorClass, string>;
8
+ /** Every verb of every thing, with the errors it declares: a rule's refusal may not be among them. */
9
+ readonly verbs: ReadonlyArray<{
10
+ readonly file: string;
11
+ readonly errors: ReadonlyArray<AnyErrorClass>;
12
+ }>;
13
+ }
14
+ /**
15
+ * The model's `invariants` for one thing, or undefined when it has none. Refused, naming the file: a key that isn't the thing's own
16
+ * field, a `while` that isn't one of its machine's states, a thing that lives as actors, a refusal that isn't the thing's own error,
17
+ * is owned by another rule, is in a verb's `errors:`, or carries a field outside the key.
18
+ */
19
+ export declare const invariantsOf: (t: ThingFiles, ctx: RuleContext, problems: Array<string>) => ThingModel["invariants"];
20
+ /** What an operation is, as far as a rule can tell. */
21
+ export interface Acting {
22
+ readonly thing: string;
23
+ readonly move: {
24
+ readonly to: ReadonlyArray<string>;
25
+ } | null;
26
+ readonly steps: Readonly<Record<string, StepModel>>;
27
+ }
28
+ /**
29
+ * The rules an operation can break (G5, section 3): its move on the rule's thing can end in a `while` state (any move, for a rule with
30
+ * no `while`); one of its database steps names the thing in `writes`; or the thing has no machine, and the operation is on it and has a
31
+ * database step that leaves `writes` unset (unknown; `writes: []` is reads only, S31). `refusals` maps each broken rule's refusal to the rule's full name; `breaks` is every rule broken, refusal or not.
32
+ */
33
+ export declare const breakersOf: (op: Acting, things: Readonly<Record<string, ThingModel>>) => {
34
+ readonly refusals: Readonly<Record<string, string>>;
35
+ readonly breaks: ReadonlyArray<string>;
36
+ };
37
+ /** A verb's declared errors, empty while they are a blank. */
38
+ export declare const declaredErrors: (errors: unknown) => ReadonlyArray<AnyErrorClass>;
@@ -0,0 +1,134 @@
1
+ import { Blanks, VERSION_RULE, versionRule } from "orthograph/server";
2
+ import { pascal } from "./layout.js";
3
+ import { describeValue, sameValue, valueOfInput } from "./same-value.js";
4
+ /** The key's field names, or undefined once a problem is found in the key (a missing field, another thing's, an empty tuple). */
5
+ const keyOf = (rule, t, at, ctx, problems) => {
6
+ const fields = rule.fields;
7
+ if (fields.length === 0)
8
+ return void problems.push(`${at} needs a key: at least one field of ${t.name}`);
9
+ const names = fields.map((f) => {
10
+ if (f === undefined || f.kind !== "field")
11
+ return void problems.push(`${at}: its key is not a field of ${t.name}; write it as ${pascal(t.name)}.fields.<name>`);
12
+ if (f.of !== t.thing)
13
+ return void problems.push(`${at}: its key ${ctx.thingNames.get(f.of) ?? "?"}.${f.key} is a field of another thing, not of ${t.name}; a rule's key is a field of the thing whose invariants.ts it is in`);
14
+ return f.key;
15
+ });
16
+ return names.every((n) => n !== undefined) ? names : undefined;
17
+ };
18
+ /** The states a rule is `while`, by name, refused when one is not a state of this thing's own machine. */
19
+ const scopeOf = (rule, t, at, problems) => {
20
+ if (rule.while === undefined)
21
+ return undefined;
22
+ if (t.machine === undefined) {
23
+ problems.push(`${at}: is \`while\` states, and ${t.name} has no machine, so no states`);
24
+ return [];
25
+ }
26
+ const known = Object.keys(t.machine.states);
27
+ return rule.while.flatMap((s) => {
28
+ if (s === undefined || s.kind !== "state")
29
+ problems.push(`${at}: its \`while\` names something that is not a state of ${t.name}'s machine (it has ${known.join(", ")}); write it as machine.states.<state>`);
30
+ else if (s.machine !== t.machine)
31
+ problems.push(`${at}: its \`while\` names the state ${s.key} of another thing's machine, not ${t.name}'s (${known.join(", ")})`);
32
+ else
33
+ return [s.key];
34
+ return [];
35
+ });
36
+ };
37
+ /**
38
+ * The model's `invariants` for one thing, or undefined when it has none. Refused, naming the file: a key that isn't the thing's own
39
+ * field, a `while` that isn't one of its machine's states, a thing that lives as actors, a refusal that isn't the thing's own error,
40
+ * is owned by another rule, is in a verb's `errors:`, or carries a field outside the key.
41
+ */
42
+ export const invariantsOf = (t, ctx, problems) => {
43
+ // A thing with versions holds one more rule that no file declares (see `versionRule`): the framework's, so two first saves cannot both be revision 1.
44
+ const own = t.thing === undefined || t.invariants.has(VERSION_RULE) ? undefined : versionRule(t.thing);
45
+ const rules = own === undefined ? t.invariants : new Map([...t.invariants, [VERSION_RULE, own]]);
46
+ if (rules.size === 0)
47
+ return undefined;
48
+ const file = `${t.base}/invariants.ts`;
49
+ const owners = new Map();
50
+ const model = {};
51
+ const spelled = new Map();
52
+ for (const [name, rule] of [...rules].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
53
+ const at = `${file}: ${t.name}.${name}`;
54
+ const clash = spelled.get(name.toLowerCase());
55
+ if (clash !== undefined)
56
+ problems.push(`${at}: ${t.name}.${clash} and ${t.name}.${name} differ only in case, and the database compares index names without regard to case (the second index would fail to be created); rename one`);
57
+ else
58
+ spelled.set(name.toLowerCase(), name);
59
+ if (rule.form !== "unique") {
60
+ problems.push(`${at}: is a "${rule.form}" rule, and only unique is known`);
61
+ continue;
62
+ }
63
+ if (t.thing?.lives === "actor")
64
+ problems.push(`${at}: a rule needs a thing that lives in the database, and ${t.name} lives as actors: each instance is its own Durable Object, a commit writes one instance, and there is no shared index or list to look in`);
65
+ const fields = keyOf(rule, t, at, ctx, problems);
66
+ const scope = scopeOf(rule, t, at, problems);
67
+ const refuse = rule.refuse === undefined ? undefined : refusalOf(rule, t, name, fields ?? [], file, ctx, owners, problems);
68
+ model[name] = {
69
+ kind: "unique", fields: fields ?? [],
70
+ ...(rule === own ? { framework: true } : {}),
71
+ ...(scope === undefined ? {} : { while: scope }),
72
+ ...(refuse === undefined ? {} : { refuse }),
73
+ ...(rule.description === undefined ? {} : { description: rule.description }),
74
+ };
75
+ }
76
+ return model;
77
+ };
78
+ const refusalOf = (rule, t, name, key, file, ctx, owners, problems) => {
79
+ const error = rule.refuse;
80
+ const tag = ctx.errorNames.get(error);
81
+ const at = `${file}: ${t.name}.${name}`;
82
+ if (tag === undefined || ![...t.errors.values()].includes(error)) {
83
+ problems.push(`${at}: refuses ${tag ?? "an error that is not declared"}, which is not an error of ${t.name}; a rule refuses with an error from the same thing's errors.ts`);
84
+ return undefined;
85
+ }
86
+ const first = owners.get(error);
87
+ if (first !== undefined)
88
+ problems.push(`${at}: ${tag} is already refused for ${t.name}.${first}; an error belongs to at most one rule`);
89
+ else
90
+ owners.set(error, name);
91
+ for (const [field, input] of Object.entries(error.fields)) {
92
+ if (!key.includes(field)) {
93
+ problems.push(`${at}: ${tag} carries ${field}, which is not in the rule's key (${key.join(", ")}); the runtime fills the refusal from the caller's own row, so it may carry only key fields`);
94
+ continue;
95
+ }
96
+ const keyField = t.thing?.fields[field];
97
+ if (keyField === undefined)
98
+ continue;
99
+ const carried = valueOfInput(input);
100
+ if (!sameValue(carried, keyField.value))
101
+ problems.push(`${at}: ${tag} carries ${field} as ${describeValue(carried)}, and the key field ${field} is ${describeValue(keyField.value)}; the runtime copies the caller's own value into the refusal, so declare the field with the key field's own value (share the constant), as ${pascal(t.name)}.fields.${field}`);
102
+ }
103
+ for (const verb of ctx.verbs) {
104
+ if (verb.errors.includes(error))
105
+ problems.push(`${at}: ${tag} is refused by the runtime for ${t.name}.${name}; take it out of \`errors\` in ${verb.file}.`);
106
+ }
107
+ return tag;
108
+ };
109
+ /**
110
+ * The rules an operation can break (G5, section 3): its move on the rule's thing can end in a `while` state (any move, for a rule with
111
+ * no `while`); one of its database steps names the thing in `writes`; or the thing has no machine, and the operation is on it and has a
112
+ * database step that leaves `writes` unset (unknown; `writes: []` is reads only, S31). `refusals` maps each broken rule's refusal to the rule's full name; `breaks` is every rule broken, refusal or not.
113
+ */
114
+ export const breakersOf = (op, things) => {
115
+ const database = Object.values(op.steps).filter((s) => s.type === "database");
116
+ const refusals = {};
117
+ const breaks = [];
118
+ for (const [thing, t] of Object.entries(things)) {
119
+ for (const [name, rule] of Object.entries(t.invariants ?? {})) {
120
+ const own = op.thing === thing;
121
+ const byMove = own && op.move !== null && (rule.while === undefined || op.move.to.some((s) => rule.while.includes(s)));
122
+ const byWrites = database.some((s) => s.writes?.includes(thing));
123
+ const bare = own && t.machine === null && database.some((s) => s.writes === undefined);
124
+ if (!byMove && !byWrites && !bare)
125
+ continue;
126
+ breaks.push(`${thing}.${name}`);
127
+ if (rule.refuse !== undefined)
128
+ refusals[rule.refuse] = `${thing}.${name}`;
129
+ }
130
+ }
131
+ return { refusals, breaks };
132
+ };
133
+ /** A verb's declared errors, empty while they are a blank. */
134
+ export const declaredErrors = (errors) => (Blanks.isBlank(errors) ? [] : errors);
@@ -0,0 +1,15 @@
1
+ import { type Allowed, type AnyCall, type Assertion } from "orthograph";
2
+ import type { AllowedModel, JourneyModel, OperationModel, StartingWorldModel } from "../types.ts";
3
+ import type { Layout } from "./layout.ts";
4
+ /** A step's blanks: in its call's payload and due instant (the keeper's) and in each check (the check itself, its fields, its id or its value). */
5
+ export declare const stepBlanks: (step: {
6
+ readonly call: AnyCall;
7
+ readonly checks: ReadonlyArray<Assertion>;
8
+ }) => string[];
9
+ /** The cast members whose names the script already uses, each refused with a plain message naming where it is cast. */
10
+ export declare const castClashes: (cast: Readonly<Record<string, unknown>>, file: string, who: string) => ReadonlyArray<string>;
11
+ export declare const storiesOf: (layout: Layout, operations: Readonly<Record<string, OperationModel>>, allowed: (rule: Allowed, file: string) => AllowedModel, problems?: Array<string>) => {
12
+ journeys: Record<string, JourneyModel>;
13
+ startingWorlds: Record<string, StartingWorldModel>;
14
+ journeyBlanks: Record<string, string[]>;
15
+ };