behavior-contracts 0.10.1 → 0.11.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 (97) hide show
  1. package/README.md +246 -350
  2. package/cli-contract.yaml +49 -51
  3. package/dist/authoring.d.ts +80 -420
  4. package/dist/authoring.d.ts.map +1 -1
  5. package/dist/authoring.js +53 -1157
  6. package/dist/authoring.js.map +1 -1
  7. package/dist/behavior.d.ts +31 -15
  8. package/dist/behavior.d.ts.map +1 -1
  9. package/dist/behavior.js +55 -0
  10. package/dist/behavior.js.map +1 -1
  11. package/dist/builder.d.ts +4 -4
  12. package/dist/builder.d.ts.map +1 -1
  13. package/dist/builder.js +18 -16
  14. package/dist/builder.js.map +1 -1
  15. package/dist/cli.js +5 -5
  16. package/dist/cli.js.map +1 -1
  17. package/dist/commands/codegen.d.ts.map +1 -1
  18. package/dist/commands/codegen.js +12 -56
  19. package/dist/commands/codegen.js.map +1 -1
  20. package/dist/commands/ts-compile.d.ts +23 -0
  21. package/dist/commands/ts-compile.d.ts.map +1 -0
  22. package/dist/commands/ts-compile.js +693 -0
  23. package/dist/commands/ts-compile.js.map +1 -0
  24. package/dist/commands/ts-extract.d.ts +55 -7
  25. package/dist/commands/ts-extract.d.ts.map +1 -1
  26. package/dist/commands/ts-extract.js +177 -64
  27. package/dist/commands/ts-extract.js.map +1 -1
  28. package/dist/generated/contract.d.ts.map +1 -1
  29. package/dist/generated/contract.js +2 -2
  30. package/dist/generated/contract.js.map +1 -1
  31. package/dist/generated/program.js +4 -4
  32. package/dist/generated/program.js.map +1 -1
  33. package/dist/generator/core.d.ts +11 -1
  34. package/dist/generator/core.d.ts.map +1 -1
  35. package/dist/generator/core.js +5 -4
  36. package/dist/generator/core.js.map +1 -1
  37. package/dist/generator/emit-php.d.ts +0 -17
  38. package/dist/generator/emit-php.d.ts.map +1 -1
  39. package/dist/generator/emit-php.js +25 -1
  40. package/dist/generator/emit-php.js.map +1 -1
  41. package/dist/generator/emit-python.d.ts +0 -7
  42. package/dist/generator/emit-python.d.ts.map +1 -1
  43. package/dist/generator/emit-python.js +34 -1
  44. package/dist/generator/emit-python.js.map +1 -1
  45. package/dist/generator/emit-straightline-typed-typescript.js +1 -1
  46. package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
  47. package/dist/generator/emit-typed-native-go.d.ts +1 -1
  48. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  49. package/dist/generator/emit-typed-native-go.js +122 -112
  50. package/dist/generator/emit-typed-native-go.js.map +1 -1
  51. package/dist/generator/emit-typed-native-rust.d.ts +3 -2
  52. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  53. package/dist/generator/emit-typed-native-rust.js +61 -125
  54. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  55. package/dist/generator/emit-typescript-native.js +1 -1
  56. package/dist/generator/emit-typescript-native.js.map +1 -1
  57. package/dist/generator/emit-typescript.js +1 -1
  58. package/dist/generator/emit-typescript.js.map +1 -1
  59. package/dist/generator/typed.d.ts +5 -1
  60. package/dist/generator/typed.d.ts.map +1 -1
  61. package/dist/generator/typed.js +40 -9
  62. package/dist/generator/typed.js.map +1 -1
  63. package/dist/guard.d.ts +11 -0
  64. package/dist/guard.d.ts.map +1 -1
  65. package/dist/guard.js +35 -8
  66. package/dist/guard.js.map +1 -1
  67. package/dist/index.d.ts +20 -57
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +25 -101
  70. package/dist/index.js.map +1 -1
  71. package/dist/lowering.d.ts +251 -0
  72. package/dist/lowering.d.ts.map +1 -0
  73. package/dist/lowering.js +682 -0
  74. package/dist/lowering.js.map +1 -0
  75. package/dist/provenance.js +4 -4
  76. package/dist/provenance.js.map +1 -1
  77. package/dist/runtime.d.ts +52 -0
  78. package/dist/runtime.d.ts.map +1 -0
  79. package/dist/runtime.js +77 -0
  80. package/dist/runtime.js.map +1 -0
  81. package/dist/spec-versions.d.ts +25 -0
  82. package/dist/spec-versions.d.ts.map +1 -0
  83. package/dist/spec-versions.js +26 -0
  84. package/dist/spec-versions.js.map +1 -0
  85. package/dist/type-gate.d.ts +12 -0
  86. package/dist/type-gate.d.ts.map +1 -1
  87. package/dist/type-gate.js +79 -3
  88. package/dist/type-gate.js.map +1 -1
  89. package/package.json +5 -1
  90. package/dist/bind.d.ts +0 -88
  91. package/dist/bind.d.ts.map +0 -1
  92. package/dist/bind.js +0 -155
  93. package/dist/bind.js.map +0 -1
  94. package/dist/lower.d.ts +0 -35
  95. package/dist/lower.d.ts.map +0 -1
  96. package/dist/lower.js +0 -118
  97. package/dist/lower.js.map +0 -1
package/dist/authoring.js CHANGED
@@ -1,346 +1,59 @@
1
- import { SPEC_VERSIONS } from "./index.js";
2
- import { mintCompiled } from "./provenance.js";
3
- import { assertAllNodeTypesDetermined, canonicalizeType } from "./type-gate.js";
4
- import { assertPortableComponentGraph, assertPortableTypeNotation, PortabilityError } from "./guard.js";
5
- import { buildComponentCore, checkPortableEntry, checkPortNames, checkDeclaredPortTypes, collectNodeIdRefs, DEFAULT_PLAN_CONCURRENCY, } from "./builder.js";
6
- export class AuthoringFailure extends Error {
7
- code;
8
- constructor(code, message) {
9
- super(message);
10
- this.code = code;
11
- this.name = "AuthoringFailure";
12
- }
13
- }
14
- function afail(code, message) {
15
- throw new AuthoringFailure(code, message);
16
- }
17
- // ── root マーカー(クラス単位・effect 非依存)───────────────────────────────────
18
- const BEHAVIOR_MARK = /* @__PURE__ */ Symbol.for("behavior-contracts.authoring.behavior");
19
- /**
20
- * `SemanticBehavior` — 共有 authoring の基底クラス(既定の root マーカー)。
21
- * 継承したクラスの各 public メソッドが 1 root Behavior として publish される。
22
- * マーカー以外の実装・状態は持たない(authoring は effect 非依存・宣言のみ)。
23
- */
24
- export class SemanticBehavior {
25
- }
1
+ // Failure 型は lowering.ts が所有する(規則の SSoT)。authoring 面からも従来どおり見えるよう re-export。
2
+ export { AuthoringFailure } from "./lowering.js";
3
+ // ── root / leaf マーカー(クラス単位・effect 非依存・runtime no-op)─────────────────
26
4
  /**
27
- * `@behavior` — クラスデコレータ形の root マーカー(`SemanticBehavior` 継承と**同義**。
28
- * 同じクラス本体はどちらのマーカーでも同一 IR に lower される)。
29
- * TC39 standard / legacy いずれのデコレータ位置でも、素の関数呼び出しでも使える。
5
+ * `@behavior` — root マーカー。`@behavior static` メソッド = 1 root Behavior(合成コンポーネント)。
6
+ * runtime は no-op(AST リーダーが名前で識別・実行しない)。plain 呼び出し(`behavior(fn)` — node
7
+ * type-stripping 用)・TC39 method-decorator いずれの適用位置でも型が通ればよい。
30
8
  */
