@kubohiroya/turbowarp-http-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.ja.md +32 -14
  2. package/README.md +104 -43
  3. package/assets/block-icon.svg +1 -0
  4. package/dist/cli.js +131 -17
  5. package/dist/cli.js.map +1 -1
  6. package/dist/compiler/adapters/cloudflare.d.ts +2 -0
  7. package/dist/compiler/adapters/cloudflare.js +477 -0
  8. package/dist/compiler/adapters/cloudflare.js.map +1 -0
  9. package/dist/compiler/adapters/firebase.d.ts +2 -0
  10. package/dist/compiler/adapters/firebase.js +489 -0
  11. package/dist/compiler/adapters/firebase.js.map +1 -0
  12. package/dist/compiler/adapters/index.d.ts +2 -0
  13. package/dist/compiler/adapters/index.js +3 -0
  14. package/dist/compiler/adapters/index.js.map +1 -0
  15. package/dist/compiler/binary/codec.d.ts +4 -0
  16. package/dist/compiler/binary/codec.js +45 -0
  17. package/dist/compiler/binary/codec.js.map +1 -0
  18. package/dist/compiler/binary/error.d.ts +3 -0
  19. package/dist/compiler/binary/error.js +21 -0
  20. package/dist/compiler/binary/error.js.map +1 -0
  21. package/dist/compiler/binary/index.d.ts +4 -0
  22. package/dist/compiler/binary/index.js +5 -0
  23. package/dist/compiler/binary/index.js.map +1 -0
  24. package/dist/compiler/binary/runtime.d.ts +18 -0
  25. package/dist/compiler/binary/runtime.js +123 -0
  26. package/dist/compiler/binary/runtime.js.map +1 -0
  27. package/dist/compiler/binary/types.d.ts +17 -0
  28. package/dist/compiler/binary/types.js +2 -0
  29. package/dist/compiler/binary/types.js.map +1 -0
  30. package/dist/compiler/feature-flags.d.ts +4 -0
  31. package/dist/compiler/feature-flags.js +4 -0
  32. package/dist/compiler/feature-flags.js.map +1 -0
  33. package/dist/compiler/index.d.ts +35 -0
  34. package/dist/compiler/index.js +84 -0
  35. package/dist/compiler/index.js.map +1 -0
  36. package/dist/compiler/ir-v2/canonical.d.ts +3 -0
  37. package/dist/compiler/ir-v2/canonical.js +50 -0
  38. package/dist/compiler/ir-v2/canonical.js.map +1 -0
  39. package/dist/compiler/ir-v2/index.d.ts +4 -0
  40. package/dist/compiler/ir-v2/index.js +5 -0
  41. package/dist/compiler/ir-v2/index.js.map +1 -0
  42. package/dist/compiler/ir-v2/parse.d.ts +10 -0
  43. package/dist/compiler/ir-v2/parse.js +753 -0
  44. package/dist/compiler/ir-v2/parse.js.map +1 -0
  45. package/dist/compiler/ir-v2/strict-json.d.ts +4 -0
  46. package/dist/compiler/ir-v2/strict-json.js +133 -0
  47. package/dist/compiler/ir-v2/strict-json.js.map +1 -0
  48. package/dist/compiler/ir-v2/types.d.ts +412 -0
  49. package/dist/compiler/ir-v2/types.js +84 -0
  50. package/dist/compiler/ir-v2/types.js.map +1 -0
  51. package/dist/compiler/kvs/lowering.d.ts +13 -0
  52. package/dist/compiler/kvs/lowering.js +77 -0
  53. package/dist/compiler/kvs/lowering.js.map +1 -0
  54. package/dist/compiler/manifest/error.d.ts +7 -0
  55. package/dist/compiler/manifest/error.js +9 -0
  56. package/dist/compiler/manifest/error.js.map +1 -0
  57. package/dist/compiler/manifest/index.d.ts +6 -0
  58. package/dist/compiler/manifest/index.js +7 -0
  59. package/dist/compiler/manifest/index.js.map +1 -0
  60. package/dist/compiler/manifest/operations.d.ts +12 -0
  61. package/dist/compiler/manifest/operations.js +60 -0
  62. package/dist/compiler/manifest/operations.js.map +1 -0
  63. package/dist/compiler/manifest/parse.d.ts +9 -0
  64. package/dist/compiler/manifest/parse.js +280 -0
  65. package/dist/compiler/manifest/parse.js.map +1 -0
  66. package/dist/compiler/manifest/registry.d.ts +3 -0
  67. package/dist/compiler/manifest/registry.js +48 -0
  68. package/dist/compiler/manifest/registry.js.map +1 -0
  69. package/dist/compiler/manifest/resolve.d.ts +14 -0
  70. package/dist/compiler/manifest/resolve.js +116 -0
  71. package/dist/compiler/manifest/resolve.js.map +1 -0
  72. package/dist/compiler/manifest/types.d.ts +95 -0
  73. package/dist/compiler/manifest/types.js +3 -0
  74. package/dist/compiler/manifest/types.js.map +1 -0
  75. package/dist/compiler/named-body/index.d.ts +1 -0
  76. package/dist/compiler/named-body/index.js +2 -0
  77. package/dist/compiler/named-body/index.js.map +1 -0
  78. package/dist/compiler/named-body/lowering.d.ts +18 -0
  79. package/dist/compiler/named-body/lowering.js +83 -0
  80. package/dist/compiler/named-body/lowering.js.map +1 -0
  81. package/dist/compiler/pipeline/compiler.d.ts +18 -0
  82. package/dist/compiler/pipeline/compiler.js +105 -0
  83. package/dist/compiler/pipeline/compiler.js.map +1 -0
  84. package/dist/compiler/pipeline/core-generator.d.ts +3 -0
  85. package/dist/compiler/pipeline/core-generator.js +483 -0
  86. package/dist/compiler/pipeline/core-generator.js.map +1 -0
  87. package/dist/compiler/pipeline/index.d.ts +5 -0
  88. package/dist/compiler/pipeline/index.js +6 -0
  89. package/dist/compiler/pipeline/index.js.map +1 -0
  90. package/dist/compiler/pipeline/registry.d.ts +7 -0
  91. package/dist/compiler/pipeline/registry.js +17 -0
  92. package/dist/compiler/pipeline/registry.js.map +1 -0
  93. package/dist/compiler/pipeline/requirements.d.ts +9 -0
  94. package/dist/compiler/pipeline/requirements.js +135 -0
  95. package/dist/compiler/pipeline/requirements.js.map +1 -0
  96. package/dist/compiler/pipeline/types.d.ts +65 -0
  97. package/dist/compiler/pipeline/types.js +2 -0
  98. package/dist/compiler/pipeline/types.js.map +1 -0
  99. package/dist/compiler/runtime/error.d.ts +6 -0
  100. package/dist/compiler/runtime/error.js +9 -0
  101. package/dist/compiler/runtime/error.js.map +1 -0
  102. package/dist/compiler/runtime/index.d.ts +1 -0
  103. package/dist/compiler/runtime/index.js +2 -0
  104. package/dist/compiler/runtime/index.js.map +1 -0
  105. package/dist/compiler/structured-data/index.d.ts +3 -0
  106. package/dist/compiler/structured-data/index.js +4 -0
  107. package/dist/compiler/structured-data/index.js.map +1 -0
  108. package/dist/compiler/structured-data/lowering.d.ts +30 -0
  109. package/dist/compiler/structured-data/lowering.js +202 -0
  110. package/dist/compiler/structured-data/lowering.js.map +1 -0
  111. package/dist/compiler/structured-data/path.d.ts +2 -0
  112. package/dist/compiler/structured-data/path.js +60 -0
  113. package/dist/compiler/structured-data/path.js.map +1 -0
  114. package/dist/compiler/structured-data/runtime.d.ts +20 -0
  115. package/dist/compiler/structured-data/runtime.js +210 -0
  116. package/dist/compiler/structured-data/runtime.js.map +1 -0
  117. package/dist/compiler/turbowarp-v2.d.ts +8 -0
  118. package/dist/compiler/turbowarp-v2.js +479 -0
  119. package/dist/compiler/turbowarp-v2.js.map +1 -0
  120. package/dist/compiler/validator/index.d.ts +4 -0
  121. package/dist/compiler/validator/index.js +5 -0
  122. package/dist/compiler/validator/index.js.map +1 -0
  123. package/dist/compiler/validator/ir-validator.d.ts +10 -0
  124. package/dist/compiler/validator/ir-validator.js +463 -0
  125. package/dist/compiler/validator/ir-validator.js.map +1 -0
  126. package/dist/compiler/validator/resource-lifetime.d.ts +18 -0
  127. package/dist/compiler/validator/resource-lifetime.js +106 -0
  128. package/dist/compiler/validator/resource-lifetime.js.map +1 -0
  129. package/dist/compiler/validator/turbowarp-subset.d.ts +3 -0
  130. package/dist/compiler/validator/turbowarp-subset.js +241 -0
  131. package/dist/compiler/validator/turbowarp-subset.js.map +1 -0
  132. package/dist/compiler/validator/types.d.ts +30 -0
  133. package/dist/compiler/validator/types.js +7 -0
  134. package/dist/compiler/validator/types.js.map +1 -0
  135. package/dist/config.d.ts +11 -0
  136. package/dist/config.js +12 -0
  137. package/dist/config.js.map +1 -0
  138. package/dist/digest-cli.js +0 -0
  139. package/dist/extension-manifest.json +102 -0
  140. package/dist/named-body.d.ts +57 -0
  141. package/dist/named-body.js +396 -0
  142. package/dist/named-body.js.map +1 -0
  143. package/dist/named-data-namespace.d.ts +3 -0
  144. package/dist/named-data-namespace.js +6 -0
  145. package/dist/named-data-namespace.js.map +1 -0
  146. package/dist/protocol.d.ts +13 -1
  147. package/dist/protocol.js +34 -0
  148. package/dist/protocol.js.map +1 -1
  149. package/dist/resource-named-body-provider.d.ts +8 -0
  150. package/dist/resource-named-body-provider.js +88 -0
  151. package/dist/resource-named-body-provider.js.map +1 -0
  152. package/dist/server.d.ts +10 -1
  153. package/dist/server.js +37 -7
  154. package/dist/server.js.map +1 -1
  155. package/dist/turbowarp-http-server.js +1614 -1099
  156. package/docs/binary-resource-semantics.ja.md +84 -0
  157. package/docs/cloudflare-worker-compiler.ja.md +90 -0
  158. package/docs/compiler-manifest-registry.ja.md +79 -0
  159. package/docs/compiler-platform-pipeline.ja.md +94 -0
  160. package/docs/deploy-ir-v2.ja.md +123 -0
  161. package/docs/fixed-input-editors.ja.md +23 -0
  162. package/docs/index.html +86 -0
  163. package/docs/ir-v2-conformance.ja.md +65 -0
  164. package/docs/named-response-body.ja.md +120 -0
  165. package/docs/platform-storage-adapters.ja.md +99 -0
  166. package/docs/server-executable-subset.ja.md +88 -0
  167. package/docs/structured-data-lowering.ja.md +63 -0
  168. package/docs/turbowarp-http-server.architecture.html +4 -0
  169. package/examples/compiler/message-app.v2.ir.json +41 -0
  170. package/package.json +45 -20
  171. package/schemas/block-editor-fixed-inputs.schema.json +85 -0
  172. package/schemas/compiler-extension-manifest.schema.json +126 -0
  173. package/schemas/compiler-manifest-lock-v1.schema.json +48 -0
  174. package/schemas/deploy-ir-v2.schema.json +835 -0
  175. package/schemas/ir-v2-conformance-fixture.schema.json +44 -0
  176. package/src/block-definitions.json +76 -0
  177. package/src/cli.ts +136 -23
  178. package/src/compiler/adapters/cloudflare.ts +510 -0
  179. package/src/compiler/adapters/firebase.ts +538 -0
  180. package/src/compiler/adapters/index.ts +2 -0
  181. package/src/compiler/binary/codec.ts +61 -0
  182. package/src/compiler/binary/error.ts +25 -0
  183. package/src/compiler/binary/index.ts +4 -0
  184. package/src/compiler/binary/runtime.ts +133 -0
  185. package/src/compiler/binary/types.ts +26 -0
  186. package/src/compiler/feature-flags.ts +7 -0
  187. package/src/compiler/index.ts +114 -0
  188. package/src/compiler/ir-v2/canonical.ts +46 -0
  189. package/src/compiler/ir-v2/index.ts +9 -0
  190. package/src/compiler/ir-v2/parse.ts +921 -0
  191. package/src/compiler/ir-v2/strict-json.ts +129 -0
  192. package/src/compiler/ir-v2/types.ts +462 -0
  193. package/src/compiler/kvs/lowering.ts +88 -0
  194. package/src/compiler/manifest/error.ts +29 -0
  195. package/src/compiler/manifest/index.ts +17 -0
  196. package/src/compiler/manifest/operations.ts +175 -0
  197. package/src/compiler/manifest/parse.ts +390 -0
  198. package/src/compiler/manifest/registry.ts +74 -0
  199. package/src/compiler/manifest/resolve.ts +159 -0
  200. package/src/compiler/manifest/types.ts +112 -0
  201. package/src/compiler/named-body/index.ts +1 -0
  202. package/src/compiler/named-body/lowering.ts +186 -0
  203. package/src/compiler/pipeline/compiler.ts +138 -0
  204. package/src/compiler/pipeline/core-generator.ts +486 -0
  205. package/src/compiler/pipeline/index.ts +5 -0
  206. package/src/compiler/pipeline/registry.ts +18 -0
  207. package/src/compiler/pipeline/requirements.ts +139 -0
  208. package/src/compiler/pipeline/types.ts +59 -0
  209. package/src/compiler/runtime/error.ts +11 -0
  210. package/src/compiler/runtime/index.ts +1 -0
  211. package/src/compiler/structured-data/index.ts +3 -0
  212. package/src/compiler/structured-data/lowering.ts +314 -0
  213. package/src/compiler/structured-data/path.ts +53 -0
  214. package/src/compiler/structured-data/runtime.ts +221 -0
  215. package/src/compiler/turbowarp-v2.ts +610 -0
  216. package/src/compiler/validator/index.ts +4 -0
  217. package/src/compiler/validator/ir-validator.ts +812 -0
  218. package/src/compiler/validator/resource-lifetime.ts +153 -0
  219. package/src/compiler/validator/turbowarp-subset.ts +387 -0
  220. package/src/compiler/validator/types.ts +68 -0
  221. package/src/config.ts +1 -1
  222. package/src/extension.ts +87 -1
  223. package/src/fixed-input-editors.ts +181 -0
  224. package/src/fixed-input-schema.ts +15 -0
  225. package/src/named-body.ts +495 -0
  226. package/src/named-data-namespace.ts +6 -0
  227. package/src/protocol.ts +50 -1
  228. package/src/resource-named-body-provider.ts +106 -0
  229. package/src/server.ts +88 -8
  230. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
  231. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
  232. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
  233. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
  234. package/docs/turbowarp-http-server.architecture.visual-check.html +0 -32
  235. package/docs/turbowarp-http-server.architecture.visual-check.json +0 -547
  236. package/schemas/extension-manifest.schema.json +0 -49
  237. package/src/extension-manifest.ts +0 -149
