@serene-pub/sdk 0.6.0-pr-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Document compilation (04 §5a, F3, F6).
3
+ *
4
+ * The builder chain is an *authoring format only*. SP imports the document and
5
+ * never the JS — there is no importer path that evaluates a builder chain.
6
+ *
7
+ * Edges are derived here, 1:1 with pipeline_edges rows: the linear chain carries a
8
+ * default edge, and every $ref becomes an explicit one.
9
+ */
10
+ import { collectDataRefs, envoyConfigKey, isEnvoyConfigKey, isSlotRef } from './refs.js';
11
+ import { getDefinition } from './descriptors.js';
12
+ import { getGenre } from './genres.js';
13
+ import { envoySlugOf, envoySlugOfRef } from './participants.js';
14
+ /** The message write whose `speaker` a document may name literally. */
15
+ const CREATE_MESSAGE_ID = 'core:outlet/create-message';
16
+ import { requiredConnections } from './connections.js';
17
+ import { isStreaming } from './shapes.js';
18
+ import { canonicalize, contentHash } from './hash.js';
19
+ /** A clause's own ports; a junction's fired-branch ports never shadow them (M4). @experimental */
20
+ export const JUNCTION_CLAUSE_PORTS = new Set(['main', 'values', 'branches', 'ok']);
21
+ /**
22
+ * A junction's branch-end nodes (M4): the last node of each chain, by
23
+ * position. What a junction publishes beyond its clause ports is read off
24
+ * these.
25
+ * @experimental
26
+ */
27
+ export function junctionBranchEnds(nodes, clause, clauses = []) {
28
+ return clause.chains.map((chain) => {
29
+ const inChain = nodes.filter((n) => n.clauseId === clause.id && n.clauseChain === chain);
30
+ const last = inChain.reduce((a, n) => (!a || n.position > a.position ? n : a), undefined);
31
+ // A branch that ends in a nested clause has no node end: what it
32
+ // publishes is the clause's union, not a node's ports (M4 review).
33
+ const nested = clauses.filter((c) => c.clauseId === clause.id && c.clauseChain === chain);
34
+ const endsInClause = nested.some((c) => !last || c.position > last.position);
35
+ return { chain, node: endsInClause ? undefined : last };
36
+ });
37
+ }
38
+ /** The shape every branch of junction `id` agrees `port` has, else undefined (M4). */
39
+ function junctionPortShape(built, id, port) {
40
+ const clause = built.clauses.find((c) => c.id === id);
41
+ if (!clause || clause.kind !== 'junction' || JUNCTION_CLAUSE_PORTS.has(port))
42
+ return undefined;
43
+ const shapes = junctionBranchEnds(built.nodes, clause, built.clauses).map(({ node }) => node ? getDefinition(`${node.definitionId}@${node.definitionVersion}`)?.ports.out?.[port] : undefined);
44
+ return shapes.length && shapes.every((s) => s && s === shapes[0]) ? shapes[0] : undefined;
45
+ }
46
+ /** Nodes that participate in the top-level sequential spine (not inside a clause). */
47
+ const spineOf = (nodes) => nodes.filter((n) => !n.clauseId);
48
+ /**
49
+ * Compile a built spec to the document a host stores. A document that is
50
+ * already compiled (a helper such as `turnOrderSpec()` returns one) comes back
51
+ * as a copy, so a list of pipelines can hold either; one written for another
52
+ * document schema is refused. Its graph checks are the host's publish
53
+ * `validate()`, which every stored document meets.
54
+ * @experimental
55
+ */
56
+ export function compile(built) {
57
+ if ('schemaVersion' in built) {
58
+ if (built.schemaVersion !== 1)
59
+ throw new Error(`spec '${built.id}' is a document for schema ${String(built.schemaVersion)} — this SDK compiles schema 1`);
60
+ return importDocument(built);
61
+ }
62
+ const nodes = built.nodes.map((n) => ({
63
+ key: n.key,
64
+ kind: n.kind,
65
+ definitionId: n.definitionId,
66
+ definitionVersion: n.definitionVersion,
67
+ config: n.config,
68
+ clauseId: n.clauseId,
69
+ clauseKind: n.clauseKind,
70
+ clauseChain: n.clauseChain,
71
+ position: n.position,
72
+ ...(n.expose ? { expose: n.expose } : {}),
73
+ }));
74
+ const edges = [];
75
+ // Explicit $ref edges.
76
+ for (const n of built.nodes) {
77
+ for (const { path, ref } of collectDataRefs(n.config)) {
78
+ const upstream = built.nodes.find((x) => x.key === ref.node);
79
+ const outShape = upstream
80
+ ? getDefinition(`${upstream.definitionId}@${upstream.definitionVersion}`)?.ports.out?.[ref.port]
81
+ : junctionPortShape(built, ref.node, ref.port);
82
+ // Whether an edge streams is decided here, at publish — so it is readable
83
+ // off the spec rather than discovered by running it (01 §11).
84
+ edges.push({
85
+ from: ref.node,
86
+ fromPort: ref.port,
87
+ to: n.key,
88
+ toPort: path.join('.'),
89
+ shape: outShape,
90
+ streaming: outShape ? isStreaming(outShape) : undefined,
91
+ });
92
+ }
93
+ }
94
+ // Implicit chain edges along the spine.
95
+ const spine = spineOf(built.nodes);
96
+ for (let i = 1; i < spine.length; i++) {
97
+ const prev = spine[i - 1];
98
+ const cur = spine[i];
99
+ const already = edges.some((e) => e.to === cur.key && e.from === prev.key);
100
+ if (!already)
101
+ edges.push({
102
+ from: prev.key,
103
+ fromPort: 'main',
104
+ to: cur.key,
105
+ toPort: 'main',
106
+ implicit: true,
107
+ });
108
+ }
109
+ // Resolve config references that were left to publish (16 §5b-i).
110
+ for (const n of nodes) {
111
+ const resolved = {};
112
+ for (const [k, v] of Object.entries(n.config)) {
113
+ if (!isSlotRef(v))
114
+ continue;
115
+ const ref = v;
116
+ if (ref.resolveDownstreamOracle) {
117
+ const target = resolveDownstreamOracle(built, n.key);
118
+ resolved[k] = target;
119
+ }
120
+ else if (ref.ofEnvoy) {
121
+ // An envoy's config (R-18 (2)): the genre the spec serves must
122
+ // declare the key. Checked against the registry when the genre
123
+ // is one this build declares; a genre this build has never
124
+ // seen (a plugin's, declared elsewhere) cannot be checked here.
125
+ // The host checks it where the document lands as rows
126
+ // (`saveDocument`, U5g review W4): the genre's declaration and
127
+ // each action's envoy are re-run through `envoysFindings` /
128
+ // `envoyFindings`, and a reference to a key the genre's
129
+ // published declaration does not carry is refused there.
130
+ // ⏳ Today no plugin document reaches `saveDocument` — the app
131
+ // publishes the core catalog only — so the host's check is
132
+ // the boundary a plugin publish path will meet, not one any
133
+ // plugin has met. The address is the synthetic node key the
134
+ // executor resolves config for.
135
+ const genreId = built.input?.genre;
136
+ const known = genreId ? getGenre(genreId) : undefined;
137
+ if (known && !known.envoys?.some((e) => e.key === ref.ofEnvoy))
138
+ throw new Error(`node '${n.key}' references the prompts of envoy '${ref.ofEnvoy}', which ` +
139
+ `'${genreId}' does not declare` +
140
+ (known.envoys?.length
141
+ ? ` — it declares ${known.envoys.map((e) => `'${e.key}'`).join(', ')}`
142
+ : ' — it declares no envoys'));
143
+ if (!genreId)
144
+ throw new Error(`node '${n.key}' references the prompts of envoy '${ref.ofEnvoy}', but the spec ` +
145
+ `serves no genre — an envoy is a genre's (or an action's), and the inlet lock ` +
146
+ `names which (24 §4)`);
147
+ resolved[k] = envoyConfigKey(ref.ofEnvoy);
148
+ }
149
+ else if (ref.ofNode) {
150
+ if (!built.nodes.some((x) => x.key === ref.ofNode)) {
151
+ throw new Error(`node '${n.key}' references config of unknown node '${ref.ofNode}'`);
152
+ }
153
+ resolved[k] = ref.ofNode;
154
+ }
155
+ }
156
+ if (Object.keys(resolved).length)
157
+ n.resolvedRefs = resolved;
158
+ }
159
+ // A message written as a named envoy (ruled 2026-09-26: everyone has a
160
+ // name): a literal `speaker: 'envoy:<slug>'` on a message write must name
161
+ // an envoy the served genre or this spec's own actions declare — refused
162
+ // by name here, where the author is, because at the write it would be a
163
+ // line under a name nothing declares. A genre this build has never seen
164
+ // cannot be checked; the host refuses the write there.
165
+ for (const n of built.nodes) {
166
+ if (n.definitionId !== CREATE_MESSAGE_ID)
167
+ continue;
168
+ const slug = envoySlugOfRef(n.config.speaker);
169
+ if (slug === null)
170
+ continue;
171
+ const genreId = built.input?.genre;
172
+ const known = genreId ? getGenre(genreId) : undefined;
173
+ const own = (built.meta.contributes?.actions ?? []).flatMap((a) => a.envoy?.key ? [envoySlugOf({ action: { specId: built.id } }, a.envoy.key)] : []);
174
+ if (own.includes(slug))
175
+ continue;
176
+ if (genreId && !known)
177
+ continue;
178
+ if (known?.envoys?.some((e) => e.key === slug))
179
+ continue;
180
+ const declared = [...(known?.envoys ?? []).map((e) => e.key), ...own];
181
+ throw new Error(`node '${n.key}' speaks as envoy '${slug}', which ` +
182
+ (genreId ? `'${genreId}' and this spec's actions do not declare` : `nothing declares — the spec serves no genre`) +
183
+ (declared.length ? ` — declared: ${declared.map((k) => `'${k}'`).join(', ')}` : ' — none are declared'));
184
+ }
185
+ return {
186
+ schemaVersion: 1,
187
+ id: built.id,
188
+ version: built.meta.version,
189
+ genre: built.meta.genre,
190
+ input: built.input,
191
+ contributes: built.meta.contributes,
192
+ taxonomy: built.meta.taxonomy,
193
+ includes: built.includes,
194
+ presets: built.presets,
195
+ nodes,
196
+ edges,
197
+ clauses: built.clauses,
198
+ };
199
+ }
200
+ /**
201
+ * Follow the spine forward from `fromKey` to the first oracle. Linearity is what
202
+ * makes this well-defined (F25). Ambiguity or absence is a publish error that names
203
+ * the candidates — the teaching-error pattern (15 §1.3).
204
+ * @experimental
205
+ */
206
+ export function resolveDownstreamOracle(built, fromKey) {
207
+ const ordered = built.nodes.slice().sort((a, b) => a.position - b.position);
208
+ const start = ordered.findIndex((n) => n.key === fromKey);
209
+ const after = ordered.slice(start + 1).filter((n) => n.kind === 'oracle');
210
+ // Oracles inside a clause are per-chain; only spine oracles are unambiguous targets.
211
+ const spineOracles = after.filter((n) => !n.clauseId);
212
+ if (spineOracles.length === 0) {
213
+ const candidates = after.map((n) => n.key);
214
+ throw new Error(`slot.downstreamOracle() on '${fromKey}' found no oracle downstream on the spine. ` +
215
+ (candidates.length
216
+ ? `Oracles exist inside clauses (${candidates.join(', ')}) — name one explicitly with slot.oracleRef('…').`
217
+ : `Add an oracle, or use slot.oracleRef('…').`));
218
+ }
219
+ return spineOracles[0].key;
220
+ }
221
+ /**
222
+ * Canonical form — stable key order, for hashing and round-trip identity (F3).
223
+ *
224
+ * The sort and the digest below moved to `hash.ts` unchanged, because the type
225
+ * registries now need the same two and a document and a declaration must not
226
+ * disagree about what identical content is. Same bytes in, same string out.
227
+ * @experimental
228
+ */
229
+ export function canonical(doc) {
230
+ return canonicalize(doc);
231
+ }
232
+ /** Cheap deterministic content hash — stands in for the real canonical_hash (02 §3). @experimental */
233
+ export function canonicalHash(doc) {
234
+ return contentHash(doc);
235
+ }
236
+ /** Import: document → the same in-memory form. `import(export(x))` is identity (F3). @experimental */
237
+ export function importDocument(doc) {
238
+ return JSON.parse(JSON.stringify(doc));
239
+ }
240
+ /**
241
+ * Export a document, with the presets a user selected (12 §7).
242
+ *
243
+ * **A filtered export is a different document, not a lossy copy of the same one**, so its
244
+ * canonical hash legitimately differs from the source's. F3's identity law is about a
245
+ * given export round-tripping — `import(export(x)) === export(x)` — and that still holds
246
+ * exactly.
247
+ * @experimental
248
+ */
249
+ export function exportDocument(doc, opts = {}) {
250
+ const omitted = [];
251
+ const want = opts.presets ?? 'all';
252
+ const keep = (p) => want === 'all' ? true : want === 'none' ? false : want.includes(p.slug);
253
+ const presets = [];
254
+ for (const p of doc.presets ?? []) {
255
+ if (!keep(p)) {
256
+ omitted.push({ what: `preset '${p.slug}'`, reason: 'not selected for export' });
257
+ continue;
258
+ }
259
+ const values = [];
260
+ for (const v of p.values) {
261
+ // Connection details never leave, whatever else was chosen (12 §7).
262
+ if (v.slot === 'connection') {
263
+ omitted.push({
264
+ what: `${p.slug} → ${v.nodeKey}.connection`,
265
+ reason: 'connection details never leave a pub',
266
+ });
267
+ continue;
268
+ }
269
+ if (opts.bindings === 'flattened' && isRef(v.value)) {
270
+ const resolved = opts.resolve?.(v.slot, v.value.$ref);
271
+ if (resolved === undefined) {
272
+ omitted.push({
273
+ what: `${p.slug} → ${v.nodeKey}.${v.slot}`,
274
+ reason: `could not resolve '${v.value.$ref}' to flatten`,
275
+ });
276
+ continue;
277
+ }
278
+ values.push({ ...v, value: resolved });
279
+ continue;
280
+ }
281
+ values.push(v);
282
+ }
283
+ presets.push({ ...p, values });
284
+ }
285
+ // A preset with a default that did not travel would import as a spec with no default.
286
+ if (presets.length && !presets.some((p) => p.default)) {
287
+ const lost = (doc.presets ?? []).find((p) => p.default);
288
+ if (lost)
289
+ omitted.push({
290
+ what: `default preset '${lost.slug}'`,
291
+ reason: 'not selected; the import has no shipped default',
292
+ });
293
+ }
294
+ return { doc: { ...doc, presets }, omitted, requires: requiredConnections(doc) };
295
+ }
296
+ const isRef = (v) => !!v && typeof v === 'object' && typeof v.$ref === 'string';
297
+ /**
298
+ * The envoy config addresses a document references — every `resolvedRefs`
299
+ * target spelled `envoy:<key>`, once each. The executor resolves config for
300
+ * these beside the nodes and clauses; the host projects the genre's
301
+ * declaration at exactly these keys.
302
+ * @internal
303
+ */
304
+ export function envoyConfigKeysOf(doc) {
305
+ const out = new Set();
306
+ for (const n of doc.nodes)
307
+ for (const target of Object.values(n.resolvedRefs ?? {}))
308
+ if (isEnvoyConfigKey(target))
309
+ out.add(target);
310
+ return [...out];
311
+ }
312
+ //# sourceMappingURL=document.js.map
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Template engines are a registry, not a hardcoded choice (F2 — types are open
3
+ * registries, ids namespaced, `core:` reserved).
4
+ *
5
+ * `SlotDecl.engine` used to be the literal `'jinja2'`, which quietly said "there is one
6
+ * template language and core owns it." An extension shipping its own compiler had nowhere
7
+ * to register it, and a template slot had no way to say what it was written in. Now the
8
+ * engine is a versioned id like everything else, and it travels **on the template value**
9
+ * — so two slots in one spec may use different engines.
10
+ *
11
+ * That is safe for a reason worth stating: source templates render *before* Assemble
12
+ * (16 §3b, enforced by port shapes), so only text crosses into allocation. Mixing engines
13
+ * cannot confuse the budget, because the budget never sees a template — it sees rendered
14
+ * blocks and a cost profile.
15
+ *
16
+ * ## The cost profile is why this interface has four members instead of one
17
+ *
18
+ * The budget guarantee (16 §7) is that Assemble's estimate is a **ceiling**: literals are
19
+ * counted exactly, per-iteration literals are counted once and multiplied, conditionals
20
+ * take their largest branch. That is a static analysis of the template, so it can only be
21
+ * done by whoever understands the syntax — the engine.
22
+ *
23
+ * An engine that cannot analyse itself is still legal. It reports `exact: false`, Assemble
24
+ * widens its safety margin, and the receipt records that the estimate was approximate. So
25
+ * a sloppy engine costs its users context headroom rather than correctness — a pressure
26
+ * gradient rather than a ban.
27
+ */
28
+ import { type TemplateFinding, type TemplateScope } from "./template.js";
29
+ /** @experimental */
30
+ export type EngineId = string;
31
+ /** What a template slot actually stores: the source **and** what it is written in. @experimental */
32
+ export interface TemplateValue {
33
+ engine: EngineId;
34
+ source: string;
35
+ }
36
+ /** @experimental */
37
+ export interface CostProfile {
38
+ /** Tokens contributed by literal text outside any repetition. */
39
+ fixed: number;
40
+ /** Tokens contributed per iteration of the named loop variable. */
41
+ perIteration: Record<string, number>;
42
+ /**
43
+ * False when the engine could not analyse statically and these numbers are a guess.
44
+ * Assemble widens its margin and the receipt says so — the estimate degrades to
45
+ * conservative rather than to wrong (16 §7).
46
+ */
47
+ exact: boolean;
48
+ }
49
+ /** @experimental */
50
+ export interface TemplateEngine {
51
+ id: EngineId;
52
+ /** Human-facing, for the template editor's language picker. */
53
+ label: string;
54
+ render(source: string, scope: Record<string, unknown>): string;
55
+ /** Variables the source references — feeds the editor and publish-time checking (16 §4). */
56
+ extract(source: string): string[];
57
+ /** Publish-time diagnostics against the slot's declared `variables` (13 §7j-a). */
58
+ check(source: string, declared: TemplateScope): TemplateFinding[];
59
+ /**
60
+ * Static token cost, given a tokenizer. Called once per (source, tokenizer) and
61
+ * cached — never per allocation step, or the budget loop has a cliff exactly when
62
+ * a user's context is biggest.
63
+ */
64
+ costProfile(source: string, count: (s: string) => number): CostProfile;
65
+ }
66
+ /** @experimental */
67
+ export declare function defineEngine(e: TemplateEngine): TemplateEngine;
68
+ /** @experimental */
69
+ export declare const getEngine: (id: EngineId) => TemplateEngine | undefined;
70
+ /** @experimental */
71
+ export declare const allEngines: () => TemplateEngine[];
72
+ /** @experimental */
73
+ export declare function _clearEngines(): void;
74
+ /** Resolve and render, with an error that names the engine rather than failing obscurely. @experimental */
75
+ export declare function renderWith(value: TemplateValue, scope: Record<string, unknown>): string;
76
+ /** @experimental */
77
+ export declare const jinja2: TemplateEngine;
78
+ /**
79
+ * No substitution at all. Useful on its own — a fixed system preamble is a template with
80
+ * no variables — and useful as the reference implementation of an exact cost profile.
81
+ * @experimental
82
+ */
83
+ export declare const plain: TemplateEngine;
84
+ /**
85
+ * Handlebars — **the engine Serene Pub's context templates are actually written in.**
86
+ *
87
+ * Registered as a declaration rather than an implementation: a template's engine is a
88
+ * datapoint on the slot (12 §2a), and the host supplies the renderer. The SDK ships no
89
+ * Handlebars dependency, so `render` here refuses rather than silently producing
90
+ * something that is not what core would produce — a near-miss renderer is worse than an
91
+ * absent one, because parity would fail in a way that looks like a template bug.
92
+ *
93
+ * The correction this represents is worth stating: the draft assumed Jinja throughout,
94
+ * and every core template in SP is Handlebars with a registered helper set. The
95
+ * template-engine registry is exactly the mechanism that makes that a one-line change
96
+ * rather than a redesign, which is the argument for having built it.
97
+ * @experimental
98
+ */
99
+ export declare const handlebars: TemplateEngine;
100
+ /**
101
+ * Liquid — core's **second** template engine, added beside Handlebars rather than
102
+ * instead of it.
103
+ *
104
+ * Host-supplied for the same reason Handlebars is: core renders with its own
105
+ * registered tag and filter set (`systemBlock`/`assistantBlock`/`userBlock`, `json`,
106
+ * `jsonValue`, `pad`) under a configuration a second implementation would not
107
+ * reproduce, and a near-miss renderer fails as what reads like a template bug.
108
+ * @experimental
109
+ */
110
+ export declare const liquid: TemplateEngine;
111
+ /** Sugar so a spec reads `template: jinja(SOURCE)` rather than repeating the id. @experimental */
112
+ export declare const templateOf: (engine: TemplateEngine) => (source: string) => TemplateValue;
113
+ /** @experimental */
114
+ export declare const jinja: (source: string) => TemplateValue;
115
+ /** @experimental */
116
+ export declare const text: (source: string) => TemplateValue;
117
+ //# sourceMappingURL=engines.d.ts.map
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Template engines are a registry, not a hardcoded choice (F2 — types are open
3
+ * registries, ids namespaced, `core:` reserved).
4
+ *
5
+ * `SlotDecl.engine` used to be the literal `'jinja2'`, which quietly said "there is one
6
+ * template language and core owns it." An extension shipping its own compiler had nowhere
7
+ * to register it, and a template slot had no way to say what it was written in. Now the
8
+ * engine is a versioned id like everything else, and it travels **on the template value**
9
+ * — so two slots in one spec may use different engines.
10
+ *
11
+ * That is safe for a reason worth stating: source templates render *before* Assemble
12
+ * (16 §3b, enforced by port shapes), so only text crosses into allocation. Mixing engines
13
+ * cannot confuse the budget, because the budget never sees a template — it sees rendered
14
+ * blocks and a cost profile.
15
+ *
16
+ * ## The cost profile is why this interface has four members instead of one
17
+ *
18
+ * The budget guarantee (16 §7) is that Assemble's estimate is a **ceiling**: literals are
19
+ * counted exactly, per-iteration literals are counted once and multiplied, conditionals
20
+ * take their largest branch. That is a static analysis of the template, so it can only be
21
+ * done by whoever understands the syntax — the engine.
22
+ *
23
+ * An engine that cannot analyse itself is still legal. It reports `exact: false`, Assemble
24
+ * widens its safety margin, and the receipt records that the estimate was approximate. So
25
+ * a sloppy engine costs its users context headroom rather than correctness — a pressure
26
+ * gradient rather than a ban.
27
+ */
28
+ import { render as renderJinja, extractRefs, checkTemplate } from "./template.js";
29
+ import { refuseUnlessIdentical } from './hash.js';
30
+ const engines = new Map();
31
+ /** @experimental */
32
+ export function defineEngine(e) {
33
+ const existing = engines.get(e.id);
34
+ // `label` is the name in the editor's language picker and nothing else reads
35
+ // it, so renaming one is display text — the same rule `i18n` gets everywhere.
36
+ if (existing)
37
+ refuseUnlessIdentical(existing, e, `duplicate template engine id: ${e.id}`, {
38
+ display: ['label'],
39
+ });
40
+ engines.set(e.id, e);
41
+ return e;
42
+ }
43
+ /** @experimental */
44
+ export const getEngine = (id) => engines.get(id);
45
+ /** @experimental */
46
+ export const allEngines = () => [...engines.values()];
47
+ /** @experimental */
48
+ export function _clearEngines() {
49
+ engines.clear();
50
+ }
51
+ /** Resolve and render, with an error that names the engine rather than failing obscurely. @experimental */
52
+ export function renderWith(value, scope) {
53
+ const e = engines.get(value.engine);
54
+ if (!e) {
55
+ throw new Error(`no template engine registered for '${value.engine}'. ` +
56
+ `Available: ${allEngines()
57
+ .map((x) => x.id)
58
+ .join(", ") || "none"}. ` +
59
+ `An engine ships with the plugin that declares it — this usually means the plugin is disabled.`);
60
+ }
61
+ return e.render(value.source, scope);
62
+ }
63
+ // ── Core engines ────────────────────────────────────────────────────────────
64
+ /**
65
+ * Split a source into literal text and the structural tags around it. Deliberately
66
+ * crude — it is the toy engine's profiler, and its job here is to demonstrate the
67
+ * contract, not to be a Jinja parser.
68
+ */
69
+ function jinjaCost(source, count) {
70
+ const loops = [
71
+ ...source.matchAll(/\{%\s*for\s+\w+\s+in\s+(\w+)\s*%\}([\s\S]*?)\{%\s*endfor\s*%\}/g)
72
+ ];
73
+ const perIteration = {};
74
+ let body = source;
75
+ for (const m of loops) {
76
+ // Literal text inside the loop, minus expansions: counted once, charged per item.
77
+ const literal = m[2].replace(/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g, "");
78
+ perIteration[m[1]] = (perIteration[m[1]] ?? 0) + count(literal);
79
+ body = body.replace(m[0], "");
80
+ }
81
+ const fixedLiteral = body.replace(/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g, "");
82
+ return { fixed: count(fixedLiteral), perIteration, exact: true };
83
+ }
84
+ /** @experimental */
85
+ export const jinja2 = defineEngine({
86
+ id: "core:template/jinja2@1",
87
+ label: "Jinja2",
88
+ render: renderJinja,
89
+ extract: (s) => [...new Set(extractRefs(s).map((r) => r.path.join(".")))],
90
+ check: checkTemplate,
91
+ costProfile: jinjaCost
92
+ });
93
+ /**
94
+ * No substitution at all. Useful on its own — a fixed system preamble is a template with
95
+ * no variables — and useful as the reference implementation of an exact cost profile.
96
+ * @experimental
97
+ */
98
+ export const plain = defineEngine({
99
+ id: "core:template/plain@1",
100
+ label: "Plain text",
101
+ render: (s) => s,
102
+ extract: () => [],
103
+ check: () => [],
104
+ costProfile: (s, count) => ({
105
+ fixed: count(s),
106
+ perIteration: {},
107
+ exact: true
108
+ })
109
+ });
110
+ /**
111
+ * Handlebars — **the engine Serene Pub's context templates are actually written in.**
112
+ *
113
+ * Registered as a declaration rather than an implementation: a template's engine is a
114
+ * datapoint on the slot (12 §2a), and the host supplies the renderer. The SDK ships no
115
+ * Handlebars dependency, so `render` here refuses rather than silently producing
116
+ * something that is not what core would produce — a near-miss renderer is worse than an
117
+ * absent one, because parity would fail in a way that looks like a template bug.
118
+ *
119
+ * The correction this represents is worth stating: the draft assumed Jinja throughout,
120
+ * and every core template in SP is Handlebars with a registered helper set. The
121
+ * template-engine registry is exactly the mechanism that makes that a one-line change
122
+ * rather than a redesign, which is the argument for having built it.
123
+ * @experimental
124
+ */
125
+ export const handlebars = defineEngine({
126
+ id: "core:template/handlebars@1",
127
+ label: "Handlebars",
128
+ render: () => {
129
+ throw new Error("the Handlebars engine is host-supplied: core renders with its own registered " +
130
+ "helper set, and a second implementation here would differ in ways that read " +
131
+ "as template bugs");
132
+ },
133
+ // `{{a.b}}`, `{{#each xs}}`, `{{#if x}}` — enough to answer "what does this template
134
+ // reference", which is what variable-awareness needs (16 §4).
135
+ // Two patterns, not one: a single pattern with an optional keyword backtracks on
136
+ // `{{/each}}` and reports `each` as a variable, and a diagnostics list with helper
137
+ // names in it teaches a user to distrust the panel.
138
+ // One pass, in source order. The lookahead skips closing tags outright —
139
+ // without it, `{{/each}}` backtracks into reporting `each` as a variable.
140
+ extract: (s) => {
141
+ const found = new Set();
142
+ for (const m of s.matchAll(/\{\{(?!\/)#?\s*(?:each|if|unless|with)?\s*([\w.]+)/g))
143
+ if (m[1] && m[1] !== "this")
144
+ found.add(m[1]);
145
+ return [...found];
146
+ },
147
+ check: () => [],
148
+ // Not exact: the helper set can expand a reference into arbitrary text, so a
149
+ // character count is an estimate and says so (16 §7a).
150
+ costProfile: (s, count) => ({
151
+ fixed: count(s),
152
+ perIteration: {},
153
+ exact: false
154
+ })
155
+ });
156
+ /**
157
+ * Liquid — core's **second** template engine, added beside Handlebars rather than
158
+ * instead of it.
159
+ *
160
+ * Host-supplied for the same reason Handlebars is: core renders with its own
161
+ * registered tag and filter set (`systemBlock`/`assistantBlock`/`userBlock`, `json`,
162
+ * `jsonValue`, `pad`) under a configuration a second implementation would not
163
+ * reproduce, and a near-miss renderer fails as what reads like a template bug.
164
+ * @experimental
165
+ */
166
+ export const liquid = defineEngine({
167
+ id: "core:template/liquid@1",
168
+ label: "Liquid",
169
+ render: () => {
170
+ throw new Error("the Liquid engine is host-supplied: core renders with its own registered " +
171
+ "tag and filter set, and a second implementation here would differ in ways " +
172
+ "that read as template bugs");
173
+ },
174
+ // `{{ a.b }}`, `{% for x in xs %}`, `{% if x %}` — enough to answer "what does this
175
+ // template reference", which is what variable-awareness needs (16 §4). Filters,
176
+ // literals and the loop's own binding are excluded: a diagnostics list with
177
+ // `upcase` or `"quoted"` in it teaches a user to distrust the panel.
178
+ extract: (s) => {
179
+ const found = new Set();
180
+ for (const m of s.matchAll(/\{\{-?\s*([A-Za-z_][\w.]*)/g))
181
+ found.add(m[1]);
182
+ for (const m of s.matchAll(/\{%-?\s*(?:if|elsif|unless|case|when|assign\s+\w+\s*=|echo)\s+([A-Za-z_][\w.]*)/g))
183
+ found.add(m[1]);
184
+ for (const m of s.matchAll(/\{%-?\s*(?:for|tablerow)\s+\w+\s+in\s+([A-Za-z_][\w.]*)/g))
185
+ found.add(m[1]);
186
+ return [...found];
187
+ },
188
+ check: () => [],
189
+ // Not exact, for the same reason Handlebars is not: a filter or a custom tag can
190
+ // expand a reference into arbitrary text (16 §7a).
191
+ costProfile: (s, count) => ({
192
+ fixed: count(s),
193
+ perIteration: {},
194
+ exact: false
195
+ })
196
+ });
197
+ /** Sugar so a spec reads `template: jinja(SOURCE)` rather than repeating the id. @experimental */
198
+ export const templateOf = (engine) => (source) => ({ engine: engine.id, source });
199
+ /** @experimental */
200
+ export const jinja = templateOf(jinja2);
201
+ /** @experimental */
202
+ export const text = templateOf(plain);
203
+ //# sourceMappingURL=engines.js.map