@serene-pub/sdk 0.6.0-pr-4 → 0.6.0-pr-6

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 (230) hide show
  1. package/README.md +23 -19
  2. package/dist/actions.d.ts +178 -69
  3. package/dist/actions.js +109 -40
  4. package/dist/annexFields.d.ts +12 -5
  5. package/dist/annexFields.js +6 -2
  6. package/dist/announce.d.ts +220 -30
  7. package/dist/announce.js +212 -7
  8. package/dist/attributes.d.ts +290 -11
  9. package/dist/attributes.js +317 -32
  10. package/dist/bands.d.ts +41 -6
  11. package/dist/bands.js +83 -33
  12. package/dist/bridges.d.ts +61 -0
  13. package/dist/bridges.js +112 -0
  14. package/dist/builder.d.ts +436 -106
  15. package/dist/builder.js +389 -46
  16. package/dist/cadences.d.ts +578 -0
  17. package/dist/cadences.js +1111 -0
  18. package/dist/candidates.d.ts +5 -3
  19. package/dist/candidates.js +3 -2
  20. package/dist/capabilities.d.ts +93 -15
  21. package/dist/capabilities.js +57 -6
  22. package/dist/checkMethods.d.ts +240 -0
  23. package/dist/checkMethods.js +362 -0
  24. package/dist/clauses.d.ts +2 -1
  25. package/dist/clauses.js +2 -1
  26. package/dist/component.d.ts +24 -7
  27. package/dist/component.js +16 -6
  28. package/dist/componentBuild.d.ts +16 -5
  29. package/dist/componentBuild.js +14 -5
  30. package/dist/componentClient.d.ts +61 -30
  31. package/dist/componentClient.js +11 -1
  32. package/dist/componentImports.d.ts +8 -5
  33. package/dist/componentImports.js +23 -4
  34. package/dist/componentModule.js +2 -1
  35. package/dist/componentWire.d.ts +2 -1
  36. package/dist/componentWire.js +34 -2
  37. package/dist/composerStates.d.ts +96 -0
  38. package/dist/composerStates.js +190 -0
  39. package/dist/conditions.d.ts +424 -0
  40. package/dist/conditions.js +521 -0
  41. package/dist/config.d.ts +69 -19
  42. package/dist/config.js +64 -26
  43. package/dist/connections.d.ts +9 -4
  44. package/dist/connections.js +7 -4
  45. package/dist/conversions.d.ts +41 -0
  46. package/dist/conversions.js +50 -0
  47. package/dist/declarations.d.ts +70 -18
  48. package/dist/declarations.js +194 -24
  49. package/dist/descriptors.d.ts +427 -100
  50. package/dist/descriptors.js +344 -59
  51. package/dist/dev.d.ts +6 -5
  52. package/dist/dev.js +6 -5
  53. package/dist/document.d.ts +121 -27
  54. package/dist/document.js +77 -24
  55. package/dist/dowry.d.ts +241 -0
  56. package/dist/dowry.js +315 -0
  57. package/dist/engines.d.ts +16 -7
  58. package/dist/engines.js +6 -4
  59. package/dist/entities.d.ts +156 -0
  60. package/dist/entities.js +259 -0
  61. package/dist/eventMapLaws.d.ts +19 -8
  62. package/dist/eventMapLaws.js +9 -6
  63. package/dist/events.d.ts +648 -40
  64. package/dist/events.js +451 -34
  65. package/dist/executor.d.ts +123 -41
  66. package/dist/executor.js +210 -103
  67. package/dist/exposure.d.ts +128 -0
  68. package/dist/exposure.js +168 -0
  69. package/dist/extension.d.ts +99 -35
  70. package/dist/extension.js +43 -9
  71. package/dist/facets.d.ts +2 -1
  72. package/dist/facets.js +4 -2
  73. package/dist/fit.d.ts +198 -0
  74. package/dist/fit.js +351 -0
  75. package/dist/foldedSections.d.ts +4 -2
  76. package/dist/foldedSections.js +2 -1
  77. package/dist/functions.d.ts +554 -0
  78. package/dist/functions.js +712 -0
  79. package/dist/genres.d.ts +408 -130
  80. package/dist/genres.js +412 -108
  81. package/dist/guardedConnection.d.ts +4 -3
  82. package/dist/guardedConnection.js +4 -3
  83. package/dist/handlebarsReach.d.ts +1 -1
  84. package/dist/handlebarsReach.js +1 -1
  85. package/dist/hash.d.ts +16 -5
  86. package/dist/hash.js +14 -4
  87. package/dist/hookGrants.d.ts +4 -3
  88. package/dist/hookGrants.js +7 -5
  89. package/dist/hooks.d.ts +42 -21
  90. package/dist/hooks.js +17 -12
  91. package/dist/hostElements.d.ts +47 -17
  92. package/dist/hostElements.js +62 -17
  93. package/dist/hostState.d.ts +110 -0
  94. package/dist/hostState.js +140 -0
  95. package/dist/i18n.d.ts +5 -3
  96. package/dist/i18n.js +5 -3
  97. package/dist/identity.d.ts +5 -4
  98. package/dist/identity.js +5 -4
  99. package/dist/index.d.ts +26 -0
  100. package/dist/index.js +55 -0
  101. package/dist/jsonSchema.d.ts +178 -0
  102. package/dist/jsonSchema.js +558 -0
  103. package/dist/layout.d.ts +36 -15
  104. package/dist/layout.js +2 -2
  105. package/dist/loadouts.d.ts +97 -0
  106. package/dist/loadouts.js +81 -0
  107. package/dist/media.d.ts +153 -16
  108. package/dist/media.js +47 -2
  109. package/dist/messageBlocks.d.ts +223 -37
  110. package/dist/messageBlocks.js +231 -24
  111. package/dist/migration.d.ts +16 -8
  112. package/dist/migration.js +14 -8
  113. package/dist/names.d.ts +2 -1
  114. package/dist/names.js +2 -1
  115. package/dist/nodeInput.d.ts +2 -1
  116. package/dist/nodeInput.js +2 -1
  117. package/dist/participants.d.ts +54 -24
  118. package/dist/participants.js +27 -14
  119. package/dist/personGate.d.ts +2 -1
  120. package/dist/personGate.js +2 -1
  121. package/dist/pluginHarness.d.ts +22 -35
  122. package/dist/pluginHarness.js +18 -143
  123. package/dist/pluginPermissions.d.ts +2 -1
  124. package/dist/pluginPermissions.js +13 -2
  125. package/dist/pluginRuleRef.d.ts +2 -2
  126. package/dist/pluginRuleRef.js +1 -1
  127. package/dist/predicates.d.ts +16 -11
  128. package/dist/predicates.js +7 -6
  129. package/dist/preview.d.ts +53 -7
  130. package/dist/preview.js +54 -13
  131. package/dist/primers.d.ts +177 -0
  132. package/dist/primers.js +265 -0
  133. package/dist/promptBlocks.d.ts +5 -3
  134. package/dist/promptBlocks.js +5 -3
  135. package/dist/rankingDecisions.d.ts +2 -1
  136. package/dist/rankingDecisions.js +2 -1
  137. package/dist/receipt.d.ts +76 -29
  138. package/dist/receipt.js +9 -4
  139. package/dist/receiverRules.js +3 -2
  140. package/dist/refs.d.ts +42 -9
  141. package/dist/refs.js +45 -13
  142. package/dist/registrations.d.ts +384 -0
  143. package/dist/registrations.js +625 -0
  144. package/dist/registry.d.ts +42 -23
  145. package/dist/registry.js +7 -5
  146. package/dist/repertoires.d.ts +502 -0
  147. package/dist/repertoires.js +666 -0
  148. package/dist/review.d.ts +16 -5
  149. package/dist/review.js +11 -4
  150. package/dist/rulesetDocument.d.ts +95 -0
  151. package/dist/rulesetDocument.js +190 -0
  152. package/dist/rulesetSections.d.ts +597 -0
  153. package/dist/rulesetSections.js +1249 -0
  154. package/dist/rulesetTemplates.d.ts +161 -0
  155. package/dist/rulesetTemplates.js +242 -0
  156. package/dist/rulesets.d.ts +899 -0
  157. package/dist/rulesets.js +1378 -0
  158. package/dist/sampling.d.ts +54 -0
  159. package/dist/sampling.js +95 -3
  160. package/dist/sceneSettings.d.ts +320 -0
  161. package/dist/sceneSettings.js +433 -0
  162. package/dist/scope.d.ts +50 -7
  163. package/dist/scope.js +22 -3
  164. package/dist/scripts.d.ts +112 -22
  165. package/dist/scripts.js +135 -19
  166. package/dist/sessionDossier.d.ts +638 -0
  167. package/dist/sessionDossier.js +33 -0
  168. package/dist/sessionLayout.d.ts +492 -55
  169. package/dist/sessionLayout.js +697 -90
  170. package/dist/sessionSettings.d.ts +32 -5
  171. package/dist/settings.d.ts +66 -20
  172. package/dist/settings.js +19 -12
  173. package/dist/settingsSlot.d.ts +11 -8
  174. package/dist/settingsSlot.js +11 -8
  175. package/dist/shapes.d.ts +139 -37
  176. package/dist/shapes.js +152 -38
  177. package/dist/sheets.d.ts +4 -2
  178. package/dist/sheets.js +6 -3
  179. package/dist/statShapes.d.ts +10 -2
  180. package/dist/statShapes.js +10 -2
  181. package/dist/status.d.ts +27 -9
  182. package/dist/status.js +20 -6
  183. package/dist/storage.d.ts +11 -67
  184. package/dist/storage.js +9 -13
  185. package/dist/storyTime.d.ts +13 -7
  186. package/dist/storyTime.js +11 -6
  187. package/dist/strokes.d.ts +176 -0
  188. package/dist/strokes.js +281 -0
  189. package/dist/surfaces.d.ts +54 -25
  190. package/dist/surfaces.js +3 -3
  191. package/dist/template.d.ts +9 -5
  192. package/dist/template.js +5 -3
  193. package/dist/templateCheck.d.ts +2 -2
  194. package/dist/templateCheck.js +2 -2
  195. package/dist/templateFit.d.ts +37 -8
  196. package/dist/templateFit.js +92 -8
  197. package/dist/templateIds.d.ts +3 -3
  198. package/dist/templateIds.js +3 -3
  199. package/dist/templateScopeAt.d.ts +22 -12
  200. package/dist/templateScopeAt.js +32 -19
  201. package/dist/testing.d.ts +11 -4
  202. package/dist/testing.js +13 -5
  203. package/dist/ties.d.ts +210 -0
  204. package/dist/ties.js +300 -0
  205. package/dist/tokenizers.d.ts +2 -2
  206. package/dist/tokenizers.js +2 -2
  207. package/dist/turnLock.d.ts +4 -2
  208. package/dist/turnLock.js +2 -1
  209. package/dist/turnOrder.d.ts +39 -22
  210. package/dist/turnOrder.js +30 -13
  211. package/dist/validate.d.ts +11 -8
  212. package/dist/validate.js +195 -29
  213. package/dist/values.d.ts +17 -8
  214. package/dist/values.js +11 -6
  215. package/dist/variables.d.ts +46 -7
  216. package/dist/variables.js +87 -6
  217. package/dist/verdicts.d.ts +20 -13
  218. package/dist/verdicts.js +17 -11
  219. package/dist/vocabularies.d.ts +192 -0
  220. package/dist/vocabularies.js +326 -0
  221. package/dist/widgetDecls.d.ts +20 -4
  222. package/dist/widgetDecls.js +6 -2
  223. package/dist/widgets.d.ts +1580 -111
  224. package/dist/widgets.js +113 -18
  225. package/dist/wire.d.ts +13 -6
  226. package/dist/wire.js +3 -3
  227. package/dist/worldinfo.d.ts +11 -6
  228. package/dist/worldinfo.js +8 -4
  229. package/host-elements.d.ts +101 -0
  230. package/package.json +1 -1
