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

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 +35 -3
@@ -0,0 +1,248 @@
1
+ // Turns the layout into the model: every declaration named, every reference resolved, every entry hashed.
2
+ import { Duration } from "effect";
3
+ import { admitsAgent } from "orthograph";
4
+ import { Blanks } from "orthograph/server";
5
+ import { EMPTY_LOCK } from "#modules/lock/service.js";
6
+ import { approvalOf } from "./approval.js";
7
+ import { IDEMPOTENCY_CONFLICT, prefixes, refusalsOf } from "./codes.js";
8
+ import { foundModel, mintsOf, missedBy } from "./found.js";
9
+ import { isVersioned } from "./handler-files.js";
10
+ import { exitClashes, notFoundShapes, operationExitClashes } from "./exits.js";
11
+ import { unfillable } from "./fillable.js";
12
+ import { RUNS_NEEDS, deviceProblems } from "./device.js";
13
+ import { Times } from "#modules/time/service.js";
14
+ import { environmentsOf } from "./environments.js";
15
+ import { secretsOf } from "./secrets.js";
16
+ import { allowedOf, rolePathProblem } from "./allowed.js";
17
+ import { storiesOf } from "./journeys.js";
18
+ import { hashOf } from "./hash.js";
19
+ import { alertRulesOf } from "./rules.js";
20
+ import { crossStore, storesOf } from "./stores.js";
21
+ import { breakersOf, declaredErrors } from "./invariants.js";
22
+ import { camel } from "./layout.js";
23
+ import { formsOf } from "./forms.js";
24
+ import { withReadNotServed } from "./bits.js";
25
+ import { readModelOf } from "./reads.js";
26
+ import { assetsOf, tokensUsed } from "./assets.js";
27
+ import { fieldsOf } from "./fields.js";
28
+ import { chainOperationProblems, chainReadProblems, collisionProblems } from "./operations.js";
29
+ import { metaOf } from "./money.js";
30
+ import { thingsOf } from "./things.js";
31
+ export const describe = (layout, before = EMPTY_LOCK, mounts = {}) => {
32
+ const problems = [...layout.problems];
33
+ const valueNames = new Map([...layout.values].map(([n, v]) => [v, n]));
34
+ const schemaNames = new Map([...layout.values].map(([n, v]) => [v.schema, n]));
35
+ const thingNames = new Map([...layout.things].flatMap(([n, t]) => (t.thing ? [[t.thing, n]] : [])));
36
+ const eventNames = new Map([...layout.things.values()].flatMap((t) => [...t.events].map(([n, e]) => [e, n])));
37
+ const eventThing = new Map([...layout.things].flatMap(([n, t]) => [...t.events.values()].map((e) => [e, n])));
38
+ const opNames = new Map([...layout.things].flatMap(([n, t]) => [...t.verbs].map(([verb, v]) => [v.declaration, `${n}.${verb}`])));
39
+ const opName = (declaration) => opNames.get(declaration);
40
+ // A feature mount's `on` verb makes an operation of its plugin the hop of an event, as the operation's own `on:` does.
41
+ const mountHops = new Map();
42
+ for (const m of layout.mounts.values())
43
+ for (const v of m.mount.verbs)
44
+ if (v.verb === "on")
45
+ mountHops.set(v.operation, [...(mountHops.get(v.operation) ?? []), v.hop]);
46
+ const errorNames = new Map([...layout.things.values()].flatMap((t) => [...t.errors].map(([n, e]) => [e, n])));
47
+ const roleNames = new Map([...layout.things.values()].flatMap((t) => [...t.roles].map(([n, r]) => [r, `${t.name}.${n}`])));
48
+ const names = { assets: new Map([...layout.assets].map(([n, a]) => [a.asset, n])), things: thingNames };
49
+ const { fieldModel, fieldsModel } = fieldsOf({ valueNames, schemaNames, thingNames, roleNames, names, problems });
50
+ // What isn't written yet, by declaration and part.
51
+ const blanks = {};
52
+ const blankIn = (owner, parts) => {
53
+ const found = Object.entries(parts).flatMap(([k, v]) => (Blanks.isBlank(v) ? [`${k}: ${v.what}`] : []));
54
+ if (found.length > 0)
55
+ blanks[owner] = [...(blanks[owner] ?? []), ...found];
56
+ return found.length > 0;
57
+ };
58
+ const storeNames = new Map([...layout.stores].map(([n, s]) => [s.store, n]));
59
+ const chainStores = new Set([...layout.stores].filter(([, s]) => s.store.of === "chain.evm").map(([n]) => n));
60
+ /** Whether a thing lives in a chain store: its operations run on the chain, and its fields have Solidity types. */
61
+ const onChain = (thing) => thing?.store !== undefined && chainStores.has(storeNames.get(thing.store) ?? "");
62
+ const hasChain = chainStores.size > 0;
63
+ const assets = assetsOf(layout, problems);
64
+ const prefix = prefixes(layout.things, problems);
65
+ // The id prefixes some thing owns: its own `id` field's. A field that names another prefix names nothing.
66
+ // `per` is the identity's own: the people who sign in are a thing of Better Auth's, which a blueprint refers to without declaring.
67
+ const owned = new Set(["per", ...[...layout.things.values()].flatMap((t) => { const m = t.thing?.fields["id"]?.value.meta; return m?.type === "id" ? [m.prefix] : []; })]);
68
+ // A thing some operation's payload names where no role check reads it gets a `<Thing>NotFound` (K16, M1.46).
69
+ const missable = new Set([...layout.things.values()].flatMap((t) => [...t.verbs.values()].flatMap(({ declaration: d }) => missedBy(d, Blanks.isBlank))));
70
+ const verbs = [...layout.things.values()].flatMap((t) => [...t.verbs.values()].map(({ file, declaration: d }) => ({ file, errors: d.kind === "operation" ? declaredErrors(d.errors) : [] })));
71
+ const { things, lock } = thingsOf({ layout, before, problems, prefix, missable, verbs, chain: { is: onChain, has: hasChain, storeNames }, names, thingNames, eventNames, errorNames, fieldsModel, fieldModel, blankIn });
72
+ const allowedModel = allowedOf(layout, roleNames, problems);
73
+ const keeperUsed = Times.keeperUsed([...layout.things.values()].flatMap((t) => [...t.verbs.values()].map((v) => v.declaration.allowed)));
74
+ // With a keeper in the blueprint, even an operation open to anyone refuses it NotAllowed (M8-checks call 4).
75
+ const openToAll = (allowed) => !keeperUsed && allowed.every((a) => a.kind === "anyone");
76
+ const hopsOf = (op) => [...op.on, ...(mountHops.get(op) ?? [])];
77
+ const pathNames = { role: (r) => roleNames.get(r) ?? "?", thing: (t) => thingNames.get(t) ?? "?" };
78
+ /** The problems with an operation's or a read's role paths: each must walk to an instance of its role's thing (#767). */
79
+ const rolePaths = (thing, d, file) => {
80
+ // The thing's own name, before a mount prefixed it: what a plugin's blueprint wrote its paths against.
81
+ const from = layout.things.get(thing)?.from;
82
+ const ownName = from === undefined || from.kind === "app" ? thing : from.thing;
83
+ return d.allowed.flatMap((entry) => rolePathProblem({ entry, payload: d.payload, own: d.thing, ownName, names: pathNames, where: file }) ?? []);
84
+ };
85
+ const readCtx = { layout, thingNames, problems, allowedModel, fieldsModel, openToAll, onChain, rolePaths };
86
+ const operations = {};
87
+ const blankOperations = {};
88
+ const entries = new Map();
89
+ for (const [thing, t] of [...layout.things].sort(([a], [b]) => a.localeCompare(b))) {
90
+ for (const [verb, { file, declaration: op, from: verbFrom }] of [...t.verbs].sort(([a], [b]) => a.localeCompare(b))) {
91
+ // A `Blueprint.todo` among `allowed` is a blank too (#742, item 7), named by its place in the list.
92
+ const allowed = Blanks.isBlank(op.allowed) ? { allowed: op.allowed } : Object.fromEntries(op.allowed.map((a, i) => [`allowed[${i}]`, a]));
93
+ const parts = op.kind === "read"
94
+ ? { [op.by === "list" ? "where" : "fields"]: op.by === "list" ? op.where : op.fields, ...allowed }
95
+ : { description: op.description, payload: op.payload, answer: op.answer, ...allowed, errors: op.errors, steps: op.steps, move: op.move };
96
+ const name = `${thing}.${verb}`;
97
+ const incomplete = blankIn(name, parts);
98
+ const steps = op.kind === "operation" && !Blanks.isBlank(op.steps) ? Object.entries(op.steps) : [];
99
+ blankIn(name, Object.fromEntries(steps.map(([key, step]) => [`steps.${key}`, step])));
100
+ if (incomplete) {
101
+ blankOperations[name] = {
102
+ name, thing, verb, file, kind: op.kind, from: t.from, blanks: blanks[name],
103
+ ...(op.kind === "operation" && !Blanks.isBlank(op.description) ? { description: op.description } : {}),
104
+ };
105
+ continue;
106
+ }
107
+ operations[name] = operationModel(thing, verb, file, verbFrom ?? t.from, op);
108
+ const store = t.thing?.store === undefined ? undefined : storeNames.get(t.thing.store);
109
+ if (store !== undefined && chainStores.has(store))
110
+ entries.set(store, [...(entries.get(store) ?? []), { file, name, identifier: camel(verb) }]);
111
+ }
112
+ }
113
+ // One contract per chain store: its verbs share the generated entries' names.
114
+ for (const verbsOf of entries.values())
115
+ problems.push(...collisionProblems(verbsOf));
116
+ function operationModel(thing, verb, file, from, declared) {
117
+ if (declared.thing !== layout.things.get(thing)?.thing)
118
+ problems.push(`${file}: declares an operation of another thing`);
119
+ if (declared.kind === "read")
120
+ return readModel(thing, verb, file, from, declared);
121
+ const op = declared;
122
+ const chain = onChain(layout.things.get(thing)?.thing);
123
+ const onDevice = op.runs === "client" && (layout.things.get(thing)?.from.kind ?? "app") !== "app"; // a plugin's, with its code for each host
124
+ // On a chain store where it runs is the compiler's word, so a written `runs` is refused in operations.ts.
125
+ if (!chain && op.runs !== "server" && !onDevice)
126
+ problems.push(`${file}: runs "${op.runs}" is not supported yet: ${RUNS_NEEDS[op.runs] ?? "an unknown place"}`);
127
+ else if (onDevice)
128
+ problems.push(...deviceProblems(file, op));
129
+ const machine = things[thing]?.machine;
130
+ const move = op.move
131
+ ? { key: op.move.key, from: op.move.from, to: op.move.to, emits: eventNames.get(op.move.emits) ?? "?" }
132
+ : null;
133
+ if (op.move && op.move.machine !== layout.things.get(thing)?.machine)
134
+ problems.push(`${file}: moves another thing's machine`);
135
+ problems.push(...unfillable(op, `${thing}.${verb}`, thing, move?.emits ?? "?", `${layout.things.get(thing)?.base ?? `blueprint/things/${thing}`}/events.ts`));
136
+ const errors = op.errors.map((e) => errorNames.get(e) ?? problem(problems, `${file}: declares an error not exported from an errors.ts`));
137
+ // Each refusal goes on the wire by its name: two classes of one name in one union can't be told apart.
138
+ for (const tag of new Set(errors.filter((n, i) => errors.indexOf(n) !== i && n !== "?"))) {
139
+ problems.push(`${file}: ${thing}.${verb}'s errors are a union with two classes tagged ${tag}, so the refusal is ambiguous on the wire: rename one`);
140
+ }
141
+ const allowed = op.allowed.map((a) => allowedModel(a, file));
142
+ problems.push(...rolePaths(thing, op, file));
143
+ problems.push(...Times.keeper({ file, name: `${thing}.${verb}`, kind: "operation", move: op.move, allowed }));
144
+ for (const a of op.allowed) {
145
+ const role = (a.kind === "narrowed" ? a.entry : a);
146
+ const r = role.kind === "role" ? role : role.kind === "role-of" ? role.role : undefined;
147
+ const within = r?.actor?.within;
148
+ if (within !== undefined && !(within.key in op.payload))
149
+ problems.push(`${file}: ${thing}.${verb} uses a role that compares the call's ${within.key} with the account's, and its payload has no ${within.key} to compare`);
150
+ }
151
+ const found = foundModel(op, (x) => thingNames.get(x), (x) => things[x]?.notFound?.error);
152
+ const steps = Object.fromEntries(Object.entries(op.steps).map(([k, s]) => [k,
153
+ Blanks.isBlank(s) ? { name: `${thing}.${verb}.${k}`, type: "blank" } : stepModel(thing, verb, k, s, op.errors, file)]));
154
+ // The refusals the runtime makes for the rules this operation can break (G5), never among its `errors`.
155
+ const broken = breakersOf({ thing, move, steps }, things);
156
+ if (op.runs === "client" && broken.breaks.length > 0)
157
+ problems.push(`${file}: ${thing}.${verb} runs on the device, which has no store, and can break ${broken.breaks.join(", ")}`);
158
+ const refusals = [
159
+ ...errors,
160
+ ...Object.keys(broken.refusals),
161
+ ...(move && move.from.length > 0 && machine ? [machine.notFrom.error] : []),
162
+ ...new Set(Object.values(found.notFound ?? {}).filter((e) => !errors.includes(e))),
163
+ ...(openToAll(allowed) ? [] : ["NotAllowed"]),
164
+ // An operation that keeps its answer by request key refuses a key reused with another payload (HAN-10, G3).
165
+ ...(op.idempotent === "request" ? [IDEMPOTENCY_CONFLICT] : []),
166
+ ];
167
+ const ctx = { owner: { name: thing, thing: op.thing }, chain };
168
+ const payload = fieldsModel(op.payload, `${file} payload`, { place: "a payload", ...ctx });
169
+ const answer = fieldsModel(op.answer, `${file} answer`, { place: "answer", ...ctx });
170
+ const mints = mintsOf(move?.from.length === 0, thing, answer, payload);
171
+ // A save or restore of a thing with versions made from an old version is refused with the declared error that carries `current`
172
+ // alone (K40 fix 2): found by that shape, whatever the app names it, and the server reads it from here.
173
+ const keeps = ["save", "restore"].includes(verb) && isVersioned({ kind: "operation", verb, payload }, layout.things.get(thing)?.thing?.versions);
174
+ const stale = keeps ? errors.filter((_, i) => Object.keys(op.errors[i].fields).join() === "current") : [];
175
+ if (keeps && stale.length !== 1)
176
+ problems.push(`${file}: ${thing}.${verb} ${verb}s a version of ${thing}, so it declares one error whose only field is current, its refusal of a save made from an old version; it declares ${stale.length === 0 ? "none" : stale.join(" and ")}`);
177
+ if (chain)
178
+ problems.push(...chainOperationProblems({ file, name: `${thing}.${verb}`, thing, op, roleNames, payload, answer, event: move ? things[thing]?.events[move.emits] : undefined, emits: move?.emits ?? "?", mints }));
179
+ const entry = {
180
+ kind: "operation",
181
+ name: `${thing}.${verb}`, thing, verb, identifier: camel(verb), file, from, description: op.description,
182
+ payload, answer, move, errors, ...(hopsOf(op).length > 0 ? { on: hopsOf(op).map((h) => ({ event: eventNames.get(h.event) ?? problem(problems, `${file}: is delivered an event that is not exported from an events.ts`), thing: eventThing.get(h.event) ?? "?" })) } : {}), ...(Object.keys(broken.refusals).length > 0 ? { invariants: broken.refusals } : {}), breaks: broken.breaks, refusals, allowed, agentTool: !onDevice && admitsAgent(op.allowed), ...found, ...(mints !== undefined ? { mints } : {}), ...(keeps && stale.length === 1 ? { stale: stale[0] } : {}),
183
+ steps,
184
+ ...(blanks[`${thing}.${verb}`] ? { blanks: blanks[`${thing}.${verb}`] } : {}),
185
+ idempotent: op.idempotent ?? null,
186
+ ...approvalOf(op, file, problems),
187
+ runs: (chain ? "chain" : onDevice ? "client" : "server"), test: op.test,
188
+ budget: op.budget ? { p95Ms: Duration.toMillis(op.budget.p95) } : null,
189
+ };
190
+ const split = crossStore(file, `${thing}.${verb}`, thing, move !== null, entry.steps, things);
191
+ if (split)
192
+ problems.push(split);
193
+ return { ...entry, hash: hashOf(entry) };
194
+ }
195
+ /** A step: a span named after it; a call step also says which call of which mounted adapter, or why it can't. */
196
+ function stepModel(thing, verb, key, step, declared, file) {
197
+ const plain = {
198
+ name: `${thing}.${verb}.${key}`, type: step.type, ...writesOf(step.writes, file),
199
+ ...(step.optional ? { optional: true } : {}),
200
+ };
201
+ if (step.type !== "call")
202
+ return plain;
203
+ const { call } = step;
204
+ const reach = layout.calls.get(call);
205
+ const where = `${file}: step ${key}`;
206
+ if (!reach) {
207
+ const missing = call?.kind === "missing-call";
208
+ problems.push(missing
209
+ ? `${where} calls ${call.name}, which the adapter doesn't have`
210
+ : `${where} calls something that no mounted adapter offers: mount its adapter (ortho add adapter <package>) and write the call as <mount>.calls.<call>`);
211
+ return plain;
212
+ }
213
+ if (!reach.included)
214
+ problems.push(`${where} calls ${reach.call} of ${reach.package}, which ${reach.file} doesn't include: add p.include(p.calls.${reach.call}) there`);
215
+ for (const e of call.errors) {
216
+ if (!declared.includes(e))
217
+ problems.push(`${where} calls ${reach.call}, which may fail as ${errorNames.get(e) ?? "an error that is not declared"}: declare it in the operation's errors`);
218
+ }
219
+ return { ...plain, call: { mount: reach.mount, call: reach.call, mode: call.mode } };
220
+ }
221
+ /** The names of the things a step writes: only when it names any. */
222
+ function writesOf(writes, where) {
223
+ return writes ? { writes: writes.map((w) => thingNames.get(w) ?? problem(problems, `${where}: a step writes a thing that isn't in the blueprint`)) } : {};
224
+ }
225
+ function readModel(thing, verb, file, from, read) {
226
+ return readModelOf(readCtx, thing, verb, file, from, read);
227
+ }
228
+ const refusals = withReadNotServed(refusalsOf(things, problems, hasChain), operations);
229
+ const written = new Map([...layout.things].flatMap(([n, t]) => (t.written === undefined ? [] : [[n, t.written]])));
230
+ problems.push(...exitClashes(things, written), ...operationExitClashes(things, operations, written), ...notFoundShapes(things));
231
+ const values = Object.fromEntries([...layout.values].sort(([a], [b]) => a.localeCompare(b)).map(([n, v]) => [n, metaOf(v.meta, `${layout.valueFiles.get(n) ?? "blueprint/values"}: value ${n}`, undefined, names, problems)]));
232
+ const secrets = secretsOf(layout, problems);
233
+ const environments = environmentsOf(layout, problems, tokensUsed(things, operations), secrets);
234
+ const stores = storesOf(layout, problems);
235
+ const { journeyBlanks, ...stories } = storiesOf(layout, operations, allowedModel, problems);
236
+ const allBlanks = { ...blanks, ...journeyBlanks };
237
+ const alertRules = alertRulesOf({ operations, refusals, things, journeys: stories.journeys, environments });
238
+ const forms = formsOf({ layout, mounts, things, thingNames, eventNames, opName, problems });
239
+ return {
240
+ model: { ...forms, refusals, values, ...(Object.keys(assets).length > 0 ? { assets } : {}), things, ...(Object.keys(stores).length > 0 ? { stores } : {}), operations, ...stories, ...(Object.keys(blankOperations).length > 0 ? { blankOperations } : {}), ...(Object.keys(allBlanks).length > 0 ? { blanks: allBlanks } : {}), ...(Object.keys(secrets).length > 0 ? { secrets } : {}), ...(Object.keys(environments).length > 0 ? { environments } : {}), alertRules },
241
+ problems,
242
+ lock,
243
+ };
244
+ };
245
+ const problem = (problems, p) => {
246
+ problems.push(p);
247
+ return "?";
248
+ };
@@ -0,0 +1,5 @@
1
+ import type { Operation } from "orthograph";
2
+ /** What an operation that doesn't run on the server needs: a language that does. Only the Effect language exists today. */
3
+ export declare const RUNS_NEEDS: Readonly<Record<string, string>>;
4
+ /** What an operation on the device can't have: there is no server there to know who calls, store anything, or move a machine. */
5
+ export declare const deviceProblems: (file: string, op: Operation) => ReadonlyArray<string>;
@@ -0,0 +1,12 @@
1
+ /** What an operation that doesn't run on the server needs: a language that does. Only the Effect language exists today. */
2
+ export const RUNS_NEEDS = {
3
+ client: "an operation runs on the caller's own device only when a mounted plugin supplies it, with a code entry for each of node, browser and world; this app's own operations all run on the server",
4
+ chain: "it needs a language that runs operations on a chain (language-solidity, or language-noir on Aztec), and this project's only language, language-effect, runs them all on the server",
5
+ };
6
+ /** What an operation on the device can't have: there is no server there to know who calls, store anything, or move a machine. */
7
+ export const deviceProblems = (file, op) => [
8
+ ...(op.allowed.every((a) => a.kind === "anyone") ? [] : [`${file}: a client operation runs on the caller's device, where no server knows who is calling: it must be allowed to Blueprint.anyone`]),
9
+ ...(op.move ? [`${file}: a client operation has no store, so it can't move a machine`] : []),
10
+ ...(Object.values(op.steps).some((s) => s.type === "call") ? [`${file}: a client operation can't have a call step yet (the wallet reaches the chain through the chain port as a library, M1-plugins section 8.2; a call step on the device waits for an adapter that needs one)`] : []),
11
+ ...(op.idempotent ? [`${file}: a client operation has no server to keep an idempotency key`] : []),
12
+ ];
@@ -0,0 +1,7 @@
1
+ import type { EnvironmentModel, SecretModel } from "../types.ts";
2
+ import type { Layout } from "./layout.ts";
3
+ /**
4
+ * `tokens` is each chain store's fixed token assets (the ones its things count); an environment that runs the store
5
+ * must bind each to a contract (M6-money item 2).
6
+ */
7
+ export declare const environmentsOf: (layout: Layout, problems: Array<string>, tokens?: ReadonlyMap<string, ReadonlySet<string>>, secrets?: Readonly<Record<string, SecretModel>>) => Readonly<Record<string, EnvironmentModel>>;
@@ -0,0 +1,90 @@
1
+ // Reads the environments into the model: the name comes from the file, never from a string inside it.
2
+ import { Duration, Option } from "effect";
3
+ import { Times } from "#modules/time/service.js";
4
+ import { hashOf } from "./hash.js";
5
+ const SECRET = /^[A-Z][A-Z0-9_]*$/;
6
+ const byKey = (entries) => [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
7
+ const GROUP = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
8
+ const sinkOf = (s) => (s.which === "local" ? { sink: "local" } : { sink: "axiom", group: s.group });
9
+ const publication = (p) => p.how === "npm" ? { how: "npm", tag: p.tag } : p.how === "homebrew" ? { how: "homebrew", tap: p.tap } : { how: "binaries", on: p.on };
10
+ /** Every runtime secret of the mounts and the app, in every environment: a release or builder secret never reaches a running place. */
11
+ const runtimeOf = (secrets) => Object.entries(secrets).flatMap(([name, s]) => (s.kind === "runtime" ? [[name, s.how]] : []));
12
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
13
+ /** What an environment binds a store to: a database, or (for a chain store) a network. */
14
+ const bindingOf = (b) => b.kind === "chain" ? { chain: b.of, network: b.network } : b.which;
15
+ /**
16
+ * `tokens` is each chain store's fixed token assets (the ones its things count); an environment that runs the store
17
+ * must bind each to a contract (M6-money item 2).
18
+ */
19
+ export const environmentsOf = (layout, problems, tokens = new Map(), secrets = {}) => Object.fromEntries(byKey([...layout.environments]).map(([name, { file, declaration: e }]) => {
20
+ const lifetime = e.lifetime === undefined ? Option.none() : Duration.fromInput(e.lifetime);
21
+ if (e.lifetime !== undefined && Option.isNone(lifetime))
22
+ problems.push(`${file}: lifetime isn't a duration`);
23
+ if (e.promotesFrom !== undefined && (e.promotesFrom === name || !layout.environments.has(e.promotesFrom))) {
24
+ problems.push(`${file}: promotesFrom "${e.promotesFrom}" isn't another environment in blueprint/environments/`);
25
+ }
26
+ for (const secret of Object.keys(e.secrets ?? {})) {
27
+ if (!SECRET.test(secret))
28
+ problems.push(`${file}: secret "${secret}" must be UPPER_SNAKE_CASE`);
29
+ if (secrets[secret])
30
+ problems.push(`${file}: secret "${secret}" is declared by a secrets.ts, so an environment doesn't name it too`);
31
+ }
32
+ if ((e.deploy !== undefined || e.publish !== undefined) && e.cloud === undefined)
33
+ problems.push(`${file}: deploys or publishes, so it needs a cloud`);
34
+ for (const [bound, to] of Object.entries(e.stores ?? {})) {
35
+ const declared = layout.stores.get(bound);
36
+ if (!declared)
37
+ problems.push(`${file}: stores binds "${bound}", which isn't a declared store (${layout.stores.size > 0 ? `the stores are ${[...layout.stores.keys()].join(", ")}` : "the blueprint declares none"})`);
38
+ else if (declared.store.of === "chain.evm" ? to.kind !== "chain" : declared.store.of !== "database" || to.kind !== "database") {
39
+ problems.push(declared.store.of === "chain.evm"
40
+ ? `${file}: stores binds "${bound}", a chain.evm store, to a database: a chain store is bound to a network, as Chain.evm.network("anvil")`
41
+ : `${file}: stores binds "${bound}", a ${declared.store.of} store, to ${to.kind === "chain" ? "a chain" : "a database"}: only a database store is bound this way`);
42
+ }
43
+ }
44
+ const chains = Object.entries(e.stores ?? {}).filter(([, to]) => to.kind === "chain").map(([store]) => store);
45
+ for (const [asset, per] of Object.entries(e.assets ?? {})) {
46
+ if (layout.assets.get(asset)?.asset.of !== "token")
47
+ problems.push(`${file}: assets binds "${asset}", which isn't a token asset in blueprint/assets/ (${[...layout.assets].filter(([, a]) => a.asset.of === "token").map(([n]) => n).join(", ") || "the blueprint declares none"})`);
48
+ for (const [store, token] of Object.entries(per)) {
49
+ if (layout.stores.get(store)?.store.of !== "chain.evm")
50
+ problems.push(`${file}: assets binds "${asset}" for "${store}", which isn't a chain store of the blueprint`);
51
+ if (!ADDRESS.test(token.address))
52
+ problems.push(`${file}: assets binds "${asset}" for "${store}" to "${token.address}", which isn't an EVM address (0x and 40 hex digits)`);
53
+ }
54
+ }
55
+ for (const store of chains) {
56
+ for (const asset of [...(tokens.get(store) ?? [])].sort()) {
57
+ if (e.assets?.[asset]?.[store] === undefined)
58
+ problems.push(`${file}: the environment runs the chain store ${store}, whose things count the token asset ${asset}, and doesn't bind it: add assets: { ${asset}: { ${store}: Chain.evm.token("0x…") } }`);
59
+ }
60
+ }
61
+ if (e.issues !== undefined && e.issues.length === 0)
62
+ problems.push(`${file}: issues names no way in: leave it out to issue every way in`);
63
+ const sinks = e.telemetry ?? [];
64
+ for (const s of sinks)
65
+ if (s.which === "axiom" && !GROUP.test(s.group))
66
+ problems.push(`${file}: the Axiom group "${s.group}" isn't a dataset group name (letters, digits, - _ .)`);
67
+ const named = sinks.map((s) => JSON.stringify(sinkOf(s)));
68
+ if (new Set(named).size !== named.length)
69
+ problems.push(`${file}: telemetry names the same sink twice`);
70
+ // An environment in a promotion chain (it promotes from another, or another promotes from it) holds real worlds only (K23 section 1).
71
+ const promotes = e.promotesFrom !== undefined || [...layout.environments.values()].some((other) => other.declaration.promotesFrom === name);
72
+ const clock = e.clock === undefined ? undefined : Times.clock({ file, clock: e.clock, environment: name, promotes });
73
+ problems.push(...(clock?.problems ?? []));
74
+ const entry = {
75
+ name, file, runs: e.runs, ...(e.identity === undefined ? {} : { identity: e.identity.which }),
76
+ ...(e.issues === undefined ? {} : { issues: [...new Set(e.issues)].sort() }),
77
+ ...(clock?.clock === undefined ? {} : { clock: clock.clock }),
78
+ lifetimeMs: Option.isSome(lifetime) ? Duration.toMillis(lifetime.value) : null,
79
+ cloud: e.cloud ? { provider: e.cloud.provider, database: e.cloud.database.which } : null,
80
+ database: e.database?.which ?? null,
81
+ ...(e.stores && Object.keys(e.stores).length > 0 ? { stores: Object.fromEntries(byKey(Object.entries(e.stores)).map(([k, d]) => [k, bindingOf(d)])) } : {}),
82
+ ...(e.assets && Object.keys(e.assets).length > 0 ? { assets: Object.fromEntries(byKey(Object.entries(e.assets)).map(([a, per]) => [a, Object.fromEntries(byKey(Object.entries(per)).map(([store, t]) => [store, { chain: t.of, address: t.address }]))])) } : {}),
83
+ secrets: Object.fromEntries(byKey([...Object.entries(e.secrets ?? {}).map(([k, s]) => [k, s.how]), ...runtimeOf(secrets)])),
84
+ promotesFrom: e.promotesFrom ?? null,
85
+ ...(e.telemetry === undefined ? {} : { telemetry: sinks.map(sinkOf) }),
86
+ deploy: Object.fromEntries(byKey(Object.entries(e.deploy ?? {})).map(([k, d]) => [k, { how: d.how, domain: d.domain }])),
87
+ publish: Object.fromEntries(byKey(Object.entries(e.publish ?? {})).map(([k, p]) => [k, (Array.isArray(p) ? p : [p]).map(publication)])),
88
+ };
89
+ return [name, { ...entry, hash: hashOf(entry) }];
90
+ }));
@@ -0,0 +1,49 @@
1
+ import type { FromModel } from "../types.ts";
2
+ /** Exits the runtime keeps, and whose they are. */
3
+ export declare const RESERVED_EXITS: ReadonlyMap<number, string>;
4
+ type ThingExits = {
5
+ readonly identifier: string;
6
+ readonly errors: Readonly<Record<string, {
7
+ readonly exit: number;
8
+ }>>;
9
+ readonly machine: {
10
+ readonly notFrom: {
11
+ readonly error: string;
12
+ readonly exit: number;
13
+ };
14
+ } | null;
15
+ readonly from: FromModel;
16
+ };
17
+ /** A thing's blueprint file, as the author sees it: in the app, or in the plugin it came from. */
18
+ export declare const fileOf: (thing: string, from: FromModel, file: string) => string;
19
+ /**
20
+ * A thing's declared `<Thing>NotFound` is the runtime's not-found refusal, which carries only the missing `id`: any other
21
+ * field would be one nothing fills, so it is refused (K16, M1.46).
22
+ */
23
+ export declare const notFoundShapes: (things: Readonly<Record<string, ThingExits & {
24
+ readonly errors: Readonly<Record<string, {
25
+ readonly fields: object;
26
+ }>>;
27
+ }>>) => string[];
28
+ /**
29
+ * A generated adapter's things, by name, and its `<package>/src/written.ts`: its four errors take one base set there by hand
30
+ * (`export const exit = <base>`, G16-adapter-mounts call 1), so a refusal of their exits names that setting, not the errors file.
31
+ */
32
+ export type Written = ReadonlyMap<string, string>;
33
+ /** One problem per declared exit that clashes, naming the error, its exit, whose it is, and the file declaring it. */
34
+ export declare const exitClashes: (things: Readonly<Record<string, ThingExits>>, written?: Written) => ReadonlyArray<string>;
35
+ /**
36
+ * What one operation may refuse is judged as a whole: two refusals at one exit, whichever things declared them, can't be
37
+ * told apart by the CLI. A pair from one thing is already named by `exitClashes`; this names the pairs across things.
38
+ */
39
+ export declare const operationExitClashes: (things: Readonly<Record<string, ThingExits>>, operations: Readonly<Record<string, {
40
+ readonly file: string;
41
+ readonly name: string;
42
+ readonly errors: ReadonlyArray<string>;
43
+ readonly invariants?: Readonly<Record<string, string>>;
44
+ readonly move: {
45
+ readonly from: ReadonlyArray<string>;
46
+ } | null;
47
+ readonly thing: string;
48
+ }>>, written?: Written) => ReadonlyArray<string>;
49
+ export {};
@@ -0,0 +1,85 @@
1
+ /** Exits the runtime keeps, and whose they are. */
2
+ export const RESERVED_EXITS = new Map([
3
+ [0, "success"], [1, "a defect"], [2, "InvalidPayload"], [3, "NotAllowed"], [4, "NotFound"],
4
+ [120, "IdempotencyConflict"], [121, "the runtime"], [122, "the runtime"], [123, "the runtime"], [124, "the runtime"], [125, "the runtime"],
5
+ ]);
6
+ const LOWEST = 5;
7
+ const HIGHEST = 119;
8
+ /** A thing's blueprint file, as the author sees it: in the app, or in the plugin it came from. */
9
+ export const fileOf = (thing, from, file) => from.kind !== "app" ? `${from.package}/blueprint/things/${from.thing}/${file}.js` : `blueprint/things/${thing}/${file}.ts`;
10
+ /**
11
+ * A thing's declared `<Thing>NotFound` is the runtime's not-found refusal, which carries only the missing `id`: any other
12
+ * field would be one nothing fills, so it is refused (K16, M1.46).
13
+ */
14
+ export const notFoundShapes = (things) => Object.entries(things).flatMap(([thing, t]) => {
15
+ const name = `${t.identifier}NotFound`;
16
+ const extra = Object.keys(t.errors[name]?.fields ?? {}).filter((f) => f !== "id");
17
+ return extra.length === 0 ? [] : [`${fileOf(thing, t.from, "errors")}: ${name} is the runtime's not-found refusal, which carries only the missing id; drop ${extra.join(", ")}`];
18
+ });
19
+ /** Whose a reserved or out-of-range exit is, or undefined when a refusal may use it. */
20
+ const unusable = (exit, mayBeNotFound) => !Number.isInteger(exit) ? "not a whole number"
21
+ : mayBeNotFound && exit === 4 ? undefined
22
+ : RESERVED_EXITS.has(exit) ? `${RESERVED_EXITS.get(exit)}'s`
23
+ : exit < LOWEST || exit > HIGHEST ? `outside ${LOWEST} to ${HIGHEST}, which are the blueprint's` : undefined;
24
+ /** What to change for a generated adapter's exits. */
25
+ const setExit = (files, so) => `set \`exit\` in ${files.join(" or ")} to a base whose four exits (base to base+3) ${so}`;
26
+ /** One problem per declared exit that clashes, naming the error, its exit, whose it is, and the file declaring it. */
27
+ export const exitClashes = (things, written = new Map()) => Object.entries(things).flatMap(([thing, t]) => {
28
+ const file = fileOf(thing, t.from, "errors");
29
+ const setting = written.get(thing);
30
+ const notFrom = t.machine?.notFrom;
31
+ const machineBad = notFrom === undefined ? undefined : unusable(notFrom.exit, false);
32
+ const taken = new Map(notFrom ? [[notFrom.exit, notFrom.error]] : []);
33
+ return [
34
+ ...(notFrom && machineBad ? [`${fileOf(thing, t.from, "machine")}: ${notFrom.error}'s exit ${notFrom.exit} is ${machineBad}; pick another`] : []),
35
+ ...Object.entries(t.errors).flatMap(([name, { exit }]) => {
36
+ // Only the thing's own declared `<Thing>NotFound` may keep the not-found exit: it is that refusal.
37
+ const bad = unusable(exit, name === `${t.identifier}NotFound`);
38
+ const owner = taken.get(exit);
39
+ if (owner === undefined)
40
+ taken.set(exit, name);
41
+ if (bad !== undefined)
42
+ return [`${file}: ${name}'s exit ${exit} is ${bad}; ${setting === undefined ? "pick another" : setExit([setting], `fit ${LOWEST} to ${HIGHEST}`)}`];
43
+ return owner !== undefined ? [`${file}: ${name}'s exit ${exit} is ${owner}'s; pick another`] : [];
44
+ }),
45
+ ];
46
+ });
47
+ /**
48
+ * What one operation may refuse is judged as a whole: two refusals at one exit, whichever things declared them, can't be
49
+ * told apart by the CLI. A pair from one thing is already named by `exitClashes`; this names the pairs across things.
50
+ */
51
+ export const operationExitClashes = (things, operations, written = new Map()) => {
52
+ const whose = (thing) => { const from = things[thing]?.from; return from === undefined || from.kind === "app" ? thing : from.package; };
53
+ const exits = new Map();
54
+ for (const [thing, t] of Object.entries(things)) {
55
+ if (t.machine)
56
+ exits.set(t.machine.notFrom.error, { exit: t.machine.notFrom.exit, thing });
57
+ for (const [name, { exit }] of Object.entries(t.errors))
58
+ exits.set(name, { exit, thing });
59
+ }
60
+ return Object.values(operations).flatMap((o) => {
61
+ // The refusals the runtime makes for a rule count too, and are named with the rule's file (G5).
62
+ const ruled = o.invariants ?? {};
63
+ const names = [...new Set([...o.errors, ...(o.move && o.move.from.length > 0 && things[o.thing]?.machine ? [things[o.thing].machine.notFrom.error] : []), ...Object.keys(ruled)])];
64
+ const by = (name) => { const rule = ruled[name]; const owner = rule === undefined ? undefined : things[rule.split(".")[0]]; return rule === undefined || owner === undefined ? "" : ` (${name} is refused for ${rule} in ${fileOf(rule.split(".")[0], owner.from, "invariants")})`; };
65
+ // A clash with a generated adapter's errors is one line per pair of things, naming the setting that moves all four.
66
+ const adapters = new Map();
67
+ const lines = names.flatMap((name, i) => names.slice(0, i).flatMap((other) => {
68
+ const a = exits.get(other);
69
+ const b = exits.get(name);
70
+ if (!(a && b && a.exit === b.exit && a.thing !== b.thing && unusable(a.exit, true) === undefined))
71
+ return [];
72
+ if (written.has(a.thing) || written.has(b.thing)) {
73
+ const key = [a.thing, b.thing].sort().join(" ");
74
+ adapters.set(key, { things: [a.thing, b.thing], exits: [...(adapters.get(key)?.exits ?? []), a.exit] });
75
+ return [];
76
+ }
77
+ return [`${o.file}: ${o.name} refuses both ${other} and ${name} at exit ${a.exit}: ${name}'s exit ${a.exit} is ${other}'s; pick another${by(name)}${by(other)}`];
78
+ }));
79
+ return [...lines, ...[...adapters.values()].map(({ things: [a, b], exits: at }) => {
80
+ const files = [a, b].flatMap((t) => written.get(t) ?? []);
81
+ const others = [a, b].filter((t) => !written.has(t)).map((t) => fileOf(t, things[t].from, "errors"));
82
+ return `${o.file}: ${o.name} refuses errors of ${whose(a)} and ${whose(b)} at the same ${at.length === 1 ? "exit" : "exits"} (${at.join(", ")}): ${setExit(files, `miss every other exit ${o.name} refuses, within ${LOWEST} to ${HIGHEST}`)}${others.length > 0 ? `, or pick others in ${others.join(" and ")}` : ""}`;
83
+ })];
84
+ });
85
+ };
@@ -0,0 +1,23 @@
1
+ import type { Field, FieldsInput, Role, Thing, Value } from "orthograph";
2
+ import type { FieldModel, FieldsModel } from "../types.ts";
3
+ import { type Names, type Owner } from "./money.ts";
4
+ /** Where a field is declared: `Blueprint.issued` is allowed in one of these. */
5
+ export type Place = "answer" | "a payload" | "an error" | "an event" | "a thing's field" | "a read answer";
6
+ /** Which declaration a field belongs to: the thing it is of (undefined for a named value), and whether that thing lives on a chain. */
7
+ export interface FieldContext {
8
+ readonly place: Place;
9
+ readonly owner?: Owner;
10
+ readonly chain?: boolean;
11
+ }
12
+ export interface FieldsEnv {
13
+ readonly valueNames: ReadonlyMap<Value, string>;
14
+ readonly schemaNames: ReadonlyMap<unknown, string>;
15
+ readonly thingNames: ReadonlyMap<Thing, string>;
16
+ readonly roleNames: ReadonlyMap<Role, string>;
17
+ readonly names: Names;
18
+ readonly problems: Array<string>;
19
+ }
20
+ export declare const fieldsOf: ({ valueNames, schemaNames, thingNames, roleNames, names, problems }: FieldsEnv) => {
21
+ fieldModel: (input: Field | Value, where: string, ctx: FieldContext) => FieldModel;
22
+ fieldsModel: (fields: FieldsInput, where: string, ctx: FieldContext) => FieldsModel;
23
+ };
@@ -0,0 +1,50 @@
1
+ import { chainField } from "./chain.js";
2
+ import { isNullable, jsonShape } from "./nullable.js";
3
+ import { metaOf } from "./money.js";
4
+ const problem = (problems, p) => {
5
+ problems.push(p);
6
+ return "?";
7
+ };
8
+ export const fieldsOf = ({ valueNames, schemaNames, thingNames, roleNames, names, problems }) => {
9
+ const fieldRef = (f) => {
10
+ const thing = thingNames.get(f.of);
11
+ return thing ? `${thing}.${f.key}` : undefined;
12
+ };
13
+ /** Public is the default and is left out; a private role is named as `thing.role`. */
14
+ const visibilityModel = (v, where) => v === "public" ? undefined
15
+ : v === "secret" ? "secret"
16
+ : { private: v.to.map((r) => roleNames.get(r) ?? problem(problems, `${where}: is private to a role not exported from a roles.ts`)) };
17
+ /** `Blueprint.issued` is allowed in one place: a secret value in an operation's answer. Anywhere else it is refused, naming the field. */
18
+ const issuedIn = (input, where, place) => {
19
+ if (input.issued !== true)
20
+ return false;
21
+ if (place !== "answer")
22
+ problems.push(`${where}: is marked Blueprint.issued in ${place}: only a secret value in an operation's answer is issued`);
23
+ else if (input.visibility !== "secret")
24
+ problems.push(`${where}: is marked Blueprint.issued but is ${input.visibility === "public" ? "public" : "private"}: only a secret value is issued`);
25
+ return place === "answer" && input.visibility === "secret";
26
+ };
27
+ const fieldModel = (input, where, ctx) => {
28
+ const value = input.kind === "field" ? input.value : input;
29
+ // `Blueprint.issued(Secret)` is a copy of the named value, so it is found by the schema it shares with it.
30
+ const named = valueNames.get(value) ?? (input.issued === true || input.description !== undefined ? schemaNames.get(value.schema) : undefined);
31
+ const ref = input.kind === "field" ? fieldRef(input) : undefined;
32
+ if (input.kind === "field" && !ref)
33
+ problems.push(`${where}: uses a field of a thing that isn't in the blueprint`);
34
+ const visibility = visibilityModel(input.visibility, where);
35
+ const issued = issuedIn(input, where, ctx.place);
36
+ const meta = metaOf(value.meta, where, ctx.owner, names, problems);
37
+ // A width that is no whole number from 1 to 256 is refused for every store; on a chain it must also be a multiple of 8 (chain.ts).
38
+ if ((meta.type === "uint" || meta.type === "money") && !(Number.isInteger(meta.bits) && meta.bits >= 1 && meta.bits <= 256)) {
39
+ problems.push(`${where}: a ${meta.type} of ${String(meta.bits)} bits is no width: bits is a whole number from 1 to 256 (a chain store needs 8 to 256, in steps of 8)`);
40
+ }
41
+ if (meta.type === "decimal" && !(Number.isInteger(meta.places) && meta.places >= 0)) {
42
+ problems.push(`${where}: a decimal of ${String(meta.places)} places is no decimal: places is a whole number of at least 0`);
43
+ }
44
+ const json = ctx.place === "a payload" ? jsonShape(value) : undefined;
45
+ const solidity = ctx.chain ? chainField(value, meta, input.visibility, where, problems) : undefined;
46
+ return { value: meta, ...(value.optional === true ? { optional: true } : {}), ...(ctx.place === "a thing's field" && isNullable(value) ? { nullable: true } : {}), ...(json === undefined ? {} : { json }), ...(solidity === undefined ? {} : { solidity }), ...(named ? { named } : {}), ...(ref ? { ref } : {}), ...(input.description === undefined ? {} : { description: input.description }), ...(visibility ? { visibility } : {}), ...(issued ? { issued: true } : {}) };
47
+ };
48
+ const fieldsModel = (fields, where, ctx) => Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, fieldModel(f, `${where} field ${k}`, ctx)]));
49
+ return { fieldModel, fieldsModel };
50
+ };
@@ -0,0 +1,3 @@
1
+ import type { Operation } from "orthograph";
2
+ /** One problem per event field nothing can fill, for this operation's move. */
3
+ export declare const unfillable: (op: Operation, name: string, thing: string, event: string, eventsFile: string) => ReadonlyArray<string>;
@@ -0,0 +1,9 @@
1
+ /** One problem per event field nothing can fill, for this operation's move. */
2
+ export const unfillable = (op, name, thing, event, eventsFile) => {
3
+ if (!op.move)
4
+ return [];
5
+ const supplied = new Set([...Object.keys(op.thing.fields), ...Object.keys(op.payload), ...Object.keys(op.answer)]);
6
+ return Object.keys(op.move.emits.fields)
7
+ .filter((field) => !supplied.has(field))
8
+ .map((field) => `${eventsFile}: ${event}.${field} is in none of ${thing}'s fields, ${name}'s payload or its answer, so nothing can fill it`);
9
+ };