@crubal/engine 0.0.0-stage → 0.4.0

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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +97 -2
  3. package/dist/bin/crubal.d.ts +2 -0
  4. package/dist/bin/crubal.js +103 -0
  5. package/dist/bin/crubal.js.map +1 -0
  6. package/dist/src/access.d.ts +149 -0
  7. package/dist/src/access.js +584 -0
  8. package/dist/src/access.js.map +1 -0
  9. package/dist/src/acts.d.ts +531 -0
  10. package/dist/src/acts.js +1466 -0
  11. package/dist/src/acts.js.map +1 -0
  12. package/dist/src/address.d.ts +29 -0
  13. package/dist/src/address.js +59 -0
  14. package/dist/src/address.js.map +1 -0
  15. package/dist/src/arrival.d.ts +55 -0
  16. package/dist/src/arrival.js +127 -0
  17. package/dist/src/arrival.js.map +1 -0
  18. package/dist/src/browser.d.ts +10 -0
  19. package/dist/src/browser.js +13 -0
  20. package/dist/src/browser.js.map +1 -0
  21. package/dist/src/bundle.d.ts +74 -0
  22. package/dist/src/bundle.js +1108 -0
  23. package/dist/src/bundle.js.map +1 -0
  24. package/dist/src/canonical.d.ts +6 -0
  25. package/dist/src/canonical.js +47 -0
  26. package/dist/src/canonical.js.map +1 -0
  27. package/dist/src/carriers.d.ts +7 -0
  28. package/dist/src/carriers.js +33 -0
  29. package/dist/src/carriers.js.map +1 -0
  30. package/dist/src/conditions.d.ts +28 -0
  31. package/dist/src/conditions.js +227 -0
  32. package/dist/src/conditions.js.map +1 -0
  33. package/dist/src/corpus.d.ts +8 -0
  34. package/dist/src/corpus.js +1207 -0
  35. package/dist/src/corpus.js.map +1 -0
  36. package/dist/src/defs.d.ts +174 -0
  37. package/dist/src/defs.js +690 -0
  38. package/dist/src/defs.js.map +1 -0
  39. package/dist/src/dictionary.d.ts +77 -0
  40. package/dist/src/dictionary.js +629 -0
  41. package/dist/src/dictionary.js.map +1 -0
  42. package/dist/src/exchange.d.ts +259 -0
  43. package/dist/src/exchange.js +1088 -0
  44. package/dist/src/exchange.js.map +1 -0
  45. package/dist/src/forms.d.ts +16 -0
  46. package/dist/src/forms.js +181 -0
  47. package/dist/src/forms.js.map +1 -0
  48. package/dist/src/index.d.ts +32 -0
  49. package/dist/src/index.js +34 -0
  50. package/dist/src/index.js.map +1 -0
  51. package/dist/src/lex.d.ts +21 -0
  52. package/dist/src/lex.js +142 -0
  53. package/dist/src/lex.js.map +1 -0
  54. package/dist/src/lifecycle.d.ts +92 -0
  55. package/dist/src/lifecycle.js +451 -0
  56. package/dist/src/lifecycle.js.map +1 -0
  57. package/dist/src/log.d.ts +91 -0
  58. package/dist/src/log.js +629 -0
  59. package/dist/src/log.js.map +1 -0
  60. package/dist/src/migrate.d.ts +129 -0
  61. package/dist/src/migrate.js +415 -0
  62. package/dist/src/migrate.js.map +1 -0
  63. package/dist/src/model.d.ts +81 -0
  64. package/dist/src/model.js +188 -0
  65. package/dist/src/model.js.map +1 -0
  66. package/dist/src/packages.d.ts +372 -0
  67. package/dist/src/packages.js +1158 -0
  68. package/dist/src/packages.js.map +1 -0
  69. package/dist/src/print-text.d.ts +7 -0
  70. package/dist/src/print-text.js +223 -0
  71. package/dist/src/print-text.js.map +1 -0
  72. package/dist/src/publish.d.ts +27 -0
  73. package/dist/src/publish.js +279 -0
  74. package/dist/src/publish.js.map +1 -0
  75. package/dist/src/read-text.d.ts +10 -0
  76. package/dist/src/read-text.js +400 -0
  77. package/dist/src/read-text.js.map +1 -0
  78. package/dist/src/records.d.ts +32 -0
  79. package/dist/src/records.js +104 -0
  80. package/dist/src/records.js.map +1 -0
  81. package/dist/src/review.d.ts +22 -0
  82. package/dist/src/review.js +198 -0
  83. package/dist/src/review.js.map +1 -0
  84. package/dist/src/rules.d.ts +101 -0
  85. package/dist/src/rules.js +670 -0
  86. package/dist/src/rules.js.map +1 -0
  87. package/dist/src/schedule.d.ts +24 -0
  88. package/dist/src/schedule.js +126 -0
  89. package/dist/src/schedule.js.map +1 -0
  90. package/dist/src/std-packages.d.ts +9 -0
  91. package/dist/src/std-packages.js +268 -0
  92. package/dist/src/std-packages.js.map +1 -0
  93. package/dist/src/store.d.ts +191 -0
  94. package/dist/src/store.js +671 -0
  95. package/dist/src/store.js.map +1 -0
  96. package/dist/src/surface.d.ts +47 -0
  97. package/dist/src/surface.js +92 -0
  98. package/dist/src/surface.js.map +1 -0
  99. package/dist/src/tree.d.ts +35 -0
  100. package/dist/src/tree.js +159 -0
  101. package/dist/src/tree.js.map +1 -0
  102. package/dist/src/units-table.d.ts +1 -0
  103. package/dist/src/units-table.js +200 -0
  104. package/dist/src/units-table.js.map +1 -0
  105. package/dist/src/units.d.ts +42 -0
  106. package/dist/src/units.js +98 -0
  107. package/dist/src/units.js.map +1 -0
  108. package/dist/src/versions.d.ts +10 -0
  109. package/dist/src/versions.js +27 -0
  110. package/dist/src/versions.js.map +1 -0
  111. package/dist/src/views.d.ts +372 -0
  112. package/dist/src/views.js +1170 -0
  113. package/dist/src/views.js.map +1 -0
  114. package/package.json +60 -4