@@ -0,0 +1,712 @@
1
+ /**
2
+ * 🚧 **Function modules** — the small rules a ruleset is built from
3
+ * (PLAN-rulesets-functions D1, D4; owner rulings 2026-10-22: "functions, not
4
+ * packs", "all functions are scripts").
5
+ *
6
+ * A function module is a declarative **header** — its name, its meaning in
7
+ * one sentence, its kind, the **function bindings** it needs (an attribute,
8
+ * an entry type, a zone type, a scope, an owner — each resolved by tag, by
9
+ * pick, or bound by the ruleset that uses it), what it adds, the prose the
10
+ * model reads, an optional schema fragment for JSON replies, its options
11
+ * form, the phases its handlers run at, the events it emits, and whether a
12
+ * person may invoke it as an action — plus an optional **body** (script
13
+ * source, run in the sandbox, with a handler per phase). A function with no
14
+ * body is header-only: the model reads its prose and judges in words.
15
+ *
16
+ * A function never writes state (R8): its handlers return deltas, lines,
17
+ * outcome words, emitted events and asks, and the pipeline's outlet applies
18
+ * or proposes them under the registration's mode. A function never assumes
19
+ * another; it declares what it needs.
20
+ *
21
+ * Declared once, versioned in its id (`core:function/die-target@1`) and
22
+ * hashed like every registry here (`functionHash`); an identical
23
+ * re-declaration is a no-op. A ruleset lists the functions it uses as
24
+ * **function references** — `{ ref, key?, bindings?, options? }`, a
25
+ * reference and a pin, never a copy (`FunctionRef`); editing a body forks it
26
+ * into the ruleset (`forkFunction`, `forkedFrom`).
27
+ *
28
+ * Core's catalogue ships as function modules (lane A2). The ids core
29
+ * reserves are named here (`CORE_FUNCTION_IDS`) so a ruleset may reference
30
+ * them before the modules are registered: a reserved id resolves later.
31
+ *
32
+ * ⚠ A **function binding** is what a function needs and what a ruleset ties
33
+ * it to — always "function binding" where it could stand alone (R3), never
34
+ * the bare _binding_ (the cast-member ↔ card link, NOMENCLATURE §8). Not a
35
+ * pipeline node either: a function runs inside the ruleset handler.
36
+ * @experimental
37
+ * @ruling PLAN-rulesets-functions D1, D4 (2026-10-23)
38
+ */
39
+ import { i18nFindings, i18nText } from './i18n.js';
40
+ import { declarationHash, refuseUnlessIdentical } from './hash.js';
41
+ import { checkSchema, checkValues, settingsSchemaFindings } from './settings.js';
42
+ import { EVENT_ID, eventById, packageEventById } from './events.js';
43
+ import { finding, RulesetError } from './repertoires.js';
44
+ import { ATTRIBUTE_KINDS, attributeKindsInWords, NUMBER_ATTRIBUTE_KINDS, rulesetAttributeFindings, rulesetOutcomeFindings, zoneTypeFindings, } from './rulesetSections.js';
45
+ /** 🚧 The grammar of a function id: `owner:function/name@N`. @experimental */
46
+ export const FUNCTION_ID_PATTERN = /^[a-z0-9]+(?:[.-][a-z0-9]+)*:function\/[a-z0-9]+(?:-[a-z0-9]+)*@\d+$/;
47
+ /** 🚧 Whether a value is a function id by its grammar — registered or not. @experimental */
48
+ export const isFunctionId = (id) => typeof id === 'string' && FUNCTION_ID_PATTERN.test(id);
49
+ /** 🚧 A function id's parts: `core:function/die-target@1` → `{ owner: 'core', name: 'die-target', version: 1 }`. @experimental */
50
+ export function parseFunctionId(id) {
51
+ if (!isFunctionId(id))
52
+ return undefined;
53
+ return {
54
+ owner: id.slice(0, id.indexOf(':')),
55
+ name: id.slice(id.indexOf('/') + 1, id.lastIndexOf('@')),
56
+ version: Number(id.slice(id.lastIndexOf('@') + 1)),
57
+ };
58
+ }
59
+ // ── Vocabulary ──────────────────────────────────────────────────────────────
60
+ /**
61
+ * 🚧 The kinds core reads — the catalogue's groups: `value` (a number worked
62
+ * out or kept), `deciding` (how a moment that could go either way is decided
63
+ * — dice, cards, a spend, a comparison, judgement), `changing` (what moves a
64
+ * value), `pieces` (entries made, given, spent), `zones` (entries moved
65
+ * between zones), `scope` (who is in reach — returns members, never
66
+ * changes), `asking` (asks people and waits), `time` (time and order),
67
+ * `progression` (levels, experience, economy).
68
+ * @experimental
69
+ */
70
+ export const CORE_FUNCTION_KINDS = ['value', 'deciding', 'changing', 'pieces', 'zones', 'scope', 'asking', 'time', 'progression'];
71
+ /** 🚧 Whether a kind is a package's own (`owner:name`). @experimental */
72
+ export const isPackageFunctionKind = (kind) => typeof kind === 'string' && /^[a-z0-9]+(?:[.-][a-z0-9]+)*:[a-z0-9]+(?:-[a-z0-9]+)*$/.test(kind);
73
+ /**
74
+ * 🚧 The phases a function's handlers run at, in the handler's fixed order
75
+ * (D3): `effects` (what a held piece or a standing rule does), `derived`
76
+ * (worked-out values), `before` and `after` (around a decision — the old
77
+ * `pre-roll` / `post-roll`), `render` (what the model reads).
78
+ * @experimental
79
+ */
80
+ export const FUNCTION_PHASES = ['effects', 'derived', 'before', 'after', 'render'];
81
+ /**
82
+ * 🚧 What a function binding ties a function to: one of the ruleset's
83
+ * attributes, entry types or zone types, a **scope** (who is in reach), or an
84
+ * **owner** kind (`cast` · `world` · `location`).
85
+ * @experimental
86
+ */
87
+ export const FUNCTION_BINDING_TARGETS = ['attribute', 'entry-type', 'zone-type', 'scope', 'owner'];
88
+ /**
89
+ * 🚧 The field types an entry field may hold to fill a role — the one field
90
+ * language's scalar words (`FieldType`). `entryFields: true` is the first two.
91
+ * @experimental
92
+ */
93
+ export const ENTRY_FIELD_BINDING_TYPES = ['number', 'integer', 'string', 'text', 'boolean', 'enum'];
94
+ /**
95
+ * 🚧 The attribute kinds an `attribute` role takes: its `kinds`, else every
96
+ * kind (RF fix 6, 2026-10-23). Empty for a role tied to anything else.
97
+ * @experimental
98
+ */
99
+ export const functionBindingKinds = (b) => b?.to !== 'attribute' ? [] : Array.isArray(b.kinds) && b.kinds.length ? b.kinds : ATTRIBUTE_KINDS;
100
+ /**
101
+ * 🚧 The entry field types an `attribute` role takes (`entryFields`): `true`
102
+ * is a number field (`number`, `integer`); a list is its own. Empty when no
103
+ * entry field may fill it.
104
+ * @experimental
105
+ */
106
+ export const functionBindingFieldTypes = (b) => b?.to !== 'attribute' || b.entryFields === undefined ? [] : b.entryFields === true ? ['number', 'integer'] : Array.isArray(b.entryFields) ? b.entryFields : [];
107
+ /** The most a function body may weigh — the sandbox's source cap. @experimental */
108
+ export const MAX_FUNCTION_BODY_BYTES = 256 * 1024;
109
+ /** Display text outside `i18n`/`description`: the meaning and every label. */
110
+ const FUNCTION_DISPLAY_KEYS = { display: ['meaning', 'label'] };
111
+ /**
112
+ * 🚧 A function module's content hash — what a ruleset may pin
113
+ * (`FunctionRef.hash`) and what an identical re-declaration is judged by.
114
+ * Display text (the meaning, labels, descriptions) is not content; the
115
+ * prose the model reads is.
116
+ * @experimental
117
+ */
118
+ export const functionHash = (decl) => declarationHash(decl, FUNCTION_DISPLAY_KEYS);
119
+ // ── Core's reserved ids ─────────────────────────────────────────────────────
120
+ /**
121
+ * 🚧 The function ids core reserves (lane A2 ships the modules): a ruleset
122
+ * may reference one before it is registered, and it resolves later
123
+ * (`resolveFunctionRef` → `reserved`). Grouped as the catalogue is:
124
+ *
125
+ * · deciding — `judge` (judged in words; header-only), `dieTarget`,
126
+ * `dicePool`, `cardDraw`, `compare`, `spend` (a bid), `table` (roll on a
127
+ * table);
128
+ * · scopes (D4) — `samePlace`, `withinTie`, `aimedAt`, `everyone`;
129
+ * · ⏳ what the aliases read the shapes before functions as
130
+ * (`rulesetSections`): `check` (a named check, decided by one of the
131
+ * ruleset's ways), `workedOut` (a derived selector), `tally` (a tally
132
+ * selector), `typedBonuses` (`conventions.bonuses`), `castingPool`
133
+ * (`conventions.casting`).
134
+ * @experimental
135
+ */
136
+ export const CORE_FUNCTION_IDS = Object.freeze({
137
+ judge: 'core:function/judge@1',
138
+ dieTarget: 'core:function/die-target@1',
139
+ dicePool: 'core:function/dice-pool@1',
140
+ cardDraw: 'core:function/card-draw@1',
141
+ compare: 'core:function/compare@1',
142
+ spend: 'core:function/spend@1',
143
+ table: 'core:function/table@1',
144
+ samePlace: 'core:function/same-place@1',
145
+ withinTie: 'core:function/within-tie@1',
146
+ aimedAt: 'core:function/aimed-at@1',
147
+ everyone: 'core:function/everyone@1',
148
+ check: 'core:function/check@1',
149
+ workedOut: 'core:function/worked-out@1',
150
+ tally: 'core:function/tally@1',
151
+ typedBonuses: 'core:function/typed-bonuses@1',
152
+ castingPool: 'core:function/casting-pool@1',
153
+ });
154
+ const F = CORE_FUNCTION_IDS;
155
+ /** 🚧 Core's reserved function ids and what each is, before it is registered. @experimental */
156
+ export const RESERVED_FUNCTIONS = Object.freeze({
157
+ [F.judge]: Object.freeze({ kind: 'deciding', methodKind: 'none' }),
158
+ [F.dieTarget]: Object.freeze({ kind: 'deciding', decides: true, chance: true, rollsDice: true, methodKind: 'die-target' }),
159
+ [F.dicePool]: Object.freeze({ kind: 'deciding', decides: true, chance: true, rollsDice: true, methodKind: 'dice-pool' }),
160
+ [F.cardDraw]: Object.freeze({ kind: 'deciding', decides: true, chance: true, methodKind: 'card-draw' }),
161
+ [F.compare]: Object.freeze({ kind: 'deciding', decides: true, methodKind: 'compare' }),
162
+ [F.spend]: Object.freeze({ kind: 'deciding', decides: true, methodKind: 'bid' }),
163
+ [F.table]: Object.freeze({ kind: 'deciding', decides: true, chance: true, rollsDice: true }),
164
+ [F.samePlace]: Object.freeze({ kind: 'scope' }),
165
+ [F.withinTie]: Object.freeze({ kind: 'scope' }),
166
+ [F.aimedAt]: Object.freeze({ kind: 'scope' }),
167
+ [F.everyone]: Object.freeze({ kind: 'scope' }),
168
+ [F.check]: Object.freeze({ kind: 'deciding' }),
169
+ [F.workedOut]: Object.freeze({ kind: 'value' }),
170
+ [F.tally]: Object.freeze({ kind: 'value' }),
171
+ [F.typedBonuses]: Object.freeze({ kind: 'value' }),
172
+ [F.castingPool]: Object.freeze({ kind: 'changing' }),
173
+ });
174
+ /** 🚧 Whether an id is one core reserves (`CORE_FUNCTION_IDS`). @experimental */
175
+ export const isReservedFunctionId = (id) => typeof id === 'string' && Object.prototype.hasOwnProperty.call(RESERVED_FUNCTIONS, id);
176
+ /**
177
+ * 🚧 The deciding function each core check method kind is read as
178
+ * (`die-target` → `core:function/die-target@1`, `bid` →
179
+ * `core:function/spend@1`, `none` → `core:function/judge@1`) — what the
180
+ * aliases write for `conventions.methods`, and read back
181
+ * (`normaliseRuleset`).
182
+ * @experimental
183
+ */
184
+ export const CHECK_METHOD_FUNCTIONS = Object.freeze({
185
+ 'die-target': F.dieTarget,
186
+ 'dice-pool': F.dicePool,
187
+ 'card-draw': F.cardDraw,
188
+ compare: F.compare,
189
+ bid: F.spend,
190
+ none: F.judge,
191
+ });
192
+ /** 🚧 The check method kind a function id is the function of, when it is one (`CHECK_METHOD_FUNCTIONS` read back). @experimental */
193
+ export const checkMethodKindOfFunction = (id) => typeof id === 'string' ? RESERVED_FUNCTIONS[id]?.methodKind : undefined;
194
+ /** 🚧 Core's scope functions (D4), by name — what a `visibility` or a scope binding names. @experimental */
195
+ export const CORE_SCOPE_IDS = Object.freeze({
196
+ samePlace: F.samePlace,
197
+ withinTie: F.withinTie,
198
+ aimedAt: F.aimedAt,
199
+ everyone: F.everyone,
200
+ });
201
+ // ── Visibility and scopes (D4) ──────────────────────────────────────────────
202
+ /**
203
+ * 🚧 The three words a `visibility` may say instead of a scope: `holder`
204
+ * (only who carries it — the owner of a zone, the holder of a value),
205
+ * `gm` (the game master's steps alone), `everyone`.
206
+ * @experimental
207
+ */
208
+ export const VISIBILITY_WORDS = ['holder', 'gm', 'everyone'];
209
+ /** 🚧 Whether a value is a visibility word. @experimental */
210
+ export const isVisibilityWord = (v) => VISIBILITY_WORDS.includes(v);
211
+ /** The owner kinds a function binding of `to: 'owner'` takes. */
212
+ const OWNER_KINDS = ['cast', 'world', 'location'];
213
+ /**
214
+ * 🚧 Why a visibility is refused (`bad-visibility`): neither a visibility
215
+ * word nor a scope — a function of kind `scope`, registered, reserved by
216
+ * core, or among `own` (the modules a ruleset carries).
217
+ * @internal
218
+ */
219
+ export function visibilityFindings(v, at, own = new Map()) {
220
+ if (v === undefined || isVisibilityWord(v))
221
+ return [];
222
+ if (!isFunctionId(v))
223
+ return [finding('bad-visibility', `${at} is '${String(v)}'. Say ${VISIBILITY_WORDS.map((w) => `'${w}'`).join(', ')}, or a scope — a function of kind 'scope' (${F.samePlace}).`)];
224
+ const kind = functionKindOf(v, own);
225
+ if (kind === undefined)
226
+ return [finding('unknown-function', `${at} names '${v}', which no registered, reserved or carried function is.`)];
227
+ if (kind !== 'scope')
228
+ return [finding('bad-visibility', `${at} names '${v}', a '${kind}' function. Who sees a thing is a scope — a function of kind 'scope'.`)];
229
+ return [];
230
+ }
231
+ /** A function id's kind: carried, registered, else reserved by core. */
232
+ function functionKindOf(id, own) {
233
+ return own.get(id)?.kind ?? registry.get(id)?.kind ?? RESERVED_FUNCTIONS[id]?.kind;
234
+ }
235
+ // ── Findings ────────────────────────────────────────────────────────────────
236
+ const ROLE_NAME = /^[a-z][a-zA-Z0-9]*(?:-[a-z0-9]+)*$/;
237
+ const TAG_WORD = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
238
+ const VERB_NAME = /^[a-z][a-zA-Z0-9]*(?:-[a-z0-9]+)*$/;
239
+ /** A list of tag words — lowercase words joined by '-'. @internal */
240
+ export const tagListFindings = (tags, at) => tags === undefined
241
+ ? []
242
+ : !Array.isArray(tags) || tags.some((t) => typeof t !== 'string' || !TAG_WORD.test(t)) || new Set(tags).size !== tags.length
243
+ ? [finding('bad-tags', `${at} is a list of distinct tags — lowercase words joined by '-' ('resource', 'relationship').`)]
244
+ : [];
245
+ /** A settings schema the one field language accepts: structure, then the schema check's errors. */
246
+ function schemaFindings(schema, at, reason) {
247
+ if (schema === undefined)
248
+ return [];
249
+ const structural = settingsSchemaFindings(schema, at);
250
+ if (structural.length)
251
+ return structural.map((f) => finding(reason, f));
252
+ const out = [];
253
+ for (const [k, d] of Object.entries(schema))
254
+ if (typeof d?.type !== 'string')
255
+ out.push(finding(reason, `${at}.${k} has no type. A field says its type — { type: 'integer', label: 'Bonus' }.`));
256
+ if (out.length)
257
+ return out;
258
+ return checkSchema(schema)
259
+ .filter((f) => f.severity === 'error')
260
+ .map((f) => finding(reason, `${at}${f.field ? `.${f.field}` : ''}: ${f.message} — ${f.fix}`));
261
+ }
262
+ /**
263
+ * 🚧 Every reason a function module is refused, each opened by its reason's
264
+ * name: `bad-function-id` · `display-text` · `unknown-function-kind` ·
265
+ * `reserved-kind` (a reserved core id declared as another kind) ·
266
+ * `missing-prose` · `bad-function-binding` · `bad-phase` · `bad-schema` ·
267
+ * `bad-form` · `bad-body` · `body-without-phases` · `phases-without-body` ·
268
+ * `bad-emits` · `bad-invokable` · `bad-adds` (with the attribute, outcome
269
+ * and zone type reasons inside) · `bad-tags` · `bad-chance` · `bad-fork`.
270
+ * @experimental
271
+ */
272
+ export function functionFindings(id, props) {
273
+ const out = [];
274
+ const at = String(id);
275
+ if (!isFunctionId(id))
276
+ out.push(finding('bad-function-id', `'${at}' is not a function id. Use 'owner:function/name@N' — 'core:function/die-target@1'.`));
277
+ if (!props || typeof props !== 'object')
278
+ return [...out, finding('bad-function', `${at} is { name, meaning, kind, prose, … }.`)];
279
+ out.push(...i18nFindings(props.name, `${at} name`, { required: true }).map((f) => finding('display-text', f)));
280
+ out.push(...i18nFindings(props.meaning, `${at} meaning`, { required: true }).map((f) => finding('display-text', f)));
281
+ const kind = props.kind;
282
+ if (!CORE_FUNCTION_KINDS.includes(kind) && !isPackageFunctionKind(kind))
283
+ out.push(finding('unknown-function-kind', `${at}.kind is '${String(kind)}'. Say one of ${CORE_FUNCTION_KINDS.join(', ')}, or a package's own as 'owner:name'.`));
284
+ const reserved = RESERVED_FUNCTIONS[at];
285
+ if (reserved && kind !== reserved.kind)
286
+ out.push(finding('reserved-kind', `${at} is reserved by core as a '${reserved.kind}' function; it is declared as '${String(kind)}'.`));
287
+ if (typeof props.prose !== 'string' || !props.prose.trim())
288
+ out.push(finding('missing-prose', `${at} has no prose. Say in a sentence or two what the model reads when it is present — "{{what}} comes back each morning."`));
289
+ const bindings = props.bindings;
290
+ if (bindings !== undefined) {
291
+ if (!bindings || typeof bindings !== 'object' || Array.isArray(bindings))
292
+ out.push(finding('bad-function-binding', `${at}.bindings is a map of roles — { what: { to: 'attribute', pick: true } }.`));
293
+ else
294
+ for (const [role, b] of Object.entries(bindings)) {
295
+ const where = `${at}.bindings.${role}`;
296
+ if (!ROLE_NAME.test(role))
297
+ out.push(finding('bad-function-binding', `${where}: a role is named in lowercase words — 'what', 'whom'.`));
298
+ if (!b || typeof b !== 'object') {
299
+ out.push(finding('bad-function-binding', `${where} is { to, tags?, pick?, many?, kinds?, entryFields?, label? }.`));
300
+ continue;
301
+ }
302
+ if (!FUNCTION_BINDING_TARGETS.includes(b.to))
303
+ out.push(finding('bad-function-binding', `${where}.to is '${String(b.to)}'. Say one of ${FUNCTION_BINDING_TARGETS.join(', ')}.`));
304
+ out.push(...tagListFindings(b.tags, `${where}.tags`));
305
+ for (const flag of ['pick', 'many'])
306
+ if (b[flag] !== undefined && b[flag] !== true)
307
+ out.push(finding('bad-function-binding', `${where}.${flag} is true or left out.`));
308
+ // 🚧 The attribute kinds a role takes (RF fix 6, 2026-10-23).
309
+ if (b.kinds !== undefined) {
310
+ const ks = b.kinds;
311
+ if (b.to !== 'attribute')
312
+ out.push(finding('bad-function-binding', `${where}.kinds: only an attribute role takes attribute kinds.`));
313
+ else if (!Array.isArray(ks) || !ks.length || ks.some((k) => !ATTRIBUTE_KINDS.includes(k)) || new Set(ks).size !== ks.length)
314
+ out.push(finding('bad-function-binding', `${where}.kinds is a list of distinct attribute kinds, among ${ATTRIBUTE_KINDS.join(', ')} — or left out for every kind.`));
315
+ }
316
+ if (b.entryFields !== undefined) {
317
+ const ef = b.entryFields;
318
+ if (b.to !== 'attribute')
319
+ out.push(finding('bad-function-binding', `${where}.entryFields: only an attribute role may be filled by an entry type's field.`));
320
+ else if (ef !== true && (!Array.isArray(ef) || !ef.length || ef.some((t) => !ENTRY_FIELD_BINDING_TYPES.includes(t)) || new Set(ef).size !== ef.length))
321
+ out.push(finding('bad-function-binding', `${where}.entryFields is true (a number field), or a list of distinct field types among ${ENTRY_FIELD_BINDING_TYPES.join(', ')}.`));
322
+ }
323
+ out.push(...i18nFindings(b.label, `${where}.label`).map((f) => finding('display-text', f)));
324
+ for (const k of Object.keys(b))
325
+ if (!['to', 'tags', 'pick', 'many', 'kinds', 'entryFields', 'label'].includes(k))
326
+ out.push(finding('bad-function-binding', `${where} says '${k}'. A function binding is { to, tags?, pick?, many?, kinds?, entryFields?, label? }.`));
327
+ }
328
+ }
329
+ const phases = props.phases;
330
+ if (phases !== undefined && (!Array.isArray(phases) || phases.some((p) => !FUNCTION_PHASES.includes(p)) || new Set(phases).size !== phases.length))
331
+ out.push(finding('bad-phase', `${at}.phases is a list of distinct phases, among ${FUNCTION_PHASES.join(', ')}.`));
332
+ out.push(...schemaFindings(props.schema, `${at}.schema`, 'bad-schema'));
333
+ out.push(...schemaFindings(props.form, `${at}.form`, 'bad-form'));
334
+ // 🚧 Option roles (RF fix 8): each names an option its form has, and says what it names.
335
+ if (props.optionRoles !== undefined) {
336
+ if (!props.optionRoles || typeof props.optionRoles !== 'object' || Array.isArray(props.optionRoles))
337
+ out.push(finding('bad-function-options', `${at}.optionRoles is a map of option → { names: 'value' | 'function', kinds? }.`));
338
+ else
339
+ for (const [k, r] of Object.entries(props.optionRoles)) {
340
+ if (!props.form || !Object.prototype.hasOwnProperty.call(props.form, k))
341
+ out.push(finding('bad-function-options', `${at}.optionRoles.${k}: its form has no option '${k}'.`));
342
+ if (r?.names !== 'value' && r?.names !== 'function')
343
+ out.push(finding('bad-function-options', `${at}.optionRoles.${k}.names is 'value' or 'function'.`));
344
+ if (r?.kinds !== undefined && (r.names !== 'value' || !Array.isArray(r.kinds) || r.kinds.some((x) => !ATTRIBUTE_KINDS.includes(x))))
345
+ out.push(finding('bad-function-options', `${at}.optionRoles.${k}.kinds: a value role's attribute kinds, among ${ATTRIBUTE_KINDS.join(', ')}.`));
346
+ }
347
+ }
348
+ const hasBody = props.body !== undefined;
349
+ if (hasBody && (typeof props.body !== 'string' || !props.body.trim()))
350
+ out.push(finding('bad-body', `${at}.body is the module's script source, or left out for a header-only function.`));
351
+ else if (hasBody && props.body.length > MAX_FUNCTION_BODY_BYTES)
352
+ out.push(finding('bad-body', `${at}.body is ${props.body.length} bytes; a function body is at most ${MAX_FUNCTION_BODY_BYTES}.`));
353
+ if (props.seedKey !== undefined && (typeof props.seedKey !== 'string' || !props.seedKey))
354
+ out.push(finding('bad-body', `${at}.seedKey names a seeded script row, or is left out.`));
355
+ if (hasBody && props.seedKey !== undefined)
356
+ out.push(finding('bad-body', `${at} says both body and seedKey. A module's body is its own source, or (⏳) a seeded row's — one of them.`));
357
+ const scripted = hasBody || props.seedKey !== undefined;
358
+ const phaseCount = Array.isArray(phases) ? phases.length : 0;
359
+ if (scripted && !phaseCount)
360
+ out.push(finding('body-without-phases', `${at} has a body and no phases. Say the phases its handlers run at — ${FUNCTION_PHASES.join(', ')}.`));
361
+ if (!scripted && phaseCount)
362
+ out.push(finding('phases-without-body', `${at} lists phases and has no body. A header-only function runs nothing; drop the phases or write the body.`));
363
+ if (props.emits !== undefined && (!Array.isArray(props.emits) || props.emits.some((e) => typeof e !== 'string' || !EVENT_ID.test(e))))
364
+ out.push(finding('bad-emits', `${at}.emits is a list of event ids — 'core:event/turn-ended@1', 'acme:event/confession-accepted@1'.`));
365
+ const inv = props.invokable;
366
+ if (inv !== undefined) {
367
+ if (!inv || typeof inv !== 'object')
368
+ out.push(finding('bad-invokable', `${at}.invokable is { label, description?, form? }.`));
369
+ else {
370
+ out.push(...i18nFindings(inv.label, `${at}.invokable.label`, { required: true }).map((f) => finding('display-text', f)));
371
+ out.push(...i18nFindings(inv.description, `${at}.invokable.description`).map((f) => finding('display-text', f)));
372
+ out.push(...schemaFindings(inv.form, `${at}.invokable.form`, 'bad-invokable'));
373
+ }
374
+ }
375
+ out.push(...addsFindings(props.adds, `${at}.adds`));
376
+ for (const flag of ['chance', 'rollsDice'])
377
+ if (props[flag] !== undefined && props[flag] !== true)
378
+ out.push(finding('bad-chance', `${at}.${flag} is true or left out.`));
379
+ if (props.rollsDice === true && props.chance !== true)
380
+ out.push(finding('bad-chance', `${at} rolls dice and does not say chance. Dice are chance — say chance: true too.`));
381
+ if (props.forkedFrom !== undefined && !isFunctionId(props.forkedFrom))
382
+ out.push(finding('bad-fork', `${at}.forkedFrom is the id of the function it was forked from — 'core:function/die-target@1'.`));
383
+ return out;
384
+ }
385
+ function addsFindings(adds, at) {
386
+ if (adds === undefined)
387
+ return [];
388
+ if (!adds || typeof adds !== 'object' || Array.isArray(adds))
389
+ return [finding('bad-adds', `${at} is { attributes?, events?, verbs?, outcomes?, zoneTypes? }.`)];
390
+ const out = [];
391
+ for (const k of Object.keys(adds))
392
+ if (!['attributes', 'events', 'verbs', 'outcomes', 'zoneTypes'].includes(k))
393
+ out.push(finding('bad-adds', `${at} says '${k}'. A function adds attributes, events, verbs, outcomes or zone types.`));
394
+ const list = (v, k) => {
395
+ if (v === undefined)
396
+ return [];
397
+ if (!Array.isArray(v)) {
398
+ out.push(finding('bad-adds', `${at}.${k} is a list.`));
399
+ return [];
400
+ }
401
+ return v;
402
+ };
403
+ list(adds.attributes, 'attributes').forEach((a, i) => out.push(...rulesetAttributeFindings(a, `${at}.attributes[${i}]`)));
404
+ list(adds.events, 'events').forEach((e, i) => {
405
+ const ev = e;
406
+ if (typeof ev?.id !== 'string' || !EVENT_ID.test(ev.id))
407
+ out.push(finding('bad-adds', `${at}.events[${i}].id is an event id under the function's owner — 'acme:event/confession-accepted@1'.`));
408
+ out.push(...i18nFindings(ev?.name, `${at}.events[${i}].name`, { required: true }).map((f) => finding('display-text', f)));
409
+ });
410
+ const verbs = list(adds.verbs, 'verbs');
411
+ if (verbs.some((v) => typeof v !== 'string' || !VERB_NAME.test(v)))
412
+ out.push(finding('bad-adds', `${at}.verbs is a list of verb names — 'change', 'reveal', 'move'.`));
413
+ list(adds.outcomes, 'outcomes').forEach((o, i) => out.push(...rulesetOutcomeFindings(o, `${at}.outcomes[${i}]`)));
414
+ list(adds.zoneTypes, 'zoneTypes').forEach((z, i) => out.push(...zoneTypeFindings(z, `${at}.zoneTypes[${i}]`)));
415
+ return out;
416
+ }
417
+ // ── The registry ────────────────────────────────────────────────────────────
418
+ const registry = new Map();
419
+ const freezeDeep = (v) => {
420
+ if (v && typeof v === 'object' && !Object.isFrozen(v)) {
421
+ for (const x of Object.values(v))
422
+ freezeDeep(x);
423
+ Object.freeze(v);
424
+ }
425
+ return v;
426
+ };
427
+ function register(id, props) {
428
+ const found = functionFindings(id, props);
429
+ if (found.length)
430
+ throw new RulesetError(String(id), found);
431
+ const decl = freezeDeep({ ...JSON.parse(JSON.stringify(props)), id });
432
+ const existing = registry.get(id);
433
+ if (existing) {
434
+ refuseUnlessIdentical(existing, decl, `duplicate function id: ${id}`, FUNCTION_DISPLAY_KEYS);
435
+ return existing;
436
+ }
437
+ registry.set(id, decl);
438
+ return decl;
439
+ }
440
+ /**
441
+ * 🚧 Declare a function module (core's, or a package's through
442
+ * `definePluginFunction`). Refused on any finding (`RulesetError`). An
443
+ * identical re-declaration is a no-op — a dev server's reload re-runs this —
444
+ * and a different one under a claimed id throws with both hashes.
445
+ * @experimental
446
+ */
447
+ export function defineFunction(id, props) {
448
+ return register(id, props);
449
+ }
450
+ /** 🚧 The package door: the same registration, minus core's namespace. @experimental */
451
+ export function definePluginFunction(pluginId, id, props) {
452
+ if (typeof id === 'string' && id.startsWith('core:'))
453
+ throw new Error(`plugin '${pluginId}' may not declare '${id}': the 'core:' namespace is reserved. Publish it under your own ` +
454
+ `namespace — a function two parties can define is one whose rules depend on load order.`);
455
+ return register(id, props);
456
+ }
457
+ /** 🚧 A registered function module by id. @experimental */
458
+ export const getFunction = (id) => registry.get(id);
459
+ /** 🚧 Every registered function module. @experimental */
460
+ export const functions = () => [...registry.values()];
461
+ /** 🚧 Forget a package's function (uninstall). Core's stay. @internal */
462
+ export function _withdrawFunction(id) {
463
+ if (typeof id !== 'string' || id.startsWith('core:'))
464
+ return false;
465
+ return registry.delete(id);
466
+ }
467
+ /** @internal */
468
+ export function _clearFunctions() {
469
+ registry.clear();
470
+ }
471
+ /** 🚧 The key a reference is named by: its own, else the function's name segment. @experimental */
472
+ export const functionRefKey = (ref) => typeof ref?.key === 'string' && ref.key ? ref.key : (parseFunctionId(String(ref?.ref))?.name ?? String(ref?.ref));
473
+ /**
474
+ * 🚧 Resolve one reference: the module it carries, else the registry's,
475
+ * else a reserved core id (resolved later). Findings: `bad-function-ref`,
476
+ * `unknown-function`, `module-not-ref` (a carried module under another id),
477
+ * `function-hash-moved`.
478
+ * @experimental
479
+ */
480
+ export function resolveFunctionRef(ref) {
481
+ const key = functionRefKey(ref);
482
+ if (!ref || typeof ref !== 'object' || !isFunctionId(ref.ref))
483
+ return { ref, key, findings: [finding('bad-function-ref', `A function reference is { ref: 'owner:function/name@N', key?, bindings?, options? } — '${String(ref?.ref)}' is no function id.`)] };
484
+ const out = [];
485
+ if (ref.module !== undefined && ref.module?.id !== ref.ref)
486
+ out.push(finding('module-not-ref', `The function carried under '${key}' is '${String(ref.module?.id)}', and the reference names '${ref.ref}'. A carried module is referenced by its own id.`));
487
+ const decl = ref.module ?? registry.get(ref.ref);
488
+ const reserved = decl ? undefined : RESERVED_FUNCTIONS[ref.ref];
489
+ if (!decl && !reserved)
490
+ out.push(finding('unknown-function', `'${ref.ref}' is no registered function, none core reserves, and the ruleset carries no module of it.`));
491
+ if (decl && ref.hash !== undefined && functionHash(decl) !== ref.hash)
492
+ out.push(finding('function-hash-moved', `'${ref.ref}' was pinned at ${ref.hash}; it hashes ${functionHash(decl)} now. Re-pin it, or keep the version you pinned.`));
493
+ return { ref, key, ...(decl ? { decl } : {}), ...(reserved ? { reserved } : {}), findings: out };
494
+ }
495
+ /**
496
+ * 🚧 The kind of the function a reference names — its module's, else the
497
+ * reserved id's — or `undefined` when it names nothing.
498
+ * @experimental
499
+ */
500
+ export const functionRefKind = (ref) => ref?.module?.kind ?? (typeof ref?.ref === 'string' ? (registry.get(ref.ref)?.kind ?? RESERVED_FUNCTIONS[ref.ref]?.kind) : undefined);
501
+ /** A body that exports a `decide` handler — `export function decide(…)`, `export const decide`, or `export { decide }`. */
502
+ const DECIDE_EXPORT = /\bexport\s+(?:async\s+)?function\s*\*?\s*decide\s*\(|\bexport\s+(?:const|let|var)\s+decide\b|\bexport\s*\{[^}]*\bdecide\b[^}]*\}/;
503
+ /**
504
+ * 🚧 Whether a function body exports a `decide` handler — what makes a
505
+ * deciding function a **way** by itself (2026-10-23).
506
+ * @experimental
507
+ */
508
+ export const functionExportsDecide = (body) => typeof body === 'string' && DECIDE_EXPORT.test(body);
509
+ /**
510
+ * 🚧 Whether a reference **decides** by the rules: a reserved deciding
511
+ * resolver (`judge` and `check` do not — judged in words; decided by the way
512
+ * it names), or a registered or carried function of kind `deciding` that is
513
+ * a **way**: its body exports `decide`, or a check names it as its way
514
+ * (`ways`, the keys the ruleset's checks name under `options.way`) and it
515
+ * has a body (or ⏳ a seeded one) or chance. A deciding function that only
516
+ * shapes a decision (an edge, margins, natural faces) decides nothing by
517
+ * itself; a header-only one is judged in words.
518
+ * @experimental
519
+ */
520
+ export function functionRefDecides(ref, ways) {
521
+ const decl = ref?.module ?? (typeof ref?.ref === 'string' ? registry.get(ref.ref) : undefined);
522
+ if (decl) {
523
+ if (decl.kind !== 'deciding')
524
+ return false;
525
+ if (functionExportsDecide(decl.body))
526
+ return true;
527
+ return ways?.has(functionRefKey(ref)) === true && (decl.body !== undefined || decl.seedKey !== undefined || decl.chance === true);
528
+ }
529
+ return RESERVED_FUNCTIONS[String(ref?.ref)]?.decides === true;
530
+ }
531
+ /**
532
+ * 🚧 The keys a ruleset's checks name as their way (`options.way` on a
533
+ * `core:function/check@1` reference) — the `ways` `functionRefDecides` reads.
534
+ * @experimental
535
+ */
536
+ export function functionWayKeys(functions) {
537
+ const out = new Set();
538
+ for (const f of functions ?? []) {
539
+ const way = f?.ref === CORE_FUNCTION_IDS.check ? f.options?.way : undefined;
540
+ if (typeof way === 'string' && way)
541
+ out.add(way);
542
+ }
543
+ return out;
544
+ }
545
+ /**
546
+ * 🚧 Every reason one function reference in a ruleset is refused:
547
+ * `resolveFunctionRef`'s, the carried module's own (`functionFindings`),
548
+ * then — when the function resolves — `unknown-function-binding` (a role it
549
+ * does not declare), `unbound-function-binding` (a role with neither tags
550
+ * nor pick, left unbound), `bad-function-binding` (bound to nothing the
551
+ * ruleset has: an attribute, entry type or zone type id, a scope, an owner
552
+ * kind), 🚧 `bad-binding-kind` (an attribute, or an entry's field, of a kind
553
+ * the role does not take — RF fix 6; 🚧 an option role's value too, RF fix
554
+ * 8), 🚧 `unknown-way` (an option role naming none of the ruleset's
555
+ * functions — a check's `way`, an outcome's `check`; RF fix 8),
556
+ * `bad-function-options` (against its `form`), `unknown-event` (it emits an
557
+ * event no one declares).
558
+ * @internal
559
+ */
560
+ export function functionRefFindings(ref, at, ctx) {
561
+ const r = resolveFunctionRef(ref);
562
+ const out = r.findings.map((f) => f.replace('] ', `] ${at}: `));
563
+ if (ref?.module !== undefined)
564
+ out.push(...functionFindings(ref.module.id, ref.module));
565
+ if (ref?.bindings !== undefined && (!ref.bindings || typeof ref.bindings !== 'object' || Array.isArray(ref.bindings)))
566
+ out.push(finding('bad-function-binding', `${at}.bindings is a map of role → what it is tied to.`));
567
+ if (ref?.options !== undefined && (!ref.options || typeof ref.options !== 'object' || Array.isArray(ref.options)))
568
+ out.push(finding('bad-function-options', `${at}.options is a map of option values.`));
569
+ const decl = r.decl;
570
+ if (!decl)
571
+ return out;
572
+ const declared = decl.bindings ?? {};
573
+ const bound = (ref.bindings && typeof ref.bindings === 'object' ? ref.bindings : {});
574
+ for (const role of Object.keys(bound))
575
+ if (!Object.prototype.hasOwnProperty.call(declared, role))
576
+ out.push(finding('unknown-function-binding', `${at}.bindings.${role}: ${decl.id} declares no role '${role}' (${Object.keys(declared).join(', ') || 'none'}).`));
577
+ for (const [role, b] of Object.entries(declared)) {
578
+ const v = bound[role];
579
+ if (v === undefined) {
580
+ if (!b.tags?.length && b.pick !== true)
581
+ out.push(finding('unbound-function-binding', `${at}: ${decl.id} needs '${role}' (${b.to}) bound — it is resolved by no tag and no pick.`));
582
+ continue;
583
+ }
584
+ const values = typeof v === 'string' ? [v] : Array.isArray(v) ? v : null;
585
+ if (!values || !values.length || values.some((x) => typeof x !== 'string')) {
586
+ out.push(finding('bad-function-binding', `${at}.bindings.${role} names what it is tied to — one id, or a list of them.`));
587
+ continue;
588
+ }
589
+ if (values.length > 1 && b.many !== true)
590
+ out.push(finding('bad-function-binding', `${at}.bindings.${role} names ${values.length}; ${decl.id}'s '${role}' takes one (it does not say many).`));
591
+ const kinds = functionBindingKinds(b);
592
+ const fieldTypes = functionBindingFieldTypes(b);
593
+ // 🚧 Whose role it is, in words, for a sentence that names it (RF fix 6).
594
+ const roleWords = `${i18nText(decl.name) ?? decl.id}'s '${i18nText(b.label) ?? role}'`;
595
+ /** Why an attribute role refuses `x`: none of the ruleset's, or a kind (a field type) the role does not take. */
596
+ const attributeWhy = (x) => {
597
+ if (ctx.attributes.has(x)) {
598
+ const has = ctx.attributeKinds?.get(x);
599
+ return !has?.length || has.some((k) => kinds.includes(k))
600
+ ? null
601
+ : finding('bad-binding-kind', `${at}.bindings.${role}: ${roleWords} takes ${attributeKindsInWords(kinds)}; '${x}' is ${attributeKindsInWords(has)}.`);
602
+ }
603
+ const fieldType = ctx.entryFieldTypes?.get(x) ?? (ctx.entryFields?.has(x) ? 'number' : undefined);
604
+ if (fieldTypes.length && fieldType !== undefined)
605
+ return fieldTypes.includes(fieldType)
606
+ ? null
607
+ : finding('bad-binding-kind', `${at}.bindings.${role}: ${roleWords} takes ${attributeKindsInWords(kinds)}, or an entry's ${fieldTypes.join(' or ')} field; '${x}' is a ${fieldType} field.`);
608
+ return fieldTypes.length
609
+ ? `'${x}' is none of the ruleset's attributes, and no entry type's ${fieldTypes.join(' or ')} field ('<entry type>.<field>')`
610
+ : `'${x}' is none of the ruleset's attributes`;
611
+ };
612
+ for (const x of values) {
613
+ const why = b.to === 'attribute'
614
+ ? attributeWhy(x)
615
+ : b.to === 'entry-type'
616
+ ? ctx.entryTypes.has(x) ? null : `'${x}' is none of the ruleset's entry types`
617
+ : b.to === 'zone-type'
618
+ ? ctx.zoneTypes.has(x) ? null : `'${x}' is none of the ruleset's zone types`
619
+ : b.to === 'owner'
620
+ ? OWNER_KINDS.includes(x) ? null : `'${x}' is no owner kind (${OWNER_KINDS.join(', ')})`
621
+ : visibilityFindings(x, `${at}.bindings.${role}`, ctx.modules)[0] ?? null;
622
+ if (why)
623
+ out.push(why.startsWith('[') ? why : finding('bad-function-binding', `${at}.bindings.${role}: ${why}.`));
624
+ }
625
+ }
626
+ if (decl.form && ref.options && typeof ref.options === 'object' && !Array.isArray(ref.options)) {
627
+ for (const k of Object.keys(ref.options))
628
+ if (!Object.prototype.hasOwnProperty.call(decl.form, k))
629
+ out.push(finding('bad-function-options', `${at}.options.${k}: ${decl.id} takes ${Object.keys(decl.form).join(', ') || 'no options'}.`));
630
+ const known = Object.fromEntries(Object.entries(ref.options).filter(([k]) => Object.prototype.hasOwnProperty.call(decl.form, k)));
631
+ for (const f of checkValues(decl.form, known))
632
+ if (f.severity === 'error')
633
+ out.push(finding('bad-function-options', `${at}.options: ${f.message} — ${f.fix}`));
634
+ }
635
+ // 🚧 Option roles (RF fix 8 — RF fix 6 ★2/★3): an option naming a value
636
+ // never names a word or free text where it is counted; one naming a
637
+ // function names one of this ruleset's (a pasted Document can carry one
638
+ // that names nothing).
639
+ for (const [k, role] of Object.entries(decl.optionRoles ?? {})) {
640
+ const v = ref.options && typeof ref.options === 'object' ? ref.options[k] : undefined;
641
+ if (typeof v !== 'string' || !v)
642
+ continue;
643
+ const optionWords = `${i18nText(decl.name) ?? decl.id}'s '${i18nText(decl.form?.[k]?.label) ?? k}'`;
644
+ if (role.names === 'function') {
645
+ if (ctx.functionKeys && !ctx.functionKeys.has(v))
646
+ out.push(finding('unknown-way', `${at}.options.${k}: ${optionWords} names '${v}', which is none of the ruleset's functions${ctx.functionKeys.size ? ` (${[...ctx.functionKeys].slice(0, 8).join(', ')}${ctx.functionKeys.size > 8 ? ', …' : ''})` : ''}.`));
647
+ continue;
648
+ }
649
+ const kinds = role.kinds?.length ? role.kinds : NUMBER_ATTRIBUTE_KINDS;
650
+ const has = ctx.attributes.has(v) ? ctx.attributeKinds?.get(v) : undefined;
651
+ if (has?.length && !has.some((x) => kinds.includes(x)))
652
+ out.push(finding('bad-binding-kind', `${at}.options.${k}: ${optionWords} takes ${attributeKindsInWords(kinds)}; '${v}' is ${attributeKindsInWords(has)}.`));
653
+ const fieldType = ctx.entryFieldTypes?.get(v);
654
+ if (fieldType !== undefined && fieldType !== 'number' && fieldType !== 'integer')
655
+ out.push(finding('bad-binding-kind', `${at}.options.${k}: ${optionWords} takes ${attributeKindsInWords(kinds)}, or an entry's number field; '${v}' is a ${fieldType} field.`));
656
+ }
657
+ for (const e of decl.emits ?? [])
658
+ if (!ctx.events.has(e) && !knownEvent(e))
659
+ out.push(finding('unknown-event', `${at}: ${decl.id} emits '${e}', which no core event, package event or function of this ruleset declares.`));
660
+ return out;
661
+ }
662
+ /** A core or package event, read at call time — a package's count once declared. */
663
+ const knownEvent = (id) => eventById(id) !== undefined || packageEventById(id) !== undefined;
664
+ // ── Forks, what a function provides ─────────────────────────────────────────
665
+ /**
666
+ * 🚧 Fork a function into a ruleset — what editing a body does (D1): a copy
667
+ * under the ruleset's owner (`<owner>:function/<ruleset>-<name>@1`, or `id`),
668
+ * marked `forkedFrom` the original. Carry it in the ruleset as a reference
669
+ * with `module` (`{ ref: fork.id, module: fork }`). Pure: nothing registers.
670
+ * @experimental
671
+ */
672
+ export function forkFunction(decl, into, opts = {}) {
673
+ const m = /^([a-z0-9]+(?:[.-][a-z0-9]+)*):ruleset\/([a-z0-9]+(?:-[a-z0-9]+)*)@\d+$/.exec(String(into));
674
+ if (!m && opts.id === undefined)
675
+ throw new Error(`'${String(into)}' is not a ruleset id. Fork a function into 'owner:ruleset/name@N'.`);
676
+ const name = parseFunctionId(decl.id)?.name ?? 'function';
677
+ const id = opts.id ?? `${m[1]}:function/${m[2]}-${name}@1`;
678
+ if (!isFunctionId(id))
679
+ throw new Error(`'${id}' is not a function id. Use 'owner:function/name@N'.`);
680
+ const { id: _id, forkedFrom: _f, ...props } = JSON.parse(JSON.stringify(decl));
681
+ return freezeDeep({ ...props, id, forkedFrom: decl.id });
682
+ }
683
+ /**
684
+ * 🚧 What a function provides (D1): its kind, the attributes, events,
685
+ * verbs, outcome words and zone types it adds (by id), what it emits, its
686
+ * phases, whether it decides by the rules, its chance, and whether a person
687
+ * may invoke it. A reserved id not yet registered provides its kind and
688
+ * chance alone.
689
+ * @experimental
690
+ */
691
+ export function functionProvides(fn) {
692
+ const ref = typeof fn === 'string' ? { ref: fn } : 'ref' in fn && typeof fn.ref === 'string' ? fn : { ref: fn.id, module: fn };
693
+ const decl = ref.module ?? registry.get(ref.ref);
694
+ const reserved = decl ? undefined : RESERVED_FUNCTIONS[ref.ref];
695
+ const ids = (xs) => (xs ?? []).map((x) => String(x?.id));
696
+ return Object.freeze({
697
+ kind: String(decl?.kind ?? reserved?.kind ?? ''),
698
+ attributes: ids(decl?.adds?.attributes),
699
+ events: ids(decl?.adds?.events),
700
+ verbs: [...(decl?.adds?.verbs ?? [])],
701
+ outcomes: ids(decl?.adds?.outcomes),
702
+ zoneTypes: ids(decl?.adds?.zoneTypes),
703
+ emits: [...(decl?.emits ?? [])],
704
+ phases: [...(decl?.phases ?? [])],
705
+ decides: functionRefDecides(ref),
706
+ chance: decl ? decl.chance === true : reserved?.chance === true,
707
+ rollsDice: decl ? decl.rollsDice === true : reserved?.rollsDice === true,
708
+ invokable: decl?.invokable !== undefined,
709
+ headerOnly: decl ? decl.body === undefined && decl.seedKey === undefined : reserved?.decides !== true,
710
+ });
711
+ }
712
+ //# sourceMappingURL=functions.js.map