@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,921 @@
1
+ import {parseJsonWithoutDuplicateKeys} from './strict-json.js';
2
+ import {isNamedDataNamespace} from '../../named-data-namespace.js';
3
+ import {
4
+ DEPLOY_IR_V2_VERSION,
5
+ JSON_VALUE_TYPE_V2,
6
+ type AtomicValueTypeV2,
7
+ type AuthPolicyV2,
8
+ type BinaryContentDispositionV2,
9
+ type BinaryDeleteTargetV2,
10
+ type BinaryLocatorV2,
11
+ type BinaryMetadataV2,
12
+ type BinaryRefDescriptorV2,
13
+ type BindingDeclarationV2,
14
+ type BindingTypeV2,
15
+ type CapabilityRequirementV2,
16
+ type DeployIrV2,
17
+ type ExpressionIrV2,
18
+ type HttpMethodV2,
19
+ type JsonValue,
20
+ type PathSegmentV2,
21
+ type RouteIrV2,
22
+ type SourceRefV2,
23
+ type StatementIrV2,
24
+ type ValueTypeV2
25
+ } from './types.js';
26
+
27
+ const METHODS = new Set<HttpMethodV2>(['ALL', 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']);
28
+ const NAMED_TARGET_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
29
+ const ATOMIC_TYPES = new Set<AtomicValueTypeV2>([
30
+ 'null',
31
+ 'boolean',
32
+ 'number',
33
+ 'string',
34
+ 'json-text',
35
+ 'json-array',
36
+ 'json-object',
37
+ 'binary-ref'
38
+ ]);
39
+ const BINDING_ID = /^[A-Za-z_][A-Za-z0-9_]*$/;
40
+ const ATOMIC_TYPE_ORDER: readonly AtomicValueTypeV2[] = [
41
+ 'null',
42
+ 'boolean',
43
+ 'number',
44
+ 'string',
45
+ 'json-text',
46
+ 'json-array',
47
+ 'json-object',
48
+ 'binary-ref'
49
+ ];
50
+
51
+ export type DeployIrV2ParseErrorCode =
52
+ | 'TW2_IR_JSON_SYNTAX'
53
+ | 'TW2_IR_DUPLICATE_KEY'
54
+ | 'TW2_IR_VERSION'
55
+ | 'TW2_IR_UNKNOWN_FIELD'
56
+ | 'TW2_IR_UNKNOWN_NODE'
57
+ | 'TW2_IR_INVALID_VALUE';
58
+
59
+ export class DeployIrV2ParseError extends Error {
60
+ public readonly name = 'DeployIrV2ParseError';
61
+
62
+ public constructor(
63
+ public readonly code: DeployIrV2ParseErrorCode,
64
+ message: string,
65
+ public readonly cause?: unknown
66
+ ) {
67
+ super(message);
68
+ }
69
+ }
70
+
71
+ export function parseDeployIrV2Json(text: string): DeployIrV2 {
72
+ return withParseDiagnostic(() => parseDeployIrV2Value(parseJsonWithoutDuplicateKeys(text)));
73
+ }
74
+
75
+ export function parseDeployIrV2(value: unknown): DeployIrV2 {
76
+ return withParseDiagnostic(() => parseDeployIrV2Value(value));
77
+ }
78
+
79
+ function parseDeployIrV2Value(value: unknown): DeployIrV2 {
80
+ const root = object(value, 'IR');
81
+ exactKeys(root, ['version', 'name', 'auth', 'capabilities', 'routes'], 'IR');
82
+ if (root.version !== DEPLOY_IR_V2_VERSION) throw new Error('IR.version must be 2.');
83
+ const name = nonEmptyString(root.name, 'IR.name');
84
+ const auth = parseAuth(root.auth, 'IR.auth');
85
+ const capabilities = normalizeCapabilities(
86
+ array(root.capabilities, 'IR.capabilities').map((item, index) =>
87
+ parseCapability(item, `IR.capabilities[${index}]`)
88
+ )
89
+ );
90
+ const routes = array(root.routes, 'IR.routes').map((item, index) =>
91
+ parseRoute(item, `IR.routes[${index}]`)
92
+ );
93
+ if (routes.length === 0) throw new Error('IR.routes must not be empty.');
94
+ return {version: DEPLOY_IR_V2_VERSION, name, auth, capabilities, routes};
95
+ }
96
+
97
+ function withParseDiagnostic<T>(operation: () => T): T {
98
+ try {
99
+ return operation();
100
+ } catch (error) {
101
+ if (error instanceof DeployIrV2ParseError) throw error;
102
+ const message = error instanceof Error ? error.message : String(error);
103
+ let code: DeployIrV2ParseErrorCode = 'TW2_IR_INVALID_VALUE';
104
+ if (error instanceof SyntaxError) {
105
+ code = message.startsWith('Duplicate object key:') ? 'TW2_IR_DUPLICATE_KEY' : 'TW2_IR_JSON_SYNTAX';
106
+ } else if (message === 'IR.version must be 2.') {
107
+ code = 'TW2_IR_VERSION';
108
+ } else if (message.includes('contains unknown field:')) {
109
+ code = 'TW2_IR_UNKNOWN_FIELD';
110
+ } else if (message.includes('.kind is unsupported:')) {
111
+ code = 'TW2_IR_UNKNOWN_NODE';
112
+ }
113
+ throw new DeployIrV2ParseError(code, message, error);
114
+ }
115
+ }
116
+
117
+ function parseAuth(value: unknown, location: string): AuthPolicyV2 {
118
+ const auth = object(value, location);
119
+ const kind = nonEmptyString(auth.kind, `${location}.kind`);
120
+ if (kind === 'none') {
121
+ exactKeys(auth, ['kind'], location);
122
+ return {kind};
123
+ }
124
+ if (kind === 'jwt') {
125
+ exactKeys(auth, ['kind', 'scheme'], location);
126
+ const scheme = nonEmptyString(auth.scheme, `${location}.scheme`);
127
+ if (scheme !== 'external-jwt' && scheme !== 'trusted-access-jwt') {
128
+ throw new Error(`${location}.scheme is unsupported: ${scheme}`);
129
+ }
130
+ return {kind, scheme};
131
+ }
132
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
133
+ }
134
+
135
+ function parseCapability(value: unknown, location: string): CapabilityRequirementV2 {
136
+ const capability = object(value, location);
137
+ const kind = nonEmptyString(capability.kind, `${location}.kind`);
138
+ if (kind === 'record-store' || kind === 'key-value-store') {
139
+ exactKeys(capability, ['kind'], location);
140
+ return {kind};
141
+ }
142
+ if (kind === 'object-storage' || kind === 'streaming-body' || kind === 'named-body-provider') {
143
+ exactKeys(capability, ['kind'], location);
144
+ return {kind};
145
+ }
146
+ if (kind === 'request-metadata') {
147
+ exactKeys(capability, ['kind', 'field'], location);
148
+ if (capability.field !== 'client-address') throw new Error(`${location}.field is unsupported.`);
149
+ return {kind, field: 'client-address'};
150
+ }
151
+ if (kind === 'auth') {
152
+ exactKeys(capability, ['kind', 'scheme'], location);
153
+ const scheme = capability.scheme;
154
+ if (scheme !== 'external-jwt' && scheme !== 'trusted-access-jwt') {
155
+ throw new Error(`${location}.scheme is unsupported.`);
156
+ }
157
+ return {kind, scheme};
158
+ }
159
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
160
+ }
161
+
162
+ function parseRoute(value: unknown, location: string): RouteIrV2 {
163
+ const route = object(value, location);
164
+ exactKeys(route, ['id', 'method', 'path', 'auth', 'body', 'sourceRef'], location);
165
+ const id = nonEmptyString(route.id, `${location}.id`);
166
+ const method = nonEmptyString(route.method, `${location}.method`) as HttpMethodV2;
167
+ if (!METHODS.has(method)) throw new Error(`${location}.method is unsupported: ${method}`);
168
+ const path = nonEmptyString(route.path, `${location}.path`);
169
+ const auth = route.auth;
170
+ if (auth !== 'public' && auth !== 'required') throw new Error(`${location}.auth is invalid.`);
171
+ const body = array(route.body, `${location}.body`).map((item, index) =>
172
+ parseStatement(item, `${location}.body[${index}]`)
173
+ );
174
+ if (body.length === 0) throw new Error(`${location}.body must not be empty.`);
175
+ const sourceRef = optionalSourceRef(route.sourceRef, `${location}.sourceRef`);
176
+ return optional({id, method, path, auth, body}, 'sourceRef', sourceRef);
177
+ }
178
+
179
+ function parseStatement(value: unknown, location: string): StatementIrV2 {
180
+ const statement = object(value, location);
181
+ const kind = nonEmptyString(statement.kind, `${location}.kind`);
182
+ const sourceRef = optionalSourceRef(statement.sourceRef, `${location}.sourceRef`);
183
+ if (kind === 'set-status') {
184
+ exactKeys(statement, ['kind', 'status', 'sourceRef'], location);
185
+ const status = integer(statement.status, `${location}.status`);
186
+ if (status < 100 || status > 599) throw new Error(`${location}.status must be from 100 to 599.`);
187
+ return optional({kind, status}, 'sourceRef', sourceRef);
188
+ }
189
+ if (kind === 'set-header') {
190
+ exactKeys(statement, ['kind', 'name', 'value', 'sourceRef'], location);
191
+ return optional(
192
+ {kind, name: nonEmptyString(statement.name, `${location}.name`), value: parseExpression(statement.value, `${location}.value`)},
193
+ 'sourceRef',
194
+ sourceRef
195
+ );
196
+ }
197
+ if (kind === 'remove-header') {
198
+ exactKeys(statement, ['kind', 'name', 'sourceRef'], location);
199
+ return optional({kind, name: nonEmptyString(statement.name, `${location}.name`)}, 'sourceRef', sourceRef);
200
+ }
201
+ if (kind === 'set-handler-variable' || kind === 'change-handler-variable') {
202
+ exactKeys(statement, ['kind', 'name', 'value', 'sourceRef'], location);
203
+ return optional(
204
+ {
205
+ kind,
206
+ name: parseExpression(statement.name, `${location}.name`),
207
+ value: parseExpression(statement.value, `${location}.value`)
208
+ },
209
+ 'sourceRef',
210
+ sourceRef
211
+ );
212
+ }
213
+ if (kind === 'delete-handler-variable') {
214
+ exactKeys(statement, ['kind', 'name', 'sourceRef'], location);
215
+ return optional({kind, name: parseExpression(statement.name, `${location}.name`)}, 'sourceRef', sourceRef);
216
+ }
217
+ if (kind === 'clear-handler-variables') {
218
+ exactKeys(statement, ['kind', 'sourceRef'], location);
219
+ return optional({kind}, 'sourceRef', sourceRef);
220
+ }
221
+ if (kind === 'kvs-set-text') {
222
+ exactKeys(statement, ['kind', 'namespace', 'key', 'value', 'sourceRef'], location);
223
+ return optional(
224
+ {
225
+ kind,
226
+ namespace: parseExpression(statement.namespace, `${location}.namespace`),
227
+ key: parseExpression(statement.key, `${location}.key`),
228
+ value: parseExpression(statement.value, `${location}.value`)
229
+ },
230
+ 'sourceRef',
231
+ sourceRef
232
+ );
233
+ }
234
+ if (kind === 'kvs-delete') {
235
+ exactKeys(statement, ['kind', 'namespace', 'key', 'sourceRef'], location);
236
+ return optional(
237
+ {
238
+ kind,
239
+ namespace: parseExpression(statement.namespace, `${location}.namespace`),
240
+ key: parseExpression(statement.key, `${location}.key`)
241
+ },
242
+ 'sourceRef',
243
+ sourceRef
244
+ );
245
+ }
246
+ if (kind === 'record-create') {
247
+ exactKeys(statement, ['kind', 'collection', 'data', 'result', 'sourceRef'], location);
248
+ return optional(
249
+ {
250
+ kind,
251
+ collection: nonEmptyString(statement.collection, `${location}.collection`),
252
+ data: parseExpression(statement.data, `${location}.data`),
253
+ result: parseBinding(statement.result, `${location}.result`)
254
+ },
255
+ 'sourceRef',
256
+ sourceRef
257
+ );
258
+ }
259
+ if (kind === 'record-list') {
260
+ exactKeys(statement, ['kind', 'collection', 'result', 'sourceRef'], location);
261
+ return optional(
262
+ {
263
+ kind,
264
+ collection: nonEmptyString(statement.collection, `${location}.collection`),
265
+ result: parseBinding(statement.result, `${location}.result`)
266
+ },
267
+ 'sourceRef',
268
+ sourceRef
269
+ );
270
+ }
271
+ if (kind === 'record-get' || kind === 'record-delete') {
272
+ exactKeys(statement, ['kind', 'id', 'result', 'sourceRef'], location);
273
+ return optional(
274
+ {kind, id: parseExpression(statement.id, `${location}.id`), result: parseBinding(statement.result, `${location}.result`)},
275
+ 'sourceRef',
276
+ sourceRef
277
+ );
278
+ }
279
+ if (kind === 'asset-resolve') {
280
+ exactKeys(statement, ['kind', 'locator', 'result', 'sourceRef'], location);
281
+ return optional(
282
+ {
283
+ kind,
284
+ locator: parseBinaryLocator(statement.locator, `${location}.locator`),
285
+ result: parseBinding(statement.result, `${location}.result`)
286
+ },
287
+ 'sourceRef',
288
+ sourceRef
289
+ );
290
+ }
291
+ if (kind === 'request-body-binary') {
292
+ exactKeys(statement, ['kind', 'maxBytes', 'result', 'sourceRef'], location);
293
+ return optional(
294
+ {
295
+ kind,
296
+ maxBytes: binaryLimit(statement.maxBytes, `${location}.maxBytes`),
297
+ result: parseBinding(statement.result, `${location}.result`)
298
+ },
299
+ 'sourceRef',
300
+ sourceRef
301
+ );
302
+ }
303
+ if (kind === 'asset-object-get') {
304
+ exactKeys(statement, ['kind', 'ref', 'maxBytes', 'result', 'sourceRef'], location);
305
+ return optional(
306
+ {
307
+ kind,
308
+ ref: parseExpression(statement.ref, `${location}.ref`),
309
+ maxBytes: binaryLimit(statement.maxBytes, `${location}.maxBytes`),
310
+ result: parseBinding(statement.result, `${location}.result`)
311
+ },
312
+ 'sourceRef',
313
+ sourceRef
314
+ );
315
+ }
316
+ if (kind === 'asset-object-put') {
317
+ exactKeys(statement, ['kind', 'locator', 'body', 'metadata', 'maxBytes', 'result', 'sourceRef'], location);
318
+ return optional(
319
+ {
320
+ kind,
321
+ locator: parseBinaryLocator(statement.locator, `${location}.locator`),
322
+ body: bindingId(statement.body, `${location}.body`),
323
+ metadata: parseBinaryMetadata(statement.metadata, `${location}.metadata`),
324
+ maxBytes: binaryLimit(statement.maxBytes, `${location}.maxBytes`),
325
+ result: parseBinding(statement.result, `${location}.result`)
326
+ },
327
+ 'sourceRef',
328
+ sourceRef
329
+ );
330
+ }
331
+ if (kind === 'asset-object-delete') {
332
+ exactKeys(statement, ['kind', 'target', 'result', 'sourceRef'], location);
333
+ return optional(
334
+ {
335
+ kind,
336
+ target: parseBinaryDeleteTarget(statement.target, `${location}.target`),
337
+ result: parseBinding(statement.result, `${location}.result`)
338
+ },
339
+ 'sourceRef',
340
+ sourceRef
341
+ );
342
+ }
343
+ if (kind === 'if') {
344
+ exactKeys(statement, ['kind', 'condition', 'then', 'else', 'sourceRef'], location);
345
+ const condition = parseExpression(statement.condition, `${location}.condition`);
346
+ const then = parseStatements(statement.then, `${location}.then`);
347
+ const otherwise = statement.else === undefined ? undefined : parseStatements(statement.else, `${location}.else`);
348
+ return optional(optional({kind, condition, then}, 'else', otherwise), 'sourceRef', sourceRef);
349
+ }
350
+ if (kind === 'bounded-loop') {
351
+ exactKeys(statement, ['kind', 'maxIterations', 'body', 'sourceRef'], location);
352
+ const maxIterations = integer(statement.maxIterations, `${location}.maxIterations`);
353
+ if (maxIterations < 0 || maxIterations > 1000) {
354
+ throw new Error(`${location}.maxIterations must be from 0 to 1000.`);
355
+ }
356
+ return optional(
357
+ {kind, maxIterations, body: parseStatements(statement.body, `${location}.body`)},
358
+ 'sourceRef',
359
+ sourceRef
360
+ );
361
+ }
362
+ if (kind === 'json-for-each') {
363
+ exactKeys(statement, ['kind', 'loopId', 'root', 'path', 'maxIterations', 'body', 'sourceRef'], location);
364
+ const maxIterations = integer(statement.maxIterations, `${location}.maxIterations`);
365
+ if (maxIterations < 1 || maxIterations > 1000) {
366
+ throw new Error(`${location}.maxIterations must be from 1 to 1000.`);
367
+ }
368
+ return optional(
369
+ {
370
+ kind,
371
+ loopId: bindingId(statement.loopId, `${location}.loopId`),
372
+ root: parseExpression(statement.root, `${location}.root`),
373
+ path: parsePath(statement.path, `${location}.path`),
374
+ maxIterations,
375
+ body: parseStatements(statement.body, `${location}.body`)
376
+ },
377
+ 'sourceRef',
378
+ sourceRef
379
+ );
380
+ }
381
+ if (kind === 'respond') {
382
+ exactKeys(statement, ['kind', 'format', 'body', 'sourceRef'], location);
383
+ const format = statement.format;
384
+ if (format !== 'text' && format !== 'html' && format !== 'json') {
385
+ throw new Error(`${location}.format is invalid.`);
386
+ }
387
+ return optional({kind, format, body: parseExpression(statement.body, `${location}.body`)}, 'sourceRef', sourceRef);
388
+ }
389
+ if (kind === 'respond-binary') {
390
+ exactKeys(statement, ['kind', 'body', 'disposition', 'sourceRef'], location);
391
+ const disposition =
392
+ statement.disposition === undefined
393
+ ? undefined
394
+ : parseBinaryDisposition(statement.disposition, `${location}.disposition`);
395
+ return optional(
396
+ optional({kind, body: bindingId(statement.body, `${location}.body`)}, 'disposition', disposition),
397
+ 'sourceRef',
398
+ sourceRef
399
+ );
400
+ }
401
+ if (kind === 'respond-named-body') {
402
+ exactKeys(statement, ['kind', 'reference', 'representation', 'targetId', 'maxBytes', 'sourceRef'], location);
403
+ const referenceValue = object(statement.reference, `${location}.reference`);
404
+ exactKeys(referenceValue, ['namespace', 'name', 'kind', 'scope'], `${location}.reference`);
405
+ const namespace = nonEmptyString(referenceValue.namespace, `${location}.reference.namespace`);
406
+ if (!isNamedDataNamespace(namespace)) throw new Error(`${location}.reference.namespace is invalid.`);
407
+ const name = nonEmptyString(referenceValue.name, `${location}.reference.name`);
408
+ if (name.length > 256 || [...name].some(isControlCharacter)) {
409
+ throw new Error(`${location}.reference.name is invalid.`);
410
+ }
411
+ const dataKind = referenceValue.kind;
412
+ if (dataKind !== 'structured' && dataKind !== 'document' && dataKind !== 'binary' && dataKind !== 'asset') {
413
+ throw new Error(`${location}.reference.kind is invalid.`);
414
+ }
415
+ const scope = referenceValue.scope;
416
+ if (scope !== 'target' && scope !== 'project') throw new Error(`${location}.reference.scope is invalid.`);
417
+ const representation = statement.representation;
418
+ if (
419
+ representation !== 'json' &&
420
+ representation !== 'yaml' &&
421
+ representation !== 'html' &&
422
+ representation !== 'markdown' &&
423
+ representation !== 'raw'
424
+ ) {
425
+ throw new Error(`${location}.representation is invalid.`);
426
+ }
427
+ const targetId = optionalString(statement.targetId, `${location}.targetId`);
428
+ if (scope === 'target' && (targetId === undefined || !NAMED_TARGET_ID.test(targetId))) {
429
+ throw new Error(`${location}.targetId is required for target scope.`);
430
+ }
431
+ if (scope === 'project' && targetId !== undefined) {
432
+ throw new Error(`${location}.targetId is not allowed for project scope.`);
433
+ }
434
+ return optional(
435
+ optional(
436
+ {
437
+ kind,
438
+ reference: {namespace, name, kind: dataKind, scope},
439
+ representation,
440
+ maxBytes: binaryLimit(statement.maxBytes, `${location}.maxBytes`)
441
+ },
442
+ 'targetId',
443
+ targetId
444
+ ),
445
+ 'sourceRef',
446
+ sourceRef
447
+ );
448
+ }
449
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
450
+ }
451
+
452
+ function parseStatements(value: unknown, location: string): StatementIrV2[] {
453
+ return array(value, location).map((item, index) => parseStatement(item, `${location}[${index}]`));
454
+ }
455
+
456
+ function parseExpression(value: unknown, location: string): ExpressionIrV2 {
457
+ const expression = object(value, location);
458
+ const kind = nonEmptyString(expression.kind, `${location}.kind`);
459
+ const sourceRef = optionalSourceRef(expression.sourceRef, `${location}.sourceRef`);
460
+ if (kind === 'literal') {
461
+ exactKeys(expression, ['kind', 'valueType', 'value', 'sourceRef'], location);
462
+ const valueType = atomicType(expression.valueType, `${location}.valueType`);
463
+ if (valueType === 'binary-ref') {
464
+ const binaryRef = parseBinaryRef(expression.value, `${location}.value`);
465
+ return optional({kind, valueType, value: binaryRef}, 'sourceRef', sourceRef);
466
+ }
467
+ const literal = jsonValue(expression.value, `${location}.value`);
468
+ assertLiteralType(valueType, literal, location);
469
+ return optional({kind, valueType, value: literal}, 'sourceRef', sourceRef);
470
+ }
471
+ if (kind === 'request') {
472
+ exactKeys(expression, ['kind', 'valueType', 'source', 'sourceRef'], location);
473
+ if (expression.valueType !== 'string') throw new Error(`${location}.valueType must be string.`);
474
+ const source = expression.source;
475
+ if (!['method', 'path', 'url', 'body-text', 'content-type', 'client-address'].includes(String(source))) {
476
+ throw new Error(`${location}.source is unsupported.`);
477
+ }
478
+ return optional(
479
+ {kind, valueType: 'string', source: source as Extract<ExpressionIrV2, {kind: 'request'}>['source']},
480
+ 'sourceRef',
481
+ sourceRef
482
+ );
483
+ }
484
+ if (kind === 'request-value') {
485
+ exactKeys(expression, ['kind', 'valueType', 'source', 'name', 'sourceRef'], location);
486
+ if (expression.valueType !== 'string') throw new Error(`${location}.valueType must be string.`);
487
+ const source = expression.source;
488
+ if (source !== 'query' && source !== 'path-param' && source !== 'header') {
489
+ throw new Error(`${location}.source is unsupported.`);
490
+ }
491
+ return optional(
492
+ {kind, valueType: 'string', source, name: nonEmptyString(expression.name, `${location}.name`)},
493
+ 'sourceRef',
494
+ sourceRef
495
+ );
496
+ }
497
+ if (kind === 'concat') {
498
+ exactKeys(expression, ['kind', 'valueType', 'left', 'right', 'sourceRef'], location);
499
+ if (expression.valueType !== 'string') throw new Error(`${location}.valueType must be string.`);
500
+ return optional(
501
+ {
502
+ kind,
503
+ valueType: 'string',
504
+ left: parseExpression(expression.left, `${location}.left`),
505
+ right: parseExpression(expression.right, `${location}.right`)
506
+ },
507
+ 'sourceRef',
508
+ sourceRef
509
+ );
510
+ }
511
+ if (kind === 'handler-variable') {
512
+ exactKeys(expression, ['kind', 'valueType', 'name', 'sourceRef'], location);
513
+ const valueType = parseValueType(expression.valueType, `${location}.valueType`);
514
+ if (!isStringNumberUnion(valueType)) throw new Error(`${location}.valueType must be the number|string union.`);
515
+ return optional(
516
+ {kind, valueType: {kind: 'union', members: ['number', 'string']}, name: parseExpression(expression.name, `${location}.name`)},
517
+ 'sourceRef',
518
+ sourceRef
519
+ );
520
+ }
521
+ if (kind === 'handler-variable-exists') {
522
+ exactKeys(expression, ['kind', 'valueType', 'name', 'sourceRef'], location);
523
+ if (expression.valueType !== 'boolean') throw new Error(`${location}.valueType must be boolean.`);
524
+ return optional(
525
+ {kind, valueType: 'boolean', name: parseExpression(expression.name, `${location}.name`)},
526
+ 'sourceRef',
527
+ sourceRef
528
+ );
529
+ }
530
+ if (kind === 'handler-variable-names') {
531
+ exactKeys(expression, ['kind', 'valueType', 'sourceRef'], location);
532
+ if (expression.valueType !== 'string') throw new Error(`${location}.valueType must be string.`);
533
+ return optional({kind, valueType: 'string'}, 'sourceRef', sourceRef);
534
+ }
535
+ if (kind === 'kvs-get-text' || kind === 'kvs-has') {
536
+ exactKeys(expression, ['kind', 'valueType', 'namespace', 'key', 'sourceRef'], location);
537
+ const valueType = kind === 'kvs-get-text' ? 'string' : 'boolean';
538
+ requireValueType(expression.valueType, valueType, `${location}.valueType`);
539
+ const namespace = parseExpression(expression.namespace, `${location}.namespace`);
540
+ const key = parseExpression(expression.key, `${location}.key`);
541
+ return kind === 'kvs-get-text'
542
+ ? optional({kind, valueType: 'string', namespace, key}, 'sourceRef', sourceRef)
543
+ : optional({kind, valueType: 'boolean', namespace, key}, 'sourceRef', sourceRef);
544
+ }
545
+ if (kind === 'kvs-list-keys') {
546
+ exactKeys(expression, ['kind', 'valueType', 'namespace', 'sourceRef'], location);
547
+ requireValueType(expression.valueType, 'json-text', `${location}.valueType`);
548
+ return optional(
549
+ {kind, valueType: 'json-text', namespace: parseExpression(expression.namespace, `${location}.namespace`)},
550
+ 'sourceRef',
551
+ sourceRef
552
+ );
553
+ }
554
+ if (kind === 'binding') {
555
+ exactKeys(expression, ['kind', 'valueType', 'binding', 'sourceRef'], location);
556
+ return optional(
557
+ {
558
+ kind,
559
+ valueType: parseValueType(expression.valueType, `${location}.valueType`),
560
+ binding: bindingId(expression.binding, `${location}.binding`)
561
+ },
562
+ 'sourceRef',
563
+ sourceRef
564
+ );
565
+ }
566
+ if (kind === 'json-text-coerce') {
567
+ exactKeys(expression, ['kind', 'valueType', 'input', 'sourceRef'], location);
568
+ requireValueType(expression.valueType, 'json-text', `${location}.valueType`);
569
+ return optional(
570
+ {kind, valueType: 'json-text', input: parseExpression(expression.input, `${location}.input`)},
571
+ 'sourceRef',
572
+ sourceRef
573
+ );
574
+ }
575
+ if (kind === 'json-parse') {
576
+ exactKeys(expression, ['kind', 'valueType', 'text', 'sourceRef'], location);
577
+ requireJsonValueType(expression.valueType, `${location}.valueType`);
578
+ return optional(
579
+ {kind, valueType: JSON_VALUE_TYPE_V2, text: parseExpression(expression.text, `${location}.text`)},
580
+ 'sourceRef',
581
+ sourceRef
582
+ );
583
+ }
584
+ if (kind === 'json-stringify') {
585
+ exactKeys(expression, ['kind', 'valueType', 'value', 'sourceRef'], location);
586
+ requireValueType(expression.valueType, 'json-text', `${location}.valueType`);
587
+ return optional(
588
+ {kind, valueType: 'json-text', value: parseExpression(expression.value, `${location}.value`)},
589
+ 'sourceRef',
590
+ sourceRef
591
+ );
592
+ }
593
+ if (kind === 'json-is-valid') {
594
+ exactKeys(expression, ['kind', 'valueType', 'text', 'sourceRef'], location);
595
+ requireValueType(expression.valueType, 'boolean', `${location}.valueType`);
596
+ return optional(
597
+ {kind, valueType: 'boolean', text: parseExpression(expression.text, `${location}.text`)},
598
+ 'sourceRef',
599
+ sourceRef
600
+ );
601
+ }
602
+ if (
603
+ kind === 'json-get' ||
604
+ kind === 'json-has' ||
605
+ kind === 'json-delete' ||
606
+ kind === 'json-keys' ||
607
+ kind === 'json-length'
608
+ ) {
609
+ exactKeys(expression, ['kind', 'valueType', 'root', 'path', 'sourceRef'], location);
610
+ const root = parseExpression(expression.root, `${location}.root`);
611
+ const path = parsePath(expression.path, `${location}.path`);
612
+ if (kind === 'json-get' || kind === 'json-delete') {
613
+ requireJsonValueType(expression.valueType, `${location}.valueType`);
614
+ return optional({kind, valueType: JSON_VALUE_TYPE_V2, root, path}, 'sourceRef', sourceRef);
615
+ }
616
+ if (kind === 'json-has') {
617
+ requireValueType(expression.valueType, 'boolean', `${location}.valueType`);
618
+ return optional({kind, valueType: 'boolean', root, path}, 'sourceRef', sourceRef);
619
+ }
620
+ if (kind === 'json-keys') {
621
+ requireValueType(expression.valueType, 'json-array', `${location}.valueType`);
622
+ return optional({kind, valueType: 'json-array', root, path}, 'sourceRef', sourceRef);
623
+ }
624
+ requireValueType(expression.valueType, 'number', `${location}.valueType`);
625
+ return optional({kind, valueType: 'number', root, path}, 'sourceRef', sourceRef);
626
+ }
627
+ if (kind === 'json-set') {
628
+ exactKeys(expression, ['kind', 'valueType', 'root', 'path', 'value', 'sourceRef'], location);
629
+ requireJsonValueType(expression.valueType, `${location}.valueType`);
630
+ return optional(
631
+ {
632
+ kind,
633
+ valueType: JSON_VALUE_TYPE_V2,
634
+ root: parseExpression(expression.root, `${location}.root`),
635
+ path: parsePath(expression.path, `${location}.path`),
636
+ value: parseExpression(expression.value, `${location}.value`)
637
+ },
638
+ 'sourceRef',
639
+ sourceRef
640
+ );
641
+ }
642
+ if (kind === 'iteration-key' || kind === 'iteration-index' || kind === 'iteration-value') {
643
+ exactKeys(expression, ['kind', 'valueType', 'loopId', 'sourceRef'], location);
644
+ const loopId = bindingId(expression.loopId, `${location}.loopId`);
645
+ if (kind === 'iteration-key') {
646
+ requireValueType(expression.valueType, 'string', `${location}.valueType`);
647
+ return optional({kind, valueType: 'string', loopId}, 'sourceRef', sourceRef);
648
+ }
649
+ if (kind === 'iteration-index') {
650
+ requireValueType(expression.valueType, 'number', `${location}.valueType`);
651
+ return optional({kind, valueType: 'number', loopId}, 'sourceRef', sourceRef);
652
+ }
653
+ requireJsonValueType(expression.valueType, `${location}.valueType`);
654
+ return optional({kind, valueType: JSON_VALUE_TYPE_V2, loopId}, 'sourceRef', sourceRef);
655
+ }
656
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
657
+ }
658
+
659
+ function parseBinding(value: unknown, location: string): BindingDeclarationV2 {
660
+ const binding = object(value, location);
661
+ exactKeys(binding, ['id', 'type'], location);
662
+ return {id: bindingId(binding.id, `${location}.id`), type: parseBindingType(binding.type, `${location}.type`)};
663
+ }
664
+
665
+ function parseBindingType(value: unknown, location: string): BindingTypeV2 {
666
+ const type = object(value, location);
667
+ const kind = nonEmptyString(type.kind, `${location}.kind`);
668
+ if (kind === 'value') {
669
+ exactKeys(type, ['kind', 'valueType'], location);
670
+ return {kind, valueType: parseValueType(type.valueType, `${location}.valueType`)};
671
+ }
672
+ if (kind === 'resource') {
673
+ exactKeys(type, ['kind', 'resourceType'], location);
674
+ if (type.resourceType !== 'binary-body') throw new Error(`${location}.resourceType is unsupported.`);
675
+ return {kind, resourceType: 'binary-body'};
676
+ }
677
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
678
+ }
679
+
680
+ function parseValueType(value: unknown, location: string): ValueTypeV2 {
681
+ if (typeof value === 'string') return atomicType(value, location);
682
+ const type = object(value, location);
683
+ exactKeys(type, ['kind', 'members'], location);
684
+ if (type.kind !== 'union') throw new Error(`${location}.kind must be union.`);
685
+ const members = array(type.members, `${location}.members`).map((member, index) =>
686
+ atomicType(member, `${location}.members[${index}]`)
687
+ );
688
+ if (members.length < 2 || new Set(members).size !== members.length) {
689
+ throw new Error(`${location}.members must contain at least two unique atomic types.`);
690
+ }
691
+ return {
692
+ kind: 'union',
693
+ members: members.sort((left, right) => ATOMIC_TYPE_ORDER.indexOf(left) - ATOMIC_TYPE_ORDER.indexOf(right))
694
+ };
695
+ }
696
+
697
+ function requireValueType(value: unknown, expected: AtomicValueTypeV2, location: string): void {
698
+ if (value !== expected) throw new Error(`${location} must be ${expected}.`);
699
+ }
700
+
701
+ function requireJsonValueType(value: unknown, location: string): void {
702
+ const parsed = parseValueType(value, location);
703
+ if (JSON.stringify(parsed) !== JSON.stringify(JSON_VALUE_TYPE_V2)) {
704
+ throw new Error(`${location} must be the canonical JSON value union.`);
705
+ }
706
+ }
707
+
708
+ function parsePath(value: unknown, location: string): PathSegmentV2[] {
709
+ return array(value, location).map((item, index) => {
710
+ const segmentLocation = `${location}[${index}]`;
711
+ const segment = object(item, segmentLocation);
712
+ exactKeys(segment, ['kind', 'value'], segmentLocation);
713
+ if (segment.kind === 'key') {
714
+ if (typeof segment.value !== 'string') throw new Error(`${segmentLocation}.value must be a string.`);
715
+ return {kind: 'key', value: segment.value};
716
+ }
717
+ if (segment.kind === 'index') {
718
+ const indexValue = integer(segment.value, `${segmentLocation}.value`);
719
+ if (indexValue < 0) throw new Error(`${segmentLocation}.value must not be negative.`);
720
+ return {kind: 'index', value: indexValue};
721
+ }
722
+ throw new Error(`${segmentLocation}.kind is unsupported: ${String(segment.kind)}`);
723
+ });
724
+ }
725
+
726
+ function normalizeCapabilities(capabilities: CapabilityRequirementV2[]): CapabilityRequirementV2[] {
727
+ const entries = capabilities.map((capability) => [JSON.stringify(capability), capability] as const);
728
+ if (new Set(entries.map(([key]) => key)).size !== entries.length) {
729
+ throw new Error('IR.capabilities must not contain duplicates.');
730
+ }
731
+ return entries
732
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
733
+ .map(([, capability]) => capability);
734
+ }
735
+
736
+ function optionalSourceRef(value: unknown, location: string): SourceRefV2 | undefined {
737
+ if (value === undefined) return undefined;
738
+ const source = object(value, location);
739
+ exactKeys(source, ['targetIndex', 'targetName', 'blockId', 'opcode', 'input'], location);
740
+ const result = {
741
+ targetIndex: integer(source.targetIndex, `${location}.targetIndex`),
742
+ targetName: nonEmptyString(source.targetName, `${location}.targetName`),
743
+ blockId: nonEmptyString(source.blockId, `${location}.blockId`),
744
+ opcode: nonEmptyString(source.opcode, `${location}.opcode`)
745
+ };
746
+ if (result.targetIndex < 0) throw new Error(`${location}.targetIndex must not be negative.`);
747
+ const input = source.input === undefined ? undefined : nonEmptyString(source.input, `${location}.input`);
748
+ return optional(result, 'input', input);
749
+ }
750
+
751
+ function jsonValue(value: unknown, location: string): JsonValue {
752
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
753
+ if (typeof value === 'number') {
754
+ if (!Number.isFinite(value)) throw new Error(`${location} must be a finite JSON number.`);
755
+ return Object.is(value, -0) ? 0 : value;
756
+ }
757
+ if (Array.isArray(value)) return value.map((item, index) => jsonValue(item, `${location}[${index}]`));
758
+ const record = object(value, location);
759
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, jsonValue(item, `${location}.${key}`)]));
760
+ }
761
+
762
+ function parseBinaryRef(value: unknown, location: string): BinaryRefDescriptorV2 {
763
+ const descriptor = object(value, location);
764
+ exactKeys(descriptor, ['namespace', 'key', 'contentType', 'size', 'integrity', 'revision'], location);
765
+ return {
766
+ ...parseBinaryLocator(descriptor, location, true),
767
+ ...parseBinaryMetadata(descriptor, location, true)
768
+ };
769
+ }
770
+
771
+ function parseBinaryLocator(value: unknown, location: string, includesMetadata = false): BinaryLocatorV2 {
772
+ const locator = object(value, location);
773
+ exactKeys(
774
+ locator,
775
+ includesMetadata
776
+ ? ['namespace', 'key', 'contentType', 'size', 'integrity', 'revision']
777
+ : ['namespace', 'key'],
778
+ location
779
+ );
780
+ const namespace = nonEmptyString(locator.namespace, `${location}.namespace`);
781
+ if (!isNamedDataNamespace(namespace)) {
782
+ throw new Error(`${location}.namespace must be a logical namespace identifier of at most 64 characters.`);
783
+ }
784
+ const key = nonEmptyString(locator.key, `${location}.key`);
785
+ if (key.length > 512 || key.includes('\0') || key.includes('\\') || key.startsWith('/')) {
786
+ throw new Error(`${location}.key is not a safe logical key.`);
787
+ }
788
+ const segments = key.split('/');
789
+ if (segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) {
790
+ throw new Error(`${location}.key contains an unsafe path segment.`);
791
+ }
792
+ return {namespace, key};
793
+ }
794
+
795
+ function parseBinaryMetadata(value: unknown, location: string, includesLocator = false): BinaryMetadataV2 {
796
+ const metadata = object(value, location);
797
+ exactKeys(
798
+ metadata,
799
+ includesLocator
800
+ ? ['namespace', 'key', 'contentType', 'size', 'integrity', 'revision']
801
+ : ['contentType', 'size', 'integrity', 'revision'],
802
+ location
803
+ );
804
+ const contentType = optionalString(metadata.contentType, `${location}.contentType`);
805
+ if (contentType !== undefined && (contentType.length > 255 || !/^[^\s/;]+\/[^\s;]+(?:\s*;.*)?$/u.test(contentType) || /[\r\n]/u.test(contentType))) {
806
+ throw new Error(`${location}.contentType must be a safe media type.`);
807
+ }
808
+ const size = metadata.size === undefined ? undefined : integer(metadata.size, `${location}.size`);
809
+ if (size !== undefined && size < 0) throw new Error(`${location}.size must not be negative.`);
810
+ const integrityValue = optionalString(metadata.integrity, `${location}.integrity`);
811
+ if (integrityValue !== undefined && !/^sha256:[0-9a-f]{64}$/.test(integrityValue)) {
812
+ throw new Error(`${location}.integrity must use sha256:<64 lowercase hexadecimal characters>.`);
813
+ }
814
+ const integrity = integrityValue as `sha256:${string}` | undefined;
815
+ const revision = optionalString(metadata.revision, `${location}.revision`);
816
+ if (revision !== undefined && revision.length > 256) throw new Error(`${location}.revision is too long.`);
817
+ return optional(optional(optional(optional({}, 'contentType', contentType), 'size', size), 'integrity', integrity), 'revision', revision);
818
+ }
819
+
820
+ function parseBinaryDeleteTarget(value: unknown, location: string): BinaryDeleteTargetV2 {
821
+ const target = object(value, location);
822
+ const kind = nonEmptyString(target.kind, `${location}.kind`);
823
+ if (kind === 'ref') {
824
+ exactKeys(target, ['kind', 'ref'], location);
825
+ return {kind, ref: parseExpression(target.ref, `${location}.ref`)};
826
+ }
827
+ if (kind === 'locator') {
828
+ exactKeys(target, ['kind', 'locator'], location);
829
+ return {kind, locator: parseBinaryLocator(target.locator, `${location}.locator`)};
830
+ }
831
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
832
+ }
833
+
834
+ function parseBinaryDisposition(value: unknown, location: string): BinaryContentDispositionV2 {
835
+ const disposition = object(value, location);
836
+ const kind = nonEmptyString(disposition.kind, `${location}.kind`);
837
+ if (kind === 'inline') {
838
+ exactKeys(disposition, ['kind'], location);
839
+ return {kind};
840
+ }
841
+ if (kind === 'attachment') {
842
+ exactKeys(disposition, ['kind', 'filename'], location);
843
+ const filename = nonEmptyString(disposition.filename, `${location}.filename`);
844
+ if (filename.length > 255 || /[\r\n\0]/u.test(filename)) throw new Error(`${location}.filename is unsafe.`);
845
+ return {kind, filename};
846
+ }
847
+ throw new Error(`${location}.kind is unsupported: ${kind}`);
848
+ }
849
+
850
+ function binaryLimit(value: unknown, location: string): number {
851
+ const limit = integer(value, location);
852
+ if (limit < 1 || limit > 16 * 1024 * 1024) throw new Error(`${location} must be from 1 to 16777216.`);
853
+ return limit;
854
+ }
855
+
856
+ function assertLiteralType(type: Exclude<AtomicValueTypeV2, 'binary-ref'>, value: JsonValue, location: string): void {
857
+ const actual = value === null ? 'null' : Array.isArray(value) ? 'json-array' : typeof value === 'object' ? 'json-object' : typeof value;
858
+ if (type === 'json-text') {
859
+ if (actual !== 'string') throw new Error(`${location}.value must be a JSON text string.`);
860
+ return;
861
+ }
862
+ if (type !== actual) throw new Error(`${location}.valueType ${type} does not match ${actual}.`);
863
+ }
864
+
865
+ function isStringNumberUnion(type: ValueTypeV2): type is {kind: 'union'; members: ['number', 'string']} {
866
+ return typeof type !== 'string' && type.members.length === 2 && type.members[0] === 'number' && type.members[1] === 'string';
867
+ }
868
+
869
+ function atomicType(value: unknown, location: string): AtomicValueTypeV2 {
870
+ if (typeof value !== 'string' || !ATOMIC_TYPES.has(value as AtomicValueTypeV2)) {
871
+ throw new Error(`${location} is not an atomic IR value type.`);
872
+ }
873
+ return value as AtomicValueTypeV2;
874
+ }
875
+
876
+ function bindingId(value: unknown, location: string): string {
877
+ const id = nonEmptyString(value, location);
878
+ if (!BINDING_ID.test(id)) throw new Error(`${location} is not a valid binding ID.`);
879
+ return id;
880
+ }
881
+
882
+ function object(value: unknown, location: string): Record<string, unknown> {
883
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
884
+ throw new Error(`${location} must be an object.`);
885
+ }
886
+ return value as Record<string, unknown>;
887
+ }
888
+
889
+ function array(value: unknown, location: string): unknown[] {
890
+ if (!Array.isArray(value)) throw new Error(`${location} must be an array.`);
891
+ return value;
892
+ }
893
+
894
+ function nonEmptyString(value: unknown, location: string): string {
895
+ if (typeof value !== 'string' || value.length === 0) throw new Error(`${location} must be a non-empty string.`);
896
+ return value;
897
+ }
898
+
899
+ function optionalString(value: unknown, location: string): string | undefined {
900
+ return value === undefined ? undefined : nonEmptyString(value, location);
901
+ }
902
+
903
+ function integer(value: unknown, location: string): number {
904
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) throw new Error(`${location} must be a safe integer.`);
905
+ return value;
906
+ }
907
+
908
+ function isControlCharacter(character: string): boolean {
909
+ const codePoint = character.codePointAt(0)!;
910
+ return codePoint <= 0x1f || codePoint === 0x7f;
911
+ }
912
+
913
+ function exactKeys(record: Record<string, unknown>, allowed: readonly string[], location: string): void {
914
+ const allowedSet = new Set(allowed);
915
+ const unknown = Object.keys(record).filter((key) => !allowedSet.has(key));
916
+ if (unknown.length > 0) throw new Error(`${location} contains unknown field: ${unknown.sort()[0]}`);
917
+ }
918
+
919
+ function optional<T extends object, K extends string, V>(base: T, key: K, value: V | undefined): T & Partial<Record<K, V>> {
920
+ return value === undefined ? base : {...base, [key]: value};
921
+ }