31
- export function behavior(cls, _context) {
32
- Object.defineProperty(cls, BEHAVIOR_MARK, { value: true, configurable: true });
33
- return cls;
34
- }
35
- function isBehaviorClass(cls) {
36
- if (typeof cls !== "function")
37
- return false;
38
- if (cls[BEHAVIOR_MARK] === true)
39
- return true;
40
- return cls === SemanticBehavior || cls.prototype instanceof SemanticBehavior;
41
- }
42
- // ── recorder(式 Proxy)─────────────────────────────────────────────────────────
43
- const EXPR_META = /* @__PURE__ */ Symbol("behavior-contracts.authoring.expr");
44
- /** recorder 値なら ExprMeta を返す。 */
45
- function exprMetaOf(v) {
46
- if (v === null || (typeof v !== "object" && typeof v !== "function"))
47
- return undefined;
48
- return v[EXPR_META];
9
+ export function behavior(target, _context) {
10
+ return target;
49
11
  }
50
12
  /**
51
- * `.map` の opts キーの閉集合(**runtime-enumerable SoT**)。{@link MapOptions} の型はここから
52
- * 導出し(`Record<...> `)、新 opts キーを足すときはここに 1 語追加するのが正。matrix の網羅ゲート
53
- * (#132)はこの配列から導出するので、SoT にキーを足して matrix にケースが無ければ CI が RED になる。
54
- * 注: 要素ごと skip の `when` は opts キーではなく callback 内 `when(...)` guard 由来(`map.when` へ
55
- * lower)なので、ここには含めない(authoring 手段が別。matrix 側で別途カバーする)。
56
- */
57
- export const MAP_OPTION_KEYS = ["into", "batched"];
58
- /**
59
- * `refsConnection`(v3 fanout)の opts キーの閉集合(**runtime-enumerable SoT**)。graphddb の
60
- * `@refs` 読みが宣言する dedupe/drop 契約。{@link FanoutOptions} の型はここから導出。新 opts キーは
61
- * ここに追加するのが正で、matrix 網羅ゲート(#132)がこの配列から導出する(未カバー → CI RED)。
13
+ * `@leaf` — leaf マーカー。`@leaf static` メソッド = 1 leaf(catalog エントリは AST が
14
+ * シグネチャから導く — struct 設定なし)。runtime は no-op(AST リーダーが名前で識別・実行しない)。
62
15
  */
63
- export const FANOUT_OPTION_KEYS = ["dedupeKey", "drop", "implicitSource"];
64
- const _mapOptsSync = true;
65
- const _fanoutOptsSync = true;
66
- void _mapOptsSync;
67
- void _fanoutOptsSync;
68
- function makeExpr(meta) {
69
- return new Proxy({}, {
70
- get(_t, prop) {
71
- if (prop === EXPR_META)
72
- return meta;
73
- if (typeof prop === "symbol") {
74
- if (prop === Symbol.toPrimitive)
75
- return () => notRecordable("implicit coercion of a recorded value (use concat/add/eq/... builders)");
76
- return undefined;
77
- }
78
- // Promise-likeness / util.inspect の誤爆を避ける(record 対象でもない)。
79
- if (prop === "then" || prop === "constructor" || prop === "inspect")
80
- return undefined;
81
- if (prop === "valueOf" || prop === "toString" || prop === "toJSON")
82
- return () => notRecordable(`'${prop}' on a recorded value (implicit coercion is not statically interpretable)`);
83
- if (prop === "map")
84
- return (cb, opts) => recordMap(meta, cb, opts);
85
- if (prop === "refsConnection")
86
- return (cb, opts) => recordFanout(meta, cb, opts);
87
- if (prop === "as")
88
- return (t) => recordAs(meta, t);
89
- if (meta.refPath === null)
90
- afail("COMPUTED_ACCESS", `property '.${prop}' on a computed expression cannot be lowered (bind the value through a component result or restructure the wiring)`);
91
- if (meta.isInput && meta.refPath.length === 0)
92
- recordInputPort(prop);
93
- const path = [...meta.refPath, prop];
94
- return makeExpr({ node: { [meta.refOp]: path }, refPath: path, refOp: meta.refOp, isInput: meta.isInput });
95
- },
96
- ownKeys() {
97
- return notRecordable("spread / enumeration of a recorded value (Expression IR has no object-merge operator; wire explicit keys)");
98
- },
99
- getOwnPropertyDescriptor() {
100
- return notRecordable("property enumeration of a recorded value");
101
- },
102
- set() {
103
- return notRecordable("assignment into a recorded value (authoring is declarative)");
104
- },
105
- });
106
- }
107
- function notRecordable(what) {
108
- afail("NOT_RECORDABLE", `not statically interpretable: ${what}`);
109
- }
110
- /** 演算結果(ref path を持たない)recorder。 */
111
- function opExpr(node) {
112
- return makeExpr({ node, refPath: null, refOp: "ref", isInput: false });
113
- }
114
- /** ノード結果 recorder(`{ref:[<nodeId>]}` root。プロパティアクセスで path 延長可能)。 */
115
- function nodeHandle(id) {
116
- return makeExpr({ node: { ref: [id] }, refPath: [id], refOp: "ref", isInput: false });
117
- }
118
- // ── 値 → Expression IR lowering ────────────────────────────────────────────────
119
- /**
120
- * authoring 本体に現れた値を Expression IR へ lower する。
121
- * recorder はその IR ノードに、リテラルはそのまま(配列 → `{arr:[...]}`、オブジェクト →
122
- * `{obj:{...}}`、bigint → `{int:"..."}`)に落ちる。関数 / Date / Promise / undefined は
123
- * Portability 違反として loud に失敗する(fail-closed)。
124
- */
125
- function lowerValue(v, at) {
126
- const meta = exprMetaOf(v);
127
- if (meta) {
128
- if (meta.refPath !== null && meta.refPath.length === 0)
129
- afail("WHOLE_INPUT", `${at}: the whole '$' input cannot be wired; reference a field of it`);
130
- return meta.node;
131
- }
132
- if (v === null)
133
- return null;
134
- switch (typeof v) {
135
- case "boolean":
136
- case "string":
137
- return v;
138
- case "number":
139
- if (Number.isInteger(v) && !Number.isSafeInteger(v))
140
- afail("BAD_PORT_VALUE", `${at}: integral literal ${v} exceeds the safe range (use a bigint literal)`);
141
- if (!Number.isFinite(v))
142
- afail("BAD_PORT_VALUE", `${at}: non-finite number literal`);
143
- return v;
144
- case "bigint":
145
- return { int: v.toString() };
146
- case "undefined":
147
- afail("BAD_PORT_VALUE", `${at}: undefined cannot be wired`);
148
- break;
149
- case "function":
150
- afail("BAD_PORT_VALUE", `${at}: functions cannot be placed in IR (Portability Guard)`);
151
- break;
152
- }
153
- if (Array.isArray(v))
154
- return { arr: v.map((e, i) => lowerValue(e, `${at}[${i}]`)) };
155
- if (v instanceof Date || v instanceof Promise)
156
- afail("BAD_PORT_VALUE", `${at}: ${v.constructor.name} cannot be placed in IR (Portability Guard)`);
157
- if (typeof v === "object") {
158
- const out = {};
159
- for (const k of Object.keys(v)) {
160
- if (k === "__proto__")
161
- afail("BAD_PORT_VALUE", `${at}: object key "__proto__" is forbidden (fail-closed)`);
162
- out[k] = lowerValue(v[k], `${at}.${k}`);
163
- }
164
- return { obj: out };
165
- }
166
- afail("BAD_PORT_VALUE", `${at}: value cannot be wired`);
167
- }
168
- // ── Expression builders(expression-ir.md §3 の閉集合と 1:1)──────────────────────
169
- function binOp(op) {
170
- return (a, b) => opExpr({ [op]: [lowerValue(a, op), lowerValue(b, op)] });
171
- }
172
- function unOp(op) {
173
- return (a) => opExpr({ [op]: [lowerValue(a, op)] });
16
+ export function leaf(target, _context) {
17
+ return target;
174
18
  }
175
- /** `+`(文字列連結)。n-ary(min 2)。 */
176
- export function concat(...parts) {
177
- if (parts.length < 2)
178
- afail("BAD_PORT_VALUE", `concat expects >= 2 args, got ${parts.length}`);
179
- return opExpr({ concat: parts.map((p, i) => lowerValue(p, `concat[${i}]`)) });
180
- }
181
- export const add = /* @__PURE__ */ binOp("add");
182
- export const sub = /* @__PURE__ */ binOp("sub");
183
- export const mul = /* @__PURE__ */ binOp("mul");
184
- export const div = /* @__PURE__ */ binOp("div");
185
- export const mod = /* @__PURE__ */ binOp("mod");
186
- export const neg = /* @__PURE__ */ unOp("neg");
187
- export const eq = /* @__PURE__ */ binOp("eq");
188
- export const ne = /* @__PURE__ */ binOp("ne");
189
- export const lt = /* @__PURE__ */ binOp("lt");
190
- export const le = /* @__PURE__ */ binOp("le");
191
- export const gt = /* @__PURE__ */ binOp("gt");
192
- export const ge = /* @__PURE__ */ binOp("ge");
193
- export const and = /* @__PURE__ */ binOp("and");
194
- export const or = /* @__PURE__ */ binOp("or");
195
- export const not = /* @__PURE__ */ unOp("not");
196
- /** `??`。 */
197
- export const coalesce = /* @__PURE__ */ binOp("coalesce");
198
- export const len = /* @__PURE__ */ unOp("len");
19
+ // ── authoring builder ────────────────────────────────────────────────────────────
199
20
  /**
200
- * `opt(x)` — `?.`(optional chaining)の record 形。ref recorder を refOpt に変換する
201
- * (以降のプロパティアクセスは中間 null で null を返す — expression-ir.md `refOpt`)。
21
+ * `opt(x)` — optional-chain source マーカー。`opt(x).field` / `opt(x)` は AST リーダーが `refOpt`
22
+ * (欠損許容参照)へ lower する。runtime は passthrough(実行されない・型のためだけの identity)。
202
23
  */
203
24
  export function opt(x) {
204
- const meta = exprMetaOf(x);
205
- if (!meta || meta.refPath === null || meta.refPath.length === 0)
206
- afail("BAD_PORT_VALUE", "opt(...) expects a reference (a recorded '$' field or node result)");
207
- // `opt($.x)` は「その input Port は省略可」という**宣言**でもある。宣言(inputPorts)が optionality の
208
- // SSoT(runBehavior の束縛規則も native lowering もそこだけを読む)なので、recorder はここでその
209
- // SSoT を実際に立てる — 立てなければ「式は refOpt・宣言は required:true」という**矛盾した 2 枚の
210
- // carrier**が残り、宣言だけを読む下流は optionality を見失う。
211
- //
212
- // 単一セグメント(`opt($.x)`)のときだけ head を optional にする。多段(`opt($.user.name)`)は
213
- // 「途中/末端が null を取り得る」の宣言であって head Port 自体の省略可性ではないため触らない。
214
- if (meta.isInput && meta.refPath.length === 1)
215
- markInputPortOptional(meta.refPath[0]);
216
- return makeExpr({ node: { refOpt: meta.refPath }, refPath: meta.refPath, refOp: "refOpt", isInput: meta.isInput });
217
- }
218
- let currentFrame = null;
219
- function requireFrame(what) {
220
- if (!currentFrame)
221
- afail("NO_FRAME", `${what} was used outside compileBehaviors() (recorders only work during build-time evaluation)`);
222
- return currentFrame;
223
- }
224
- function recordInputPort(name) {
225
- const f = requireFrame(`$.${name}`);
226
- if (!f.inputPorts.has(name))
227
- f.inputPorts.set(name, { type: "unknown", required: true });
228
- }
229
- /**
230
- * markInputPortOptional — `opt($.x)` が宣言する「Port x は省略可」を recorder の schema に立てる
231
- * (`required:false`)。`$.x` アクセス時点で {@link recordInputPort} が required で登録済みなので、
232
- * ここは既存 schema の更新。型(`type`)には触らない(型は `opts.inputPorts` の担当)。
233
- */
234
- function markInputPortOptional(name) {
235
- const f = requireFrame(`opt($.${name})`);
236
- const cur = f.inputPorts.get(name);
237
- if (cur !== undefined)
238
- f.inputPorts.set(name, { ...cur, required: false });
239
- f.optionalInputs.add(name);
240
- }
241
- function nextId(f) {
242
- const id = `n${f.seq++}`;
243
- f.nodeIds.add(id);
244
- return id;
245
- }
246
- /** 分岐スタックの条件を `and` 連鎖に合成する(gate の `if`)。 */
247
- function composedCond(f) {
248
- const conds = f.branchStack.map((b) => b.cond);
249
- return conds.reduce((acc, c) => (acc === undefined ? c : { and: [acc, c] }), undefined);
250
- }
251
- /**
252
- * 分岐内に Component が初めて現れた時点で gate(CondNode)を遅延生成する。
253
- * gate は条件成立時 `{ok:true}` / 不成立時 `null` を返し、分岐内ノードは
254
- * `parent=gate, bindField:"ok"` の null-binding skip(execution-plan.md)で実行選択される。
255
- */
256
- function ensureGate(f) {
257
- const bf = f.branchStack[f.branchStack.length - 1];
258
- if (!bf)
259
- return null;
260
- if (f.branchStack.length > 1)
261
- afail("NESTED_BRANCH", `method '${f.method}': a when(...) branch containing components cannot nest inside another when(...) branch (authoring v1; flatten to sibling gates)`);
262
- if (bf.gateId === null) {
263
- const id = nextId(f);
264
- const gate = { id, cond: { if: composedCond(f), then: { obj: { ok: true } }, else: null } };
265
- f.nodes.push(gate);
266
- bf.gateId = id;
267
- }
268
- return bf;
269
- }
270
- /** ports の deps から parent(Wire)を決める: in-branch データ親 > gate > 先頭データ親。 */
271
- function chooseParent(f, deps, bf) {
272
- if (bf) {
273
- const inBranch = deps.find((d) => {
274
- const idx = f.nodes.findIndex((n) => n.id === d);
275
- return idx >= bf.startLen;
276
- });
277
- if (inBranch !== undefined)
278
- return { parent: inBranch }; // gate skip は親経由で伝播する
279
- return { parent: bf.gateId, bindField: "ok" };
280
- }
281
- if (deps.length > 0)
282
- return { parent: deps[0] };
283
- return {};
284
- }
285
- // ── Catalog → component 関数(leaf 呼び出しの record)──────────────────────────────
286
- /**
287
- * catalogComponents — consumer の Catalog から、authoring 本体で呼べる leaf コンポーネント
288
- * 関数群を作る(C2: consumer が供給するのはこの Catalog だけ)。
289
- *
290
- * 各関数は `Component({ port: <expr | literal> })` の呼び出しを componentRef ノードとして
291
- * record し、ノード結果の recorder(後続配線・`.map`・Output 参照に使える)を返す。
292
- * Port は catalog の Port schema に対して build-time 検証される(未知 Port / required 欠落は
293
- * fail-closed)。`portableToIR: false` のエントリは可搬 IR に載らないため拒否する。
294
- */
295
- export function catalogComponents(catalog) {
296
- const out = {};
297
- for (const name of Object.keys(catalog)) {
298
- const entry = catalog[name];
299
- out[name] = (ports) => recordComponentCall(name, entry, ports);
300
- }
301
- return out;
302
- }
303
- export function defineLeaf(name, meta,
304
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
305
- fn) {
306
- if (typeof name !== "string" || name === "")
307
- afail("BAD_LEAF_META", `defineLeaf: name must be a non-empty string`);
308
- if (!meta || typeof meta !== "object")
309
- afail("BAD_LEAF_META", `defineLeaf '${name}': meta must be an object with cardinality/ports/output`);
310
- if (meta.cardinality !== "one" && meta.cardinality !== "many")
311
- afail("BAD_LEAF_META", `defineLeaf '${name}': cardinality must be "one" or "many"`);
312
- if (!meta.ports || typeof meta.ports !== "object" || Array.isArray(meta.ports))
313
- afail("BAD_LEAF_META", `defineLeaf '${name}': ports must be a record of PortableType`);
314
- if (typeof fn !== "function")
315
- afail("BAD_LEAF_META", `defineLeaf '${name}': fn (the impl body) must be a function`);
316
- // runtime PortableType 注記の閉集合検査(guard と同一強度・fail-closed。core が読む唯一の型源)。
317
- for (const [k, pt] of Object.entries(meta.ports))
318
- checkPortableTypeMeta(name, `ports.${k}`, pt);
319
- checkPortableTypeMeta(name, "output", meta.output);
320
- return { name, meta, fn };
321
- }
322
- /** defineLeaf / behaviorComponents の PortableType 注記を fail-closed で検査する。 */
323
- function checkPortableTypeMeta(leaf, at, t) {
324
- try {
325
- assertPortableTypeNotation(t, at);
326
- }
327
- catch (e) {
328
- if (e instanceof PortabilityError)
329
- afail("BAD_TYPE_NOTATION", `defineLeaf '${leaf}': ${e.message}`);
330
- throw e;
25
+ return x;
26
+ }
27
+ /**
28
+ * `refsConnection(list, cb, opts)` — refs fanout の runtime SSoT。`list` の各要素へ `cb` を当て、
29
+ * `dedupeKey` で重複を落とし(`null`/`undefined` の dangling は drop)、`implicitSource` フィールドを
30
+ * 剥がして `{ items, cursor }` を返す。AST リーダーは `.refsConnection` 呼びを fanout ノードへ lower し、
31
+ * この関数は ts-runtime 実行で同じ意味論を再現する。
32
+ */
33
+ export function refsConnection(list, cb, opts) {
34
+ const seen = new Set();
35
+ const items = [];
36
+ for (const e of list) {
37
+ const r = cb(e);
38
+ if (r === null || r === undefined)
39
+ continue; // dangling は drop(既定)
40
+ const k = r[opts.dedupeKey];
41
+ if (seen.has(k))
42
+ continue;
43
+ seen.add(k);
44
+ if (opts.implicitSource !== undefined) {
45
+ const { [opts.implicitSource]: _drop, ...rest } = r;
46
+ items.push(rest);
47
+ }
48
+ else {
49
+ items.push(r);
50
+ }
331
51
  }
52
+ return { items, cursor: null };
332
53
  }
333
54
  /**
334
- * `PortableType` → `PortSchema.type` 文字列(hand-written catalog と同一の語彙)+
335
- * elemType の導出。既存 catalog(authoring.test.ts の `kv` / codegen-corpus の inputPorts)は
336
- * スカラを `"string"`/`"int"`/`"float"`/`"bool"` の TS 風文字列で、配列を
337
- * `{ type:"array", elemType: <PortableType> }` で書く。この導出はその shape を再現する:
338
- *
339
- * - スカラ → `{ type: <scalar> }`
340
- * - `{opt: T}` → 内側 T の schema に `required:false` を上書き(nullable Port)
341
- * - `{arr: T}` → `{ type:"array", elemType: T }`(map-over-input の $as 要素型解決源 — bc#101)
342
- * - `{map: T}` → `{ type:"map", elemType: T }`(動的 string キー・同種値型のマップ)
343
- * - `{obj: …}` → `{ type:"object" }`(object Port — 内部 field 型は catalog schema では持たない)
55
+ * `portSchemaFromPortable` — PortableType を CatalogEntry の PortSchema へ射影する(scalar / opt /
56
+ * arr / map / obj)。`required` は Port が省略可でない(`opt` ラップでない)ことを表す。
344
57
  */
345
58
  export function portSchemaFromPortable(pt, required) {
346
59
  if (typeof pt === "string") {
@@ -373,35 +86,19 @@ export function portSchemaFromPortable(pt, required) {
373
86
  s.required = true;
374
87
  return s;
375
88
  }
376
- /**
377
- * derivePortSchemas — node の `portSchemas`(#173・irVersion 2)を機械導出する **唯一の SSoT**。
378
- * `node.outType`(出力型契約)の入力側の双子で、port ごとの型契約を焼く(native emitter の port 境界が
379
- * これを honor し要素 kind 推論を廃す)。各 port の契約は leaf の宣言そのもの:
380
- * - **宣言 port**(`entry.inputPorts[k]` に在る)→ leaf の宣言 `PortSchema` をそのまま(emitter が honor
381
- * する契約 — 例 `{arr:"value"}` は Vec&lt;WireValue&gt;)。
382
- * - **動的 port**(`additionalPorts:true` leaf の未宣言キー)→ その leaf は「任意型の追加 port を受ける」と
383
- * **宣言**しているので、契約は不透明 `value`(=leaf の additionalPorts 宣言の意味そのもの。推論ではなく
384
- * 宣言の読み取り。authoring 入力は型消去されるため wired 値の静的型は一般に不確定であり、`value` が
385
- * その port の honest な契約)。
386
- * recordComponentCall / map・fanout fold の 3 箇所だけがこれを呼ぶ(手書き portSchemas 禁止)。
387
- */
388
- export function derivePortSchemas(entry, ports) {
389
- const out = {};
390
- for (const k of Object.keys(ports))
391
- out[k] = entry.inputPorts[k] ?? { type: "value" };
392
- return out;
393
- }
394
89
  /** cardinality → CatalogOutput.shape(one → "item" / many → "items"。既存語彙と一致)。 */
395
90
  function outputShapeFromCardinality(cardinality) {
396
91
  return { shape: cardinality === "one" ? "item" : "items" };
397
92
  }
398
93
  /**
399
- * catalogEntryFromLeaf — defineLeaf の runtime 注記から `CatalogEntry` を **導出**する
400
- * (consumer は catalog を手書きしない — §4.1)。
401
- * - `inputPorts` = 各 Port の PortableType を PortSchema へ射影(scalar/opt/arr/obj)。
402
- * - `output.shape` = cardinality(one→item / many→items)。
94
+ * `catalogEntryFromLeaf` — leaf の runtime 注記から `CatalogEntry` を **導出**する(consumer は
95
+ * catalog を手書きしない — §4.1)。
96
+ * - `inputPorts` = 各 Port の PortableType を PortSchema へ射影(scalar / opt / arr / map / obj)。
97
+ * - `output.shape` = cardinality(one → item / many → items)。
403
98
  * - `elemType` = `output`(その leaf が返す要素の確定型。typed codegen / map 要素型の SSoT)。
404
- * - `portableToIR` / `additionalPorts` は meta から(既定 true / false)。
99
+ *
100
+ * `leafSymbol`(#176 op-agnostic transport 名)は leaf 宣言側では固定せず、native emitter が CLI
101
+ * `--leaf-transport` override / 既定 `Leaf_<comp>` で解決する。
405
102
  */
406
103
  export function catalogEntryFromLeaf(def) {
407
104
  const inputPorts = {};
@@ -410,813 +107,12 @@ export function catalogEntryFromLeaf(def) {
410
107
  const required = !(typeof pt === "object" && pt !== null && "opt" in pt);
411
108
  inputPorts[k] = portSchemaFromPortable(pt, required);
412
109
  }
413
- const entry = {
110
+ return {
414
111
  name: def.name,
415
112
  inputPorts,
416
113
  output: outputShapeFromCardinality(def.meta.cardinality),
417
- portableToIR: def.meta.portableToIR ?? true,
114
+ portableToIR: true,
418
115
  elemType: def.meta.output,
419
116
  };
420
- if (def.meta.additionalPorts === true)
421
- entry.additionalPorts = true;
422
- // #176: the SPEC-fixed op-agnostic transport symbol name — carried onto each referencing node
423
- // (`leafSymbol`) so native codegen resolves it as the first candidate (before CLI override / default).
424
- if (def.meta.transport !== undefined)
425
- entry.leafSymbol = def.meta.transport;
426
- return entry;
427
- }
428
- /**
429
- * behaviorComponents — `defineLeaf` 結果のレコードから **portable catalog を導出**し、
430
- * authoring 本体で呼べる leaf コンポーネント関数群を返す(`catalogComponents(catalog)` と
431
- * **同一の call-shape** `{ [name]: (ports) => Recorded }`・同一の {@link recordComponentCall}
432
- * 機構)。consumer は catalog も handlers も手書きしない(§4.1 / SA4)。
433
- *
434
- * catalog は `defineLeaf` の型付きシグネチャ由来の runtime 注記から機械導出されるため、
435
- * 手書き catalog と**構造的に同一**(AC1)。派生後の record は既存 catalog 経路と完全に同じ
436
- * port 検証・lowering を通る。
437
- */
438
- export function behaviorComponents(leaves) {
439
- const out = {};
440
- for (const key of Object.keys(leaves)) {
441
- const def = leaves[key];
442
- const entry = catalogEntryFromLeaf(def);
443
- // SA8: leaf impl(型付き静的関数の本体)を record 時にフレームのレジストリへ登録する。
444
- // handlers 手注入を廃し、bind 時にこの registry から name→impl を自動 dispatch する(bind.ts)。
445
- out[key] = (ports) => recordComponentCall(entry.name, entry, ports, def.fn);
446
- }
447
- return out;
448
- }
449
- /**
450
- * deriveCatalog — `defineLeaf` レコードから `Catalog`(name → CatalogEntry)を導出する
451
- * (guard / typed codegen / fingerprint の SSoT を得たい consumer 向け。`behaviorComponents`
452
- * が内部で使うのと同一の {@link catalogEntryFromLeaf} 射影)。
453
- */
454
- export function deriveCatalog(leaves) {
455
- const catalog = {};
456
- for (const def of Object.values(leaves))
457
- catalog[def.name] = catalogEntryFromLeaf(def);
458
- return catalog;
459
- }
460
- /**
461
- * baseOutTypeFromEntry — catalog エントリの base ノード結果型を導出する。`elemType` は leaf の
462
- * **要素型**なので、ノード結果の確定型は `output.shape` で包む:
463
- * - `item`(既定)→ 要素型そのもの。
464
- * - `items` → `{arr: 要素型}`(リスト結果)。
465
- * - `connection` → `{obj:{items:{arr:要素型}, cursor:{opt:"string"}}}`(connection 結果)。
466
- * `elemType` が無いエントリ(手書き catalog 等)は undefined(=未確定 → ゲートが UNTYPED_NODE)。
467
- */
468
- function baseOutTypeFromEntry(entry) {
469
- if (entry.elemType === undefined)
470
- return undefined;
471
- const shape = entry.output?.shape ?? "item";
472
- if (shape === "items")
473
- return { arr: entry.elemType };
474
- if (shape === "connection")
475
- return { obj: { items: { arr: entry.elemType }, cursor: { opt: "string" } } };
476
- return entry.elemType; // item(単一)
477
- }
478
- function recordComponentCall(name, entry, portsIn, impl) {
479
- const f = requireFrame(`component '${name}'`);
480
- // SA8: behaviorComponents 由来の leaf 呼びは impl を持つ → フレームのレジストリへ登録(自動 bind の出所)。
481
- // catalogComponents(生 Catalog・impl 無し)由来は impl=undefined = 登録しない(bind は不可)。
482
- if (impl !== undefined)
483
- f.registry[name] = impl;
484
- checkPortableEntry(name, entry, afail);
485
- if (!portsIn || typeof portsIn !== "object" || Array.isArray(portsIn) || exprMetaOf(portsIn))
486
- afail("BAD_PORT_VALUE", `component '${name}': ports must be a plain object literal`);
487
- // Port schema 検証(build-time・fail-closed。builder.ts のデータ登録経路と共有 — B-3):
488
- // 未宣言 Port(additionalPorts ポリシー)・required 欠落、lower 後に宣言 Port の
489
- // スカラリテラル型。
490
- checkPortNames(name, entry, Object.keys(portsIn), afail);
491
- const ports = {};
492
- for (const k of Object.keys(portsIn))
493
- ports[k] = lowerValue(portsIn[k], `component '${name}' port '${k}'`);
494
- checkDeclaredPortTypes(name, entry, ports, afail);
495
- // map コールバック内 → MapNode の component/ports として capture(単一静的ノード)。
496
- if (f.pendingMap) {
497
- if (f.pendingMap.component !== null)
498
- afail("MAP_MULTI_COMPONENT", `method '${f.method}': a .map callback must invoke exactly one component (got a second call: '${name}')`);
499
- f.pendingMap.component = name;
500
- f.pendingMap.entry = entry; // #173: fold 時の portSchemas 導出源。
501
- f.pendingMap.ports = ports;
502
- // callback 内 leaf の base 要素型を捕捉(`.as` 未指定時の確定型 — recordMap/recordFanout が使う)。
503
- f.pendingMap.baseElemType = entry.elemType;
504
- // callback 内でこの要素結果へさらに配線することはできない(record は構造のみ)が、
505
- // `.as<T>(t)` による要素の確定型注記だけは受ける(mapResult recorder — recordAs が
506
- // pendingMap.outType へ回す)。
507
- return makeExpr({ node: null, refPath: null, refOp: "ref", isInput: false, mapResult: true });
508
- }
509
- const bf = ensureGate(f);
510
- const deps = collectNodeIdRefs(ports, f.nodeIds);
511
- const id = nextId(f);
512
- const wire = chooseParent(f, deps, bf);
513
- const node = { id, component: name, ports };
514
- if (wire.parent !== undefined)
515
- node.parent = wire.parent;
516
- if (wire.bindField !== undefined)
517
- node.bindField = wire.bindField;
518
- // base 出力型を leaf の catalog `elemType`(A1 の defineLeaf 由来)からノードへ焼く(SA5 の
519
- // 「leaf の base 型は signature 由来」= 確定)。elemType は**要素型**なので、ノード結果の型は
520
- // leaf の output.shape で包む(item=要素そのもの / items=`{arr:要素}` / connection=`{obj:{items,cursor}}`)。
521
- // projection 等で型が変わる点は後段の `.as<T>()` が recordAs で上書きする(配列/要素の別も consumer が
522
- // 確定させる)。catalog に elemType が無い(手書き catalog 等)ノードは outType 未確定のまま残り、
523
- // 全ノード型確定ゲート(type-gate.ts)が `UNTYPED_NODE` で名指して落とす。
524
- const baseOut = baseOutTypeFromEntry(entry);
525
- if (baseOut !== undefined)
526
- node.outType = baseOut;
527
- // #173: node.outType(出力型契約)の入力側の双子 — 各 port の型契約を焼く(native emitter が honor)。
528
- node.portSchemas = derivePortSchemas(entry, ports);
529
- // #176: SPEC 固定の transport シンボル名を焼く(native emitter の resolveLeafSymbol が第一候補で読む)。
530
- if (entry.leafSymbol !== undefined)
531
- node.leafSymbol = entry.leafSymbol;
532
- f.nodes.push(node);
533
- return nodeHandle(id);
534
- }
535
- // ── `.as<T>(t)`(inline 確定型注記 — SA5 / scp-only-authoring-contract §4.4)──────────
536
- /**
537
- * recordAs — node 結果 recorder の `.as<T>(t)` を lower する。projection / 合成で base 型
538
- * (leaf signature 由来)から**確定型が変わる点**を consumer が inline で確定させる surface。
539
- *
540
- * TS の型は実行時に消去されるため(consumer-interface.md C3・不変)、BC core は**推論しない**:
541
- * `.as` は引数の runtime `PortableType`(可搬型記法の閉集合)だけを読み、それを対象 body
542
- * ノードの `outType` に書き込む。TS の generic `<T>` は呼び出し側で `t` に束縛され(型が
543
- * 矛盾すれば tsc エラー)、runtime へは `t`(= SSoT)だけが渡る。注記は「推論結果」ではなく
544
- * 「consumer が静的に確定した型」であり、後段(A3 の UNTYPED_NODE gate / typed codegen)が読む。
545
- *
546
- * `.as` は **node 結果 recorder(componentRef / map / fanout の結果)** にのみ適用できる。
547
- * `$` 入力参照・演算結果(`concat(...)` 等)は body ノードを持たず注記先が無いため
548
- * `BAD_AS_TARGET` で fail-closed(型未確定の穴を作らない = SA5)。map/fanout コールバック内の
549
- * leaf 結果への `.as` は、要素の確定型として pendingMap に記録し、畳まれた MapNode/FanoutNode の
550
- * `outType` に載せる。
551
- */
552
- function recordAs(meta, t) {
553
- const f = requireFrame(".as");
554
- // runtime PortableType の閉集合検査(guard と同一強度・fail-closed)。TS の型消去後に
555
- // core が読むのはこの runtime 注記だけ(推論しない)。
556
- try {
557
- assertPortableTypeNotation(t, `.as`);
558
- }
559
- catch (e) {
560
- if (e instanceof PortabilityError)
561
- afail("BAD_TYPE_NOTATION", `method '${f.method}': .as<T>(t) — ${e.message}`);
562
- throw e;
563
- }
564
- // map/fanout コールバック内の component 結果: 要素の確定型を pendingMap へ記録する
565
- // (要素は単一 Map/Fanout ノードに畳まれるため、body ノードは未生成 — outType は畳み時に載る)。
566
- if (meta.mapResult && f.pendingMap) {
567
- f.pendingMap.outType = t;
568
- return makeExpr(meta); // 同じ map 結果 recorder(callback 内でさらに配線はしない)。
569
- }
570
- // node 結果 recorder は refPath[0] が現フレームの body ノード id(nodeHandle で作られる)。
571
- const id = meta.refPath !== null && meta.refPath.length === 1 ? meta.refPath[0] : null;
572
- const node = id !== null ? f.nodes.find((n) => n.id === id) : undefined;
573
- if (!node)
574
- afail("BAD_AS_TARGET", `method '${f.method}': .as<T>(t) can only annotate a component/map/fanout result node (not a '$' input reference, a projected field, or a computed expression)`);
575
- // 対象ノード種に応じて outType を書き込む(ComponentRefNode / MapNode / FanoutNode いずれも
576
- // outType を持つ。CondNode は Φ 合流で `.as` の対象になり得るため同様に outType を持つ)。
577
- node.outType = t;
578
- // 注記後も同じ node 結果 recorder を返す(後続配線・Output 参照に使える)。
579
- return makeExpr(meta);
580
- }
581
- // ── structured control: Map(ネイティブ `.map` を lower)───────────────────────────
582
- function recordMap(overMeta, cb, opts) {
583
- const f = requireFrame(".map");
584
- if (f.pendingMap)
585
- afail("NESTED_MAP", `method '${f.method}': nested .map is not in the v2 vocabulary (chain a second map over the augmented list — scp-ir-architecture.md §5.1)`);
586
- if (f.branchStack.length > 0)
587
- afail("MAP_IN_BRANCH", `method '${f.method}': .map inside a when(...) branch is not expressible in the IR (guard the 'over' expression instead)`);
588
- if (typeof cb !== "function")
589
- afail("MAP_NOT_LOWERABLE", `method '${f.method}': .map expects an inline arrow callback`);
590
- if (cb.length > 1)
591
- afail("MAP_NOT_LOWERABLE", `method '${f.method}': .map callback takes exactly one element binding (v1)`);
592
- if (overMeta.refPath !== null && overMeta.refPath.length === 0)
593
- afail("WHOLE_INPUT", `method '${f.method}': the whole '$' input cannot be iterated; reference an array field`);
594
- if (opts !== undefined) {
595
- if (opts === null || typeof opts !== "object")
596
- afail("MAP_NOT_LOWERABLE", ".map options must be an object");
597
- if (opts.into !== undefined && typeof opts.into !== "string")
598
- afail("MAP_NOT_LOWERABLE", ".map option 'into' must be a string key");
599
- if (opts.batched !== undefined && typeof opts.batched !== "boolean")
600
- afail("MAP_NOT_LOWERABLE", ".map option 'batched' must be a boolean");
601
- }
602
- const as = `$e${f.mapSeq++}`;
603
- const binding = makeExpr({ node: { ref: [as] }, refPath: [as], refOp: "ref", isInput: false });
604
- f.pendingMap = { as, component: null, ports: null, when: undefined, outType: undefined, baseElemType: undefined, entry: null };
605
- let pm;
606
- try {
607
- cb(binding);
608
- }
609
- finally {
610
- pm = f.pendingMap;
611
- f.pendingMap = null;
612
- }
613
- if (pm.component === null)
614
- afail("MAP_NOT_LOWERABLE", `method '${f.method}': a .map callback must invoke a catalog component (a pure-transform map has no operator in the portable Expression IR v2 vocabulary)`);
615
- const over = overMeta.node;
616
- const deps = collectNodeIdRefs(over, f.nodeIds);
617
- collectNodeIdRefs(pm.ports, f.nodeIds, deps);
618
- if (pm.when !== undefined)
619
- collectNodeIdRefs(pm.when, f.nodeIds, deps);
620
- const id = nextId(f);
621
- const node = {
622
- id,
623
- map: { over, as, component: pm.component, ports: pm.ports },
624
- };
625
- if (pm.when !== undefined)
626
- node.map.when = pm.when;
627
- if (opts?.into !== undefined)
628
- node.map.into = opts.into;
629
- if (opts?.batched === true)
630
- node.map.batched = true;
631
- if (deps.length > 0)
632
- node.map.parent = deps[0];
633
- // callback 内 `.as<T>(t)` で確定した要素型を map ノードの outType に載せる(§4.4。
634
- // `into` 指定時は augment 済みリストの要素型 — consumer が確定させた形をそのまま採る)。
635
- // `.as` 未指定時は leaf の base 要素型(catalog elemType)にフォールバック(SA5 の base 型確定)。
636
- // map ノードの outType は**要素型**(配列ラップ前)で持つ既存規約に従う(native emitter は
637
- // 配列型をここから合成する)。`into` 指定時は要素型注記が必須(base では augment 後の型を導けない)。
638
- const mapElem = pm.outType !== undefined ? pm.outType : opts?.into !== undefined ? undefined : pm.baseElemType;
639
- if (mapElem !== undefined)
640
- node.outType = mapElem;
641
- node.map.portSchemas = derivePortSchemas(pm.entry, pm.ports); // #173
642
- if (pm.entry.leafSymbol !== undefined)
643
- node.map.leafSymbol = pm.entry.leafSymbol; // #176
644
- f.nodes.push(node);
645
- return nodeHandle(id);
646
- }
647
- // ── structured control: Fanout(`refsConnection` を FanoutNode へ lower — v3)─────────
648
- /**
649
- * recordFanout — `list.refsConnection(el => C.Get({...}), { dedupeKey, drop, implicitSource })` の
650
- * record 形。graphddb の `@refs` id-list 読みが宣言する first-class fanout ノード(behaviorVersion 3)。
651
- * `.map` と同じ single-component callback capture を使うが、lower 先は {@link FanoutNode}:
652
- * dedup 済み 1 回の batched dispatch → dedupe(first-seen by dedupeKey)/drop(dangling)/strip →
653
- * connection `{items,cursor:null}`。map の無条件行整列(batched)では表現できない意味を owns する。
654
- */
655
- function recordFanout(overMeta, cb, opts) {
656
- const f = requireFrame("refsConnection");
657
- if (f.pendingMap)
658
- afail("FANOUT_IN_BRANCH", `method '${f.method}': refsConnection inside a .map callback is not expressible (chain over the connection items instead)`);
659
- if (f.branchStack.length > 0)
660
- afail("FANOUT_IN_BRANCH", `method '${f.method}': refsConnection inside a when(...) branch is not expressible in the IR (guard the 'over' expression instead)`);
661
- if (typeof cb !== "function")
662
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection expects an inline arrow callback`);
663
- if (cb.length > 1)
664
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection callback takes exactly one element binding`);
665
- if (overMeta.refPath !== null && overMeta.refPath.length === 0)
666
- afail("WHOLE_INPUT", `method '${f.method}': the whole '$' input cannot be fanned out; reference an id-list field`);
667
- if (opts === null || typeof opts !== "object")
668
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection requires an options object with a 'dedupeKey'`);
669
- if (typeof opts.dedupeKey !== "string" || opts.dedupeKey === "")
670
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection 'dedupeKey' must be a non-empty string`);
671
- const drop = opts.drop ?? "dangling";
672
- if (drop !== "dangling" && drop !== "none")
673
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection 'drop' must be "dangling" or "none"`);
674
- if (opts.implicitSource !== undefined && (typeof opts.implicitSource !== "string" || opts.implicitSource === ""))
675
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection 'implicitSource' must be a non-empty string when present`);
676
- const as = `$e${f.mapSeq++}`;
677
- const binding = makeExpr({ node: { ref: [as] }, refPath: [as], refOp: "ref", isInput: false });
678
- f.pendingMap = { as, component: null, ports: null, when: undefined, outType: undefined, baseElemType: undefined, entry: null };
679
- let pm;
680
- try {
681
- cb(binding);
682
- }
683
- finally {
684
- pm = f.pendingMap;
685
- f.pendingMap = null;
686
- }
687
- if (pm.component === null)
688
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': a refsConnection callback must invoke exactly one catalog component`);
689
- if (pm.when !== undefined)
690
- afail("FANOUT_NOT_LOWERABLE", `method '${f.method}': refsConnection callback cannot carry a when(...) guard (dedupe/drop is the fanout's own definition)`);
691
- const over = overMeta.node;
692
- const deps = collectNodeIdRefs(over, f.nodeIds);
693
- collectNodeIdRefs(pm.ports, f.nodeIds, deps);
694
- const id = nextId(f);
695
- const node = {
696
- id,
697
- fanout: {
698
- over,
699
- as,
700
- component: pm.component,
701
- ports: pm.ports,
702
- dedupeKey: opts.dedupeKey,
703
- drop,
704
- relationKind: "connection",
705
- },
706
- };
707
- if (opts.implicitSource !== undefined)
708
- node.fanout.implicitSource = opts.implicitSource;
709
- if (deps.length > 0)
710
- node.fanout.parent = deps[0];
711
- // callback 内 `.as<T>(t)` で確定した**要素型**を connection outType へ包む
712
- // (fanout は常に connection: `{obj:{items:{arr:<elem>}, cursor:{opt:"string"}}}` — behavior.ts §5.2)。
713
- // `.as` 未指定時は leaf の base 要素型(catalog elemType)にフォールバック(SA5 の base 型確定)。
714
- // `implicitSource` は結果要素から**除去される**(FANOUT_DEDUP_DROP step 3)ので、宣言する要素型
715
- // からも落とす — 型注記は produced value を述べるものであって、handler の生の返り値ではない。
716
- const fanElem0 = pm.outType !== undefined ? pm.outType : pm.baseElemType;
717
- const fanElem = stripImplicitSource(fanElem0, opts.implicitSource);
718
- if (fanElem !== undefined)
719
- node.outType = { obj: { items: { arr: fanElem }, cursor: { opt: "string" } } };
720
- node.fanout.portSchemas = derivePortSchemas(pm.entry, pm.ports); // #173
721
- if (pm.entry.leafSymbol !== undefined)
722
- node.fanout.leafSymbol = pm.entry.leafSymbol; // #176
723
- f.nodes.push(node);
724
- return nodeHandle(id);
725
- }
726
- /**
727
- * fanout の宣言要素型から `implicitSource` フィールドを落とす。
728
- *
729
- * fanout は結果要素から implicitSource フィールドを**除去**する(FANOUT_DEDUP_DROP step 3)。
730
- * 型注記は produced value を述べるものなので、除去されるフィールドを宣言に残すと「宣言と実物が
731
- * ずれた型」= 偽の注記になり、そのまま codegen へ流れる。obj 以外の要素型(除去対象を持たない)は
732
- * そのまま返す。
733
- */
734
- function stripImplicitSource(elem, implicitSource) {
735
- if (elem === undefined || implicitSource === undefined)
736
- return elem;
737
- if (typeof elem !== "object" || !("obj" in elem))
738
- return elem;
739
- if (!Object.prototype.hasOwnProperty.call(elem.obj, implicitSource))
740
- return elem;
741
- const rest = {};
742
- for (const [k, v] of Object.entries(elem.obj))
743
- if (k !== implicitSource)
744
- rest[k] = v;
745
- return { obj: rest };
746
- }
747
- // ── structured control: Conditional / Guard(`?:` / `&&` を lower)──────────────────
748
- /**
749
- * when — Conditional(`?:`)/ Guard(`&&`)の record 形(semantic-contract-programming.md
750
- * 「構造化制御構文」の Compiler 規則を評価モードで実装する):
751
- *
752
- * - 両分岐(else 省略時は then のみ)が**純式のみ** → Expression IR `{cond:[c,t,e]}` へ
753
- * inline lower(body ノードは増えない。else 省略は `null`)。
754
- * - 分岐に **Component 宣言を含む** → 分岐ごとに gate(CondNode + null-binding skip)を
755
- * 立て、両分岐が値を持つ場合は Φ(CondNode)ノードで合流する(採用側のみ実行される)。
756
- * Guard 形(else 無し)は then の値をそのまま返す — 条件不成立時は当該ノードが Skip され、
757
- * 下流へは未生成 Port の Skip 伝播規則で連鎖する。
758
- * - `.map` コールバック内では **per-element guard**(v2 `map.when`)として record される
759
- * (guard 形のみ。false の要素は handler 未呼び出しで結果から除外)。
760
- *
761
- * 条件は recorder 式でなければならない(ネイティブ `===` / `&&` の結果は record できない —
762
- * eq/and/... builder を使う)。
763
- */
764
- export function when(condition, then, otherwise) {
765
- const f = requireFrame("when");
766
- if (!exprMetaOf(condition))
767
- afail("BAD_CONDITION", `method '${f.method}': when(...) condition must be a recorded expression (native ===/&&/?: over recorded values cannot be observed at build time — use eq/ne/and/... builders)`);
768
- if (typeof then !== "function" || (otherwise !== undefined && typeof otherwise !== "function"))
769
- afail("BAD_BRANCH", `method '${f.method}': when(...) branches must be thunks (() => ...)`);
770
- const c = lowerValue(condition, "when condition");
771
- // map コールバック内: per-element guard(v2 map.when)。
772
- if (f.pendingMap) {
773
- if (otherwise !== undefined)
774
- afail("BAD_BRANCH", `method '${f.method}': when(...) inside a .map callback is guard-form only (no else — v2 'map.when' skips the element)`);
775
- const before = f.pendingMap.component;
776
- const result = then();
777
- if (f.pendingMap.component === before) {
778
- // 純式 guard → inline cond(else は null)。
779
- return opExpr({ cond: [c, lowerValue(result, "when then"), null] });
780
- }
781
- if (f.pendingMap.when !== undefined)
782
- afail("BAD_CONDITION", `method '${f.method}': a .map callback records at most one when(...) guard`);
783
- f.pendingMap.when = c;
784
- return result;
785
- }
786
- // then 分岐。
787
- const thenFrame = { cond: c, gateId: null, startLen: f.nodes.length };
788
- f.branchStack.push(thenFrame);
789
- let thenVal;
790
- try {
791
- thenVal = then();
792
- }
793
- finally {
794
- f.branchStack.pop();
795
- }
796
- const thenHasComponents = f.nodes.length > thenFrame.startLen;
797
- // else 分岐。
798
- let elseVal = null;
799
- let elseHasComponents = false;
800
- if (otherwise !== undefined) {
801
- const elseFrame = { cond: { not: [c] }, gateId: null, startLen: f.nodes.length };
802
- f.branchStack.push(elseFrame);
803
- try {
804
- elseVal = otherwise();
805
- }
806
- finally {
807
- f.branchStack.pop();
808
- }
809
- elseHasComponents = f.nodes.length > elseFrame.startLen;
810
- }
811
- // 純式のみ → Expression IR へ inline lower(Compiler 規則)。
812
- if (!thenHasComponents && !elseHasComponents)
813
- return opExpr({ cond: [c, lowerValue(thenVal, "when then"), lowerValue(elseVal, "when else")] });
814
- // Guard 形(else 無し): then の値をそのまま返す(不成立時は gate skip → 未生成 Port)。
815
- if (otherwise === undefined)
816
- return thenVal;
817
- // Φ 合流ノード: 採用側の値を単一 Port にする(cond は採用側のみ評価する)。
818
- const id = nextId(f);
819
- const phi = {
820
- id,
821
- cond: { if: c, then: lowerValue(thenVal, "when then"), else: lowerValue(elseVal, "when else") },
822
- };
823
- f.nodes.push(phi);
824
- return nodeHandle(id);
825
- }
826
- // ── source scan(NATIVE_CONTROL_SYNTAX — bc#24 audit fix)───────────────────────────
827
- /**
828
- * JS Proxy には ToBoolean / strict-equality のトラップが存在しないため、recorder 値上の
829
- * ネイティブ制御構文は評価モードでは観測できず、黙って誤った DAG に lower され得る
830
- * (`$.flag ? C.Get(..) : C.Put(..)` → 無条件 Get、`$.flag && C.Get(..)` → ガード消失、
831
- * `$.limit ?? "d"` → default 消失、`!$.flag` → リテラル false、`if ($.flag) {..}` →
832
- * then 側のみ、`switch ($.x)` → default 側のみ)。evaluation-mode recording に内在する
833
- * 制約であり Proxy では塞げないため、**compileBehaviors は評価の前にソースを走査**して
834
- * これらのトークンを一律 fail-closed で拒否する。
835
- *
836
- * 前処理(偽陽性の回避): 文字列リテラルの内容・テンプレートリテラルのテキスト部
837
- * (`${...}` 内の式コードは保持)・コメント・正規表現リテラル本体を空白化してから走査する。
838
- * 走査対象はソースの最初の `{` 以降(= 本体)。ランタイムの `Function.prototype.toString`
839
- * は型消去後のソースを返すため、TS の型レベル `?`(optional param / conditional type)は
840
- * 現れない。パラメータ既定値はビルド時に実行されるコードなので走査対象に含まれてよい。
841
- *
842
- * ヘルパの扱い: `_`-prefix ヘルパは prototype から列挙して個別に走査する。`#`-private
843
- * メソッドは prototype に現れないため、**クラスソース全体(親クラス連鎖含む)も走査する**。
844
- * record 中に実行され得るコードはすべて対象であり、未到達のヘルパも fail-closed で
845
- * 拒否される(到達可能性はソースからは判定できない)。
846
- *
847
- * 検出できない残余はヘッダ docstring / semantic-contract-programming.md「残余リスク」を参照
848
- * (クラス外の関数・eval / new Function・`for`/`while` のループ条件)。
849
- */
850
- const NATIVE_CONTROL_TOKEN = /\?\?=|&&=|\|\|=|\?\?|\?\.|&&|\|\||===|!==|==|!=|\bif\s*\(|\bswitch\s*\(|[?!]/;
851
- /** 正規表現リテラルが直前トークンの直後に開始し得るか(`/` を除算と区別する軽量判定)。 */
852
- const REGEX_PRECEDING_KEYWORDS = /* @__PURE__ */ new Set([
853
- "return", "typeof", "instanceof", "in", "of", "case", "do", "else", "void", "delete", "throw", "new", "yield", "await",
854
- ]);
855
- const WORD_CHAR = /[A-Za-z0-9_$#]/;
856
- function regexCanFollow(prev, word) {
857
- if (prev === "")
858
- return true;
859
- if (WORD_CHAR.test(prev))
860
- return REGEX_PRECEDING_KEYWORDS.has(word);
861
- return !")]}\"'`.".includes(prev);
862
- }
863
- /**
864
- * ソースから「コードでないテキスト」を空白化する(インデックス保存 — エラー位置抜粋用):
865
- * 文字列リテラル内容 / テンプレートリテラルのテキスト部(`${...}` 内コードは保持)/
866
- * 行・ブロックコメント / 正規表現リテラル本体。
867
- */
868
- function stripNonCode(src) {
869
- const out = src.split("");
870
- const blank = (idx) => {
871
- if (out[idx] !== "\n")
872
- out[idx] = " ";
873
- };
874
- // モードスタック: code(`${...}` ネスト用に {}-depth を持つ)と template。
875
- const stack = [{ tpl: false, braces: 0 }];
876
- let prev = ""; // 直前の有意(非空白)コード文字
877
- let word = ""; // 直前の識別子/キーワード(regex 開始判定用)
878
- let prevWasWord = false;
879
- let i = 0;
880
- while (i < src.length) {
881
- const top = stack[stack.length - 1];
882
- const ch = src[i];
883
- if (top.tpl) {
884
- if (ch === "\\") {
885
- blank(i);
886
- if (i + 1 < src.length)
887
- blank(i + 1);
888
- i += 2;
889
- continue;
890
- }
891
- if (ch === "`") {
892
- stack.pop();
893
- i++;
894
- prev = "`";
895
- word = "";
896
- prevWasWord = false;
897
- continue;
898
- }
899
- if (ch === "$" && src[i + 1] === "{") {
900
- stack.push({ tpl: false, braces: 0 });
901
- i += 2;
902
- prev = "{";
903
- word = "";
904
- prevWasWord = false;
905
- continue;
906
- }
907
- blank(i);
908
- i++;
909
- continue;
910
- }
911
- const nx = src[i + 1];
912
- if (ch === "/" && nx === "/") {
913
- while (i < src.length && src[i] !== "\n")
914
- blank(i++);
915
- continue;
916
- }
917
- if (ch === "/" && nx === "*") {
918
- blank(i);
919
- blank(i + 1);
920
- i += 2;
921
- while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
922
- blank(i++);
923
- if (i < src.length) {
924
- blank(i);
925
- blank(i + 1);
926
- i += 2;
927
- }
928
- continue;
929
- }
930
- if (ch === '"' || ch === "'") {
931
- i++;
932
- while (i < src.length && src[i] !== ch && src[i] !== "\n") {
933
- if (src[i] === "\\") {
934
- blank(i);
935
- i++;
936
- if (i < src.length) {
937
- blank(i);
938
- i++;
939
- }
940
- continue;
941
- }
942
- blank(i);
943
- i++;
944
- }
945
- if (i < src.length && src[i] === ch)
946
- i++;
947
- prev = ch;
948
- word = "";
949
- prevWasWord = false;
950
- continue;
951
- }
952
- if (ch === "`") {
953
- stack.push({ tpl: true, braces: 0 });
954
- i++;
955
- prev = "`";
956
- word = "";
957
- prevWasWord = false;
958
- continue;
959
- }
960
- if (ch === "/" && regexCanFollow(prev, word)) {
961
- blank(i);
962
- i++;
963
- let inClass = false;
964
- while (i < src.length && (inClass || src[i] !== "/") && src[i] !== "\n") {
965
- if (src[i] === "\\") {
966
- blank(i);
967
- i++;
968
- if (i < src.length) {
969
- blank(i);
970
- i++;
971
- }
972
- continue;
973
- }
974
- if (src[i] === "[")
975
- inClass = true;
976
- else if (src[i] === "]")
977
- inClass = false;
978
- blank(i);
979
- i++;
980
- }
981
- if (i < src.length && src[i] === "/") {
982
- blank(i);
983
- i++;
984
- }
985
- while (i < src.length && /[a-z]/i.test(src[i])) {
986
- blank(i);
987
- i++;
988
- }
989
- prev = "/";
990
- word = "";
991
- prevWasWord = false;
992
- continue;
993
- }
994
- if (ch === "{")
995
- top.braces++;
996
- else if (ch === "}") {
997
- if (top.braces === 0 && stack.length > 1) {
998
- stack.pop();
999
- i++;
1000
- prev = "}";
1001
- word = "";
1002
- prevWasWord = false;
1003
- continue;
1004
- }
1005
- top.braces--;
1006
- }
1007
- if (WORD_CHAR.test(ch)) {
1008
- word = prevWasWord ? word + ch : ch;
1009
- prevWasWord = true;
1010
- }
1011
- else {
1012
- prevWasWord = false;
1013
- if (!/\s/.test(ch))
1014
- word = "";
1015
- }
1016
- if (!/\s/.test(ch))
1017
- prev = ch;
1018
- i++;
1019
- }
1020
- return out.join("");
1021
- }
1022
- /** 検出トークン → 表示名と record-form の置き換え案内。 */
1023
- function nativeControlHint(token) {
1024
- if (token.startsWith("if"))
1025
- return { name: "if (...)", hint: "use when(cond, () => then, () => else)" };
1026
- if (token.startsWith("switch"))
1027
- return { name: "switch (...)", hint: "use when(...) chains with eq(...) conditions" };
1028
- switch (token) {
1029
- case "??=":
1030
- case "&&=":
1031
- case "||=":
1032
- return { name: token, hint: "authoring is declarative; bind a fresh const via coalesce/and/or builders" };
1033
- case "??":
1034
- return { name: "??", hint: "use coalesce(a, b)" };
1035
- case "?.":
1036
- return { name: "?.", hint: "use opt(x).field (refOpt)" };
1037
- case "&&":
1038
- return { name: "&&", hint: "use when(cond, () => x) for a guard, or and(a, b) for a boolean" };
1039
- case "||":
1040
- return { name: "||", hint: "use or(a, b) for a boolean, or coalesce(a, b) for a default" };
1041
- case "===":
1042
- case "==":
1043
- return { name: token, hint: "use eq(a, b)" };
1044
- case "!==":
1045
- case "!=":
1046
- return { name: token, hint: "use ne(a, b)" };
1047
- case "?":
1048
- return { name: "?:", hint: "use when(cond, () => then, () => else)" };
1049
- default:
1050
- return { name: "!", hint: "use not(x) or ne(a, b)" };
1051
- }
1052
- }
1053
- /** method / helper / class ソースを走査し、ネイティブ制御構文を fail-closed で拒否する。 */
1054
- function scanNativeControlSyntax(source, label) {
1055
- const stripped = stripNonCode(source);
1056
- const bodyStart = stripped.indexOf("{"); // 本体(最初の `{` 以降)のみ走査する
1057
- if (bodyStart < 0)
1058
- return;
1059
- const m = NATIVE_CONTROL_TOKEN.exec(stripped.slice(bodyStart + 1));
1060
- if (!m)
1061
- return;
1062
- const at = bodyStart + 1 + m.index;
1063
- const excerpt = source
1064
- .slice(Math.max(0, at - 30), Math.min(source.length, at + 30))
1065
- .replace(/\s+/g, " ")
1066
- .trim();
1067
- const { name, hint } = nativeControlHint(m[0]);
1068
- afail("NATIVE_CONTROL_SYNTAX", `${label}: native control syntax '${name}' cannot be observed over recorded values at build time (JS Proxy has no ToBoolean/equality trap) and would silently mislower the DAG — ${hint} (near \`${excerpt}\`)`);
1069
- }
1070
- /**
1071
- * compileBehaviors — `SemanticBehavior` 継承(または `@behavior` 付き)クラスを
1072
- * component-graph IR(scp-ir-architecture.md §5)へ lower する共有 Compiler。
1073
- *
1074
- * - **各 public メソッド = 1 root Behavior**(`components[]` の 1 エントリ。名前 = メソッド名)。
1075
- * `#`-private はランタイム不可視でそもそも列挙されない。TS の `private` 修飾子は型消去で
1076
- * ランタイムに残らないため、**評価ベースのヘルパ規約は `#` または `_`-prefix**(`_` 始まりは
1077
- * publish されない)。ヘルパはメソッド本体からの呼び出しで record にインライン展開される。
1078
- * - 評価の**前に**メソッド / ヘルパ / クラスソースを {@link scanNativeControlSyntax} で走査し、
1079
- * 評価では観測できないネイティブ制御構文(`?:` / `&&` / `||` / `??` / `?.` / `!` /
1080
- * `==`/`===`/`!=`/`!==` / `if` / `switch` / 複合論理代入)を `NATIVE_CONTROL_SYNTAX` で
1081
- * fail-closed に拒否する(bc#24 audit fix — 残余はヘッダ docstring 参照)。
1082
- * - メソッド本体は throwing-sentinel recorder で 1 回評価され、`$` 参照・component 呼び出し・
1083
- * structured control({@link when} / `.map`)が body ノード・Wire・plan に lower される。
1084
- * - 生成 IR は `assertPortableComponentGraph` を必ず通してから返す(fail-closed の自己検査)。
1085
- * 実行は既存の `runBehavior` がそのまま担う。
1086
- *
1087
- * effect(Query/Command)はここでは一切扱わない — {@link classifyBehaviorEffect} を参照。
1088
- */
1089
- export function compileBehaviors(cls, opts = {}) {
1090
- if (!isBehaviorClass(cls))
1091
- afail("NOT_A_BEHAVIOR_CLASS", `class '${cls?.name ?? String(cls)}' is not a behavior class (extend SemanticBehavior or mark it with @behavior)`);
1092
- const proto = cls.prototype;
1093
- const methodNames = Object.getOwnPropertyNames(proto).filter((name) => {
1094
- if (name === "constructor" || name.startsWith("_") || name.startsWith("#"))
1095
- return false;
1096
- const d = Object.getOwnPropertyDescriptor(proto, name);
1097
- return typeof d?.value === "function";
1098
- });
1099
- if (methodNames.length === 0)
1100
- afail("NO_PUBLIC_METHOD", `class '${cls.name}' declares no public method (each public method is one root Behavior)`);
1101
- // ── source scan(評価の前に fail loud — NATIVE_CONTROL_SYNTAX)─────────────────
1102
- // public メソッドと `_`-prefix ヘルパは個別に(正確なラベルで)、`#`-private ヘルパは
1103
- // prototype から列挙できないためクラスソース全体(親クラス連鎖含む)で走査する。
1104
- for (const method of methodNames)
1105
- scanNativeControlSyntax(proto[method].toString(), `method '${method}'`);
1106
- for (const name of Object.getOwnPropertyNames(proto)) {
1107
- if (name === "constructor" || methodNames.includes(name))
1108
- continue;
1109
- const d = Object.getOwnPropertyDescriptor(proto, name);
1110
- if (typeof d?.value === "function")
1111
- scanNativeControlSyntax(d.value.toString(), `helper '${name}'`);
1112
- }
1113
- for (let k = cls; typeof k === "function" && k !== SemanticBehavior && k !== Function.prototype; k = Object.getPrototypeOf(k)) {
1114
- const src = Function.prototype.toString.call(k);
1115
- if (!/\{\s*\[native code\]\s*\}/.test(src))
1116
- scanNativeControlSyntax(src, `class '${k.name || "<anonymous>"}'`);
1117
- }
1118
- const instance = new cls();
1119
- const components = [];
1120
- // SA8: 1 クラス = 1 レジストリ(全メソッドの leaf 呼びで共有)。record 時に behaviorComponents 由来の
1121
- // impl が name→fn で溜まり、compile 末尾で IR handle の side-channel へ退避する(IR 本体には載らない)。
1122
- // null-proto: leaf 名が 'toString'/'constructor' 等でも prototype 継承キーと混ざらない(bind ゲートの
1123
- // 完全性検査・dispatch lookup の健全性)。
1124
- const registry = Object.create(null);
1125
- for (const method of methodNames) {
1126
- const frame = {
1127
- method,
1128
- nodes: [],
1129
- nodeIds: new Set(),
1130
- inputPorts: new Map(),
1131
- optionalInputs: new Set(),
1132
- seq: 0,
1133
- mapSeq: 0,
1134
- branchStack: [],
1135
- pendingMap: null,
1136
- registry,
1137
- };
1138
- const dollar = makeExpr({ node: { ref: [] }, refPath: [], refOp: "ref", isInput: true });
1139
- currentFrame = frame;
1140
- let returned;
1141
- try {
1142
- returned = proto[method].call(instance, dollar);
1143
- }
1144
- finally {
1145
- currentFrame = null;
1146
- }
1147
- if (returned === undefined)
1148
- afail("BAD_OUTPUT", `method '${method}' must return its Output Port (got undefined)`);
1149
- if (returned instanceof Promise)
1150
- afail("BAD_OUTPUT", `method '${method}' must be synchronous and declarative (async/await is derived by the compiler, not written)`);
1151
- const output = lowerValue(returned, `method '${method}' output`);
1152
- // 上書き schema は **型**の供給点(`In<...>` は TS 型消去でランタイムに残らない)。optionality は
1153
- // `opt($.x)` が本体ソースに書いた**宣言**なので、上書きは型を足すだけで、それを黙って取り消さない:
1154
- // - 上書きが `required:true` を **明示** して `opt($.x)` と矛盾 → LOUD reject(2 枚の carrier が
1155
- // 食い違ったまま通ると、宣言だけを読む下流 [runBehavior の束縛 / native lowering] が
1156
- // optionality を見失う — それが silent な誤束縛の入口)。
1157
- // - 上書きが `required` を **述べていない**(型だけ)→ 型は上書き・`required:false` は保存。
1158
- // 逆向き(上書きが `required:false`・本体は素の `$.x`)は矛盾ではない: optional Port を素の ref で
1159
- // 読むのは正当(値が null で流れるだけ)。optionality の SSoT はあくまで宣言であって `refOpt` の
1160
- // 有無ではない。
1161
- const inputPorts = {};
1162
- for (const [k, s] of frame.inputPorts) {
1163
- const ov = opts.inputPorts?.[method]?.[k];
1164
- if (ov === undefined) {
1165
- inputPorts[k] = s;
1166
- continue;
1167
- }
1168
- if (frame.optionalInputs.has(k) && ov.required === true)
1169
- afail("PORT_OPTIONALITY_CONFLICT", `method '${method}' port '${k}': the body declares it OPTIONAL via opt($.${k}), but opts.inputPorts declares required:true — the two disagree. An optional port's declaration is what runBehavior's binding and the native lowering read, so this contradiction would silently drop the optionality. Supply required:false (or omit required and let opt($.${k}) stand).`);
1170
- inputPorts[k] = frame.optionalInputs.has(k) ? { ...ov, required: false } : ov;
1171
- }
1172
- // 上書き schema にしか現れない Port も契約として載せる(型抽出ツールの接続点)。
1173
- for (const [k, s] of Object.entries(opts.inputPorts?.[method] ?? {}))
1174
- if (!(k in inputPorts))
1175
- inputPorts[k] = s;
1176
- // lowering の末尾は builder.ts の共有 core(B-3): Component 組み立て・plan 導出
1177
- //(Kahn levels)・決定的正規化(キーソート)・Guard 自己検査は recorder 経路と
1178
- // データ登録経路(buildComponentDefinition)の単一実装。catalog port 照合は
1179
- // record 時(recordComponentCall)に同じ共有関数で済ませているため catalog は渡さない。
1180
- const component = buildComponentCore({ name: method, inputPorts, body: frame.nodes, output }, { concurrency: opts.concurrency ?? DEFAULT_PLAN_CONCURRENCY });
1181
- // SA5 全ノード型確定ゲート(#125): 全 body ノードの outType と output(Φ 合成)の全フィールド型が
1182
- // 一意に確定していることを網羅検査し(未確定は UNTYPED_NODE で fail-closed)、確定済みノード型から
1183
- // outputType を構造伝播で導出する(推論ではない)。導出型を canonical 化して component に載せることで、
1184
- // compile 産 IR が「全ノード + component が型付き」= native codegen が端まで型付きフラット化できる状態
1185
- // (consumer-interface.md §2.3 / bc#77 isFullyTyped)になる。
1186
- component.outputType = canonicalizeType(assertAllNodeTypesDetermined(component));
1187
- components.push(component);
1188
- }
1189
- const ir = { irVersion: 2, exprVersion: opts.exprVersion ?? SPEC_VERSIONS.expression, components };
1190
- assertPortableComponentGraph(ir); // fail-closed 自己検査(P0-2 Guard を必ず通す)
1191
- // SA1/SA2: compile seam だけが token を刻んで opaque handle に封じる(consumer は forge 不能)。
1192
- // 実行時 token(provenance.ts)+ 型 brand(index.ts)の二重の門で手組み IR を排除する。
1193
- // SA8: 捕捉した name→leaf impl レジストリを handle の side-channel に退避する(IR 本体・fingerprint・
1194
- // JSON には載らない = C4)。bindBehaviors が完全性ゲート後にここから自動 dispatch する。
1195
- return mintCompiled(ir, registry);
1196
- }
1197
- // ── effect 導出(consumer の CQRS 層のための共有ヘルパ — authoring は effect 非依存)────
1198
- /**
1199
- * referencedComponents — lowering 済み合成コンポーネントの body が参照する catalog 名
1200
- * (componentRef / map。重複除去・出現順)。
1201
- */
1202
- export function referencedComponents(component) {
1203
- const out = [];
1204
- for (const n of component.body) {
1205
- const name = "fanout" in n ? n.fanout.component : "map" in n ? n.map.component : "cond" in n ? null : n.component;
1206
- if (name !== null && !out.includes(name))
1207
- out.push(name);
1208
- }
1209
- return out;
1210
- }
1211
- /**
1212
- * classifyBehaviorEffect — CQRS の Query/Command 分類を **component graph から導出**する
1213
- * consumer 向けヘルパ。authoring は effect 非依存(Query/Command の語彙を持たない)であり、
1214
- * 分類は「body が consumer の write-catalog(`PutItem`/`Insert`/… — consumer が指定)を
1215
- * 参照するか」という graph の性質にすぎない、という責務分離(bc#24 / litedbmodel v2 §2.4)の
1216
- * 実装点。
1217
- */
1218
- export function classifyBehaviorEffect(component, writeComponents) {
1219
- const writes = new Set(writeComponents);
1220
- return referencedComponents(component).some((c) => writes.has(c)) ? "writing" : "read-only";
1221
117
  }
1222
118
  //# sourceMappingURL=authoring.js.map