@aitoroses/telar 0.0.0 → 0.1.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 (92) hide show
  1. package/README.md +453 -3
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1238 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +497 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/guide.d.ts +8 -0
  9. package/dist/guide.js +16 -0
  10. package/dist/install.d.ts +104 -0
  11. package/dist/install.js +402 -0
  12. package/dist/iso.d.ts +8 -0
  13. package/dist/iso.js +68 -0
  14. package/dist/node/build.d.ts +1 -0
  15. package/dist/node/build.js +34 -0
  16. package/dist/node/telar-module.d.ts +2 -0
  17. package/dist/node/telar-module.js +28 -0
  18. package/dist/observer.d.ts +47 -0
  19. package/dist/observer.js +53 -0
  20. package/dist/pieces.d.ts +230 -0
  21. package/dist/pieces.js +178 -0
  22. package/dist/powers.d.ts +46 -0
  23. package/dist/powers.js +126 -0
  24. package/dist/protocol.d.ts +212 -0
  25. package/dist/protocol.js +236 -0
  26. package/dist/query.d.ts +67 -0
  27. package/dist/query.js +102 -0
  28. package/dist/read.d.ts +37 -0
  29. package/dist/read.js +27 -0
  30. package/dist/runner.d.ts +112 -0
  31. package/dist/runner.js +134 -0
  32. package/dist/scenario/builder.d.ts +25 -0
  33. package/dist/scenario/builder.js +603 -0
  34. package/dist/scenario/templates.d.ts +35 -0
  35. package/dist/scenario/templates.js +64 -0
  36. package/dist/scenario/types.d.ts +441 -0
  37. package/dist/scenario/types.js +10 -0
  38. package/dist/scenario/validate.d.ts +7 -0
  39. package/dist/scenario/validate.js +19 -0
  40. package/dist/scenario.d.ts +4 -0
  41. package/dist/scenario.js +4 -0
  42. package/dist/schema.d.ts +219 -0
  43. package/dist/schema.js +221 -0
  44. package/dist/seating.d.ts +49 -0
  45. package/dist/seating.js +26 -0
  46. package/dist/send-hook.d.ts +46 -0
  47. package/dist/send-hook.js +123 -0
  48. package/dist/show.d.ts +34 -0
  49. package/dist/show.js +1 -0
  50. package/dist/source.d.ts +85 -0
  51. package/dist/source.js +104 -0
  52. package/dist/spec.d.ts +20 -0
  53. package/dist/spec.js +17 -0
  54. package/dist/standard-schema.d.ts +21 -0
  55. package/dist/standard-schema.js +1 -0
  56. package/dist/std/accuracy.d.ts +12 -0
  57. package/dist/std/accuracy.js +122 -0
  58. package/dist/std/ack.d.ts +14 -0
  59. package/dist/std/ack.js +43 -0
  60. package/dist/std/actions.d.ts +106 -0
  61. package/dist/std/actions.js +154 -0
  62. package/dist/std/brief.d.ts +36 -0
  63. package/dist/std/brief.js +78 -0
  64. package/dist/std/claude-code.d.ts +9 -0
  65. package/dist/std/claude-code.js +106 -0
  66. package/dist/std/compare.d.ts +29 -0
  67. package/dist/std/compare.js +36 -0
  68. package/dist/std/git-workspace.d.ts +44 -0
  69. package/dist/std/git-workspace.js +184 -0
  70. package/dist/std/judgment.d.ts +85 -0
  71. package/dist/std/judgment.js +462 -0
  72. package/dist/std/observe-command.d.ts +23 -0
  73. package/dist/std/observe-command.js +151 -0
  74. package/dist/std/observe-github-checks.d.ts +26 -0
  75. package/dist/std/observe-github-checks.js +299 -0
  76. package/dist/std/observe-http-status.d.ts +27 -0
  77. package/dist/std/observe-http-status.js +181 -0
  78. package/dist/std/plan.d.ts +7 -0
  79. package/dist/std/plan.js +28 -0
  80. package/dist/std/queries.d.ts +31 -0
  81. package/dist/std/queries.js +318 -0
  82. package/dist/std/reading.d.ts +17 -0
  83. package/dist/std/reading.js +88 -0
  84. package/dist/std/schedule.d.ts +19 -0
  85. package/dist/std/schedule.js +122 -0
  86. package/dist/std.d.ts +15 -0
  87. package/dist/std.js +15 -0
  88. package/dist/types.d.ts +366 -0
  89. package/dist/types.js +1 -0
  90. package/dist/values.d.ts +81 -0
  91. package/dist/values.js +129 -0
  92. package/package.json +62 -5