@@ -0,0 +1,812 @@
1
+ import type {
2
+ BindingDeclarationV2,
3
+ BindingTypeV2,
4
+ CapabilityRequirementV2,
5
+ DeployIrV2,
6
+ ExpressionIrV2,
7
+ RouteIrV2,
8
+ SourceRefV2,
9
+ StatementIrV2,
10
+ ValueTypeV2
11
+ } from '../ir-v2/types.js';
12
+ import {
13
+ DEFAULT_COMPILER_FEATURE_FLAGS,
14
+ type CompilerFeatureFlags
15
+ } from '../feature-flags.js';
16
+ import {
17
+ DEFAULT_SERVER_SUBSET_POLICY,
18
+ type ServerSubsetDiagnosticCode,
19
+ type ServerSubsetPolicy,
20
+ type TargetCapabilityDiagnostic,
21
+ type TargetNeutralDiagnostic
22
+ } from './types.js';
23
+ import {BinaryBodyLifetimeTracker} from './resource-lifetime.js';
24
+
25
+ type BindingEnvironment = Map<string, BindingTypeV2>;
26
+
27
+ interface ValidationContext {
28
+ route: RouteIrV2;
29
+ diagnostics: TargetNeutralDiagnostic[];
30
+ capabilities: ReadonlySet<string>;
31
+ policy: Readonly<ServerSubsetPolicy>;
32
+ loopDepth: number;
33
+ iterationLoopIds: ReadonlySet<string>;
34
+ binaryBodies: BinaryBodyLifetimeTracker;
35
+ featureFlags: Readonly<CompilerFeatureFlags>;
36
+ }
37
+
38
+ interface FlowResult {
39
+ mayContinue: boolean;
40
+ mayTerminate: boolean;
41
+ bindings: BindingEnvironment;
42
+ }
43
+
44
+ export function validateDeployIrV2Subset(
45
+ ir: DeployIrV2,
46
+ policy: Readonly<ServerSubsetPolicy> = DEFAULT_SERVER_SUBSET_POLICY,
47
+ featureFlags: Readonly<CompilerFeatureFlags> = DEFAULT_COMPILER_FEATURE_FLAGS
48
+ ): TargetNeutralDiagnostic[] {
49
+ const diagnostics: TargetNeutralDiagnostic[] = [];
50
+ const capabilities = new Set(ir.capabilities.map(capabilityKey));
51
+ if (ir.auth.kind === 'jwt' && ir.routes[0] !== undefined) {
52
+ const context: ValidationContext = {
53
+ route: ir.routes[0],
54
+ diagnostics,
55
+ capabilities,
56
+ policy,
57
+ loopDepth: 0,
58
+ iterationLoopIds: new Set(),
59
+ binaryBodies: new BinaryBodyLifetimeTracker(ir.routes[0].id, diagnostics),
60
+ featureFlags
61
+ };
62
+ requireCapability({kind: 'auth', scheme: ir.auth.scheme}, context, ir.routes[0].sourceRef);
63
+ }
64
+ for (const route of ir.routes) {
65
+ const context: ValidationContext = {
66
+ route,
67
+ diagnostics,
68
+ capabilities,
69
+ policy,
70
+ loopDepth: 0,
71
+ iterationLoopIds: new Set(),
72
+ binaryBodies: new BinaryBodyLifetimeTracker(route.id, diagnostics),
73
+ featureFlags
74
+ };
75
+ const flow = analyzeSequence(route.body, new Map(), context);
76
+ if (flow.mayContinue || !flow.mayTerminate) {
77
+ report(
78
+ context,
79
+ 'TW2_MISSING_RESPONSE',
80
+ 'Every normal control-flow path must end in one terminal response.',
81
+ 'At least one route path reaches the end of the handler without responding.',
82
+ 'Add a terminal response to every branch at the top level.',
83
+ route.sourceRef
84
+ );
85
+ }
86
+ const work = sequenceWork(route.body, policy.maxRouteWork);
87
+ if (work > policy.maxRouteWork) {
88
+ report(
89
+ context,
90
+ 'TW2_WORK_BUDGET_EXCEEDED',
91
+ `Route worst-case work ${work} exceeds the ${policy.maxRouteWork} step limit.`,
92
+ 'Bounded loops and nested expressions expand beyond the target-neutral work budget.',
93
+ 'Reduce loop bounds, nesting, or handler operations.',
94
+ route.sourceRef ?? route.body[0]?.sourceRef
95
+ );
96
+ }
97
+ }
98
+ return diagnostics;
99
+ }
100
+
101
+ export function targetCapabilityDiagnostic(input: {
102
+ targetId: string;
103
+ routeId: string;
104
+ capability: string;
105
+ sourceRef?: SourceRefV2;
106
+ }): TargetCapabilityDiagnostic {
107
+ const diagnostic: TargetCapabilityDiagnostic = {
108
+ severity: 'error',
109
+ phase: 'target-capability',
110
+ code: 'TW2_TARGET_CAPABILITY_UNSUPPORTED',
111
+ message: `Target ${input.targetId} does not support capability ${input.capability}.`,
112
+ routeId: input.routeId,
113
+ targetId: input.targetId,
114
+ reason: 'The target-neutral IR is valid, but the selected adapter cannot satisfy a declared requirement.',
115
+ suggestion: 'Choose a capable target or remove the operation that requires this capability.'
116
+ };
117
+ if (input.sourceRef !== undefined) diagnostic.sourceRef = input.sourceRef;
118
+ return diagnostic;
119
+ }
120
+
121
+ function analyzeSequence(
122
+ statements: readonly StatementIrV2[],
123
+ initialBindings: BindingEnvironment,
124
+ context: ValidationContext
125
+ ): FlowResult {
126
+ let flow: FlowResult = {mayContinue: true, mayTerminate: false, bindings: initialBindings};
127
+ for (const statement of statements) {
128
+ if (!flow.mayContinue) {
129
+ report(
130
+ context,
131
+ isTerminalResponse(statement)
132
+ ? 'TW2_MULTIPLE_RESPONSE'
133
+ : 'TW2_RESPONSE_AFTER_TERMINAL',
134
+ isTerminalResponse(statement)
135
+ ? 'A control-flow path contains more than one terminal response.'
136
+ : 'A statement appears after a terminal response.',
137
+ 'Terminal response ends the current handler path.',
138
+ 'Remove the unreachable statement or move it before the response.',
139
+ statement.sourceRef
140
+ );
141
+ continue;
142
+ }
143
+ const result = analyzeStatement(statement, flow.bindings, context);
144
+ flow = {
145
+ mayContinue: result.mayContinue,
146
+ mayTerminate: flow.mayTerminate || result.mayTerminate,
147
+ bindings: result.bindings
148
+ };
149
+ }
150
+ return flow;
151
+ }
152
+
153
+ function analyzeStatement(
154
+ statement: StatementIrV2,
155
+ bindings: BindingEnvironment,
156
+ context: ValidationContext
157
+ ): FlowResult {
158
+ if (statement.kind === 'set-header') {
159
+ const type = validateExpression(statement.value, bindings, context);
160
+ requireScratchScalar(type, context, statement.sourceRef, 'Response header values');
161
+ } else if (statement.kind === 'set-handler-variable' || statement.kind === 'change-handler-variable') {
162
+ const nameType = validateExpression(statement.name, bindings, context);
163
+ requireScratchScalar(nameType, context, statement.sourceRef, 'Handler variable names');
164
+ const valueType = validateExpression(statement.value, bindings, context);
165
+ requireScratchScalar(valueType, context, statement.sourceRef, 'Handler variable values');
166
+ } else if (statement.kind === 'delete-handler-variable') {
167
+ requireScratchScalar(
168
+ validateExpression(statement.name, bindings, context),
169
+ context,
170
+ statement.sourceRef,
171
+ 'Handler variable names'
172
+ );
173
+ } else if (statement.kind === 'kvs-set-text' || statement.kind === 'kvs-delete') {
174
+ requireCapability({kind: 'key-value-store'}, context, statement.sourceRef);
175
+ requireScratchScalar(validateExpression(statement.namespace, bindings, context), context, statement.sourceRef, 'KVS namespaces');
176
+ requireScratchScalar(validateExpression(statement.key, bindings, context), context, statement.sourceRef, 'KVS keys');
177
+ if (statement.kind === 'kvs-set-text') {
178
+ requireScratchScalar(validateExpression(statement.value, bindings, context), context, statement.sourceRef, 'KVS text values');
179
+ }
180
+ } else if (statement.kind === 'record-create') {
181
+ requireCapability({kind: 'record-store'}, context, statement.sourceRef);
182
+ validateExpression(statement.data, bindings, context);
183
+ declareBinding(statement.result, {kind: 'value', valueType: 'json-object'}, bindings, context, statement.sourceRef);
184
+ } else if (statement.kind === 'record-list') {
185
+ requireCapability({kind: 'record-store'}, context, statement.sourceRef);
186
+ declareBinding(statement.result, {kind: 'value', valueType: 'json-array'}, bindings, context, statement.sourceRef);
187
+ } else if (statement.kind === 'record-get') {
188
+ requireCapability({kind: 'record-store'}, context, statement.sourceRef);
189
+ requireScratchScalar(validateExpression(statement.id, bindings, context), context, statement.sourceRef, 'Record IDs');
190
+ declareBinding(
191
+ statement.result,
192
+ {kind: 'value', valueType: {kind: 'union', members: ['null', 'json-object']}},
193
+ bindings,
194
+ context,
195
+ statement.sourceRef
196
+ );
197
+ } else if (statement.kind === 'record-delete') {
198
+ requireCapability({kind: 'record-store'}, context, statement.sourceRef);
199
+ requireScratchScalar(validateExpression(statement.id, bindings, context), context, statement.sourceRef, 'Record IDs');
200
+ declareBinding(statement.result, {kind: 'value', valueType: 'boolean'}, bindings, context, statement.sourceRef);
201
+ } else if (statement.kind === 'asset-resolve') {
202
+ requireCapability({kind: 'object-storage'}, context, statement.sourceRef);
203
+ declareBinding(
204
+ statement.result,
205
+ {kind: 'value', valueType: {kind: 'union', members: ['null', 'binary-ref']}},
206
+ bindings,
207
+ context,
208
+ statement.sourceRef
209
+ );
210
+ } else if (statement.kind === 'request-body-binary') {
211
+ requireCapability({kind: 'streaming-body'}, context, statement.sourceRef);
212
+ validateBinaryLimit(statement.maxBytes, context, statement.sourceRef);
213
+ declareBinaryBody(statement.result, bindings, context, statement.sourceRef);
214
+ } else if (statement.kind === 'asset-object-get') {
215
+ requireCapability({kind: 'object-storage'}, context, statement.sourceRef);
216
+ requireCapability({kind: 'streaming-body'}, context, statement.sourceRef);
217
+ validateBinaryLimit(statement.maxBytes, context, statement.sourceRef);
218
+ requireValueType(
219
+ validateExpression(statement.ref, bindings, context),
220
+ 'binary-ref',
221
+ context,
222
+ statement.ref.sourceRef ?? statement.sourceRef,
223
+ 'Asset object reference'
224
+ );
225
+ declareBinaryBody(statement.result, bindings, context, statement.sourceRef);
226
+ } else if (statement.kind === 'asset-object-put') {
227
+ requireCapability({kind: 'object-storage'}, context, statement.sourceRef);
228
+ validateBinaryLimit(statement.maxBytes, context, statement.sourceRef);
229
+ context.binaryBodies.consume(statement.body, statement.sourceRef);
230
+ declareBinding(statement.result, {kind: 'value', valueType: 'binary-ref'}, bindings, context, statement.sourceRef);
231
+ } else if (statement.kind === 'asset-object-delete') {
232
+ requireCapability({kind: 'object-storage'}, context, statement.sourceRef);
233
+ if (statement.target.kind === 'ref') {
234
+ requireValueType(
235
+ validateExpression(statement.target.ref, bindings, context),
236
+ 'binary-ref',
237
+ context,
238
+ statement.target.ref.sourceRef ?? statement.sourceRef,
239
+ 'Asset delete reference'
240
+ );
241
+ }
242
+ declareBinding(statement.result, {kind: 'value', valueType: 'boolean'}, bindings, context, statement.sourceRef);
243
+ } else if (statement.kind === 'if') {
244
+ const conditionType = validateExpression(statement.condition, bindings, context);
245
+ if (!sameValueType(conditionType, 'boolean')) {
246
+ report(
247
+ context,
248
+ 'TW2_CONDITION_TYPE',
249
+ 'IR if condition must have boolean type.',
250
+ 'IR v2 does not infer Scratch truthiness for direct IR input.',
251
+ 'Insert an explicit boolean comparison in the frontend.',
252
+ statement.condition.sourceRef ?? statement.sourceRef
253
+ );
254
+ }
255
+ const thenContext = {...context, binaryBodies: context.binaryBodies.fork()};
256
+ const elseContext = {...context, binaryBodies: context.binaryBodies.fork()};
257
+ const thenFlow = analyzeSequence(statement.then, cloneBindings(bindings), thenContext);
258
+ const elseFlow =
259
+ statement.else === undefined
260
+ ? {mayContinue: true, mayTerminate: false, bindings: cloneBindings(bindings)}
261
+ : analyzeSequence(statement.else, cloneBindings(bindings), elseContext);
262
+ context.binaryBodies.mergeBranches(thenContext.binaryBodies, elseContext.binaryBodies);
263
+ return mergeBranchFlows(bindings, thenFlow, elseFlow, context, statement.sourceRef);
264
+ } else if (statement.kind === 'bounded-loop' || statement.kind === 'json-for-each') {
265
+ const nextDepth = context.loopDepth + 1;
266
+ if (statement.kind === 'json-for-each') {
267
+ requireJsonValue(
268
+ validateExpression(statement.root, bindings, context),
269
+ context,
270
+ statement.root.sourceRef ?? statement.sourceRef,
271
+ 'Structured Data for-each root'
272
+ );
273
+ if (context.iterationLoopIds.has(statement.loopId)) {
274
+ report(
275
+ context,
276
+ 'TW2_BINDING_DUPLICATE',
277
+ `Iteration loop ID ${statement.loopId} is already active.`,
278
+ 'Nested Structured Data loops require distinct lexical IDs.',
279
+ 'Generate a unique loop ID from the source block.',
280
+ statement.sourceRef
281
+ );
282
+ }
283
+ }
284
+ const minimum = statement.kind === 'json-for-each' ? 1 : 0;
285
+ if (
286
+ !Number.isSafeInteger(statement.maxIterations) ||
287
+ statement.maxIterations < minimum ||
288
+ statement.maxIterations > context.policy.maxLoopIterations
289
+ ) {
290
+ report(
291
+ context,
292
+ 'TW2_LOOP_BOUND_INVALID',
293
+ `Loop maxIterations must be an integer from ${minimum} to ${context.policy.maxLoopIterations}.`,
294
+ 'Server loops require a statically proven finite bound.',
295
+ 'Use a literal bound within the supported range.',
296
+ statement.sourceRef
297
+ );
298
+ }
299
+ if (nextDepth > context.policy.maxLoopNesting) {
300
+ report(
301
+ context,
302
+ 'TW2_LOOP_NESTING_EXCEEDED',
303
+ `Loop nesting exceeds the ${context.policy.maxLoopNesting} level limit.`,
304
+ 'Deeply nested bounded loops can still create excessive work.',
305
+ 'Flatten the iteration or split the handler.',
306
+ statement.sourceRef
307
+ );
308
+ }
309
+ const iterationLoopIds =
310
+ statement.kind === 'json-for-each'
311
+ ? new Set([...context.iterationLoopIds, statement.loopId])
312
+ : context.iterationLoopIds;
313
+ const loopBodies = context.binaryBodies.fork();
314
+ analyzeSequence(statement.body, cloneBindings(bindings), {
315
+ ...context,
316
+ loopDepth: nextDepth,
317
+ iterationLoopIds,
318
+ binaryBodies: loopBodies
319
+ });
320
+ context.binaryBodies.absorbPossibleExecution(loopBodies, statement.maxIterations, statement.sourceRef);
321
+ } else if (isTerminalResponse(statement)) {
322
+ if (statement.kind === 'respond') validateExpression(statement.body, bindings, context);
323
+ else if (statement.kind === 'respond-binary') {
324
+ requireCapability({kind: 'streaming-body'}, context, statement.sourceRef);
325
+ context.binaryBodies.consume(statement.body, statement.sourceRef);
326
+ } else {
327
+ requireCapability({kind: 'named-body-provider'}, context, statement.sourceRef);
328
+ validateBinaryLimit(statement.maxBytes, context, statement.sourceRef);
329
+ if (!context.featureFlags.namedResponseBody) {
330
+ report(
331
+ context,
332
+ 'TW2_NAMED_RESPONSE_BODY_DISABLED',
333
+ 'Named response body is disabled.',
334
+ 'The experimental named body provider contract is protected by a startup-fixed feature flag.',
335
+ 'Enable namedResponseBody explicitly for this compiler invocation or use an existing response operation.',
336
+ statement.sourceRef
337
+ );
338
+ }
339
+ }
340
+ if (context.loopDepth > 0) {
341
+ report(
342
+ context,
343
+ 'TW2_RESPONSE_IN_LOOP',
344
+ 'Terminal response is not allowed inside a loop.',
345
+ 'A loop can execute zero or multiple times, so response cardinality would be ambiguous.',
346
+ 'Move the response after the outermost loop.',
347
+ statement.sourceRef
348
+ );
349
+ }
350
+ return {mayContinue: false, mayTerminate: true, bindings};
351
+ }
352
+ return {mayContinue: true, mayTerminate: false, bindings};
353
+ }
354
+
355
+ function isTerminalResponse(
356
+ statement: StatementIrV2
357
+ ): statement is Extract<StatementIrV2, {kind: 'respond' | 'respond-binary' | 'respond-named-body'}> {
358
+ return statement.kind === 'respond' || statement.kind === 'respond-binary' || statement.kind === 'respond-named-body';
359
+ }
360
+
361
+ function declareBinaryBody(
362
+ declaration: BindingDeclarationV2,
363
+ bindings: BindingEnvironment,
364
+ context: ValidationContext,
365
+ sourceRef?: SourceRefV2
366
+ ): void {
367
+ const alreadyDeclared = bindings.has(declaration.id);
368
+ declareBinding(declaration, {kind: 'resource', resourceType: 'binary-body'}, bindings, context, sourceRef);
369
+ if (!alreadyDeclared) context.binaryBodies.declare(declaration.id, sourceRef);
370
+ }
371
+
372
+ function validateBinaryLimit(
373
+ value: number,
374
+ context: ValidationContext,
375
+ sourceRef?: SourceRefV2
376
+ ): void {
377
+ if (Number.isSafeInteger(value) && value >= 1 && value <= context.policy.maxBinaryBytes) return;
378
+ report(
379
+ context,
380
+ 'TW2_BINARY_LIMIT_INVALID',
381
+ `Binary maxBytes must be an integer from 1 to ${context.policy.maxBinaryBytes}.`,
382
+ 'Every binary source or sink requires a static limit within compiler policy.',
383
+ 'Use a smaller literal maxBytes value.',
384
+ sourceRef
385
+ );
386
+ }
387
+
388
+ function validateExpression(
389
+ expression: ExpressionIrV2,
390
+ bindings: ReadonlyMap<string, BindingTypeV2>,
391
+ context: ValidationContext
392
+ ): ValueTypeV2 {
393
+ if (expression.kind === 'request' && expression.source === 'client-address') {
394
+ requireCapability({kind: 'request-metadata', field: 'client-address'}, context, expression.sourceRef);
395
+ }
396
+ if (expression.kind === 'concat') {
397
+ const left = validateExpression(expression.left, bindings, context);
398
+ const right = validateExpression(expression.right, bindings, context);
399
+ if (!sameValueType(left, 'string') || !sameValueType(right, 'string')) {
400
+ report(
401
+ context,
402
+ 'TW2_BINDING_TYPE_MISMATCH',
403
+ 'concat operands must both have string type.',
404
+ 'IR v2 does not apply implicit JSON or binary coercion.',
405
+ 'Serialize or convert each operand explicitly.',
406
+ expression.sourceRef
407
+ );
408
+ }
409
+ }
410
+ if (expression.kind === 'handler-variable' || expression.kind === 'handler-variable-exists') {
411
+ requireScratchScalar(
412
+ validateExpression(expression.name, bindings, context),
413
+ context,
414
+ expression.sourceRef,
415
+ 'Handler variable names'
416
+ );
417
+ }
418
+ if (expression.kind === 'kvs-get-text' || expression.kind === 'kvs-has' || expression.kind === 'kvs-list-keys') {
419
+ requireCapability({kind: 'key-value-store'}, context, expression.sourceRef);
420
+ requireScratchScalar(
421
+ validateExpression(expression.namespace, bindings, context),
422
+ context,
423
+ expression.sourceRef,
424
+ 'KVS namespaces'
425
+ );
426
+ if (expression.kind !== 'kvs-list-keys') {
427
+ requireScratchScalar(validateExpression(expression.key, bindings, context), context, expression.sourceRef, 'KVS keys');
428
+ }
429
+ }
430
+ if (expression.kind === 'json-text-coerce') {
431
+ requireValueType(
432
+ validateExpression(expression.input, bindings, context),
433
+ 'string',
434
+ context,
435
+ expression.sourceRef,
436
+ 'json-text coercion input'
437
+ );
438
+ }
439
+ if (expression.kind === 'json-parse' || expression.kind === 'json-is-valid') {
440
+ requireValueType(
441
+ validateExpression(expression.text, bindings, context),
442
+ 'json-text',
443
+ context,
444
+ expression.sourceRef,
445
+ 'Structured Data JSON text input'
446
+ );
447
+ }
448
+ if (expression.kind === 'json-stringify') {
449
+ requireJsonValue(
450
+ validateExpression(expression.value, bindings, context),
451
+ context,
452
+ expression.sourceRef,
453
+ 'Structured Data serialization input'
454
+ );
455
+ }
456
+ if (
457
+ expression.kind === 'json-get' ||
458
+ expression.kind === 'json-has' ||
459
+ expression.kind === 'json-delete' ||
460
+ expression.kind === 'json-keys' ||
461
+ expression.kind === 'json-length'
462
+ ) {
463
+ requireJsonValue(
464
+ validateExpression(expression.root, bindings, context),
465
+ context,
466
+ expression.sourceRef,
467
+ 'Structured Data root'
468
+ );
469
+ }
470
+ if (expression.kind === 'json-set') {
471
+ requireJsonValue(
472
+ validateExpression(expression.root, bindings, context),
473
+ context,
474
+ expression.sourceRef,
475
+ 'Structured Data root'
476
+ );
477
+ requireJsonValue(
478
+ validateExpression(expression.value, bindings, context),
479
+ context,
480
+ expression.sourceRef,
481
+ 'Structured Data replacement'
482
+ );
483
+ }
484
+ if (
485
+ expression.kind === 'iteration-key' ||
486
+ expression.kind === 'iteration-index' ||
487
+ expression.kind === 'iteration-value'
488
+ ) {
489
+ if (!context.iterationLoopIds.has(expression.loopId)) {
490
+ report(
491
+ context,
492
+ 'TW2_ITERATION_CONTEXT_REQUIRED',
493
+ `Iteration reporter references inactive loop ${expression.loopId}.`,
494
+ 'Iteration reporters are valid only inside the lexical body of their Structured Data loop.',
495
+ 'Bind the reporter to the nearest enclosing json-for-each loop.',
496
+ expression.sourceRef
497
+ );
498
+ }
499
+ }
500
+ if (expression.kind === 'binding') {
501
+ const declared = bindings.get(expression.binding);
502
+ if (declared === undefined) {
503
+ report(
504
+ context,
505
+ 'TW2_BINDING_UNDECLARED',
506
+ `Binding ${expression.binding} is not declared in this lexical scope.`,
507
+ 'Typed bindings are compiler-assigned and scoped to their declaring control-flow region.',
508
+ 'Use the binding only after its producer and inside the same lexical scope.',
509
+ expression.sourceRef
510
+ );
511
+ } else if (declared.kind !== 'value' || !sameValueType(declared.valueType, expression.valueType)) {
512
+ report(
513
+ context,
514
+ 'TW2_BINDING_TYPE_MISMATCH',
515
+ `Binding ${expression.binding} does not match the expression value type.`,
516
+ 'Value bindings and resource bindings are distinct and cannot be substituted.',
517
+ 'Use the declared value type, or pass a binary-body only to a resource consumer.',
518
+ expression.sourceRef
519
+ );
520
+ }
521
+ }
522
+ return expression.valueType;
523
+ }
524
+
525
+ function declareBinding(
526
+ declaration: BindingDeclarationV2,
527
+ expected: BindingTypeV2,
528
+ bindings: BindingEnvironment,
529
+ context: ValidationContext,
530
+ sourceRef?: SourceRefV2
531
+ ): void {
532
+ if (bindings.has(declaration.id)) {
533
+ report(
534
+ context,
535
+ 'TW2_BINDING_DUPLICATE',
536
+ `Binding ${declaration.id} is already declared in this scope.`,
537
+ 'Compiler-generated binding IDs must be unique along a control-flow path.',
538
+ 'Allocate a new lexical binding ID.',
539
+ sourceRef
540
+ );
541
+ return;
542
+ }
543
+ if (!sameBindingType(declaration.type, expected)) {
544
+ report(
545
+ context,
546
+ 'TW2_BINDING_TYPE_MISMATCH',
547
+ `Binding ${declaration.id} has an invalid result type for its producer.`,
548
+ 'The declared binding type must match the operation result contract.',
549
+ 'Use the producer result type defined by IR v2.',
550
+ sourceRef
551
+ );
552
+ }
553
+ bindings.set(declaration.id, expected);
554
+ }
555
+
556
+ function mergeBranchFlows(
557
+ base: BindingEnvironment,
558
+ thenFlow: FlowResult,
559
+ elseFlow: FlowResult,
560
+ context: ValidationContext,
561
+ sourceRef?: SourceRefV2
562
+ ): FlowResult {
563
+ const mayContinue = thenFlow.mayContinue || elseFlow.mayContinue;
564
+ const mayTerminate = thenFlow.mayTerminate || elseFlow.mayTerminate;
565
+ if (!mayContinue) return {mayContinue, mayTerminate, bindings: cloneBindings(base)};
566
+ if (thenFlow.mayContinue && !elseFlow.mayContinue) return {mayContinue, mayTerminate, bindings: thenFlow.bindings};
567
+ if (!thenFlow.mayContinue && elseFlow.mayContinue) return {mayContinue, mayTerminate, bindings: elseFlow.bindings};
568
+
569
+ const merged = cloneBindings(base);
570
+ const names = new Set([...thenFlow.bindings.keys(), ...elseFlow.bindings.keys()]);
571
+ for (const name of names) {
572
+ if (base.has(name)) continue;
573
+ const thenType = thenFlow.bindings.get(name);
574
+ const elseType = elseFlow.bindings.get(name);
575
+ if (thenType === undefined || elseType === undefined || !sameBindingType(thenType, elseType)) {
576
+ report(
577
+ context,
578
+ 'TW2_BRANCH_BINDING_MISMATCH',
579
+ `Binding ${name} is not declared with the same type in both continuing branches.`,
580
+ 'A binding used after an if must exist consistently on every path that reaches the merge point.',
581
+ 'Declare matching bindings in both branches or keep their use inside each branch.',
582
+ sourceRef
583
+ );
584
+ continue;
585
+ }
586
+ merged.set(name, thenType);
587
+ }
588
+ return {mayContinue, mayTerminate, bindings: merged};
589
+ }
590
+
591
+ function requireCapability(
592
+ capability: CapabilityRequirementV2,
593
+ context: ValidationContext,
594
+ sourceRef?: SourceRefV2
595
+ ): void {
596
+ const key = capabilityKey(capability);
597
+ if (context.capabilities.has(key)) return;
598
+ report(
599
+ context,
600
+ 'TW2_CAPABILITY_MISSING',
601
+ `IR operation requires undeclared capability ${key}.`,
602
+ 'Target-neutral capability requirements must be complete before adapter selection.',
603
+ 'Add the logical capability to IR.capabilities.',
604
+ sourceRef
605
+ );
606
+ }
607
+
608
+ function requireScratchScalar(
609
+ type: ValueTypeV2,
610
+ context: ValidationContext,
611
+ sourceRef: SourceRefV2 | undefined,
612
+ subject: string
613
+ ): void {
614
+ const members = valueTypeMembers(type);
615
+ if (members.every((member) => member === 'string' || member === 'number' || member === 'boolean')) return;
616
+ report(
617
+ context,
618
+ 'TW2_HANDLER_VARIABLE_TYPE',
619
+ `${subject} must use a Scratch-compatible scalar value.`,
620
+ 'JSON, binary-ref, and resource state belong in typed lexical bindings.',
621
+ 'Convert to a scalar or use a compiler-generated typed binding.',
622
+ sourceRef
623
+ );
624
+ }
625
+
626
+ function requireValueType(
627
+ actual: ValueTypeV2,
628
+ expected: ValueTypeV2,
629
+ context: ValidationContext,
630
+ sourceRef: SourceRefV2 | undefined,
631
+ subject: string
632
+ ): void {
633
+ if (sameValueType(actual, expected)) return;
634
+ report(
635
+ context,
636
+ 'TW2_BINDING_TYPE_MISMATCH',
637
+ `${subject} has an incompatible value type.`,
638
+ 'IR v2 keeps json-text and typed JSON values as distinct nominal boundaries.',
639
+ 'Insert the required parse, serialize, or json-text coercion node.',
640
+ sourceRef
641
+ );
642
+ }
643
+
644
+ function requireJsonValue(
645
+ actual: ValueTypeV2,
646
+ context: ValidationContext,
647
+ sourceRef: SourceRefV2 | undefined,
648
+ subject: string
649
+ ): void {
650
+ const allowed = new Set(['null', 'boolean', 'number', 'string', 'json-array', 'json-object']);
651
+ if (valueTypeMembers(actual).every((member) => allowed.has(member))) return;
652
+ report(
653
+ context,
654
+ 'TW2_BINDING_TYPE_MISMATCH',
655
+ `${subject} must be a typed JSON value.`,
656
+ 'json-text and binary references cannot be used as parsed JSON values.',
657
+ 'Parse json-text before using the value in a Structured Data operation.',
658
+ sourceRef
659
+ );
660
+ }
661
+
662
+ function sequenceWork(statements: readonly StatementIrV2[], limit: number): number {
663
+ let total = 0;
664
+ for (const statement of statements) {
665
+ total = saturatedAdd(total, statementWork(statement, limit), limit);
666
+ }
667
+ return total;
668
+ }
669
+
670
+ function statementWork(statement: StatementIrV2, limit: number): number {
671
+ if (statement.kind === 'if') {
672
+ const branches = Math.max(sequenceWork(statement.then, limit), sequenceWork(statement.else ?? [], limit));
673
+ return saturatedAdd(saturatedAdd(1, expressionWork(statement.condition, limit), limit), branches, limit);
674
+ }
675
+ if (statement.kind === 'bounded-loop' || statement.kind === 'json-for-each') {
676
+ const rootWork = statement.kind === 'json-for-each' ? expressionWork(statement.root, limit) : 0;
677
+ return saturatedAdd(
678
+ saturatedAdd(1, rootWork, limit),
679
+ saturatedMultiply(statement.maxIterations, sequenceWork(statement.body, limit), limit),
680
+ limit
681
+ );
682
+ }
683
+ let work = 1;
684
+ if (statement.kind === 'set-header') work = saturatedAdd(work, expressionWork(statement.value, limit), limit);
685
+ if (statement.kind === 'set-handler-variable' || statement.kind === 'change-handler-variable') {
686
+ work = saturatedAdd(work, expressionWork(statement.name, limit), limit);
687
+ work = saturatedAdd(work, expressionWork(statement.value, limit), limit);
688
+ }
689
+ if (statement.kind === 'delete-handler-variable') work = saturatedAdd(work, expressionWork(statement.name, limit), limit);
690
+ if (statement.kind === 'kvs-set-text' || statement.kind === 'kvs-delete') {
691
+ work = saturatedAdd(work, expressionWork(statement.namespace, limit), limit);
692
+ work = saturatedAdd(work, expressionWork(statement.key, limit), limit);
693
+ if (statement.kind === 'kvs-set-text') work = saturatedAdd(work, expressionWork(statement.value, limit), limit);
694
+ }
695
+ if (statement.kind === 'record-create') work = saturatedAdd(work, expressionWork(statement.data, limit), limit);
696
+ if (statement.kind === 'record-get' || statement.kind === 'record-delete') {
697
+ work = saturatedAdd(work, expressionWork(statement.id, limit), limit);
698
+ }
699
+ if (statement.kind === 'respond') work = saturatedAdd(work, expressionWork(statement.body, limit), limit);
700
+ return work;
701
+ }
702
+
703
+ function expressionWork(expression: ExpressionIrV2, limit: number): number {
704
+ if (expression.kind === 'concat') {
705
+ return saturatedAdd(
706
+ saturatedAdd(1, expressionWork(expression.left, limit), limit),
707
+ expressionWork(expression.right, limit),
708
+ limit
709
+ );
710
+ }
711
+ if (expression.kind === 'handler-variable' || expression.kind === 'handler-variable-exists') {
712
+ return saturatedAdd(1, expressionWork(expression.name, limit), limit);
713
+ }
714
+ if (expression.kind === 'kvs-get-text' || expression.kind === 'kvs-has') {
715
+ return saturatedAdd(
716
+ saturatedAdd(1, expressionWork(expression.namespace, limit), limit),
717
+ expressionWork(expression.key, limit),
718
+ limit
719
+ );
720
+ }
721
+ if (expression.kind === 'kvs-list-keys') {
722
+ return saturatedAdd(1, expressionWork(expression.namespace, limit), limit);
723
+ }
724
+ if (expression.kind === 'json-text-coerce') {
725
+ return saturatedAdd(1, expressionWork(expression.input, limit), limit);
726
+ }
727
+ if (expression.kind === 'json-parse' || expression.kind === 'json-is-valid') {
728
+ return saturatedAdd(1, expressionWork(expression.text, limit), limit);
729
+ }
730
+ if (expression.kind === 'json-stringify') {
731
+ return saturatedAdd(1, expressionWork(expression.value, limit), limit);
732
+ }
733
+ if (
734
+ expression.kind === 'json-get' ||
735
+ expression.kind === 'json-has' ||
736
+ expression.kind === 'json-delete' ||
737
+ expression.kind === 'json-keys' ||
738
+ expression.kind === 'json-length'
739
+ ) {
740
+ return saturatedAdd(1, expressionWork(expression.root, limit), limit);
741
+ }
742
+ if (expression.kind === 'json-set') {
743
+ return saturatedAdd(
744
+ saturatedAdd(1, expressionWork(expression.root, limit), limit),
745
+ expressionWork(expression.value, limit),
746
+ limit
747
+ );
748
+ }
749
+ return 1;
750
+ }
751
+
752
+ function saturatedAdd(left: number, right: number, limit: number): number {
753
+ return left > limit || right > limit || left + right > limit ? limit + 1 : left + right;
754
+ }
755
+
756
+ function saturatedMultiply(left: number, right: number, limit: number): number {
757
+ if (left < 0 || right < 0 || left > limit || right > limit || left * right > limit) return limit + 1;
758
+ return left * right;
759
+ }
760
+
761
+ function capabilityKey(capability: CapabilityRequirementV2): string {
762
+ if (
763
+ capability.kind === 'record-store' ||
764
+ capability.kind === 'key-value-store' ||
765
+ capability.kind === 'object-storage' ||
766
+ capability.kind === 'streaming-body' ||
767
+ capability.kind === 'named-body-provider'
768
+ ) {
769
+ return capability.kind;
770
+ }
771
+ return `${capability.kind}:${capability.kind === 'auth' ? capability.scheme : capability.field}`;
772
+ }
773
+
774
+ function cloneBindings(bindings: ReadonlyMap<string, BindingTypeV2>): BindingEnvironment {
775
+ return new Map(bindings);
776
+ }
777
+
778
+ function sameBindingType(left: BindingTypeV2, right: BindingTypeV2): boolean {
779
+ if (left.kind !== right.kind) return false;
780
+ return left.kind === 'resource'
781
+ ? right.kind === 'resource' && left.resourceType === right.resourceType
782
+ : right.kind === 'value' && sameValueType(left.valueType, right.valueType);
783
+ }
784
+
785
+ function sameValueType(left: ValueTypeV2, right: ValueTypeV2): boolean {
786
+ return JSON.stringify(left) === JSON.stringify(right);
787
+ }
788
+
789
+ function valueTypeMembers(type: ValueTypeV2): readonly string[] {
790
+ return typeof type === 'string' ? [type] : type.members;
791
+ }
792
+
793
+ function report(
794
+ context: ValidationContext,
795
+ code: ServerSubsetDiagnosticCode,
796
+ message: string,
797
+ reason: string,
798
+ suggestion: string,
799
+ sourceRef?: SourceRefV2
800
+ ): void {
801
+ const diagnostic: TargetNeutralDiagnostic = {
802
+ severity: 'error',
803
+ phase: 'target-neutral',
804
+ code,
805
+ message,
806
+ routeId: context.route.id,
807
+ reason,
808
+ suggestion
809
+ };
810
+ if (sourceRef !== undefined) diagnostic.sourceRef = sourceRef;
811
+ context.diagnostics.push(diagnostic);
812
+ }