@@ -0,0 +1,1108 @@
1
+ // bundle.ts: a package as one JSON document (docs/design/publishing.md; spec 4.6, 5.9, 6.10, 7.9, 10.6,
2
+ // 11.6, 12.7, 14.11). Writers turn what the text readers produced into the JSON forms; the printer turns
3
+ // the JSON forms back into the text form, so the text readers stay the one parser and a bundle is read by
4
+ // printing it and reading the text. The hash is over the canonical form without `hash` and `sig`; the
5
+ // signature is Ed25519 over the hash's bytes, as a log entry's is (8.5).
6
+ import { readInstructionBlocks } from "./lifecycle.js";
7
+ import { createPrivateKey, createPublicKey, sign as edSign, verify as edVerify } from "node:crypto";
8
+ import { readAccess } from "./access.js";
9
+ import { serialize } from "./canonical.js";
10
+ import { emptyDictionary, readDefinitions } from "./defs.js";
11
+ import { facetJson } from "./dictionary.js";
12
+ import { readRecipes } from "./migrate.js";
13
+ import { readPackages } from "./packages.js";
14
+ import { actJson, actText, whenJson, whenText } from "./acts.js";
15
+ import { readRules } from "./rules.js";
16
+ import { readContracts, sha256, keyFor } from "./store.js";
17
+ import { emptyViewSet, readViews, VIEW_SET_KEYS } from "./views.js";
18
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ /** Read a package's text with every reader. */
20
+ export function parsePackage(source) {
21
+ const [info] = readPackages(source);
22
+ if (!info)
23
+ throw new Error("no package header");
24
+ const dict = readDefinitions(source);
25
+ const { perms, edges } = readAccess(source);
26
+ return { info, dict, rules: readRules(source), contracts: readContracts(source), views: readViews(source), perms, edges, recipes: readRecipes(source), instructions: readInstructionBlocks(source) };
27
+ }
28
+ // ─── Writers: the JSON forms ─────────────────────────────────────────────────
29
+ const PRECISION_CODE = { year: "y", month: "ym", day: "ymd", hour: "ymdh", minute: "ymdhm", second: "ymdhms", any: "any" };
30
+ export function kindJson(dict, k) {
31
+ const o = { kind: k.name, levels: [...k.levels] };
32
+ if (k.base)
33
+ o.base = k.base;
34
+ if (k.schema)
35
+ o.schema = k.schema;
36
+ const vary = {};
37
+ for (const level of k.levels) {
38
+ const keys = dict.vary.get(level);
39
+ if (keys?.size)
40
+ vary[level] = [...keys];
41
+ }
42
+ if (Object.keys(vary).length)
43
+ o.vary = vary;
44
+ if (k.follows)
45
+ o.follows = { ...k.follows };
46
+ if (k.follow)
47
+ o.follow = Object.fromEntries(Object.entries(k.follow).map(([l, a]) => [l, [...a]]));
48
+ if (k.shares && Object.keys(k.shares).length)
49
+ o.shares = { ...k.shares };
50
+ if (k.face && Object.keys(k.face).length)
51
+ o.face = { ...k.face };
52
+ const identify = {};
53
+ const match = {};
54
+ for (const level of k.levels) {
55
+ const i = dict.identify.get(level);
56
+ if (i?.length)
57
+ identify[level] = [...i];
58
+ const m = dict.match.get(level);
59
+ if (m?.length)
60
+ match[level] = m.map((g) => [...g]);
61
+ }
62
+ if (Object.keys(identify).length)
63
+ o.identify = identify;
64
+ if (Object.keys(match).length)
65
+ o.match = match;
66
+ const archive = dict.archive.get(k.name);
67
+ if (archive)
68
+ o.archive = archive;
69
+ return o;
70
+ }
71
+ export function classLineJson(l) {
72
+ const o = { facet: l.facet };
73
+ if (l.required)
74
+ o.required = true;
75
+ if (l.values)
76
+ o.values = [...l.values];
77
+ if (l.length !== undefined)
78
+ o.length = String(l.length);
79
+ if (l.pick !== undefined)
80
+ o.pick = l.pick;
81
+ if (l.range)
82
+ o.range = { min: l.range.min, max: l.range.max };
83
+ if (l.precision)
84
+ o.precision = l.precision;
85
+ if (l.level)
86
+ o.level = l.level;
87
+ if (l.when)
88
+ o.when = l.when;
89
+ if (l.frame)
90
+ o.frame = l.frame;
91
+ return o;
92
+ }
93
+ export function classJson(c) {
94
+ const o = { class: c.name };
95
+ if (c.label)
96
+ o.label = c.label;
97
+ if (c.describe)
98
+ o.describe = c.describe;
99
+ if (c.for.length)
100
+ o.for = [...c.for];
101
+ if (c.uses.length)
102
+ o.uses = [...c.uses];
103
+ const lines = [];
104
+ let section;
105
+ for (const l of c.lines) {
106
+ if (l.section !== section) {
107
+ section = l.section;
108
+ if (section)
109
+ lines.push({ section });
110
+ }
111
+ lines.push(classLineJson(l));
112
+ }
113
+ o.facets = lines;
114
+ if (c.parts.length)
115
+ o.parts = c.parts.map((p) => ({ slot: p.slot, wears: p.wears, pick: p.many ? "any" : "1", ...(p.fungible ? { fungible: true } : {}), ...(p.match ? { match: p.match } : {}) }));
116
+ if (c.state && c.state !== "active")
117
+ o.state = c.state;
118
+ if (c.version)
119
+ o.version = c.version;
120
+ for (const [k, v] of Object.entries(c.extra))
121
+ o[k] = v;
122
+ return o;
123
+ }
124
+ export function ruleJson(r) {
125
+ const o = { rule: r.name };
126
+ if (r.for !== "everywhere")
127
+ o.for = r.for;
128
+ if (r.whenText)
129
+ o.when = r.whenText;
130
+ o.then = r.thenText;
131
+ o.strength = r.strength;
132
+ if (r.because)
133
+ o.because = r.because;
134
+ if (r.version)
135
+ o.version = r.version;
136
+ return o;
137
+ }
138
+ const mapJson = (m) => ({
139
+ ...(m.from.startsWith('"') ? { literal: JSON.parse(m.from) } : { from: m.from }),
140
+ to: m.to,
141
+ ...(m.values.length ? { values: m.values.map(([from, to]) => ({ from, to })) } : {}),
142
+ });
143
+ export function contractJson(c) {
144
+ const o = { contract: c.name, kind: c.kind };
145
+ for (const k of ["label", "describe", "for"])
146
+ if (c.parts[k] !== undefined)
147
+ o[k] = c.parts[k];
148
+ if (c.needs.length)
149
+ o.needs = c.needs.map(classLineJson);
150
+ if (c.gives.length)
151
+ o.gives = [...c.gives];
152
+ if (Object.keys(c.terms).length)
153
+ o.terms = { ...c.terms };
154
+ if (c.stores.length)
155
+ o.stores = c.stores.map(mapJson);
156
+ else {
157
+ if (c.writes.length)
158
+ o.writes = c.writes.map(mapJson);
159
+ if (c.reads.length)
160
+ o.reads = c.reads.map(mapJson);
161
+ }
162
+ if (c.stream.length)
163
+ o.stream = [...c.stream];
164
+ for (const k of ["when", "who", "from", "to", "mode", "undo", "ref", "prefix"])
165
+ if (c[k])
166
+ o[k] = c[k];
167
+ // A form's role (7.7, revision 14) rides the bundle too, else an installed form reads as keep.
168
+ if (c.role)
169
+ o.role = c.role;
170
+ // origin is a part of the kinds that bring values in (7.2); the reader defaults it for the rest.
171
+ if (c.origin && ["receive", "form", "take"].includes(c.kind))
172
+ o.origin = c.origin;
173
+ if (c.lands !== "value")
174
+ o.lands = c.lands;
175
+ if (!c.absorb)
176
+ o.absorb = false;
177
+ if (c.ignore.length)
178
+ o.ignore = [...c.ignore];
179
+ if (c.keepRaw.length)
180
+ o["keep-raw"] = [...c.keepRaw];
181
+ for (const [k, v] of Object.entries(c.parts)) {
182
+ if (["label", "describe", "for", "needs", "gives", "terms", "writes", "reads", "stream", "when", "who", "from", "to", "mode", "undo", "ref", "origin", "prefix", "lands", "absorb", "ignore", "keep-raw", "kind", "role"].includes(k))
183
+ continue;
184
+ if (k === "retry") {
185
+ const m = v.match(/^(\d+)\s+every\s+(\S+)$/);
186
+ o.retry = m ? { times: m[1], every: m[2] } : v;
187
+ }
188
+ else
189
+ o[k] = v;
190
+ }
191
+ return o;
192
+ }
193
+ export function recipeJson(r) {
194
+ const steps = r.steps.map((s) => {
195
+ const o = { facet: s.facet };
196
+ switch (s.verb) {
197
+ case "rename":
198
+ case "precision":
199
+ case "retype":
200
+ o[s.verb] = { from: s.from, to: s.to };
201
+ break;
202
+ case "merge":
203
+ o.merge = { from: [...s.from], to: s.to };
204
+ break;
205
+ case "convert":
206
+ o.convert = { from: s.from, to: s.to, rounding: s.rounding };
207
+ break;
208
+ case "split":
209
+ o.split = { value: s.value, when: s.when.map((w) => ({ if: w.cond, to: w.to })), ...(s.else !== undefined ? { else: s.else } : {}) };
210
+ break;
211
+ case "move":
212
+ o.move = { to: s.to };
213
+ break;
214
+ case "hand":
215
+ o.hand = { to: s.to };
216
+ break;
217
+ case "review":
218
+ o.review = s.cond;
219
+ break;
220
+ case "recompute":
221
+ o.recompute = true;
222
+ break;
223
+ case "fill":
224
+ o.fill = { value: s.value, ...(s.level ? { level: s.level } : {}), ...(s.when ? { when: s.when } : {}) };
225
+ break;
226
+ case "parts":
227
+ // A step the bundle did not carry (0.3.15–0.3.22): the printed text lost it, and an install read the
228
+ // migration back with no steps, so the recipe never ran (Media Encyclopedia, 2026-10-27).
229
+ o.parts = { to: s.to, ...(s.when ? { when: s.when } : {}), map: s.map.map(([from, to]) => ({ from, to })) };
230
+ break;
231
+ }
232
+ return o;
233
+ });
234
+ return { migration: { from: r.from, to: r.to }, steps };
235
+ }
236
+ export function shapeJson(s) {
237
+ return { shape: s.name, slots: s.slots.map((sl) => ({ ...(sl.from.startsWith('"') ? { template: JSON.parse(sl.from) } : { from: sl.from }), to: sl.to, ...(sl.required ? { required: true } : {}) })) };
238
+ }
239
+ /** A display's JSON form (12.9): the layout family, the slot lines, the tokens as an object, the words. */
240
+ export function displayJson(d) {
241
+ return { display: d.name, ...(d.label ? { label: d.label } : {}), ...(d.describe ? { describe: d.describe } : {}), layout: d.layout, slots: d.slots.map((sl) => ({ from: sl.from, to: sl.to })), ...(d.tokens.size ? { tokens: Object.fromEntries(d.tokens) } : {}) };
242
+ }
243
+ /** A print's JSON form (12.12): what it prints, its inches, its fields and its elements as written. */
244
+ export function printJson(p) {
245
+ const box = (b) => ({ x: b.x, y: b.y, w: b.w, h: b.h });
246
+ return {
247
+ print: p.name,
248
+ ...(p.label ? { label: p.label } : {}),
249
+ ...(p.describe ? { describe: p.describe } : {}),
250
+ for: p.for,
251
+ inches: { w: p.inches.w, h: p.inches.h },
252
+ ...(p.stretch ? { stretch: true } : {}),
253
+ fields: p.fields.map((f) => ({ slot: f.slot, from: f.from })),
254
+ elements: p.elements.map((e) => {
255
+ if (e.type === "rect")
256
+ return { type: "rect", box: box(e.box), fill: e.fill, ...(e.stroke !== undefined ? { stroke: e.stroke } : {}) };
257
+ if (e.type === "barcode")
258
+ return { type: "barcode", box: box(e.box), field: e.field, ...(e.rotate ? { rotate: e.rotate } : {}), ...(e.text ? { text: true } : {}) };
259
+ if (e.type === "qr")
260
+ return { type: "qr", box: box(e.box), field: e.field, ...(e.gravity ? { gravity: e.gravity } : {}) };
261
+ if (e.type === "image")
262
+ return { type: "image", box: box(e.box), field: e.field };
263
+ return { type: "text", x: e.x, y: e.y, size: e.size, ...("field" in e.source ? { field: e.source.field } : { literal: e.source.literal }), ...(e.anchor ? { anchor: e.anchor } : {}), ...(e.weight ? { weight: e.weight } : {}), ...(e.clip ? { clip: box(e.clip) } : {}), ...(e.rotate ? { rotate: e.rotate } : {}), ...(e.lines ? { lines: e.lines } : {}) };
264
+ }),
265
+ };
266
+ }
267
+ export function filterJson(f) {
268
+ const o = { filter: f.name, facet: f.facet };
269
+ if (f.marked)
270
+ o.marked = true;
271
+ else if (f.buckets)
272
+ o.buckets = f.buckets.map((b) => (b.range ? { name: b.name, range: { min: String(b.range[0]), max: String(b.range[1]) } } : { name: b.name, values: [...(b.values ?? [])] }));
273
+ // Buckets by period and the facets summed per bucket (12.3) travel as `by` and `sum`.
274
+ if (f.period)
275
+ o.by = f.period;
276
+ if (f.sums.length)
277
+ o.sum = [...f.sums];
278
+ if (f.dependent.length)
279
+ o.dependent = [...f.dependent];
280
+ return o;
281
+ }
282
+ export function viewJson(v) {
283
+ const select = {};
284
+ if (v.level)
285
+ select.level = v.level;
286
+ if (v.wears.length)
287
+ select.wears = [...v.wears];
288
+ if (v.when)
289
+ select.when = v.when;
290
+ if (v.list)
291
+ select.list = v.list;
292
+ const o = { view: v.name, select };
293
+ if (v.partition)
294
+ o.partition = v.partition;
295
+ if (v.of)
296
+ o.of = v.of;
297
+ if (v.pin.length)
298
+ o.pin = [...v.pin];
299
+ if (v.hide.length)
300
+ o.hide = [...v.hide];
301
+ if (v.order.length)
302
+ o.order = v.order.map((x) => ({ key: x.key, dir: x.dir }));
303
+ if (v.page !== 24)
304
+ o.page = String(v.page);
305
+ o.shape = v.shapes.length === 1 ? v.shapes[0] : [...v.shapes];
306
+ if (v.filters.length)
307
+ o.filters = [...v.filters];
308
+ if (v.index.length)
309
+ o.index = [...v.index];
310
+ if (v.show !== "public")
311
+ o.show = v.show;
312
+ if (v.fresh !== "write")
313
+ o.fresh = v.fresh;
314
+ if (v.version)
315
+ o.version = v.version;
316
+ return o;
317
+ }
318
+ /** The `role:` blocks, from the presets and menu items the access reader made of them (12.4). */
319
+ export function rolesJson(perms) {
320
+ const out = [];
321
+ for (const p of perms.presets.values()) {
322
+ const own = p.items.filter((i) => i.startsWith(`${p.name}.`));
323
+ if (!own.length || own.length !== p.items.length)
324
+ continue;
325
+ const may = {};
326
+ for (const i of own) {
327
+ const item = perms.menu.get(i);
328
+ if (item)
329
+ for (const [verb, targets] of Object.entries(item.verbs))
330
+ may[verb] = [...targets];
331
+ }
332
+ out.push({ role: p.name, audience: p.audience, may });
333
+ }
334
+ return out;
335
+ }
336
+ export function permissionsJson(perms) {
337
+ const roleItems = new Set(rolesJson(perms).flatMap((r) => Object.keys(r.may).map((v) => `${r.role}.${v}`)));
338
+ const menu = {};
339
+ for (const m of perms.menu.values())
340
+ if (!roleItems.has(m.name))
341
+ menu[m.name] = { verbs: Object.fromEntries(Object.entries(m.verbs).map(([v, t]) => [v, [...t]])), ...(m.on ? { on: m.on } : {}) };
342
+ const presets = {};
343
+ for (const p of perms.presets.values())
344
+ if (!roleItems.has(`${p.name}.${Object.keys(perms.menu.get(p.items[0] ?? "")?.verbs ?? {})[0]}`) && !p.items.every((i) => roleItems.has(i)))
345
+ presets[p.name] = { items: [...p.items], audience: p.audience, ...(p.holds?.length ? { holds: [...p.holds] } : {}) };
346
+ const relations = {};
347
+ for (const [r, v] of perms.relations)
348
+ relations[r] = v.only ? { only: true } : {};
349
+ if (!perms.name && !Object.keys(menu).length && !Object.keys(relations).length)
350
+ return undefined;
351
+ return { permissions: perms.name ?? "", menu, presets, relations };
352
+ }
353
+ /** A utility block's JSON form (11.6). */
354
+ export function utilityJson(u) {
355
+ const o = { utility: u.name, version: u.version };
356
+ if (u.label)
357
+ o.label = u.label;
358
+ if (u.describe)
359
+ o.describe = u.describe;
360
+ if (u.group)
361
+ o.group = u.group;
362
+ if (u.owner)
363
+ o.owner = u.owner;
364
+ if (u.serves.length)
365
+ o.serves = u.serves.map((s) => ({ as: s.as, ...(s.items ? { items: [...s.items] } : {}) }));
366
+ if (u.needs.length)
367
+ o.needs = u.needs.map((n) => ({ name: n.name, ...(n.version ? { version: n.version } : {}) }));
368
+ if (u.setup.length)
369
+ o.setup = u.setup.map((s) => ("connection" in s ? { connection: s.connection } : { setting: s.setting }));
370
+ if (u.acts.length)
371
+ o.acts = u.acts.map((a) => a.name);
372
+ if (u.mark)
373
+ o.mark = { glyph: u.mark.glyph, hue: u.mark.hue };
374
+ return o;
375
+ }
376
+ const pressJson = (p) => ({ word: p.word, to: p.to, ...(p.glyph ? { glyph: p.glyph } : {}) });
377
+ /** A flow (12.11) in the bundle: as written, its stops as `{name, act?, of?}`, its done as `{filter, value}`. */
378
+ export function flowJson(f) {
379
+ const o = { flow: f.name, version: f.version };
380
+ if (f.label)
381
+ o.label = f.label;
382
+ if (f.utility)
383
+ o.utility = f.utility;
384
+ o.follow = f.follow;
385
+ if (f.serves.length)
386
+ o.serves = f.serves.map((x) => ({ as: x.as, ...(x.items ? { items: [...x.items] } : {}) }));
387
+ if (f.context.length)
388
+ o.context = [...f.context];
389
+ if (f.replaces)
390
+ o.replaces = f.replaces;
391
+ if (f.closed)
392
+ o.closed = { start: f.closed.start, finish: f.closed.finish, rest: f.closed.rest, ...(f.closed.cancel ? { cancel: f.closed.cancel } : {}) };
393
+ o.stops = f.stops.map((st) => ({ name: st.name, ...(st.act ? { act: st.act } : {}), ...(st.of ? { of: st.of } : {}), ...(st.with?.length ? { with: st.with.map((w) => ({ facet: w.facet, value: w.value })) } : {}), ...(st.already ? { already: st.already } : {}), ...(st.cases?.length ? { cases: st.cases.map(caseJson) } : {}), ...(st.asks?.length ? { asks: st.asks.map((q) => ({ name: q.name, ...(q.utility ? { utility: q.utility } : {}), act: q.act, when: whenJson(q.when), ...(q.open !== undefined ? { open: q.open } : {}), ...(q.words ? { words: q.words } : {}) })) } : {}), ...(st.offers?.length ? { offers: st.offers.map((o) => ({ ...(o.utility ? { utility: o.utility } : {}), act: o.act })) } : {}) }));
394
+ if (f.done)
395
+ o.done = { filter: f.done.filter, value: f.done.value, ...(f.done.mark ? { mark: true } : {}) };
396
+ return o;
397
+ }
398
+ /** A lane (12.10) in the bundle: as written, its presses as `{word, to}`, its picks as `{filter, value}`. */
399
+ export function laneJson(s) {
400
+ const o = { lane: s.name, version: s.version };
401
+ if (s.label)
402
+ o.label = s.label;
403
+ if (s.describe)
404
+ o.describe = s.describe;
405
+ if (s.about)
406
+ o.about = s.about;
407
+ if (s.sort)
408
+ o.sort = s.sort;
409
+ if (s.owner)
410
+ o.owner = s.owner;
411
+ if (s.utility)
412
+ o.utility = s.utility;
413
+ if (s.view)
414
+ o.view = s.view;
415
+ if (s.serve)
416
+ o.serve = s.serve;
417
+ // A step lane (revision 34) travels as its step and its untils; its picks are the step's two buckets, never written.
418
+ if (s.step)
419
+ o.step = s.step;
420
+ if (s.until?.length)
421
+ o.until = [...s.until];
422
+ if (s.after?.length)
423
+ o.after = [...s.after];
424
+ if (s.pick && !s.step)
425
+ o.pick = { filter: s.pick.filter, value: s.pick.value };
426
+ if (s.done && !s.step)
427
+ o.done = s.done === "viewed" ? "viewed" : { filter: s.done.filter, value: s.done.value };
428
+ if (s.group)
429
+ o.group = s.group;
430
+ o.band = s.band;
431
+ o.house = String(s.house);
432
+ if (s.serves.length)
433
+ o.serves = s.serves.map((x) => ({ as: x.as, ...(x.items ? { items: [...x.items] } : {}) }));
434
+ const home = {};
435
+ if (s.home.figure)
436
+ home.figure = s.home.figure.of === "count" ? "count" : `${s.home.figure.of} ${s.home.figure.slot}`;
437
+ if (s.home.word)
438
+ home.word = "one" in s.home.word ? { one: s.home.word.one, many: s.home.word.many } : s.home.word.word;
439
+ if (s.home.press)
440
+ home.press = pressJson(s.home.press);
441
+ if (s.home.chips.length)
442
+ home.chips = [...s.home.chips];
443
+ o.home = home;
444
+ if (s.card) {
445
+ const c = { name: [...s.card.name] };
446
+ if (s.card.sub.length)
447
+ c.sub = [...s.card.sub];
448
+ if (s.card.lines.length)
449
+ c.lines = [...s.card.lines];
450
+ if (s.card.state)
451
+ c.state = s.card.state;
452
+ if (s.card.moment)
453
+ c.moment = s.card.moment;
454
+ if (s.card.figure)
455
+ c.figure = s.card.figure;
456
+ if (s.card.primary)
457
+ c.primary = pressJson(s.card.primary);
458
+ if (s.card.quiet)
459
+ c.quiet = pressJson(s.card.quiet);
460
+ if (s.card.quick.length)
461
+ c.quick = s.card.quick.map(pressJson);
462
+ c.opens = s.card.opens;
463
+ if (s.card.face)
464
+ c.face = s.card.face;
465
+ o.card = c;
466
+ }
467
+ return o;
468
+ }
469
+ /** The whole package as the JSON document, without `hash` and `sig`. */
470
+ export function bundleOf(p) {
471
+ const { info, dict } = p;
472
+ const o = { crubal: String(info.crubal), package: info.name, version: info.version, owner: info.owner, id: `${info.owner}/${info.name}` };
473
+ for (const k of ["label", "describe", "licence"])
474
+ if (info.header[k])
475
+ o[k] = info.header[k];
476
+ if (info.extends.length)
477
+ o.extends = info.extends.map((e) => ({ package: e.name, version: e.version }));
478
+ if (info.prefixes.size)
479
+ o.prefixes = Object.fromEntries([...info.prefixes].map(([k, v]) => [k, v.target]));
480
+ if (info.header.units) {
481
+ const [pkg = "", ver = ""] = info.header.units.split(/\s+\//).map((s) => s.trim());
482
+ o.units = { package: pkg, version: ver };
483
+ }
484
+ for (const k of ["confirm", "split", "recur"])
485
+ if (info.header[k])
486
+ o[k] = info.header[k];
487
+ if (dict.trust.length)
488
+ o.trust = [...dict.trust];
489
+ if (dict.facetTrust.size)
490
+ o["facet-trust"] = Object.fromEntries([...dict.facetTrust].map(([k, v]) => [k, [...v]]));
491
+ if (Object.keys(info.terms).length)
492
+ o.terms = { ...info.terms };
493
+ const members = {};
494
+ const facets = [...dict.facets.values()].filter((f) => !f.key.includes(":") || info.name === "core");
495
+ for (const f of facets)
496
+ if (f.version)
497
+ members[`facet:${f.key}`] = f.version;
498
+ for (const c of dict.classes.values())
499
+ if (c.version)
500
+ members[`class:${c.name}`] = c.version;
501
+ for (const r of p.rules)
502
+ if (r.version)
503
+ members[`rule:${r.name}`] = r.version;
504
+ for (const c of p.contracts)
505
+ if (c.parts.version)
506
+ members[`contract:${c.name}`] = c.parts.version;
507
+ for (const v of p.views.views.values())
508
+ if (v.version)
509
+ members[`view:${v.name}`] = v.version;
510
+ for (const u of info.utilities)
511
+ if (u.version)
512
+ members[`utility:${u.name}`] = u.version;
513
+ for (const s of info.lanes)
514
+ if (s.version)
515
+ members[`lane:${s.name}`] = s.version;
516
+ for (const f of info.flows)
517
+ if (f.version)
518
+ members[`flow:${f.name}`] = f.version;
519
+ for (const a of info.acts)
520
+ if (a.version)
521
+ members[`act:${a.name}`] = a.version;
522
+ o.members = members;
523
+ if (dict.kinds.size)
524
+ o.kinds = [...dict.kinds.values()].map((k) => kindJson(dict, k));
525
+ if (facets.length)
526
+ o.facets = facets.map(facetJson);
527
+ if (dict.classes.size)
528
+ o.classes = [...dict.classes.values()].map(classJson);
529
+ if (p.rules.length)
530
+ o.rules = p.rules.map(ruleJson);
531
+ if (p.contracts.length)
532
+ o.contracts = p.contracts.map(contractJson);
533
+ if (p.views.shapes.size)
534
+ o.shapes = [...p.views.shapes.values()].map(shapeJson);
535
+ if (p.views.displays.size)
536
+ o.displays = [...p.views.displays.values()].map(displayJson);
537
+ if (p.views.prints.size)
538
+ o.prints = [...p.views.prints.values()].map(printJson);
539
+ if (p.views.filters.size)
540
+ o.filters = [...p.views.filters.values()].map(filterJson);
541
+ if (p.views.views.size)
542
+ o.views = [...p.views.views.values()].map(viewJson);
543
+ const roles = rolesJson(p.perms);
544
+ if (roles.length)
545
+ o.roles = roles;
546
+ const perms = permissionsJson(p.perms);
547
+ if (perms)
548
+ o.permissions = perms;
549
+ if (p.perms.ownership.size)
550
+ o.ownership = Object.fromEntries([...p.perms.ownership].map(([k, v]) => [k, [...v]]));
551
+ if (p.perms.emergency)
552
+ o.emergency = { approvers: String(p.perms.emergency.approvers), longest: p.perms.emergency.longest };
553
+ if (p.recipes.length)
554
+ o.recipes = p.recipes.map(recipeJson);
555
+ if (p.instructions.size)
556
+ o.instructions = [...p.instructions].map(([issuer, list]) => ({ issuer, instructions: list.map((i) => ({ n: i.n, op: i.op, key: i.key, ...(i.to ? { to: i.to } : {}), ...(i.map.length ? { map: i.map.map(([a, b]) => ({ from: a, to: b })) } : {}) })) }));
557
+ if (info.groups.length)
558
+ o.groups = info.groups.map((g) => ({ group: g.name, ...(g.label ? { label: g.label } : {}), ...(g.owner ? { owner: g.owner } : {}), ...(g.order !== undefined ? { order: String(g.order) } : {}) }));
559
+ if (info.utilities.length)
560
+ o.utilities = info.utilities.map(utilityJson);
561
+ if (info.lanes.length)
562
+ o.lanes = info.lanes.map(laneJson);
563
+ if (info.flows.length)
564
+ o.flows = info.flows.map(flowJson);
565
+ if (info.acts.length)
566
+ o.acts = info.acts.map(actJson);
567
+ return o;
568
+ }
569
+ // ─── Printer: the JSON forms back to the text form ───────────────────────────
570
+ /** Quote a value when the text form would otherwise misread it (2.5). */
571
+ export function q(s) {
572
+ if (s === "" || /^[&_\-\["{]|^\.\.\.$/.test(s) || /, |: | \/\/|[\n\r\t]/.test(s) || /^\s|\s$/.test(s) || /^-?\d/.test(s) && false)
573
+ return JSON.stringify(s);
574
+ return s;
575
+ }
576
+ const list = (xs) => (xs ?? []).map((x) => q(String(x))).join(", ");
577
+ const str = (v) => (v === undefined ? undefined : typeof v === "string" ? v : String(v));
578
+ function facetText(f, depth) {
579
+ const pad = " ".repeat(depth);
580
+ const out = [`${pad}facet: ${f.facet}`];
581
+ const line = (k, v) => { if (v !== undefined)
582
+ out.push(`${pad} ${k}: ${v}`); };
583
+ line("type", str(f.type));
584
+ for (const k of ["label", "ask", "describe"])
585
+ if (typeof f[k] === "string")
586
+ line(k, q(f[k]));
587
+ line("pick", str(f.pick));
588
+ if (f.ordered === true)
589
+ line("ordered", "yes");
590
+ line("state", str(f.state));
591
+ if (Array.isArray(f.qualifiers))
592
+ line("qualifiers", list(f.qualifiers));
593
+ if (Array.isArray(f.aliases))
594
+ line("aliases", list(f.aliases));
595
+ if (Array.isArray(f["same-as"]))
596
+ line("same-as", list(f["same-as"]));
597
+ line("agree-by", str(f["agree-by"]));
598
+ line("length", str(f.length));
599
+ line("unit", str(f.unit));
600
+ if (Array.isArray(f.accepts))
601
+ line("accepts", list(f.accepts));
602
+ if (isObj(f.range))
603
+ line("range", `${f.range.min}..${f.range.max}${f.range.step ? ` step ${f.range.step}` : ""}`);
604
+ line("places", str(f.places));
605
+ line("precision", str(f.precision));
606
+ line("zone", str(f.zone));
607
+ if (Array.isArray(f.words))
608
+ line("words", list(f.words));
609
+ if (Array.isArray(f.values)) {
610
+ const vals = f.values.map((v) => (isObj(v) ? [q(String(v.value)), ...(v.aliases ?? []).map((a) => `~${q(a)}`)].join(" ") : q(String(v))));
611
+ if (f.open === true)
612
+ vals.push("...");
613
+ line("values", vals.join(", "));
614
+ }
615
+ for (const k of ["fixed", "ranked", "scored", "required", "na", "unique", "transitions"])
616
+ if (f[k] === true)
617
+ line(k, "yes");
618
+ line("to", str(f.to));
619
+ if (Array.isArray(f.facets)) {
620
+ out.push(`${pad} facets:`);
621
+ for (const c of f.facets)
622
+ if (isObj(c))
623
+ out.push(...facetText(c, depth + 2));
624
+ }
625
+ line("identity", str(f.identity));
626
+ if (typeof f.when === "string")
627
+ line("when", f.when);
628
+ line("combine", str(f.combine));
629
+ line("version", str(f.version));
630
+ for (const [k, v] of Object.entries(f))
631
+ if (k.includes(":"))
632
+ line(k, str(v));
633
+ return out;
634
+ }
635
+ /** A class line's text from its settings (5.3), the shorthand marks in their order (4.5). */
636
+ export function lineText(l, type) {
637
+ let s = `${l.required === true ? "!" : ""}${l.level ? `${l.level}::` : ""}${l.facet}`;
638
+ if (Array.isArray(l.values))
639
+ s += `{${l.values.map((v) => q(String(v)).replace(/\|/g, "\\|")).join("|")}}`;
640
+ if (l.length !== undefined)
641
+ s += `$${l.length}`;
642
+ if (l.pick !== undefined)
643
+ s += l.pick === "any" ? "*" : `*${l.pick}`;
644
+ if (isObj(l.range))
645
+ s += ` ${l.range.min}..${l.range.max}`;
646
+ if (typeof l.precision === "string")
647
+ s += `@${type === "time" ? (l.precision === "second" ? "hms" : "hm") : (PRECISION_CODE[l.precision] ?? l.precision)}`;
648
+ if (typeof l.frame === "string")
649
+ s += ` frame: ${l.frame}`;
650
+ if (typeof l.when === "string")
651
+ s += ` when ${l.when}`;
652
+ return s;
653
+ }
654
+ const kv = (pad, k, v) => (v === undefined ? [] : [`${pad}${k}: ${Array.isArray(v) ? list(v) : q(String(v))}`]);
655
+ function kindText(k) {
656
+ const out = [`kind: ${k.kind}`, ...kv(" ", "levels", k.levels), ...kv(" ", "base", k.base)];
657
+ if (typeof k.schema === "string")
658
+ out.push(` schema: ${k.schema}`);
659
+ else if (isObj(k.schema))
660
+ out.push(" schema:", ...Object.entries(k.schema).map(([l, t]) => ` ${l}: ${t}`));
661
+ for (const block of ["vary", "identify"])
662
+ if (isObj(k[block]))
663
+ out.push(` ${block}:`, ...Object.entries(k[block]).map(([l, keys]) => ` ${l}: ${keys.join(", ")}`));
664
+ if (isObj(k.follows))
665
+ out.push(" follows:", ...Object.entries(k.follows).map(([a, b]) => ` ${a}: ${b}`));
666
+ if (isObj(k.follow))
667
+ out.push(" follow:", ...Object.entries(k.follow).map(([l, aspects]) => ` ${l}: ${aspects.join(", ")}`));
668
+ if (isObj(k.shares))
669
+ out.push(" shares:", ...Object.entries(k.shares).map(([l, facet]) => ` ${l}: ${facet}`));
670
+ if (isObj(k.face))
671
+ out.push(" face:", ...Object.entries(k.face).map(([l, face]) => ` ${l}: ${face}`));
672
+ if (isObj(k.match))
673
+ out.push(" match:", ...Object.entries(k.match).map(([l, groups]) => ` ${l}: ${groups.map((g) => g.join(" + ")).join("; ")}`));
674
+ out.push(...kv(" ", "archive", k.archive));
675
+ return out;
676
+ }
677
+ function classText(c) {
678
+ const out = [`class: ${c.class}`, ...kv(" ", "label", c.label), ...kv(" ", "describe", c.describe), ...kv(" ", "for", c.for), ...kv(" ", "uses", c.uses), ...kv(" ", "state", c.state), ...kv(" ", "version", c.version)];
679
+ // The class's prefixed settings (5.2), as a facet's travel (facetText).
680
+ for (const [k, v] of Object.entries(c))
681
+ if (k.includes(":"))
682
+ out.push(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`);
683
+ if (Array.isArray(c.facets)) {
684
+ out.push(" facets:");
685
+ for (const l of c.facets)
686
+ if (isObj(l))
687
+ out.push(typeof l.section === "string" ? ` section: ${q(l.section)}` : ` ${lineText(l)}`);
688
+ }
689
+ if (Array.isArray(c.parts)) {
690
+ out.push(" parts:");
691
+ for (const p of c.parts)
692
+ if (isObj(p))
693
+ out.push(` ${p.slot}: ${p.wears}${p.pick === "any" ? " *" : ""}${p.fungible === true ? " fungible: yes" : ""}${p.match ? ` match: ${p.match}` : ""}`);
694
+ }
695
+ return out;
696
+ }
697
+ const mapText = (m) => [` ${typeof m.literal === "string" ? JSON.stringify(m.literal) : m.from} -> ${m.to}`, ...(m.values ?? []).map((v) => ` ${q(String(v.from))} -> ${q(String(v.to))}`)];
698
+ function contractText(c) {
699
+ const out = [`contract: ${c.contract}`, ...kv(" ", "kind", c.kind)];
700
+ for (const k of ["label", "describe", "for"])
701
+ out.push(...kv(" ", k, c[k]));
702
+ if (Array.isArray(c.needs))
703
+ out.push(" needs:", ...c.needs.map((l) => ` ${lineText(l)}`));
704
+ for (const k of ["writes", "reads", "stores"])
705
+ if (Array.isArray(c[k]))
706
+ out.push(` ${k}:`, ...c[k].flatMap(mapText));
707
+ for (const k of ["role", "gives", "stream", "when", "who", "from", "to", "mode", "undo", "ref", "origin", "prefix", "lands", "ignore", "keep-raw"])
708
+ out.push(...kv(" ", k, c[k]));
709
+ if (isObj(c.terms) && Object.keys(c.terms).length) {
710
+ out.push(" terms:");
711
+ for (const [k, v] of Object.entries(c.terms))
712
+ out.push(` ${k}: ${String(v)}`);
713
+ }
714
+ if (c.absorb === false)
715
+ out.push(" absorb: no");
716
+ for (const [k, v] of Object.entries(c)) {
717
+ if (["contract", "kind", "label", "describe", "for", "needs", "writes", "reads", "stores", "gives", "terms", "stream", "when", "who", "from", "to", "mode", "undo", "ref", "origin", "prefix", "lands", "ignore", "keep-raw", "absorb", "role"].includes(k))
718
+ continue;
719
+ if (k === "retry" && isObj(v))
720
+ out.push(` retry: ${v.times} every ${v.every}`);
721
+ else
722
+ out.push(...kv(" ", k, v));
723
+ }
724
+ return out;
725
+ }
726
+ function ruleText(r) {
727
+ return [`rule: ${r.rule}`, ...kv(" ", "for", r.for), ...(typeof r.when === "string" ? [` when: ${r.when}`] : []), ` then: ${r.then}`, ...kv(" ", "strength", r.strength), ...kv(" ", "because", r.because), ...kv(" ", "version", r.version)];
728
+ }
729
+ function instructionsText(b) {
730
+ const out = [`instructions: ${String(b.issuer)}`];
731
+ for (const i of b.instructions ?? []) {
732
+ out.push(` ${String(i.n)}: ${String(i.op)}${String(i.key)}${i.to ? ` -> ${String(i.to)}` : ""}`);
733
+ for (const m of i.map ?? [])
734
+ out.push(` ${q(String(m.from))} -> ${q(String(m.to))}`);
735
+ }
736
+ return out;
737
+ }
738
+ function recipeText(r) {
739
+ const m = r.migration;
740
+ const out = [`migration: ${m.from} -> ${m.to}`];
741
+ let facet;
742
+ for (const s of r.steps ?? []) {
743
+ if (s.facet !== facet) {
744
+ facet = String(s.facet);
745
+ out.push(` facet: ${facet}`);
746
+ }
747
+ for (const verb of ["rename", "precision", "retype"])
748
+ if (isObj(s[verb]))
749
+ out.push(` ${verb}: ${q(String(s[verb].from))} -> ${q(String(s[verb].to))}`);
750
+ if (isObj(s.merge))
751
+ out.push(` merge: ${list(s.merge.from)} -> ${q(String(s.merge.to))}`);
752
+ if (isObj(s.convert))
753
+ out.push(` convert: ${s.convert.from} -> ${s.convert.to}`, ...(s.convert.rounding && s.convert.rounding !== "nearest" ? [` rounding: ${s.convert.rounding}`] : []));
754
+ if (isObj(s.split))
755
+ out.push(` split: ${q(String(s.split.value))}`, ...(s.split.when ?? []).map((w) => ` when: ${w.if} -> ${q(String(w.to))}`), ...(s.split.else !== undefined ? [` else: ${q(String(s.split.else))}`] : []));
756
+ if (isObj(s.move))
757
+ out.push(` move: -> ${s.move.to}`);
758
+ if (isObj(s.hand))
759
+ out.push(` hand: -> ${s.hand.to}`);
760
+ if (typeof s.review === "string")
761
+ out.push(` review: ${s.review}`);
762
+ if (s.recompute === true)
763
+ out.push(" recompute");
764
+ if (isObj(s.fill))
765
+ out.push(` fill: ${q(String(s.fill.value))}`, ...(typeof s.fill.level === "string" ? [` for: ${s.fill.level}::`] : []), ...(typeof s.fill.when === "string" ? [` when: ${s.fill.when}`] : []));
766
+ if (isObj(s.parts))
767
+ out.push(` parts: -> ${s.parts.to}`, ...(typeof s.parts.when === "string" ? [` when: ${s.parts.when}`] : []), ...(s.parts.map ?? []).map((m) => ` ${m.from} -> ${m.to}`));
768
+ }
769
+ return out;
770
+ }
771
+ const shapeText = (s) => [`shape: ${s.shape}`, " slots:", ...(s.slots ?? []).map((sl) => ` ${sl.required === true ? "!" : ""}${typeof sl.template === "string" ? JSON.stringify(sl.template) : sl.from} -> ${sl.to}`)];
772
+ const printText = (p) => {
773
+ const b = (v) => (isObj(v) ? `${v.x} ${v.y} ${v.w} ${v.h}` : "0 0 1 1");
774
+ const el = (e) => {
775
+ if (e.type === "rect")
776
+ return `rect ${b(e.box)} fill ${String(e.fill ?? "white")}${e.stroke !== undefined ? ` stroke ${String(e.stroke)}` : ""}`;
777
+ if (e.type === "barcode")
778
+ return `barcode ${b(e.box)} ${String(e.field)}${e.rotate ? ` rotate ${String(e.rotate)}` : ""}${e.text === true ? " text" : ""}`;
779
+ if (e.type === "qr")
780
+ return `qr ${b(e.box)} ${String(e.field)}${e.gravity ? ` gravity ${String(e.gravity)}` : ""}`;
781
+ if (e.type === "image")
782
+ return `image ${b(e.box)} ${String(e.field)}`;
783
+ return `text ${String(e.x)} ${String(e.y)} ${String(e.size)} ${typeof e.literal === "string" ? JSON.stringify(e.literal) : String(e.field)}${e.anchor ? ` anchor ${String(e.anchor)}` : ""}${e.weight ? ` weight ${String(e.weight)}` : ""}${isObj(e.clip) ? ` clip ${b(e.clip)}` : ""}${e.rotate ? ` rotate ${String(e.rotate)}` : ""}${typeof e.lines === "number" ? ` lines ${String(e.lines)}` : ""}`;
784
+ };
785
+ const inches = isObj(p.inches) ? p.inches : {};
786
+ return [
787
+ `print: ${p.print}`,
788
+ ...(typeof p.label === "string" ? [` label: ${p.label}`] : []),
789
+ ...(typeof p.describe === "string" ? [` describe: ${p.describe}`] : []),
790
+ ` for: ${p.for}`,
791
+ ` inches: ${String(inches.w)} ${String(inches.h)}`,
792
+ ...(p.stretch === true ? [" stretch: yes"] : []),
793
+ ...(p.fields?.length ? [" fields:", ...p.fields.map((f) => ` ${f.slot} -> ${f.from}`)] : []),
794
+ ...(p.elements?.length ? [" elements:", ...p.elements.map((e) => ` ${el(e)}`)] : []),
795
+ ];
796
+ };
797
+ const displayText = (d) => [
798
+ `display: ${d.display}`,
799
+ ...(typeof d.label === "string" ? [` label: ${d.label}`] : []),
800
+ ...(typeof d.describe === "string" ? [` describe: ${d.describe}`] : []),
801
+ ` layout: ${d.layout}`,
802
+ ...(d.slots?.length ? [" slots:", ...d.slots.map((sl) => ` ${sl.from} -> ${sl.to}`)] : []),
803
+ ...(isObj(d.tokens) && Object.keys(d.tokens).length ? [" tokens:", ...Object.entries(d.tokens).map(([k, v]) => ` ${k}: ${String(v)}`)] : []),
804
+ ];
805
+ function filterText(f) {
806
+ const out = [`filter: ${f.filter}`, ` facet: ${f.facet}`];
807
+ if (Array.isArray(f.buckets))
808
+ out.push(" buckets:", ...f.buckets.map((b) => { const bb = b; const name = /[\s:]/.test(String(bb.name)) ? JSON.stringify(bb.name) : String(bb.name); return isObj(bb.range) ? ` ${name}: ${bb.range.min}..${bb.range.max}` : ` ${name}: ${list(bb.values)}`; }));
809
+ else if (typeof f.by === "string")
810
+ out.push(` buckets: by ${f.by}`);
811
+ else if (f.marked === true)
812
+ out.push(" buckets: marked");
813
+ out.push(...kv(" ", "sum", f.sum));
814
+ out.push(...kv(" ", "dependent", f.dependent));
815
+ return out;
816
+ }
817
+ function viewText(v) {
818
+ const sel = (v.select ?? {});
819
+ const out = [`view: ${v.view}`, " select:", ...kv(" ", "level", sel.level), ...kv(" ", "wears", sel.wears), ...(typeof sel.when === "string" ? [` when: ${sel.when}`] : []), ...kv(" ", "list", sel.list)];
820
+ if (!Object.keys(sel).length)
821
+ out.pop();
822
+ out.push(...kv(" ", "partition", v.partition), ...(typeof v.of === "string" ? [` of: ${v.of}`] : []), ...kv(" ", "pin", v.pin), ...kv(" ", "hide", v.hide));
823
+ if (Array.isArray(v.order))
824
+ out.push(` order: ${v.order.map((o) => `${o.key} ${o.dir}`).join(", ")}`);
825
+ out.push(...kv(" ", "page", v.page), ...kv(" ", "shape", v.shape), ...kv(" ", "filters", v.filters), ...kv(" ", "index", v.index), ...kv(" ", "show", v.show), ...kv(" ", "fresh", v.fresh), ...kv(" ", "version", v.version));
826
+ return out;
827
+ }
828
+ const roleText = (r) => [`role: ${r.role}`, ` audience: ${r.audience}`, " may:", ...Object.entries(r.may ?? {}).map(([verb, t]) => ` ${verb}: ${t.join(", ")}`)];
829
+ function permissionsText(p) {
830
+ const out = [`permissions: ${p.permissions}`];
831
+ const menu = (p.menu ?? {});
832
+ if (Object.keys(menu).length)
833
+ out.push(" menu:", ...Object.entries(menu).map(([name, item]) => { const it = item; const verbs = Object.entries(it.verbs ?? {}).map(([v, t]) => `${v} ${t.join(" ")}`).join(", "); return ` ${name}: ${verbs}${it.on ? ` on: ${it.on}` : ""}`; }));
834
+ const presets = (p.presets ?? {});
835
+ if (Object.keys(presets).length)
836
+ out.push(" presets:", ...Object.entries(presets).map(([name, pr]) => ` ${name}: ${pr.items.join(", ")} audience: ${pr.audience}${Array.isArray(pr.holds) && pr.holds.length ? ` holds: ${pr.holds.join(", ")}` : ""}`));
837
+ const rel = (p.relations ?? {});
838
+ if (Object.keys(rel).length)
839
+ out.push(` relations: ${Object.entries(rel).map(([r, v]) => (v.only === true ? `${r} only` : r)).join(", ")}`);
840
+ return out;
841
+ }
842
+ /** The text form of a bundle: the package header, then every member, in the long form. */
843
+ export function printBundle(b) {
844
+ const out = [`package: ${b.package} /${b.version}`];
845
+ out.push(...kv(" ", "owner", b.owner), ...kv(" ", "label", b.label), ...kv(" ", "describe", b.describe), ` crubal: ${b.crubal ?? "2"}`, ...kv(" ", "licence", b.licence));
846
+ if (Array.isArray(b.extends))
847
+ out.push(` extends: ${b.extends.map((e) => `${e.package} /${e.version}`).join(", ")}`);
848
+ if (isObj(b.prefixes))
849
+ out.push(" prefixes:", ...Object.entries(b.prefixes).map(([k, v]) => ` ${k}: ${v}`));
850
+ if (isObj(b.units))
851
+ out.push(` units: ${b.units.package} /${b.units.version}`);
852
+ for (const k of ["confirm", "split", "recur"])
853
+ out.push(...kv(" ", k, b[k]));
854
+ if (isObj(b.terms))
855
+ out.push(" terms:", ...Object.entries(b.terms).map(([a, t]) => ` ${a}: ${t}`));
856
+ out.push("");
857
+ if (Array.isArray(b.trust))
858
+ out.push("trust:", ...b.trust.map((t) => ` ${t}`), "");
859
+ if (isObj(b["facet-trust"]))
860
+ out.push("facet-trust:", ...Object.entries(b["facet-trust"]).map(([k, v]) => ` ${k}: ${v.join(", ")}`), "");
861
+ const blocks = (key, fn) => { for (const x of b[key] ?? [])
862
+ out.push(...fn(x), ""); };
863
+ blocks("kinds", kindText);
864
+ blocks("facets", (f) => facetText(f, 0));
865
+ blocks("classes", classText);
866
+ blocks("rules", ruleText);
867
+ blocks("contracts", contractText);
868
+ blocks("recipes", recipeText);
869
+ blocks("instructions", instructionsText);
870
+ blocks("shapes", shapeText);
871
+ blocks("displays", displayText);
872
+ blocks("prints", printText);
873
+ blocks("filters", filterText);
874
+ blocks("views", viewText);
875
+ blocks("roles", roleText);
876
+ if (isObj(b.permissions))
877
+ out.push(...permissionsText(b.permissions), "");
878
+ if (isObj(b.ownership))
879
+ out.push("ownership:", ...Object.entries(b.ownership).map(([k, v]) => ` ${k}: ${v.join(", ")}`), "");
880
+ if (isObj(b.emergency))
881
+ out.push("emergency:", ` approvers: ${b.emergency.approvers}`, ` longest: ${b.emergency.longest}`, "");
882
+ blocks("groups", (g) => [`group: ${g.group}`, ...kv(" ", "label", g.label), ...kv(" ", "owner", g.owner), ...kv(" ", "order", g.order)]);
883
+ blocks("utilities", utilityText);
884
+ blocks("lanes", laneText);
885
+ blocks("flows", flowText);
886
+ blocks("acts", actText);
887
+ return `${out.join("\n").trimEnd()}\n`;
888
+ }
889
+ const quoteWord = (w) => `"${w.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
890
+ const pressText = (p) => isObj(p) && typeof p.word === "string" && typeof p.to === "string"
891
+ ? `${/[:\s]/.test(p.word) ? quoteWord(p.word) : p.word}${typeof p.glyph === "string" ? ` as ${p.glyph}` : ""} -> ${p.to}`
892
+ : undefined;
893
+ const pickText = (p) => (isObj(p) ? (p.mark === true ? String(p.filter) : `${p.filter} = ${String(p.value)}`) : typeof p === "string" ? p : undefined);
894
+ const casePressJson = (p) => ({ word: p.word, runs: p.runs.map((r) => ({ act: r.act, ...(r.utility ? { utility: r.utility } : {}), ...(r.onFound ? { onFound: true } : {}) })) });
895
+ const caseJson = (c) => ({ kind: c.kind, ...(c.name ? { name: c.name } : {}), answer: c.answer, ...(c.when ? { when: { lane: c.when.lane, facet: c.when.facet } } : {}), yes: casePressJson(c.yes), no: casePressJson(c.no), ...(c.or.length ? { or: c.or.map(casePressJson) } : {}) });
896
+ const casePressText = (p) => {
897
+ const runs = (Array.isArray(p.runs) ? p.runs : []).map((r) => `${typeof r.utility === "string" ? `${r.utility}.` : ""}${r.act}${r.onFound === true ? " on found" : ""}`);
898
+ return `${p.word}${runs.length ? ` -> ${runs.join(", ")}` : ""}`;
899
+ };
900
+ /** The lines beneath a stop (12.11, revision 41): already, then each case with its presses. */
901
+ function stopCaseText(st) {
902
+ const out = [];
903
+ if (st.already === "ignore")
904
+ out.push(" already: ignore");
905
+ for (const c of Array.isArray(st.cases) ? st.cases : []) {
906
+ const when = isObj(c.when) ? ` when any ${c.when.lane} where ${c.when.facet} = record` : "";
907
+ out.push(` ${c.kind === "flag" ? `flag ${c.name}` : "stranger"}: ${c.answer}${when}`);
908
+ if (isObj(c.yes))
909
+ out.push(` yes: ${casePressText(c.yes)}`);
910
+ if (isObj(c.no))
911
+ out.push(` no: ${casePressText(c.no)}`);
912
+ for (const o of Array.isArray(c.or) ? c.or : [])
913
+ out.push(` or: ${casePressText(o)}`);
914
+ }
915
+ // Revision 48: the questions the link asks, and those it offers.
916
+ for (const q of Array.isArray(st.asks) ? st.asks : [])
917
+ out.push(` asks ${q.name}: ${typeof q.utility === "string" ? `${q.utility}.` : ""}${q.act} when ${isObj(q.when) ? whenText(q.when) : ""}${typeof q.open === "string" ? ` open ${q.open}` : ""}${typeof q.words === "string" ? ` "${q.words}"` : ""}`);
918
+ const offers = Array.isArray(st.offers) ? st.offers : [];
919
+ if (offers.length)
920
+ out.push(` offers: ${offers.map((o) => `${typeof o.utility === "string" ? `${o.utility}.` : ""}${o.act}`).join(", ")}`);
921
+ return out;
922
+ }
923
+ function flowText(f) {
924
+ const out = [`flow: ${f.flow} /${f.version}`, ...kv(" ", "label", f.label), ...kv(" ", "utility", f.utility), ...kv(" ", "follow", f.follow)];
925
+ if (Array.isArray(f.serves))
926
+ out.push(` serves: ${f.serves.map((x) => `${x.as}${Array.isArray(x.items) ? `(${x.items.join(", ")})` : ""}`).join(", ")}`);
927
+ if (Array.isArray(f.context) && f.context.length)
928
+ out.push(` context: ${f.context.join(", ")}`);
929
+ out.push(...kv(" ", "replaces", f.replaces));
930
+ if (f.closed && typeof f.closed === "object") {
931
+ const cl = f.closed;
932
+ out.push(` closed: ${cl.start} to ${cl.finish} over ${cl.rest}${typeof cl.cancel === "string" ? ` cancel ${cl.cancel}` : ""}`);
933
+ }
934
+ if (Array.isArray(f.stops)) {
935
+ out.push(" stops:");
936
+ for (const st of f.stops) {
937
+ out.push(` ${st.name}${typeof st.act === "string" ? ` -> ${st.act}` : ""}${typeof st.of === "string" ? ` of ${st.of}` : ""}${Array.isArray(st.with) && st.with.length ? ` with ${st.with.map((w) => `${w.facet} = ${w.value}`).join(", ")}` : ""}`);
938
+ out.push(...stopCaseText(st));
939
+ }
940
+ }
941
+ if (f.done !== undefined)
942
+ out.push(` done: ${pickText(f.done)}`);
943
+ return out;
944
+ }
945
+ function laneText(s) {
946
+ const out = [`lane: ${s.lane} /${s.version}`, ...kv(" ", "label", s.label), ...kv(" ", "describe", s.describe), ...kv(" ", "about", s.about), ...kv(" ", "sort", s.sort), ...kv(" ", "owner", s.owner), ...kv(" ", "utility", s.utility), ...kv(" ", "view", s.view), ...kv(" ", "serve", s.serve)];
947
+ if (typeof s.step === "string")
948
+ out.push(` step: ${s.step}`);
949
+ if (Array.isArray(s.until) && s.until.length)
950
+ out.push(` until: ${s.until.join(", ")}`);
951
+ if (Array.isArray(s.after) && s.after.length)
952
+ out.push(` after: ${s.after.join(", ")}`);
953
+ if (s.pick !== undefined)
954
+ out.push(` pick: ${pickText(s.pick)}`);
955
+ if (s.done !== undefined)
956
+ out.push(` done: ${pickText(s.done)}`);
957
+ out.push(...kv(" ", "group", s.group), ...kv(" ", "band", s.band), ...kv(" ", "house", s.house));
958
+ if (Array.isArray(s.serves))
959
+ out.push(` serves: ${s.serves.map((x) => `${x.as}${Array.isArray(x.items) ? `(${x.items.join(", ")})` : ""}`).join(", ")}`);
960
+ if (isObj(s.home)) {
961
+ const h = s.home;
962
+ out.push(" home:");
963
+ if (typeof h.figure === "string")
964
+ out.push(` figure: ${h.figure}`);
965
+ if (isObj(h.word))
966
+ out.push(` word: one ${quoteWord(String(h.word.one))} many ${quoteWord(String(h.word.many))}`);
967
+ else if (typeof h.word === "string")
968
+ out.push(` word: ${quoteWord(h.word)}`);
969
+ const pr = pressText(h.press);
970
+ if (pr)
971
+ out.push(` press: ${pr}`);
972
+ if (Array.isArray(h.chips) && h.chips.length)
973
+ out.push(` chips: ${h.chips.join(", ")}`);
974
+ }
975
+ if (isObj(s.card)) {
976
+ const c = s.card;
977
+ out.push(" card:");
978
+ for (const k of ["name", "sub", "lines"])
979
+ if (Array.isArray(c[k]) && c[k].length)
980
+ out.push(` ${k}: ${c[k].join(", ")}`);
981
+ for (const k of ["state", "moment", "figure"])
982
+ if (typeof c[k] === "string")
983
+ out.push(` ${k}: ${c[k]}`);
984
+ for (const k of ["primary", "quiet"]) {
985
+ const t = pressText(c[k]);
986
+ if (t)
987
+ out.push(` ${k}: ${t}`);
988
+ }
989
+ if (Array.isArray(c.quick))
990
+ for (const q of c.quick) {
991
+ const t = pressText(q);
992
+ if (t)
993
+ out.push(` quick: ${t}`);
994
+ }
995
+ if (typeof c.opens === "string")
996
+ out.push(` opens: ${c.opens}`);
997
+ if (typeof c.face === "string")
998
+ out.push(` face: ${c.face}`);
999
+ }
1000
+ return out;
1001
+ }
1002
+ function utilityText(u) {
1003
+ const out = [`utility: ${u.utility} /${u.version}`, ...kv(" ", "label", u.label), ...kv(" ", "describe", u.describe), ...kv(" ", "group", u.group), ...kv(" ", "owner", u.owner)];
1004
+ if (Array.isArray(u.serves))
1005
+ out.push(` serves: ${u.serves.map((s) => `${s.as}${Array.isArray(s.items) ? `(${s.items.join(", ")})` : ""}`).join(", ")}`);
1006
+ if (Array.isArray(u.needs))
1007
+ out.push(` needs: ${u.needs.map((n) => `${n.name}${n.version ? ` /${n.version}` : ""}`).join(", ")}`);
1008
+ if (Array.isArray(u.setup))
1009
+ out.push(` setup: ${u.setup.map((s) => (typeof s.connection === "string" ? `connection ${s.connection}` : `setting ${s.setting}`)).join(", ")}`);
1010
+ if (Array.isArray(u.acts) && u.acts.length)
1011
+ out.push(` acts: ${u.acts.join(", ")}`);
1012
+ if (u.mark && typeof u.mark === "object" && !Array.isArray(u.mark)) {
1013
+ const m = u.mark;
1014
+ if (typeof m.glyph === "string" && typeof m.hue === "string")
1015
+ out.push(` mark: ${m.glyph} ${m.hue}`);
1016
+ }
1017
+ return out;
1018
+ }
1019
+ /** Read a bundle: print it to text and read the text, so there is one parser. */
1020
+ export function readBundle(b) {
1021
+ const text = printBundle(b);
1022
+ return { ...parsePackage(text), text };
1023
+ }
1024
+ /** Read a bundle's definitions into a dictionary that already holds what the package extends. */
1025
+ export function readBundleInto(b, into = emptyDictionary()) {
1026
+ return readDefinitions(printBundle(b), into);
1027
+ }
1028
+ /** An empty Parsed to read packages onto, in order. */
1029
+ export function emptyParsed() {
1030
+ const { perms } = readAccess("");
1031
+ return { info: { name: "", version: "", owner: "", line: 0, crubal: 2, crubalLine: 0, extends: [], prefixes: new Map(), trust: [], dict: emptyDictionary(), contracts: [], header: {}, terms: {}, utilities: [], groups: [], lanes: [], flows: [], acts: [] }, dict: emptyDictionary(), rules: [], contracts: [], views: emptyViewSet(), perms, edges: [], recipes: [], instructions: new Map() };
1032
+ }
1033
+ /**
1034
+ * Read a bundle onto what is already read (the packages it extends, or the installed packages before the
1035
+ * owner's own definitions): the dictionary grows, and a member of the same name replaces the earlier one.
1036
+ */
1037
+ export function readBundleOnto(bundle, base) {
1038
+ const text = printBundle(bundle);
1039
+ readDefinitions(text, base.dict);
1040
+ const [info] = readPackages(text);
1041
+ if (info)
1042
+ base.info = { ...info, dict: base.dict, terms: Object.keys(info.terms).length ? info.terms : base.info.terms, utilities: [...base.info.utilities.filter((h) => !info.utilities.some((n) => n.name === h.name)), ...info.utilities], groups: [...base.info.groups.filter((h) => !info.groups.some((n) => n.name === h.name)), ...info.groups], lanes: [...base.info.lanes.filter((h) => !info.lanes.some((n) => n.name === h.name)), ...info.lanes], flows: [...base.info.flows.filter((h) => !info.flows.some((n) => n.name === h.name)), ...info.flows], acts: [...base.info.acts.filter((h) => !info.acts.some((n) => n.name === h.name)), ...info.acts] };
1043
+ const byName = (have, next) => [...have.filter((h) => !next.some((n) => n.name === h.name)), ...next];
1044
+ base.rules = byName(base.rules, readRules(text));
1045
+ base.contracts = byName(base.contracts, readContracts(text));
1046
+ const views = readViews(text);
1047
+ for (const k of VIEW_SET_KEYS)
1048
+ for (const [key, val] of views[k])
1049
+ base.views[k].set(key, val);
1050
+ const { perms, edges } = readAccess(text);
1051
+ if (perms.name)
1052
+ base.perms.name = perms.name;
1053
+ // A menu item named by more than one package (platform's `people`, every package's `people: grant …`) is
1054
+ // one item: a later package adds its verbs and targets to what stands, never replaces them. A preset of
1055
+ // the same name is replaced whole: it is one declaration, not an accumulation.
1056
+ for (const [k, v] of perms.menu) {
1057
+ const have = base.perms.menu.get(k);
1058
+ if (!have) {
1059
+ base.perms.menu.set(k, v);
1060
+ continue;
1061
+ }
1062
+ const verbs = { ...have.verbs };
1063
+ for (const [verb, targets] of Object.entries(v.verbs))
1064
+ verbs[verb] = [...new Set([...(verbs[verb] ?? []), ...targets])];
1065
+ base.perms.menu.set(k, { ...have, ...v, verbs });
1066
+ }
1067
+ for (const [k, v] of perms.presets)
1068
+ base.perms.presets.set(k, v);
1069
+ for (const [k, v] of perms.relations)
1070
+ base.perms.relations.set(k, v);
1071
+ for (const [k, v] of perms.ownership)
1072
+ base.perms.ownership.set(k, v);
1073
+ if (perms.emergency)
1074
+ base.perms.emergency = perms.emergency;
1075
+ base.edges.push(...edges);
1076
+ base.recipes.push(...readRecipes(text));
1077
+ for (const [issuer, list] of readInstructionBlocks(text))
1078
+ base.instructions.set(issuer, [...(base.instructions.get(issuer) ?? []), ...list]);
1079
+ return base;
1080
+ }
1081
+ // ─── Hash, sign, verify ──────────────────────────────────────────────────────
1082
+ export function bundleHash(b) {
1083
+ const { hash: _h, sig: _s, ...rest } = b;
1084
+ return sha256(serialize(rest));
1085
+ }
1086
+ /** Sign a bundle with the owner's Ed25519 private key (the JWK `d`, base64url); sets `hash` and `sig`. */
1087
+ export function signBundle(b, privateD, publicX) {
1088
+ const hash = bundleHash(b);
1089
+ const key = createPrivateKey({ key: { kty: "OKP", crv: "Ed25519", x: publicX, d: privateD }, format: "jwk" });
1090
+ const sig = edSign(null, Buffer.from(hash, "hex"), key).toString("base64url");
1091
+ return { ...b, hash: `sha256:${hash}`, sig };
1092
+ }
1093
+ /** Check a bundle's hash and, with the owner's published key, its signature. */
1094
+ export function verifyBundle(b, keys) {
1095
+ const hash = bundleHash(b);
1096
+ if (b.hash !== `sha256:${hash}`)
1097
+ return { valid: false, reason: "hash" };
1098
+ const owner = String(b.owner ?? "");
1099
+ // The key in force when the version was published (11.7): a rotated key still verifies what it signed.
1100
+ const k = keys ? keyFor(keys, owner, typeof b.version === "string" ? b.version : undefined) : undefined;
1101
+ if (!k)
1102
+ return keys ? { valid: false, reason: "no key" } : { valid: true };
1103
+ if (k.alg !== "Ed25519" || typeof b.sig !== "string")
1104
+ return { valid: false, reason: "signature" };
1105
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: k.public }, format: "jwk" });
1106
+ return edVerify(null, Buffer.from(hash, "hex"), key, Buffer.from(b.sig, "base64url")) ? { valid: true } : { valid: false, reason: "signature" };
1107
+ }
1108
+ //# sourceMappingURL=bundle.js.map