@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,222 @@
1
+ /**
2
+ * What a Handlebars reference can reach, at one point in a template.
3
+ *
4
+ * Typed templates P4. The template checker (`@serene-pub/sdk/template-check`)
5
+ * and a host's editor assist both need the same three answers — what `../`
6
+ * climbs to, what a block param is bound to, and what one `{{#each}}` element
7
+ * is — and when they were two copies they drifted: the assist treated an
8
+ * `{{#if}}` as a new context, so a root name inside one was "unknowable". This
9
+ * module is the one reading; it has no dependencies, so an editor that only
10
+ * scans tags (it sees half-typed source, which no parser accepts) can use it
11
+ * without the parser the checker carries.
12
+ *
13
+ * **Conservative by construction**: whatever the schema cannot speak to — an
14
+ * `'any'` root, a record's author-chosen key, a subexpression's result —
15
+ * resolves as *unchecked*, never as wrong.
16
+ */
17
+ import { elementOf, resolvePath } from './template.js';
18
+ /** The root: names resolve against the scope. @experimental */
19
+ export const rootHandlebarsReach = () => ({ unchecked: false, params: new Map() });
20
+ /**
21
+ * Read a written path the way Handlebars' parser does, for a caller that only
22
+ * has the text (an editor scanning tags). The checker reads the parser's own
23
+ * AST instead and builds the same shape from it.
24
+ * @experimental
25
+ */
26
+ export function handlebarsPath(expr) {
27
+ let rest = expr.trim();
28
+ if (rest.startsWith('@'))
29
+ return { depth: 0, scoped: false, data: true, parts: splitSegments(rest.slice(1)) };
30
+ let depth = 0;
31
+ while (rest.startsWith('../')) {
32
+ rest = rest.slice(3);
33
+ depth++;
34
+ }
35
+ if (rest === '..')
36
+ return { depth: depth + 1, scoped: false, data: false, parts: [] };
37
+ let scoped = false;
38
+ if (rest.startsWith('./')) {
39
+ scoped = true;
40
+ rest = rest.slice(2);
41
+ }
42
+ let parts = splitSegments(rest);
43
+ if (parts[0] === 'this') {
44
+ scoped = true;
45
+ parts = parts.slice(1);
46
+ }
47
+ if (parts.length === 1 && parts[0] === '.')
48
+ parts = [];
49
+ return { depth, scoped, data: false, parts };
50
+ }
51
+ /**
52
+ * `this.[extra lore].note` → `['this', 'extra lore', 'note']`.
53
+ *
54
+ * Splitting on `.` alone is right until a segment literal holds one, and
55
+ * unwrapping the brackets is what lets the name match the schema's key — the
56
+ * schema knows `extra lore`, not `[extra lore]`. A half-typed `[extra lo` still
57
+ * names its segment.
58
+ */
59
+ function splitSegments(expr) {
60
+ const out = [];
61
+ let cur = '';
62
+ let inBracket = false;
63
+ for (const c of expr) {
64
+ if (c === '[') {
65
+ inBracket = true;
66
+ continue;
67
+ }
68
+ if (c === ']') {
69
+ inBracket = false;
70
+ continue;
71
+ }
72
+ if (c === '.' && !inBracket) {
73
+ if (cur)
74
+ out.push(cur);
75
+ cur = '';
76
+ continue;
77
+ }
78
+ cur += c;
79
+ }
80
+ if (cur)
81
+ out.push(cur);
82
+ return out;
83
+ }
84
+ const UNCHECKED = { kind: 'unchecked' };
85
+ /** Is this the root reach, where names resolve against the scope? */
86
+ const isRoot = (r) => !r.context && !r.parent;
87
+ /**
88
+ * Resolve a path within a reach — Handlebars' own order: `../` climbs first; a
89
+ * block param only answers an unscoped, unclimbed name; the root answers from
90
+ * the scope; any other context answers from its type.
91
+ * @experimental
92
+ */
93
+ export function resolveHandlebarsPath(path, reach, scope) {
94
+ if (path.data)
95
+ return UNCHECKED;
96
+ let r = reach;
97
+ for (let i = 0; i < path.depth; i++) {
98
+ if (!r.parent)
99
+ return UNCHECKED;
100
+ r = r.parent;
101
+ }
102
+ const [first, ...tail] = path.parts;
103
+ if (first === undefined)
104
+ return {
105
+ kind: 'resolved',
106
+ base: r.context,
107
+ label: 'this',
108
+ rest: [],
109
+ resolution: resolvePath(r.context, []),
110
+ };
111
+ if (!path.depth && !path.scoped && reach.params.has(first)) {
112
+ const bound = reach.params.get(first);
113
+ return {
114
+ kind: 'resolved',
115
+ base: bound,
116
+ label: first,
117
+ rest: tail,
118
+ resolution: resolvePath(bound, tail, first),
119
+ };
120
+ }
121
+ if (isRoot(r)) {
122
+ const decl = scope[first];
123
+ if (decl === undefined)
124
+ return { kind: 'unknown-root', root: first, available: Object.keys(scope) };
125
+ return {
126
+ kind: 'resolved',
127
+ base: decl,
128
+ label: first,
129
+ rest: tail,
130
+ resolution: resolvePath(decl, tail, first),
131
+ };
132
+ }
133
+ if (r.unchecked || !r.context)
134
+ return UNCHECKED;
135
+ return {
136
+ kind: 'resolved',
137
+ base: r.context,
138
+ label: 'this',
139
+ rest: path.parts,
140
+ resolution: resolvePath(r.context, path.parts, 'this'),
141
+ };
142
+ }
143
+ /** What a path's value is, as a declaration — undefined when unknowable. @experimental */
144
+ export function typeOfHandlebarsPath(path, reach, scope) {
145
+ const r = resolveHandlebarsPath(path, reach, scope);
146
+ if (r.kind !== 'resolved' || !r.resolution.ok)
147
+ return undefined;
148
+ return r.resolution.field ?? (r.rest.length ? undefined : r.base);
149
+ }
150
+ /** A declaration that is a walkable field — not `'any'`, not the legacy name list. @experimental */
151
+ export function asVarField(decl) {
152
+ return decl && decl !== 'any' && !Array.isArray(decl) ? decl : undefined;
153
+ }
154
+ /**
155
+ * The reach a block's body sees.
156
+ *
157
+ * Only `each` and `with` move the context, and only they give `../` a step to
158
+ * climb; `if`, `unless` and every other block helper keep the reach they were
159
+ * opened in (plus any `as |x|` names, unchecked). `each` binds its first param
160
+ * to one element and the second to the index or key; `with` binds it to the
161
+ * value itself.
162
+ *
163
+ * An `{{else}}` branch of `each`/`with` runs in the reach the block was opened
164
+ * in — the caller keeps that one, it is not this.
165
+ * @experimental
166
+ */
167
+ export function enterHandlebarsBlock(reach, helper, target, blockParams = []) {
168
+ if (helper !== 'each' && helper !== 'with') {
169
+ if (!blockParams.length)
170
+ return reach;
171
+ const params = new Map(reach.params);
172
+ for (const name of blockParams)
173
+ params.set(name, undefined);
174
+ return { ...reach, params };
175
+ }
176
+ const context = helper === 'each' ? elementOf(target) : asVarField(target);
177
+ const params = new Map(reach.params);
178
+ if (blockParams[0])
179
+ params.set(blockParams[0], context);
180
+ for (const extra of blockParams.slice(1))
181
+ params.set(extra, undefined);
182
+ return { context, unchecked: !context, params, parent: reach };
183
+ }
184
+ /**
185
+ * The nearest name, when there is an obviously-nearest one — the "did you
186
+ * mean" half of a finding.
187
+ *
188
+ * Deliberately tight: within one edit for a name of four characters or fewer,
189
+ * two otherwise. A wrong guess sends someone to change a line that was
190
+ * correct, which costs more than saying nothing. Ties resolve alphabetically,
191
+ * so the answer is stable.
192
+ * @experimental
193
+ */
194
+ export function nearestName(typed, available) {
195
+ if (!typed || !available.length)
196
+ return undefined;
197
+ const limit = typed.length <= 4 ? 1 : 2;
198
+ let best;
199
+ let bestDistance = Infinity;
200
+ for (const name of [...available].sort()) {
201
+ const d = editDistance(typed.toLowerCase(), name.toLowerCase());
202
+ if (d < bestDistance && d <= limit) {
203
+ best = name;
204
+ bestDistance = d;
205
+ }
206
+ }
207
+ return best;
208
+ }
209
+ /** Levenshtein, two rows. */
210
+ function editDistance(a, b) {
211
+ if (a === b)
212
+ return 0;
213
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
214
+ for (let i = 1; i <= a.length; i++) {
215
+ const row = [i];
216
+ for (let j = 1; j <= b.length; j++)
217
+ row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
218
+ prev = row;
219
+ }
220
+ return prev[b.length];
221
+ }
222
+ //# sourceMappingURL=handlebarsReach.js.map
package/dist/hash.d.ts ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * One canonical form, one digest, one re-declaration rule.
3
+ *
4
+ * Two things in the SDK have to answer "is this the same content as that": a
5
+ * spec document's `canonicalHash` (02 §3), and every registry here that refuses
6
+ * a second declaration under an id it already holds. They must not answer
7
+ * differently, so the sort and the digest live here once and both call in — a
8
+ * second hashing scheme is how two places quietly start disagreeing about what
9
+ * "the same" means.
10
+ *
11
+ * ## Why the registries needed an answer at all
12
+ *
13
+ * `if (map.has(id)) throw` is the right guard for the case it was written for:
14
+ * two *different* declarations claiming one id means one of them silently wins
15
+ * and which one depends on load order. It is the wrong guard for a case nobody
16
+ * had in mind — a module re-evaluating with the same source. That is exactly
17
+ * what a dev server's hot reload does: saving an app file that imports
18
+ * `@serene-pub/contracts` re-runs every `describe*` in it against a registry
19
+ * living in a module that was *not* reloaded, so the first id threw, the reload
20
+ * failed, and the server retried in a loop.
21
+ *
22
+ * The fix is to key the refusal on content rather than on arrival. Deliberately
23
+ * not gated on `import.meta.hot` or `NODE_ENV`: an identical re-declaration is
24
+ * harmless everywhere, and an environment check would only hide the case where
25
+ * it is *not* identical — which is the case the guard exists for.
26
+ */
27
+ /** Canonical form — stable key order, for hashing and round-trip identity (F3). @experimental */
28
+ export declare function canonicalize(v: unknown): string;
29
+ /** Cheap deterministic content hash — stands in for the real canonical_hash (02 §3). @experimental */
30
+ export declare function contentHash(v: unknown): string;
31
+ /**
32
+ * What this strip is *for*, said once so nobody reads it as the whole rule:
33
+ * the denylist below is the re-declaration guard of every registry whose
34
+ * declarations are hashed whole — genres, scripts, engines, wire formats,
35
+ * events, facets, variables, sheets, attributes. A **node definition** is the
36
+ * exception (plans/31 V6, 2026-09-17): its hash is an *allowlist* of its
37
+ * contract — `definitionContract` in `descriptors.ts` — and everything else on
38
+ * a `Descriptor` is policy, never hashed. `provisional`, `reviewDefault`,
39
+ * `timeoutMs`, `timeoutKind`, `toggleable`, `public` and `usage` are policy,
40
+ * so flipping one moves no pin; the digest and the canonical form are still
41
+ * this file's.
42
+ */
43
+ /**
44
+ * What a registry knows about its own declarations that this file cannot.
45
+ *
46
+ * Display text is not always spelled `i18n`. `ScriptKindDecl.blastRadius` is
47
+ * the badge the script panel shows and says so in its own docblock; a
48
+ * `TemplateEngine`'s and a `WireFormat`'s `label` is the name in a picker; a
49
+ * `FieldDecl`'s `label` is its display text. All of them were hashed, so re-badging a
50
+ * script or renaming a parameter threw `duplicate id` and put the reload loop
51
+ * straight back — the one case the docblock at the top of this file promises is
52
+ * fixed.
53
+ *
54
+ * The registry declares the list rather than this helper recognising the words,
55
+ * because only the registry can tell them apart. `blastRadius` is a badge and
56
+ * `semantics` is a contract; `WidgetDecl.title` is a heading and
57
+ * `EntryRoles.title` is which field the engine reads as a row's title — same
58
+ * word, opposite answers, both inside one `Descriptor`. A helper that knew key
59
+ * names would have to be right about every registry's vocabulary forever, and
60
+ * would be wrong the first time two registries disagreed. Keeping the judgement
61
+ * at the call site is what lets this stay one rule.
62
+ * @experimental
63
+ */
64
+ export interface DisplayKeys {
65
+ /**
66
+ * Display-text keys this registry's declarations carry *outside*
67
+ * `i18n`/`description`. Stripped recursively, like those two — a field's
68
+ * label sits two levels down inside a slot.
69
+ */
70
+ display?: readonly string[];
71
+ }
72
+ /**
73
+ * What is *material* about a declaration, as the registries compare them.
74
+ *
75
+ * Two departures from hashing a declaration as plain data, and both are rules
76
+ * this codebase already applies to the registry rows these declarations project
77
+ * into (core's `typeContentHash`):
78
+ *
79
+ * · **Display text is not content.** `i18n` and `description` are stripped
80
+ * recursively, along with whatever else the calling registry names as
81
+ * display (see `DisplayKeys`), because renaming a node or copyediting an
82
+ * explanation is not a change to what the declaration means. It is also what
83
+ * makes the reload case fully fixed rather than half fixed: editing a label
84
+ * is the most common thing a person saves, and it must not put the loop
85
+ * back.
86
+ * · **Behaviour is.** A template engine or a wire format is almost entirely
87
+ * functions, and `JSON.stringify` drops those silently — so hashing one as
88
+ * data would make *every* declaration under an id identical and the guard
89
+ * would stop guarding. Functions canonicalize to their source text, which is
90
+ * the comparison a re-evaluation needs: the same source re-runs to the same
91
+ * hash, an edited one does not.
92
+ *
93
+ * ## Exported, because the strip is the one thing every hash here shares
94
+ *
95
+ * A `Descriptor` is compared when it is re-declared, and projected into a
96
+ * `pipeline_definition_registry` row whose `content_hash` decides whether an
97
+ * upgrading install may republish it. Those are two answers to one question —
98
+ * *is this the same content?* — and they were once computed by two functions
99
+ * that disagreed: core stripped `i18n` and `description`, this stripped
100
+ * `label` as well (see `DESCRIPTOR_DISPLAY_KEYS`), so renaming a parameter was
101
+ * free on one side and a frozen-type conflict on the other. Both now call
102
+ * `definitionContract`, which reads every contract field through this strip
103
+ * (`declarationData`); the strip is exported so that function is the only
104
+ * place a definition's material is composed, and so the registries that hash
105
+ * a declaration whole keep the same words for display text.
106
+ * @experimental
107
+ */
108
+ export declare function declarationMaterial(v: unknown, opts?: DisplayKeys): unknown;
109
+ /**
110
+ * `declarationMaterial` for a declaration that is **data**: display text out,
111
+ * and a function value **omitted** rather than rendered as source.
112
+ *
113
+ * The node-definition contract (`definitionContract`) reads its fields
114
+ * through this. A definition's contract is what a registry row carries so
115
+ * core can judge a plugin without executing it (F6), and a row cannot carry
116
+ * a function — so a function is not contract, and its source text is not
117
+ * either. No `Descriptor` field is a function today; the rule is here so the
118
+ * day one is, it is classified rather than digested by accident.
119
+ * @experimental
120
+ */
121
+ export declare function declarationData(v: unknown, opts?: DisplayKeys): unknown;
122
+ /** The content hash of a declaration — see `declarationMaterial` for what counts. @experimental */
123
+ export declare function declarationHash(v: unknown, opts?: DisplayKeys): string;
124
+ /**
125
+ * The one rule every registry here applies when an id is declared twice.
126
+ *
127
+ * Identical content is a no-op and the caller goes on to store the *new*
128
+ * declaration. Storing the new one rather than keeping the old is what makes a
129
+ * reloaded module authoritative over the one it replaced: the two agree on
130
+ * everything hashed, and on the display text that is not hashed the fresher
131
+ * declaration is the one the author just wrote.
132
+ *
133
+ * Different content throws exactly as before, with both hashes named — because
134
+ * the first question an author asks a "duplicate id" error is "but they *are*
135
+ * the same", and the two hashes are the evidence that they are not.
136
+ * @experimental
137
+ */
138
+ export declare function refuseUnlessIdentical(existing: unknown, next: unknown, why: string, opts?: DisplayKeys): void;
139
+ /**
140
+ * The refusal itself, for a registry that digests its own material: the
141
+ * descriptor registry compares two `definitionContractHash`es through this,
142
+ * so a "duplicate type id" reads the same whichever material was digested.
143
+ * @experimental
144
+ */
145
+ export declare function refuseUnlessSameHash(registered: string, redeclared: string, why: string): void;
146
+ //# sourceMappingURL=hash.d.ts.map
package/dist/hash.js ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * One canonical form, one digest, one re-declaration rule.
3
+ *
4
+ * Two things in the SDK have to answer "is this the same content as that": a
5
+ * spec document's `canonicalHash` (02 §3), and every registry here that refuses
6
+ * a second declaration under an id it already holds. They must not answer
7
+ * differently, so the sort and the digest live here once and both call in — a
8
+ * second hashing scheme is how two places quietly start disagreeing about what
9
+ * "the same" means.
10
+ *
11
+ * ## Why the registries needed an answer at all
12
+ *
13
+ * `if (map.has(id)) throw` is the right guard for the case it was written for:
14
+ * two *different* declarations claiming one id means one of them silently wins
15
+ * and which one depends on load order. It is the wrong guard for a case nobody
16
+ * had in mind — a module re-evaluating with the same source. That is exactly
17
+ * what a dev server's hot reload does: saving an app file that imports
18
+ * `@serene-pub/contracts` re-runs every `describe*` in it against a registry
19
+ * living in a module that was *not* reloaded, so the first id threw, the reload
20
+ * failed, and the server retried in a loop.
21
+ *
22
+ * The fix is to key the refusal on content rather than on arrival. Deliberately
23
+ * not gated on `import.meta.hot` or `NODE_ENV`: an identical re-declaration is
24
+ * harmless everywhere, and an environment check would only hide the case where
25
+ * it is *not* identical — which is the case the guard exists for.
26
+ */
27
+ const sortDeep = (v) => {
28
+ if (Array.isArray(v))
29
+ return v.map(sortDeep);
30
+ if (v && typeof v === 'object') {
31
+ return Object.fromEntries(Object.entries(v)
32
+ .sort(([a], [b]) => a.localeCompare(b))
33
+ .map(([k, val]) => [k, sortDeep(val)]));
34
+ }
35
+ return v;
36
+ };
37
+ /** Canonical form — stable key order, for hashing and round-trip identity (F3). @experimental */
38
+ export function canonicalize(v) {
39
+ return JSON.stringify(sortDeep(v));
40
+ }
41
+ /** Cheap deterministic content hash — stands in for the real canonical_hash (02 §3). @experimental */
42
+ export function contentHash(v) {
43
+ const s = canonicalize(v);
44
+ let h1 = 0xdeadbeef;
45
+ let h2 = 0x41c6ce57;
46
+ for (let i = 0; i < s.length; i++) {
47
+ const c = s.charCodeAt(i);
48
+ h1 = Math.imul(h1 ^ c, 2654435761);
49
+ h2 = Math.imul(h2 ^ c, 1597334677);
50
+ }
51
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
52
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
53
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
54
+ }
55
+ /**
56
+ * The display-text keys every declaration carries, whatever registry it is in.
57
+ *
58
+ * Always stripped, and deliberately not expressed as a default that
59
+ * `DisplayKeys.display` replaces: a registry passing `{ display: ['label'] }`
60
+ * meaning "and also this one" would silently put `i18n` back into the hash and
61
+ * restore the reload loop for the most common edit there is. The option adds to
62
+ * this pair; nothing subtracts from it.
63
+ */
64
+ const UNIVERSAL_DISPLAY = ['i18n', 'description'];
65
+ const stripDisplay = (v, display, functions = 'source') => {
66
+ if (typeof v === 'function')
67
+ return functions === 'source' ? `[fn] ${String(v)}` : undefined;
68
+ if (Array.isArray(v))
69
+ return v.map((e) => stripDisplay(e, display, functions));
70
+ if (v && typeof v === 'object') {
71
+ return Object.fromEntries(Object.entries(v)
72
+ .filter(([k, val]) => !display.has(k) && !(functions === 'omit' && typeof val === 'function'))
73
+ .map(([k, val]) => [k, stripDisplay(val, display, functions)]));
74
+ }
75
+ return v;
76
+ };
77
+ const DEFAULT_DISPLAY = new Set(UNIVERSAL_DISPLAY);
78
+ /** Built once per hash rather than per node, since the strip recurses. */
79
+ const displaySet = (opts) => opts?.display?.length ? new Set([...UNIVERSAL_DISPLAY, ...opts.display]) : DEFAULT_DISPLAY;
80
+ /**
81
+ * What is *material* about a declaration, as the registries compare them.
82
+ *
83
+ * Two departures from hashing a declaration as plain data, and both are rules
84
+ * this codebase already applies to the registry rows these declarations project
85
+ * into (core's `typeContentHash`):
86
+ *
87
+ * · **Display text is not content.** `i18n` and `description` are stripped
88
+ * recursively, along with whatever else the calling registry names as
89
+ * display (see `DisplayKeys`), because renaming a node or copyediting an
90
+ * explanation is not a change to what the declaration means. It is also what
91
+ * makes the reload case fully fixed rather than half fixed: editing a label
92
+ * is the most common thing a person saves, and it must not put the loop
93
+ * back.
94
+ * · **Behaviour is.** A template engine or a wire format is almost entirely
95
+ * functions, and `JSON.stringify` drops those silently — so hashing one as
96
+ * data would make *every* declaration under an id identical and the guard
97
+ * would stop guarding. Functions canonicalize to their source text, which is
98
+ * the comparison a re-evaluation needs: the same source re-runs to the same
99
+ * hash, an edited one does not.
100
+ *
101
+ * ## Exported, because the strip is the one thing every hash here shares
102
+ *
103
+ * A `Descriptor` is compared when it is re-declared, and projected into a
104
+ * `pipeline_definition_registry` row whose `content_hash` decides whether an
105
+ * upgrading install may republish it. Those are two answers to one question —
106
+ * *is this the same content?* — and they were once computed by two functions
107
+ * that disagreed: core stripped `i18n` and `description`, this stripped
108
+ * `label` as well (see `DESCRIPTOR_DISPLAY_KEYS`), so renaming a parameter was
109
+ * free on one side and a frozen-type conflict on the other. Both now call
110
+ * `definitionContract`, which reads every contract field through this strip
111
+ * (`declarationData`); the strip is exported so that function is the only
112
+ * place a definition's material is composed, and so the registries that hash
113
+ * a declaration whole keep the same words for display text.
114
+ * @experimental
115
+ */
116
+ export function declarationMaterial(v, opts) {
117
+ return stripDisplay(v, displaySet(opts));
118
+ }
119
+ /**
120
+ * `declarationMaterial` for a declaration that is **data**: display text out,
121
+ * and a function value **omitted** rather than rendered as source.
122
+ *
123
+ * The node-definition contract (`definitionContract`) reads its fields
124
+ * through this. A definition's contract is what a registry row carries so
125
+ * core can judge a plugin without executing it (F6), and a row cannot carry
126
+ * a function — so a function is not contract, and its source text is not
127
+ * either. No `Descriptor` field is a function today; the rule is here so the
128
+ * day one is, it is classified rather than digested by accident.
129
+ * @experimental
130
+ */
131
+ export function declarationData(v, opts) {
132
+ return stripDisplay(v, displaySet(opts), 'omit');
133
+ }
134
+ /** The content hash of a declaration — see `declarationMaterial` for what counts. @experimental */
135
+ export function declarationHash(v, opts) {
136
+ return contentHash(stripDisplay(v, displaySet(opts)));
137
+ }
138
+ /**
139
+ * The one rule every registry here applies when an id is declared twice.
140
+ *
141
+ * Identical content is a no-op and the caller goes on to store the *new*
142
+ * declaration. Storing the new one rather than keeping the old is what makes a
143
+ * reloaded module authoritative over the one it replaced: the two agree on
144
+ * everything hashed, and on the display text that is not hashed the fresher
145
+ * declaration is the one the author just wrote.
146
+ *
147
+ * Different content throws exactly as before, with both hashes named — because
148
+ * the first question an author asks a "duplicate id" error is "but they *are*
149
+ * the same", and the two hashes are the evidence that they are not.
150
+ * @experimental
151
+ */
152
+ export function refuseUnlessIdentical(existing, next, why, opts) {
153
+ refuseUnlessSameHash(declarationHash(existing, opts), declarationHash(next, opts), why);
154
+ }
155
+ /**
156
+ * The refusal itself, for a registry that digests its own material: the
157
+ * descriptor registry compares two `definitionContractHash`es through this,
158
+ * so a "duplicate type id" reads the same whichever material was digested.
159
+ * @experimental
160
+ */
161
+ export function refuseUnlessSameHash(registered, redeclared, why) {
162
+ if (registered === redeclared)
163
+ return;
164
+ throw new Error(`${why} (registered ${registered}, redeclared ${redeclared})`);
165
+ }
166
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The grant table (plans 29 R-3): which members each kind of plugin hook finds
3
+ * on its `ctx`. The ONE copy — the app's sandboxes derive every call's grants
4
+ * from it, the boot check reads each kind's keys from it, an author's harness
5
+ * builds its context from it, and the plugin permissions guide is rendered
6
+ * from it (K1c). Nothing else in here, so the runtime can import it without
7
+ * the test harness behind it.
8
+ */
9
+ /**
10
+ * The kinds of hook the host dispatches — the four node kinds a plugin may
11
+ * implement, a chain link (a script kind's hook), an event listener and a
12
+ * lifecycle callback.
13
+ *
14
+ * Spelled exactly as the app's `$lib/server/plugins/hookCtx.ts` spells it,
15
+ * because it is the same table read by three things that must agree: each
16
+ * sandbox's `invoke` derives its grants from it, the boot check reads the keys
17
+ * per kind from it, and — now — an author's harness builds its context from it.
18
+ * A fourth copy that disagreed would be the drift the boot check exists to
19
+ * catch, so when the app's table moves this one moves with it.
20
+ * @experimental
21
+ */
22
+ export type HookCtxKind = 'task' | 'query' | 'oracle' | 'outlet' | 'chain-link' | 'event' | 'lifecycle';
23
+ /** @experimental */
24
+ export declare const HOOK_CTX_KINDS: readonly HookCtxKind[];
25
+ /** Which of the two permission-gated members a kind's context carries. @experimental */
26
+ export interface HookCtxGrants {
27
+ /** The extension's own namespaced rows and files (`ctx.storage`). */
28
+ storage: boolean;
29
+ /** Host-scoped network access (`ctx.fetch`). */
30
+ fetch: boolean;
31
+ }
32
+ /** @internal */
33
+ export declare function isHookCtxKind(v: unknown): v is HookCtxKind;
34
+ /**
35
+ * The grants for a kind. An unknown kind is a programming error at the call
36
+ * site — every caller names one — so it throws rather than defaulting: a
37
+ * default in either direction is a grant nobody decided.
38
+ * @experimental
39
+ */
40
+ export declare function hookCtxGrants(kind: unknown): HookCtxGrants;
41
+ /**
42
+ * The keys a hook of this kind finds on `ctx`, in the order the sandboxes
43
+ * define them — what a test compares `Object.keys(ctx)` against.
44
+ * @experimental
45
+ */
46
+ export declare function hookCtxKeysFor(kind: HookCtxKind): string[];
47
+ //# sourceMappingURL=hookGrants.d.ts.map
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The grant table (plans 29 R-3): which members each kind of plugin hook finds
3
+ * on its `ctx`. The ONE copy — the app's sandboxes derive every call's grants
4
+ * from it, the boot check reads each kind's keys from it, an author's harness
5
+ * builds its context from it, and the plugin permissions guide is rendered
6
+ * from it (K1c). Nothing else in here, so the runtime can import it without
7
+ * the test harness behind it.
8
+ */
9
+ /** @experimental */
10
+ export const HOOK_CTX_KINDS = [
11
+ 'task',
12
+ 'query',
13
+ 'oracle',
14
+ 'outlet',
15
+ 'chain-link',
16
+ 'event',
17
+ 'lifecycle',
18
+ ];
19
+ /**
20
+ * The table.
21
+ *
22
+ * - **task**, **chain-link** — neither. A task is pure (F11) and a chain link
23
+ * is a script: the in-app script host hands one `{ random, log }` and a
24
+ * plugin's link gets the same.
25
+ * - **query**, **outlet**, **event**, **lifecycle** — storage. F32: an
26
+ * extension's own rows, no network.
27
+ * - **oracle** — storage and fetch. The one kind that calls out, which is what
28
+ * `effects: 'external'` names.
29
+ */
30
+ const GRANTS = {
31
+ task: { storage: false, fetch: false },
32
+ 'chain-link': { storage: false, fetch: false },
33
+ query: { storage: true, fetch: false },
34
+ outlet: { storage: true, fetch: false },
35
+ event: { storage: true, fetch: false },
36
+ lifecycle: { storage: true, fetch: false },
37
+ oracle: { storage: true, fetch: true },
38
+ };
39
+ /** @internal */
40
+ export function isHookCtxKind(v) {
41
+ // Own keys only: `'constructor' in GRANTS` is true through the prototype,
42
+ // and a kind read off a manifest or a registry row must not pass by it.
43
+ return typeof v === 'string' && Object.hasOwn(GRANTS, v);
44
+ }
45
+ /**
46
+ * The grants for a kind. An unknown kind is a programming error at the call
47
+ * site — every caller names one — so it throws rather than defaulting: a
48
+ * default in either direction is a grant nobody decided.
49
+ * @experimental
50
+ */
51
+ export function hookCtxGrants(kind) {
52
+ if (!isHookCtxKind(kind))
53
+ throw new Error(`a plugin hook context was built without a hook ctx kind (got ${JSON.stringify(kind)}); ` +
54
+ `name one of ${HOOK_CTX_KINDS.join(' · ')} (plans/29 R-3)`);
55
+ return GRANTS[kind];
56
+ }
57
+ /** The members every kind's context carries, before the grants. */
58
+ const BASE_KEYS = ['random', 'now', 'log', 'signal'];
59
+ /**
60
+ * The keys a hook of this kind finds on `ctx`, in the order the sandboxes
61
+ * define them — what a test compares `Object.keys(ctx)` against.
62
+ * @experimental
63
+ */
64
+ export function hookCtxKeysFor(kind) {
65
+ const g = hookCtxGrants(kind);
66
+ return [...BASE_KEYS.slice(0, 3), ...(g.storage ? ['storage'] : []), ...(g.fetch ? ['fetch'] : []), BASE_KEYS[3]];
67
+ }
68
+ //# sourceMappingURL=hookGrants.js.map