@@ -0,0 +1,1238 @@
1
+ import { isValidEvaluatorId } from "./evaluator.js";
2
+ import { isValidActionId } from "./pieces.js";
3
+ import { assertJsonValue, isArgRef, liftArg, readFieldTableMeta, } from "./values.js";
4
+ const ID_RE = /^[a-z][a-z0-9-]*$/;
5
+ const NS_ID_RE = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
6
+ const NS_OR_ID_RE = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)?$/;
7
+ const VALIDATOR_RE = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*\/[a-z][a-z0-9-]*\/[1-9][0-9]*$/;
8
+ const OBSERVER_RE = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*\/(?:[a-z][a-z0-9-]*\/)+[1-9][0-9]*$/;
9
+ const LOGIC_PREFIXES = new Set(["#", "/", "^", "!", ">", "&"]);
10
+ const THEN = "then";
11
+ function exhaustive(value) {
12
+ throw new Error(`Unexpected variant: ${String(value)}`);
13
+ }
14
+ export class SpecCompileError extends Error {
15
+ name = "SpecCompileError";
16
+ path;
17
+ constructor(path, message) {
18
+ super(path.length > 0 ? `${path}: ${message}` : message);
19
+ this.path = path;
20
+ }
21
+ }
22
+ export function installation(def) {
23
+ return Object.freeze({
24
+ kind: "installation",
25
+ name: def.name,
26
+ ...(def.profile !== undefined ? { profile: def.profile } : {}),
27
+ governedBy: def.governedBy,
28
+ roles: Object.freeze([...def.roles]),
29
+ classes: Object.freeze([...def.classes]),
30
+ root: def.root,
31
+ protocols: Object.freeze([...def.protocols]),
32
+ checks: Object.freeze([...(def.checks ?? [])]),
33
+ actions: Object.freeze([...(def.actions ?? [])]),
34
+ messages: Object.freeze([...(def.messages ?? [])]),
35
+ roster: def.roster,
36
+ ...(def.hooks !== undefined ? { hooks: def.hooks } : {}),
37
+ });
38
+ }
39
+ function fail(path, message) {
40
+ throw new SpecCompileError(path, message);
41
+ }
42
+ function checkId(value, path) {
43
+ if (!ID_RE.test(value)) {
44
+ fail(path, `invalid identifier ${JSON.stringify(value)}`);
45
+ }
46
+ return value;
47
+ }
48
+ function checkNsOrId(value, path) {
49
+ if (!NS_OR_ID_RE.test(value)) {
50
+ fail(path, `invalid namespaced id ${JSON.stringify(value)}`);
51
+ }
52
+ return value;
53
+ }
54
+ function checkNsId(value, path) {
55
+ if (!NS_ID_RE.test(value)) {
56
+ fail(path, `invalid namespaced id ${JSON.stringify(value)}`);
57
+ }
58
+ return value;
59
+ }
60
+ function checkValidatorId(value, path) {
61
+ if (!VALIDATOR_RE.test(value)) {
62
+ fail(path, `invalid validator id ${JSON.stringify(value)}`);
63
+ }
64
+ return value;
65
+ }
66
+ function checkPositiveInt(value, path) {
67
+ if (!Number.isSafeInteger(value) || value < 1) {
68
+ fail(path, `expected positive safe integer, got ${String(value)}`);
69
+ }
70
+ return value;
71
+ }
72
+ function checkFinite(value, path) {
73
+ if (!Number.isFinite(value)) {
74
+ fail(path, `expected finite number, got ${String(value)}`);
75
+ }
76
+ return value;
77
+ }
78
+ function stableEqual(a, b) {
79
+ return JSON.stringify(a) === JSON.stringify(b);
80
+ }
81
+ function registerSchema(ctx, name, schema, path) {
82
+ checkId(name, path);
83
+ const existing = ctx.schemas[name];
84
+ if (existing !== undefined) {
85
+ if (!stableEqual(existing, schema)) {
86
+ fail(path, `conflicting schema definition for ${JSON.stringify(name)}`);
87
+ }
88
+ return;
89
+ }
90
+ ctx.schemas[name] = schema;
91
+ }
92
+ const EMPTY_FIELDS = new Set();
93
+ const VALID_BRIEF_PIECES = new Set([
94
+ "you",
95
+ "owes",
96
+ "guide",
97
+ "asked",
98
+ "parentOrder",
99
+ "file",
100
+ "summary",
101
+ ]);
102
+ function validateBriefPieces(pieces, path) {
103
+ const seen = new Set();
104
+ for (const piece of pieces) {
105
+ if (!VALID_BRIEF_PIECES.has(piece)) {
106
+ fail(path, `unknown brief piece ${JSON.stringify(piece)}`);
107
+ }
108
+ if (seen.has(piece)) {
109
+ fail(path, `duplicate brief piece ${JSON.stringify(piece)}`);
110
+ }
111
+ seen.add(piece);
112
+ }
113
+ return [...pieces];
114
+ }
115
+ function schemaFieldSet(ctx, name) {
116
+ let cur = ctx.schemas[name];
117
+ for (let i = 0; i < 32 && cur !== undefined; i += 1) {
118
+ if (cur.kind === "struct") {
119
+ return new Set(Object.keys(cur.fields));
120
+ }
121
+ if (cur.kind === "ref") {
122
+ cur = ctx.schemas[cur.schema];
123
+ continue;
124
+ }
125
+ break;
126
+ }
127
+ return new Set();
128
+ }
129
+ function validateWireSchema(schema, path) {
130
+ if (schema.description !== undefined && schema.description.length === 0) {
131
+ fail(`${path}.description`, "description must be non-empty");
132
+ }
133
+ if (schema.guide !== undefined) {
134
+ const allowed = schema.kind === "struct" ? new Set(Object.keys(schema.fields)) : EMPTY_FIELDS;
135
+ validateTemplate(schema.guide, allowed, `${path}.guide`);
136
+ }
137
+ switch (schema.kind) {
138
+ case "string":
139
+ if (schema.brand !== undefined && schema.brand.length === 0) {
140
+ fail(`${path}.brand`, "brand must be non-empty");
141
+ }
142
+ if (schema.maxLength !== undefined) {
143
+ checkPositiveInt(schema.maxLength, `${path}.maxLength`);
144
+ }
145
+ if (schema.validator !== undefined) {
146
+ checkValidatorId(schema.validator, `${path}.validator`);
147
+ }
148
+ return schema;
149
+ case "number":
150
+ if (schema.brand !== undefined && schema.brand.length === 0) {
151
+ fail(`${path}.brand`, "brand must be non-empty");
152
+ }
153
+ if (schema.min !== undefined)
154
+ checkFinite(schema.min, `${path}.min`);
155
+ if (schema.max !== undefined)
156
+ checkFinite(schema.max, `${path}.max`);
157
+ if (schema.exclusiveMin !== undefined) {
158
+ checkFinite(schema.exclusiveMin, `${path}.exclusiveMin`);
159
+ }
160
+ if (schema.exclusiveMax !== undefined) {
161
+ checkFinite(schema.exclusiveMax, `${path}.exclusiveMax`);
162
+ }
163
+ return schema;
164
+ case "boolean":
165
+ if (schema.brand !== undefined && schema.brand.length === 0) {
166
+ fail(`${path}.brand`, "brand must be non-empty");
167
+ }
168
+ return schema;
169
+ case "literal":
170
+ if (typeof schema.value === "number") {
171
+ checkFinite(schema.value, `${path}.value`);
172
+ }
173
+ return schema;
174
+ case "enum": {
175
+ const seen = new Set();
176
+ for (const v of schema.values) {
177
+ if (v.length === 0)
178
+ fail(`${path}.values`, "enum values must be non-empty");
179
+ if (seen.has(v))
180
+ fail(`${path}.values`, `duplicate enum value ${JSON.stringify(v)}`);
181
+ seen.add(v);
182
+ }
183
+ return schema;
184
+ }
185
+ case "ref":
186
+ checkId(schema.schema, `${path}.schema`);
187
+ return schema;
188
+ case "array":
189
+ case "struct":
190
+ case "union":
191
+ return schema;
192
+ default:
193
+ return exhaustive(schema);
194
+ }
195
+ }
196
+ function lowerFieldMap(ctx, map, path) {
197
+ const out = {};
198
+ for (const [k, entry] of Object.entries(map)) {
199
+ if (k.length === 0)
200
+ fail(path, "struct field name must be non-empty");
201
+ if (entry.kind === "optional") {
202
+ out[k] = { schema: lowerTypeDef(ctx, entry.inner, `${path}.${k}`), optional: true };
203
+ }
204
+ else {
205
+ out[k] = { schema: lowerTypeDef(ctx, entry, `${path}.${k}`) };
206
+ }
207
+ }
208
+ return out;
209
+ }
210
+ function lowerStructType(ctx, s, path) {
211
+ if (s.node.tag !== "struct") {
212
+ fail(path, "expected struct schema");
213
+ }
214
+ if (s.node.validator !== undefined) {
215
+ checkValidatorId(s.node.validator, `${path}.validator`);
216
+ }
217
+ return validateWireSchema({
218
+ kind: "struct",
219
+ fields: lowerFieldMap(ctx, s.node.fields, `${path}.fields`),
220
+ ...(s.node.validator !== undefined ? { validator: s.node.validator } : {}),
221
+ ...s.node.annotations,
222
+ }, path);
223
+ }
224
+ function lowerContract(ctx, c, path) {
225
+ checkId(c.name, `${path}.name`);
226
+ if (!ctx.visitedContracts.has(c.name)) {
227
+ ctx.visitedContracts.add(c.name);
228
+ const lowered = lowerTypeDef(ctx, c.schema, `schemas.${c.name}`);
229
+ registerSchema(ctx, c.name, lowered, `schemas.${c.name}`);
230
+ }
231
+ else {
232
+ const lowered = lowerTypeDef(ctx, c.schema, `schemas.${c.name}`);
233
+ registerSchema(ctx, c.name, lowered, `schemas.${c.name}`);
234
+ }
235
+ return c.name;
236
+ }
237
+ function lowerTypeDef(ctx, def, path) {
238
+ if (def.kind === "contract") {
239
+ const name = lowerContract(ctx, def, path);
240
+ return { kind: "ref", schema: name };
241
+ }
242
+ const node = def.node;
243
+ switch (node.tag) {
244
+ case "primitive":
245
+ return validateWireSchema(node.wire, path);
246
+ case "array":
247
+ return validateWireSchema({
248
+ kind: "array",
249
+ item: lowerTypeDef(ctx, node.item, `${path}.item`),
250
+ ...(node.nonEmpty !== undefined ? { nonEmpty: node.nonEmpty } : {}),
251
+ ...node.annotations,
252
+ }, path);
253
+ case "struct":
254
+ if (node.validator !== undefined) {
255
+ checkValidatorId(node.validator, `${path}.validator`);
256
+ }
257
+ return validateWireSchema({
258
+ kind: "struct",
259
+ fields: lowerFieldMap(ctx, node.fields, `${path}.fields`),
260
+ ...(node.validator !== undefined ? { validator: node.validator } : {}),
261
+ ...node.annotations,
262
+ }, path);
263
+ case "tagged": {
264
+ if (node.tagKey.length === 0)
265
+ fail(path, "tag key must be non-empty");
266
+ if (node.tagValue.length === 0)
267
+ fail(path, "tag value must be non-empty");
268
+ if (node.validator !== undefined) {
269
+ checkValidatorId(node.validator, `${path}.validator`);
270
+ }
271
+ const fields = {
272
+ [node.tagKey]: { schema: { kind: "literal", value: node.tagValue } },
273
+ ...lowerFieldMap(ctx, node.fields, `${path}.fields`),
274
+ };
275
+ return validateWireSchema({
276
+ kind: "struct",
277
+ fields,
278
+ ...(node.validator !== undefined ? { validator: node.validator } : {}),
279
+ ...node.annotations,
280
+ }, path);
281
+ }
282
+ case "union": {
283
+ if (node.tagKey.length === 0)
284
+ fail(path, "union tag must be non-empty");
285
+ const entries = Object.entries(node.variants);
286
+ if (entries.length === 0)
287
+ fail(path, "union must have at least one variant");
288
+ const variants = {};
289
+ for (const [k, v] of entries) {
290
+ if (k.length === 0)
291
+ fail(`${path}.variants`, "union variant name must be non-empty");
292
+ variants[k] = lowerStructType(ctx, v, `${path}.variants.${k}`);
293
+ }
294
+ return validateWireSchema({
295
+ kind: "union",
296
+ tag: node.tagKey,
297
+ variants,
298
+ ...node.annotations,
299
+ }, path);
300
+ }
301
+ default:
302
+ return exhaustive(node);
303
+ }
304
+ }
305
+ function validateObserveParams(value, inputFields, path) {
306
+ if (Array.isArray(value)) {
307
+ for (let i = 0; i < value.length; i += 1) {
308
+ validateObserveParams(value[i], inputFields, `${path}[${String(i)}]`);
309
+ }
310
+ return;
311
+ }
312
+ if (typeof value !== "object" || value === null)
313
+ return;
314
+ const entries = Object.entries(value);
315
+ if (Object.hasOwn(value, "$check")) {
316
+ if (entries.length !== 1) {
317
+ fail(path, "$check reference must be a single-key object");
318
+ }
319
+ const target = Reflect.get(value, "$check");
320
+ if (typeof target !== "string" || target.length === 0) {
321
+ fail(`${path}.$check`, "$check reference must name a non-empty check input field");
322
+ }
323
+ if (!inputFields.has(target)) {
324
+ fail(`${path}.$check`, `unknown check input field ${JSON.stringify(target)}`);
325
+ }
326
+ return;
327
+ }
328
+ for (const [k, v] of entries) {
329
+ validateObserveParams(v, inputFields, `${path}.${k}`);
330
+ }
331
+ }
332
+ function isJsonObject(value) {
333
+ return typeof value === "object" && value !== null && !Array.isArray(value);
334
+ }
335
+ function lowerCheckObserve(obs, inputFields, path) {
336
+ if (!OBSERVER_RE.test(obs.observer)) {
337
+ fail(`${path}.observer`, `invalid observer id ${JSON.stringify(obs.observer)}`);
338
+ }
339
+ const params = assertJsonValue(obs.params, `${path}.params`);
340
+ if (!isJsonObject(params)) {
341
+ fail(`${path}.params`, "observe.params must be a JSON object");
342
+ }
343
+ validateObserveParams(params, inputFields, `${path}.params`);
344
+ return { observer: obs.observer, params };
345
+ }
346
+ function registerCheck(ctx, c, path) {
347
+ checkNsOrId(c.id, `${path}.id`);
348
+ const input = lowerContract(ctx, c.input, `${path}.input`);
349
+ if (c.evaluator !== undefined) {
350
+ if (!VALIDATOR_RE.test(c.evaluator) && !isValidEvaluatorId(c.evaluator)) {
351
+ fail(`${path}.evaluator`, `evaluator id ${JSON.stringify(c.evaluator)} must be a std evaluator telar.std/<name>/<v> or <installation>/evaluator/<name>/<v>`);
352
+ }
353
+ }
354
+ if (c.evaluator !== undefined && c.observe !== undefined) {
355
+ fail(`${path}.observe`, "check cannot declare both evaluator and observe");
356
+ }
357
+ const inputFields = schemaFieldSet(ctx, input);
358
+ const observe = c.observe !== undefined
359
+ ? lowerCheckObserve(c.observe, inputFields, `${path}.observe`)
360
+ : undefined;
361
+ if (c.guide !== undefined) {
362
+ validateTemplate(c.guide, inputFields, `${path}.guide`);
363
+ }
364
+ const decl = {
365
+ input,
366
+ ...(c.evaluator !== undefined ? { evaluator: c.evaluator } : {}),
367
+ ...(observe !== undefined ? { observe } : {}),
368
+ ...(c.guide !== undefined ? { guide: c.guide } : {}),
369
+ };
370
+ const existing = ctx.checks[c.id];
371
+ if (existing !== undefined && !stableEqual(existing, decl)) {
372
+ fail(path, `conflicting check definition for ${JSON.stringify(c.id)}`);
373
+ }
374
+ ctx.checks[c.id] = decl;
375
+ return c.id;
376
+ }
377
+ function registerAction(ctx, a, path) {
378
+ if (!isValidActionId(a.id)) {
379
+ fail(`${path}.id`, `action id ${JSON.stringify(a.id)} must match <installation>/action/<name>/<version>; std actions are telar.std/action/<name>/1`);
380
+ }
381
+ const input = lowerContract(ctx, a.input, `${path}.input`);
382
+ const output = lowerContract(ctx, a.output, `${path}.output`);
383
+ if (a.class !== undefined && !ctx.classNames.has(a.class.name)) {
384
+ fail(`${path}.class`, `unknown class ${JSON.stringify(a.class.name)}`);
385
+ }
386
+ const revert = a.revert !== undefined ? registerAction(ctx, a.revert, `${path}.revert`) : undefined;
387
+ const release = a.release !== undefined ? registerAction(ctx, a.release, `${path}.release`) : undefined;
388
+ if (a.guide !== undefined) {
389
+ const allowed = new Set([...schemaFieldSet(ctx, input), ...schemaFieldSet(ctx, output)]);
390
+ validateTemplate(a.guide, allowed, `${path}.guide`);
391
+ }
392
+ const decl = {
393
+ input,
394
+ output,
395
+ ...(a.class !== undefined ? { class: a.class.name } : {}),
396
+ ...(revert !== undefined ? { revert } : {}),
397
+ ...(release !== undefined ? { release } : {}),
398
+ ...(a.reversible !== undefined ? { reversible: a.reversible } : {}),
399
+ ...(a.guide !== undefined ? { guide: a.guide } : {}),
400
+ };
401
+ const existing = ctx.actions[a.id];
402
+ if (existing !== undefined && !stableEqual(existing, decl)) {
403
+ fail(path, `conflicting action definition for ${JSON.stringify(a.id)}`);
404
+ }
405
+ ctx.actions[a.id] = decl;
406
+ return a.id;
407
+ }
408
+ function validateTemplate(template, declaredFields, path) {
409
+ if (template.length === 0)
410
+ fail(path, "template must be non-empty");
411
+ let rest = template;
412
+ while (rest.length > 0) {
413
+ const open = rest.indexOf("{{");
414
+ if (open === -1) {
415
+ if (rest.includes("}}"))
416
+ fail(path, "unexpected `}}` in template");
417
+ break;
418
+ }
419
+ if (rest.slice(0, open).includes("}}"))
420
+ fail(path, "unexpected `}}` in template");
421
+ const after = rest.slice(open + 2);
422
+ const close = after.indexOf("}}");
423
+ if (close === -1)
424
+ fail(path, "unclosed `{{` in template");
425
+ const key = after.slice(0, close);
426
+ const first = key[0] ?? "";
427
+ if (key.length === 0 ||
428
+ key.includes("{") ||
429
+ key.includes("}") ||
430
+ LOGIC_PREFIXES.has(first) ||
431
+ /\s/.test(key)) {
432
+ fail(path, `invalid template placeholder ${JSON.stringify(key)}`);
433
+ }
434
+ if (!declaredFields.has(key)) {
435
+ fail(path, `unknown template placeholder ${JSON.stringify(key)}`);
436
+ }
437
+ rest = after.slice(close + 2);
438
+ }
439
+ }
440
+ function isMessageFieldName(value) {
441
+ return value === "id" || value === "kind" || value === "toRole" || value === "case";
442
+ }
443
+ function lowerMissArg(arg, path) {
444
+ if (typeof arg === "object" &&
445
+ arg !== null &&
446
+ "kind" in arg &&
447
+ arg.kind === "message-arg" &&
448
+ "field" in arg &&
449
+ isMessageFieldName(arg.field)) {
450
+ return { $message: arg.field };
451
+ }
452
+ if (typeof arg === "object" &&
453
+ arg !== null &&
454
+ "kind" in arg &&
455
+ arg.kind === "literal-ref" &&
456
+ "value" in arg) {
457
+ return { $literal: assertJsonValue(arg.value, path) };
458
+ }
459
+ return { $literal: assertJsonValue(arg, path) };
460
+ }
461
+ function lowerMissAction(ctx, action, path) {
462
+ if (action.kind === "redeliver") {
463
+ return { kind: "redeliver" };
464
+ }
465
+ checkId(action.protocol.name, `${path}.protocol`);
466
+ if (!ctx.roleNames.has(action.forRole.name)) {
467
+ fail(`${path}.forRole`, `unknown role ${JSON.stringify(action.forRole.name)}`);
468
+ }
469
+ const dataMap = {};
470
+ for (const [k, v] of Object.entries(action.data)) {
471
+ dataMap[k] = lowerMissArg(v, `${path}.dataMap.${k}`);
472
+ }
473
+ return {
474
+ kind: "open",
475
+ protocol: action.protocol.name,
476
+ forRole: action.forRole.name,
477
+ dataMap,
478
+ };
479
+ }
480
+ function lowerAck(ctx, ackDef, path) {
481
+ if (ackDef.kind === "none") {
482
+ return { kind: "none" };
483
+ }
484
+ const within = checkPositiveInt(ackDef.within, `${path}.within`);
485
+ const [first, ...rest] = ackDef.onMiss;
486
+ const onMiss = [
487
+ lowerMissAction(ctx, first, `${path}.onMiss[0]`),
488
+ ...rest.map((item, idx) => lowerMissAction(ctx, item, `${path}.onMiss[${String(idx + 1)}]`)),
489
+ ];
490
+ if (ackDef.kind === "read") {
491
+ return { kind: "read", within, onMiss };
492
+ }
493
+ const shape = ackDef.shape === "ack" ? "ack" : lowerContract(ctx, ackDef.shape, `${path}.shape`);
494
+ return { kind: "answer", shape, within, onMiss };
495
+ }
496
+ function registerMessage(ctx, m, path) {
497
+ checkId(m.name, `${path}.name`);
498
+ const payloadName = lowerContract(ctx, m.payload, `${path}.payload`);
499
+ const payloadSchema = ctx.schemas[payloadName];
500
+ if (payloadSchema === undefined || payloadSchema.kind !== "struct") {
501
+ fail(`${path}.payload`, `message payload ${JSON.stringify(payloadName)} must be a struct`);
502
+ }
503
+ validateTemplate(m.template.template, new Set(Object.keys(payloadSchema.fields)), `${path}.template`);
504
+ const ack = lowerAck(ctx, m.ack, `${path}.ack`);
505
+ const decl = {
506
+ payload: payloadName,
507
+ template: m.template.template,
508
+ ack,
509
+ };
510
+ const existing = ctx.messages[m.name];
511
+ if (existing !== undefined && !stableEqual(existing, decl)) {
512
+ fail(path, `conflicting message definition for ${JSON.stringify(m.name)}`);
513
+ }
514
+ ctx.messages[m.name] = decl;
515
+ return m.name;
516
+ }
517
+ function lowerArgMap(map, path) {
518
+ const out = {};
519
+ for (const [k, v] of Object.entries(map)) {
520
+ if (v === undefined)
521
+ continue;
522
+ out[k] = liftArg(v, `${path}.${k}`);
523
+ }
524
+ return out;
525
+ }
526
+ function lowerBoundSpec(ctx, spec, caseFields, path) {
527
+ const max = checkPositiveInt(spec.max, `${path}.max`);
528
+ if (!ctx.roleNames.has(spec.onLimit.name)) {
529
+ fail(`${path}.onLimit`, `unknown role ${JSON.stringify(spec.onLimit.name)}`);
530
+ }
531
+ const guideText = spec.guide?.template;
532
+ if (guideText !== undefined) {
533
+ validateTemplate(guideText, caseFields, `${path}.guide`);
534
+ }
535
+ if (spec.byField !== undefined && Object.keys(spec.byField.values).length > 0) {
536
+ const fieldName = typeof spec.byField.field === "string" ? spec.byField.field : spec.byField.field.name;
537
+ if (fieldName.length === 0)
538
+ fail(`${path}.byField.field`, "field name must be non-empty");
539
+ const values = {};
540
+ for (const [k, v] of Object.entries(spec.byField.values)) {
541
+ values[k] = checkPositiveInt(v, `${path}.byField.values.${k}`);
542
+ }
543
+ return {
544
+ max,
545
+ byField: { field: fieldName, values },
546
+ onLimit: spec.onLimit.name,
547
+ ...(guideText !== undefined ? { guide: guideText } : {}),
548
+ };
549
+ }
550
+ return {
551
+ max,
552
+ onLimit: spec.onLimit.name,
553
+ ...(guideText !== undefined ? { guide: guideText } : {}),
554
+ };
555
+ }
556
+ function isPlainRecord(value) {
557
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !isArgRef(value);
558
+ }
559
+ function lowerNeed(ctx, need, caseFields, path) {
560
+ const guideProp = (extraFields) => {
561
+ if (need.guide === undefined)
562
+ return {};
563
+ const allowed = extraFields === undefined ? caseFields : new Set([...caseFields, ...extraFields]);
564
+ validateTemplate(need.guide, allowed, `${path}.guide`);
565
+ return { guide: need.guide };
566
+ };
567
+ switch (need.kind) {
568
+ case "check-need": {
569
+ const id = registerCheck(ctx, need.check, `${path}.check`);
570
+ const checkInput = ctx.checks[id]?.input;
571
+ const extra = checkInput !== undefined ? schemaFieldSet(ctx, checkInput) : undefined;
572
+ return {
573
+ kind: "check",
574
+ check: id,
575
+ args: lowerArgMap(need.args, `${path}.args`),
576
+ ...guideProp(extra),
577
+ };
578
+ }
579
+ case "any-need": {
580
+ const [first, second, ...rest] = need.of;
581
+ return {
582
+ kind: "any",
583
+ of: [
584
+ lowerNeed(ctx, first, caseFields, `${path}.of[0]`),
585
+ lowerNeed(ctx, second, caseFields, `${path}.of[1]`),
586
+ ...rest.map((item, idx) => lowerNeed(ctx, item, caseFields, `${path}.of[${String(idx + 2)}]`)),
587
+ ],
588
+ ...guideProp(),
589
+ };
590
+ }
591
+ case "answer-need": {
592
+ const [firstRole, ...restRoles] = need.roles;
593
+ for (const r of need.roles) {
594
+ if (!ctx.roleNames.has(r.name)) {
595
+ fail(`${path}.roles`, `unknown role ${JSON.stringify(r.name)}`);
596
+ }
597
+ }
598
+ const shape = lowerContract(ctx, need.shape, `${path}.shape`);
599
+ return {
600
+ kind: "answer",
601
+ roles: [firstRole.name, ...restRoles.map((r) => r.name)],
602
+ shape,
603
+ ...(need.variants !== undefined ? { variants: [...need.variants] } : {}),
604
+ ...(need.seatLabel !== undefined
605
+ ? { seatLabel: { key: need.seatLabel.key, values: [...need.seatLabel.values] } }
606
+ : {}),
607
+ ...guideProp(),
608
+ };
609
+ }
610
+ case "auth-need": {
611
+ if (!ctx.classNames.has(need.cls.name)) {
612
+ fail(`${path}.class`, `unknown class ${JSON.stringify(need.cls.name)}`);
613
+ }
614
+ return { kind: "authorization", class: need.cls.name, ...guideProp() };
615
+ }
616
+ case "auth-from-field-need": {
617
+ const [firstCls, ...restCls] = need.allowed;
618
+ for (const cls of need.allowed) {
619
+ if (!ctx.classNames.has(cls.name)) {
620
+ fail(`${path}.allowedClasses`, `unknown class ${JSON.stringify(cls.name)}`);
621
+ }
622
+ }
623
+ return {
624
+ kind: "authorization",
625
+ classFromCaseField: need.field,
626
+ allowedClasses: [firstCls.name, ...restCls.map((c) => c.name)],
627
+ ...guideProp(),
628
+ };
629
+ }
630
+ case "children-need": {
631
+ const where = need.where === undefined
632
+ ? undefined
633
+ : {
634
+ childField: typeof need.where.childField === "string"
635
+ ? need.where.childField
636
+ : need.where.childField.name,
637
+ parentField: typeof need.where.parentField === "string"
638
+ ? need.where.parentField
639
+ : need.where.parentField.name,
640
+ };
641
+ const protocol = need.protocol !== undefined ? checkId(need.protocol.name, `${path}.protocol`) : undefined;
642
+ if (need.condition === "ended") {
643
+ return {
644
+ kind: "children",
645
+ condition: "ended",
646
+ allowEmpty: need.allowEmpty,
647
+ ...(protocol !== undefined ? { protocol } : {}),
648
+ ...(where !== undefined ? { where } : {}),
649
+ ...guideProp(),
650
+ };
651
+ }
652
+ if (need.state === undefined) {
653
+ fail(`${path}.state`, "state is required for children condition");
654
+ }
655
+ checkId(need.state, `${path}.state`);
656
+ return {
657
+ kind: "children",
658
+ condition: need.condition,
659
+ state: need.state,
660
+ allowEmpty: need.allowEmpty,
661
+ ...(protocol !== undefined ? { protocol } : {}),
662
+ ...(where !== undefined ? { where } : {}),
663
+ ...guideProp(),
664
+ };
665
+ }
666
+ case "message-need": {
667
+ const messageKind = registerMessage(ctx, need.message, `${path}.messageKind`);
668
+ const [firstRole, ...restRoles] = need.from;
669
+ for (const r of need.from) {
670
+ if (!ctx.roleNames.has(r.name)) {
671
+ fail(`${path}.fromRoles`, `unknown role ${JSON.stringify(r.name)}`);
672
+ }
673
+ }
674
+ const msgPayload = ctx.messages[messageKind]?.payload;
675
+ const extra = msgPayload !== undefined ? schemaFieldSet(ctx, msgPayload) : undefined;
676
+ return {
677
+ kind: "message",
678
+ messageKind,
679
+ fromRoles: [firstRole.name, ...restRoles.map((r) => r.name)],
680
+ ...guideProp(extra),
681
+ };
682
+ }
683
+ case "bound-reached-need":
684
+ return { kind: "bound-reached", step: checkId(need.step, `${path}.step`), ...guideProp() };
685
+ default:
686
+ return exhaustive(need);
687
+ }
688
+ }
689
+ function lowerEffect(ctx, eff, path) {
690
+ switch (eff.kind) {
691
+ case "call-action-effect": {
692
+ const id = registerAction(ctx, eff.action, `${path}.action`);
693
+ return { kind: "call-action", action: id, args: lowerArgMap(eff.args, `${path}.args`) };
694
+ }
695
+ case "record-data-effect": {
696
+ if (isPlainRecord(eff.source)) {
697
+ return {
698
+ kind: "record-data",
699
+ mode: eff.mode,
700
+ targetField: eff.targetField,
701
+ valueMap: lowerArgMap(eff.source, `${path}.valueMap`),
702
+ };
703
+ }
704
+ return {
705
+ kind: "record-data",
706
+ mode: eff.mode,
707
+ targetField: eff.targetField,
708
+ value: liftArg(eff.source, `${path}.value`),
709
+ };
710
+ }
711
+ case "open-child-effect": {
712
+ checkId(eff.protocol.name, `${path}.protocol`);
713
+ if (!ctx.roleNames.has(eff.forRole.name)) {
714
+ fail(`${path}.forRole`, `unknown role ${JSON.stringify(eff.forRole.name)}`);
715
+ }
716
+ return {
717
+ kind: "open-child",
718
+ protocol: eff.protocol.name,
719
+ forRole: eff.forRole.name,
720
+ ...(eff.seatScopeFrom !== undefined ? { seatScopeFromField: eff.seatScopeFrom } : {}),
721
+ dataMap: lowerArgMap(eff.data, `${path}.dataMap`),
722
+ };
723
+ }
724
+ case "emit-message-effect": {
725
+ const messageKind = registerMessage(ctx, eff.message, `${path}.messageKind`);
726
+ if (!ctx.roleNames.has(eff.toRole.name)) {
727
+ fail(`${path}.toRole`, `unknown role ${JSON.stringify(eff.toRole.name)}`);
728
+ }
729
+ return {
730
+ kind: "emit-message",
731
+ messageKind,
732
+ toRole: eff.toRole.name,
733
+ ...(eff.payload !== undefined
734
+ ? { payloadMap: lowerArgMap(eff.payload, `${path}.payloadMap`) }
735
+ : {}),
736
+ };
737
+ }
738
+ default:
739
+ return exhaustive(eff);
740
+ }
741
+ }
742
+ function isContract(value) {
743
+ return "kind" in value && value.kind === "contract";
744
+ }
745
+ function isFieldSchemaEntry(value) {
746
+ return (typeof value === "object" &&
747
+ value !== null &&
748
+ "kind" in value &&
749
+ (value.kind === "type" || value.kind === "contract" || value.kind === "optional"));
750
+ }
751
+ function extractPlainFieldMap(value, protoName) {
752
+ const out = {};
753
+ for (const [k, v] of Object.entries(value)) {
754
+ if (!isFieldSchemaEntry(v)) {
755
+ fail(`protocols.${protoName}.data.${k}`, "expected a schema or optional schema");
756
+ }
757
+ out[k] = v;
758
+ }
759
+ return out;
760
+ }
761
+ function lowerProtocolFieldMap(ctx, entries, protoName, dataNameOverride, openDataNameOverride) {
762
+ const dataName = dataNameOverride ?? `${protoName}-data`;
763
+ const openDataName = openDataNameOverride ?? `${protoName}-open-data`;
764
+ const dataFields = {};
765
+ const openFields = {};
766
+ const engineManaged = {};
767
+ let hasEngine = false;
768
+ for (const [k, entry] of Object.entries(entries)) {
769
+ const isEngine = entry.kind === "engine-field";
770
+ const schemaEntry = isEngine ? entry.schema : entry;
771
+ const decl = schemaEntry.kind === "optional"
772
+ ? {
773
+ schema: lowerTypeDef(ctx, schemaEntry.inner, `protocols.${protoName}.data.${k}`),
774
+ optional: true,
775
+ }
776
+ : { schema: lowerTypeDef(ctx, schemaEntry, `protocols.${protoName}.data.${k}`) };
777
+ dataFields[k] = decl;
778
+ if (isEngine) {
779
+ hasEngine = true;
780
+ if (entry.policy !== undefined) {
781
+ engineManaged[k] = entry.policy;
782
+ }
783
+ }
784
+ else {
785
+ openFields[k] = decl;
786
+ }
787
+ }
788
+ registerSchema(ctx, dataName, { kind: "struct", fields: dataFields }, `schemas.${dataName}`);
789
+ if (!hasEngine) {
790
+ return { dataName };
791
+ }
792
+ registerSchema(ctx, openDataName, { kind: "struct", fields: openFields }, `schemas.${openDataName}`);
793
+ return {
794
+ dataName,
795
+ openDataName,
796
+ ...(Object.keys(engineManaged).length > 0 ? { engineManagedFields: engineManaged } : {}),
797
+ };
798
+ }
799
+ function lowerProtocolData(ctx, p) {
800
+ const meta = readFieldTableMeta(p.data);
801
+ if (meta !== undefined) {
802
+ return lowerProtocolFieldMap(ctx, meta.entries, p.name, p.dataName, p.openDataName);
803
+ }
804
+ if (isContract(p.data)) {
805
+ const dataName = lowerContract(ctx, p.data, `protocols.${p.name}.data`);
806
+ return { dataName };
807
+ }
808
+ return lowerProtocolFieldMap(ctx, extractPlainFieldMap(p.data, p.name), p.name, p.dataName, p.openDataName);
809
+ }
810
+ function lowerProtocol(ctx, p) {
811
+ const ppath = `protocols.${p.name}`;
812
+ checkId(p.name, `${ppath}.name`);
813
+ const stateSet = new Set();
814
+ for (const s of p.states) {
815
+ checkId(s, `${ppath}.states`);
816
+ if (stateSet.has(s))
817
+ fail(`${ppath}.states`, `duplicate state ${JSON.stringify(s)}`);
818
+ stateSet.add(s);
819
+ }
820
+ if (!stateSet.has(p.start)) {
821
+ fail(`${ppath}.start`, `start state ${JSON.stringify(p.start)} not in states`);
822
+ }
823
+ const finalSet = new Set();
824
+ for (const f of p.final) {
825
+ if (!stateSet.has(f))
826
+ fail(`${ppath}.final`, `final state ${JSON.stringify(f)} not in states`);
827
+ if (finalSet.has(f))
828
+ fail(`${ppath}.final`, `duplicate final state ${JSON.stringify(f)}`);
829
+ finalSet.add(f);
830
+ }
831
+ const data = lowerProtocolData(ctx, p);
832
+ const caseFields = schemaFieldSet(ctx, data.dataName);
833
+ if (p.guide !== undefined) {
834
+ validateTemplate(p.guide, caseFields, `${ppath}.guide`);
835
+ }
836
+ const brief = p.brief !== undefined ? validateBriefPieces(p.brief, `${ppath}.brief`) : undefined;
837
+ const roleViews = {};
838
+ for (const rv of p.roleViews) {
839
+ if (!ctx.roleNames.has(rv.role.name)) {
840
+ fail(`${ppath}.roleViews`, `unknown role ${JSON.stringify(rv.role.name)}`);
841
+ }
842
+ roleViews[rv.role.name] = {
843
+ view: rv.view,
844
+ ...(rv.includePredecessor !== undefined ? { includePredecessor: rv.includePredecessor } : {}),
845
+ };
846
+ }
847
+ const roleBriefs = {};
848
+ for (const rb of p.roleBriefs) {
849
+ if (!ctx.roleNames.has(rb.role.name)) {
850
+ fail(`${ppath}.roleBriefs`, `unknown role ${JSON.stringify(rb.role.name)}`);
851
+ }
852
+ roleBriefs[rb.role.name] = validateBriefPieces(rb.pieces, `${ppath}.roleBriefs.${rb.role.name}`);
853
+ }
854
+ const acks = {};
855
+ for (const ov of p.acks) {
856
+ const mk = registerMessage(ctx, ov.message, `${ppath}.acks.${ov.message.name}`);
857
+ acks[mk] = lowerAck(ctx, ov.ack, `${ppath}.acks.${mk}`);
858
+ }
859
+ const bounds = {};
860
+ const childNames = [];
861
+ const childSet = new Set();
862
+ const addChild = (name, path) => {
863
+ checkId(name, path);
864
+ if (!childSet.has(name)) {
865
+ childSet.add(name);
866
+ childNames.push(name);
867
+ }
868
+ };
869
+ for (const child of p.children) {
870
+ addChild(child.name, `${ppath}.children`);
871
+ }
872
+ const seenSteps = new Set();
873
+ const loweredSteps = [];
874
+ for (const [idx, s] of p.steps.entries()) {
875
+ const spath = `${ppath}.steps[${String(idx)}]`;
876
+ checkId(s.name, `${spath}.name`);
877
+ if (seenSteps.has(s.name)) {
878
+ fail(`${spath}.name`, `duplicate step ${JSON.stringify(s.name)}`);
879
+ }
880
+ seenSteps.add(s.name);
881
+ if (!stateSet.has(s.from))
882
+ fail(`${spath}.from`, `unknown state ${JSON.stringify(s.from)}`);
883
+ if (!stateSet.has(s.to))
884
+ fail(`${spath}.to`, `unknown state ${JSON.stringify(s.to)}`);
885
+ const needs = s.needs.map((n, ni) => lowerNeed(ctx, n, caseFields, `${spath}.needs[${String(ni)}]`));
886
+ if (s.guide !== undefined) {
887
+ validateTemplate(s.guide, caseFields, `${spath}.guide`);
888
+ }
889
+ const thenEffects = s.then.map((e, ei) => {
890
+ if (e.kind === "open-child-effect") {
891
+ addChild(e.protocol.name, `${spath}.then[${String(ei)}].protocol`);
892
+ }
893
+ return lowerEffect(ctx, e, `${spath}.then[${String(ei)}]`);
894
+ });
895
+ let stepBound;
896
+ if (s.bound !== undefined) {
897
+ if (s.bound.kind === "inline-bound") {
898
+ stepBound = lowerBoundSpec(ctx, s.bound.spec, caseFields, `${spath}.bound`);
899
+ }
900
+ else {
901
+ const bName = checkId(s.bound.name, `${spath}.bound`);
902
+ const bDecl = lowerBoundSpec(ctx, s.bound.spec, caseFields, `${ppath}.bounds.${bName}`);
903
+ const prev = bounds[bName];
904
+ if (prev !== undefined && !stableEqual(prev, bDecl)) {
905
+ fail(`${ppath}.bounds.${bName}`, `conflicting shared bound ${JSON.stringify(bName)}`);
906
+ }
907
+ bounds[bName] = bDecl;
908
+ stepBound = { ref: bName };
909
+ }
910
+ }
911
+ loweredSteps.push({
912
+ name: s.name,
913
+ from: s.from,
914
+ to: s.to,
915
+ needs,
916
+ [THEN]: thenEffects,
917
+ ...(stepBound !== undefined ? { bound: stepBound } : {}),
918
+ ...(s.optional === true ? { optional: true } : {}),
919
+ ...(s.guide !== undefined ? { guide: s.guide } : {}),
920
+ });
921
+ }
922
+ const [firstStep, ...restSteps] = loweredSteps;
923
+ if (firstStep === undefined) {
924
+ fail(`${ppath}.steps`, "protocol must declare at least one step");
925
+ }
926
+ return {
927
+ states: [...p.states],
928
+ start: p.start,
929
+ final: [...p.final],
930
+ data: data.dataName,
931
+ ...(data.openDataName !== undefined ? { openData: data.openDataName } : {}),
932
+ ...(data.engineManagedFields !== undefined
933
+ ? { engineManagedFields: data.engineManagedFields }
934
+ : {}),
935
+ ...(p.predecessor !== undefined ? { predecessorField: p.predecessor.field } : {}),
936
+ ...(p.predecessor?.protocol !== undefined
937
+ ? {
938
+ predecessorProtocol: checkId(p.predecessor.protocol.name, `${ppath}.predecessorProtocol`),
939
+ }
940
+ : {}),
941
+ ...(Object.keys(roleViews).length > 0 ? { roleViews } : {}),
942
+ ...(brief !== undefined ? { brief } : {}),
943
+ ...(Object.keys(roleBriefs).length > 0 ? { roleBriefs } : {}),
944
+ ...(p.guide !== undefined ? { guide: p.guide } : {}),
945
+ children: childNames,
946
+ ...(Object.keys(bounds).length > 0 ? { bounds } : {}),
947
+ ...(Object.keys(acks).length > 0 ? { acks } : {}),
948
+ steps: [firstStep, ...restSteps],
949
+ };
950
+ }
951
+ function lowerProcessGrant(g, path) {
952
+ if (g.executable.length === 0 || g.executable.trim() !== g.executable) {
953
+ fail(`${path}.executable`, "executable must be non-empty trimmed text");
954
+ }
955
+ if (g.args !== undefined && g.argsPrefix !== undefined) {
956
+ fail(path, "process grant cannot specify both args and argsPrefix");
957
+ }
958
+ return {
959
+ executable: g.executable,
960
+ ...(g.args !== undefined ? { args: [...g.args] } : {}),
961
+ ...(g.argsPrefix !== undefined ? { argsPrefix: [...g.argsPrefix] } : {}),
962
+ };
963
+ }
964
+ function lowerRootGrant(g, path) {
965
+ if (g.root.length === 0 ||
966
+ g.root.trim() !== g.root ||
967
+ g.root.split("/").includes("..") ||
968
+ g.root.startsWith("/") ||
969
+ g.root === "config" ||
970
+ g.root === "artifacts") {
971
+ fail(`${path}.root`, "a granted root must be a relative path under the installation's state directory, without '..' segments, and not the reserved names 'config' or 'artifacts'");
972
+ }
973
+ return { root: g.root };
974
+ }
975
+ const HTTP_METHODS = new Set([
976
+ "GET",
977
+ "POST",
978
+ "PUT",
979
+ "PATCH",
980
+ "DELETE",
981
+ "HEAD",
982
+ ]);
983
+ function lowerNetworkGrant(g, path) {
984
+ if (g.scheme !== undefined && g.scheme !== "http" && g.scheme !== "https") {
985
+ fail(`${path}.scheme`, `unsupported network scheme ${JSON.stringify(g.scheme)}`);
986
+ }
987
+ if (g.authority.length === 0 ||
988
+ g.authority.trim() !== g.authority ||
989
+ /[/?#@\\\s]/.test(g.authority)) {
990
+ fail(`${path}.authority`, `invalid network authority ${JSON.stringify(g.authority)}`);
991
+ }
992
+ if (g.methods !== undefined) {
993
+ for (let i = 0; i < g.methods.length; i += 1) {
994
+ const m = g.methods[i];
995
+ if (m === undefined || !HTTP_METHODS.has(m)) {
996
+ fail(`${path}.methods[${i}]`, `unsupported HTTP method ${JSON.stringify(m)}`);
997
+ }
998
+ }
999
+ }
1000
+ if (g.pathPrefixes !== undefined) {
1001
+ for (let i = 0; i < g.pathPrefixes.length; i += 1) {
1002
+ const p = g.pathPrefixes[i];
1003
+ if (p === undefined || !p.startsWith("/") || p.split("/").includes("..")) {
1004
+ fail(`${path}.pathPrefixes[${i}]`, `invalid path prefix ${JSON.stringify(p)}`);
1005
+ }
1006
+ }
1007
+ }
1008
+ if (g.secrets !== undefined) {
1009
+ for (let i = 0; i < g.secrets.length; i += 1) {
1010
+ const s = g.secrets[i];
1011
+ if (s === undefined || s.length === 0 || s.trim() !== s) {
1012
+ fail(`${path}.secrets[${i}]`, `invalid secret name ${JSON.stringify(s)}`);
1013
+ }
1014
+ }
1015
+ }
1016
+ return {
1017
+ ...(g.scheme !== undefined ? { scheme: g.scheme } : {}),
1018
+ authority: g.authority,
1019
+ ...(g.methods !== undefined ? { methods: g.methods } : {}),
1020
+ ...(g.pathPrefixes !== undefined ? { pathPrefixes: g.pathPrefixes } : {}),
1021
+ ...(g.secrets !== undefined ? { secrets: g.secrets } : {}),
1022
+ };
1023
+ }
1024
+ function lowerGitGrant(g, path) {
1025
+ if (g.repos !== undefined) {
1026
+ for (let i = 0; i < g.repos.length; i += 1) {
1027
+ const r = g.repos[i];
1028
+ if (r === undefined || r.length === 0 || /\s/.test(r)) {
1029
+ fail(`${path}.repos[${i}]`, `invalid git repo ${JSON.stringify(r)}`);
1030
+ }
1031
+ }
1032
+ }
1033
+ if (g.pushBranches !== undefined) {
1034
+ for (let i = 0; i < g.pushBranches.length; i += 1) {
1035
+ const b = g.pushBranches[i];
1036
+ if (b === undefined ||
1037
+ b.length === 0 ||
1038
+ b.startsWith("-") ||
1039
+ b.startsWith("+") ||
1040
+ /\s/.test(b)) {
1041
+ fail(`${path}.pushBranches[${i}]`, `invalid git branch ${JSON.stringify(b)}`);
1042
+ }
1043
+ }
1044
+ }
1045
+ return {
1046
+ ...(g.repos !== undefined ? { repos: [...g.repos] } : {}),
1047
+ ...(g.pushBranches !== undefined ? { pushBranches: [...g.pushBranches] } : {}),
1048
+ };
1049
+ }
1050
+ function lowerGranteeGrants(g, path) {
1051
+ return {
1052
+ ...(g.process !== undefined
1053
+ ? { process: g.process.map((item, i) => lowerProcessGrant(item, `${path}.process[${i}]`)) }
1054
+ : {}),
1055
+ ...(g.roots !== undefined
1056
+ ? { roots: g.roots.map((item, i) => lowerRootGrant(item, `${path}.roots[${i}]`)) }
1057
+ : {}),
1058
+ ...(g.network !== undefined
1059
+ ? { network: g.network.map((item, i) => lowerNetworkGrant(item, `${path}.network[${i}]`)) }
1060
+ : {}),
1061
+ ...(g.clock !== undefined ? { clock: g.clock } : {}),
1062
+ ...(g.read !== undefined ? { read: g.read } : {}),
1063
+ ...(g.git !== undefined ? { git: lowerGitGrant(g.git, `${path}.git`) } : {}),
1064
+ };
1065
+ }
1066
+ function lowerRoster(roster) {
1067
+ const seating = {};
1068
+ for (const [k, v] of Object.entries(roster.seating)) {
1069
+ checkId(k, `roster.seating.${k}`);
1070
+ if (v.provider.length === 0 || v.model.length === 0) {
1071
+ fail(`roster.seating.${k}`, "provider and model must be non-empty");
1072
+ }
1073
+ seating[k] = v;
1074
+ }
1075
+ const bindings = {};
1076
+ for (const [k, v] of Object.entries(roster.bindings ?? {})) {
1077
+ if (v !== undefined)
1078
+ bindings[checkId(k, `roster.bindings.${k}`)] = v;
1079
+ }
1080
+ const caps = {};
1081
+ for (const [k, v] of Object.entries(roster.caps)) {
1082
+ if (!Number.isFinite(v) || v <= 0 || v > 1) {
1083
+ fail(`roster.caps.${k}`, `cap must be in (0, 1], got ${String(v)}`);
1084
+ }
1085
+ caps[k] = v;
1086
+ }
1087
+ if (roster.spendCapUsd !== undefined) {
1088
+ if (!Number.isFinite(roster.spendCapUsd) || roster.spendCapUsd <= 0) {
1089
+ fail("roster.spendCapUsd", `spendCapUsd must be > 0, got ${String(roster.spendCapUsd)}`);
1090
+ }
1091
+ }
1092
+ const grants = {};
1093
+ if (roster.grants !== undefined) {
1094
+ for (const [k, v] of Object.entries(roster.grants)) {
1095
+ if (!NS_OR_ID_RE.test(k)) {
1096
+ fail(`roster.grants.${k}`, `invalid grantee id ${JSON.stringify(k)}`);
1097
+ }
1098
+ grants[k] = lowerGranteeGrants(v, `roster.grants.${k}`);
1099
+ }
1100
+ }
1101
+ return {
1102
+ seating,
1103
+ ...(roster.bindings !== undefined ? { bindings } : {}),
1104
+ caps,
1105
+ ...(roster.spendCapUsd !== undefined ? { spendCapUsd: roster.spendCapUsd } : {}),
1106
+ grants,
1107
+ };
1108
+ }
1109
+ export function compile(inst) {
1110
+ checkId(inst.name, "name");
1111
+ if (inst.protocols.length === 0) {
1112
+ fail("protocols", "installation must declare at least one protocol");
1113
+ }
1114
+ const roles = {};
1115
+ const roleNames = new Set();
1116
+ for (const r of inst.roles) {
1117
+ checkId(r.name, `roles.${r.name}`);
1118
+ if (roleNames.has(r.name))
1119
+ fail(`roles.${r.name}`, `duplicate role ${JSON.stringify(r.name)}`);
1120
+ roleNames.add(r.name);
1121
+ if (r.seatLabels !== undefined) {
1122
+ for (const [lk, lvs] of Object.entries(r.seatLabels)) {
1123
+ checkId(lk, `roles.${r.name}.seatLabels.${lk}`);
1124
+ const seen = new Set();
1125
+ for (const lv of lvs) {
1126
+ checkId(lv, `roles.${r.name}.seatLabels.${lk}`);
1127
+ if (seen.has(lv)) {
1128
+ fail(`roles.${r.name}.seatLabels.${lk}`, `duplicate seat label ${JSON.stringify(lv)}`);
1129
+ }
1130
+ seen.add(lv);
1131
+ }
1132
+ }
1133
+ }
1134
+ if (r.guide !== undefined) {
1135
+ validateTemplate(r.guide, EMPTY_FIELDS, `roles.${r.name}.guide`);
1136
+ }
1137
+ const roleBrief = r.brief !== undefined ? validateBriefPieces(r.brief, `roles.${r.name}.brief`) : undefined;
1138
+ roles[r.name] = {
1139
+ view: r.view,
1140
+ ...(r.includePredecessor !== undefined ? { includePredecessor: r.includePredecessor } : {}),
1141
+ ...(r.seatLabels !== undefined ? { seatLabels: r.seatLabels } : {}),
1142
+ ...(r.guide !== undefined ? { guide: r.guide } : {}),
1143
+ ...(roleBrief !== undefined ? { brief: roleBrief } : {}),
1144
+ };
1145
+ }
1146
+ const classNames = new Set();
1147
+ for (const cls of inst.classes) {
1148
+ checkId(cls.name, `classes.${cls.name}`);
1149
+ if (classNames.has(cls.name)) {
1150
+ fail(`classes.${cls.name}`, `duplicate class ${JSON.stringify(cls.name)}`);
1151
+ }
1152
+ classNames.add(cls.name);
1153
+ }
1154
+ if (!classNames.has(inst.governedBy.name)) {
1155
+ fail("governedBy", `unknown governing class ${JSON.stringify(inst.governedBy.name)}`);
1156
+ }
1157
+ const protocolNames = new Set();
1158
+ for (const p of inst.protocols) {
1159
+ checkId(p.name, `protocols.${p.name}`);
1160
+ if (protocolNames.has(p.name)) {
1161
+ fail(`protocols.${p.name}`, `duplicate protocol ${JSON.stringify(p.name)}`);
1162
+ }
1163
+ protocolNames.add(p.name);
1164
+ }
1165
+ if (!protocolNames.has(inst.root.name)) {
1166
+ fail("root", `unknown root protocol ${JSON.stringify(inst.root.name)}`);
1167
+ }
1168
+ const ctx = {
1169
+ schemas: {},
1170
+ checks: {},
1171
+ actions: {},
1172
+ messages: {},
1173
+ roleNames,
1174
+ classNames,
1175
+ protocolNames,
1176
+ visitedContracts: new Set(),
1177
+ };
1178
+ const classes = {};
1179
+ for (const cls of inst.classes) {
1180
+ const [firstAuth, ...restAuth] = cls.authorized;
1181
+ for (const r of cls.authorized) {
1182
+ if (!roleNames.has(r.name)) {
1183
+ fail(`classes.${cls.name}.authorizedRoles`, `unknown role ${JSON.stringify(r.name)}`);
1184
+ }
1185
+ }
1186
+ const delegated = cls.delegatedWhenAway?.map((d, idx) => {
1187
+ if (!roleNames.has(d.role.name)) {
1188
+ fail(`classes.${cls.name}.delegatedWhenAway[${String(idx)}].role`, `unknown role ${JSON.stringify(d.role.name)}`);
1189
+ }
1190
+ if (!roleNames.has(d.for.name)) {
1191
+ fail(`classes.${cls.name}.delegatedWhenAway[${String(idx)}].forRole`, `unknown role ${JSON.stringify(d.for.name)}`);
1192
+ }
1193
+ return { role: d.role.name, forRole: d.for.name };
1194
+ });
1195
+ const requires = cls.requires.map((c, idx) => registerCheck(ctx, c, `classes.${cls.name}.requires[${String(idx)}]`));
1196
+ if (cls.guide !== undefined) {
1197
+ validateTemplate(cls.guide, EMPTY_FIELDS, `classes.${cls.name}.guide`);
1198
+ }
1199
+ classes[cls.name] = {
1200
+ authorizedRoles: [firstAuth.name, ...restAuth.map((r) => r.name)],
1201
+ ...(delegated !== undefined ? { delegatedWhenAway: delegated } : {}),
1202
+ requires,
1203
+ admitsImpossible: cls.admitsImpossible,
1204
+ ...(cls.guide !== undefined ? { guide: cls.guide } : {}),
1205
+ };
1206
+ }
1207
+ for (const c of inst.checks)
1208
+ registerCheck(ctx, c, `checks.${c.id}`);
1209
+ for (const a of inst.actions)
1210
+ registerAction(ctx, a, `actions.${a.id}`);
1211
+ for (const m of inst.messages)
1212
+ registerMessage(ctx, m, `messages.${m.name}`);
1213
+ const protocols = {};
1214
+ for (const p of inst.protocols) {
1215
+ protocols[p.name] = lowerProtocol(ctx, p);
1216
+ }
1217
+ const roster = lowerRoster(inst.roster);
1218
+ let hooks;
1219
+ if (inst.hooks?.send !== undefined) {
1220
+ hooks = { send: checkNsId(inst.hooks.send, "hooks.send") };
1221
+ }
1222
+ return {
1223
+ format: "telar.spec/1",
1224
+ ...(inst.profile !== undefined ? { profile: inst.profile } : {}),
1225
+ name: inst.name,
1226
+ governedBy: inst.governedBy.name,
1227
+ schemas: ctx.schemas,
1228
+ classes,
1229
+ roles,
1230
+ checks: ctx.checks,
1231
+ actions: ctx.actions,
1232
+ messages: ctx.messages,
1233
+ root: inst.root.name,
1234
+ protocols,
1235
+ roster,
1236
+ ...(hooks !== undefined ? { hooks } : {}),
1237
+ };
1238
+ }