@kubohiroya/turbowarp-http-server 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/README.ja.md +29 -13
  2. package/README.md +101 -42
  3. package/dist/cli.js +131 -17
  4. package/dist/cli.js.map +1 -1
  5. package/dist/compiler/adapters/cloudflare.d.ts +2 -0
  6. package/dist/compiler/adapters/cloudflare.js +477 -0
  7. package/dist/compiler/adapters/cloudflare.js.map +1 -0
  8. package/dist/compiler/adapters/firebase.d.ts +2 -0
  9. package/dist/compiler/adapters/firebase.js +489 -0
  10. package/dist/compiler/adapters/firebase.js.map +1 -0
  11. package/dist/compiler/adapters/index.d.ts +2 -0
  12. package/dist/compiler/adapters/index.js +3 -0
  13. package/dist/compiler/adapters/index.js.map +1 -0
  14. package/dist/compiler/binary/codec.d.ts +4 -0
  15. package/dist/compiler/binary/codec.js +45 -0
  16. package/dist/compiler/binary/codec.js.map +1 -0
  17. package/dist/compiler/binary/error.d.ts +3 -0
  18. package/dist/compiler/binary/error.js +21 -0
  19. package/dist/compiler/binary/error.js.map +1 -0
  20. package/dist/compiler/binary/index.d.ts +4 -0
  21. package/dist/compiler/binary/index.js +5 -0
  22. package/dist/compiler/binary/index.js.map +1 -0
  23. package/dist/compiler/binary/runtime.d.ts +18 -0
  24. package/dist/compiler/binary/runtime.js +123 -0
  25. package/dist/compiler/binary/runtime.js.map +1 -0
  26. package/dist/compiler/binary/types.d.ts +17 -0
  27. package/dist/compiler/binary/types.js +2 -0
  28. package/dist/compiler/binary/types.js.map +1 -0
  29. package/dist/compiler/feature-flags.d.ts +4 -0
  30. package/dist/compiler/feature-flags.js +4 -0
  31. package/dist/compiler/feature-flags.js.map +1 -0
  32. package/dist/compiler/index.d.ts +35 -0
  33. package/dist/compiler/index.js +84 -0
  34. package/dist/compiler/index.js.map +1 -0
  35. package/dist/compiler/ir-v2/canonical.d.ts +3 -0
  36. package/dist/compiler/ir-v2/canonical.js +50 -0
  37. package/dist/compiler/ir-v2/canonical.js.map +1 -0
  38. package/dist/compiler/ir-v2/index.d.ts +4 -0
  39. package/dist/compiler/ir-v2/index.js +5 -0
  40. package/dist/compiler/ir-v2/index.js.map +1 -0
  41. package/dist/compiler/ir-v2/parse.d.ts +10 -0
  42. package/dist/compiler/ir-v2/parse.js +753 -0
  43. package/dist/compiler/ir-v2/parse.js.map +1 -0
  44. package/dist/compiler/ir-v2/strict-json.d.ts +4 -0
  45. package/dist/compiler/ir-v2/strict-json.js +133 -0
  46. package/dist/compiler/ir-v2/strict-json.js.map +1 -0
  47. package/dist/compiler/ir-v2/types.d.ts +412 -0
  48. package/dist/compiler/ir-v2/types.js +84 -0
  49. package/dist/compiler/ir-v2/types.js.map +1 -0
  50. package/dist/compiler/kvs/lowering.d.ts +13 -0
  51. package/dist/compiler/kvs/lowering.js +77 -0
  52. package/dist/compiler/kvs/lowering.js.map +1 -0
  53. package/dist/compiler/manifest/error.d.ts +7 -0
  54. package/dist/compiler/manifest/error.js +9 -0
  55. package/dist/compiler/manifest/error.js.map +1 -0
  56. package/dist/compiler/manifest/index.d.ts +6 -0
  57. package/dist/compiler/manifest/index.js +7 -0
  58. package/dist/compiler/manifest/index.js.map +1 -0
  59. package/dist/compiler/manifest/operations.d.ts +12 -0
  60. package/dist/compiler/manifest/operations.js +60 -0
  61. package/dist/compiler/manifest/operations.js.map +1 -0
  62. package/dist/compiler/manifest/parse.d.ts +9 -0
  63. package/dist/compiler/manifest/parse.js +280 -0
  64. package/dist/compiler/manifest/parse.js.map +1 -0
  65. package/dist/compiler/manifest/registry.d.ts +3 -0
  66. package/dist/compiler/manifest/registry.js +48 -0
  67. package/dist/compiler/manifest/registry.js.map +1 -0
  68. package/dist/compiler/manifest/resolve.d.ts +14 -0
  69. package/dist/compiler/manifest/resolve.js +116 -0
  70. package/dist/compiler/manifest/resolve.js.map +1 -0
  71. package/dist/compiler/manifest/types.d.ts +95 -0
  72. package/dist/compiler/manifest/types.js +3 -0
  73. package/dist/compiler/manifest/types.js.map +1 -0
  74. package/dist/compiler/named-body/index.d.ts +1 -0
  75. package/dist/compiler/named-body/index.js +2 -0
  76. package/dist/compiler/named-body/index.js.map +1 -0
  77. package/dist/compiler/named-body/lowering.d.ts +18 -0
  78. package/dist/compiler/named-body/lowering.js +83 -0
  79. package/dist/compiler/named-body/lowering.js.map +1 -0
  80. package/dist/compiler/pipeline/compiler.d.ts +18 -0
  81. package/dist/compiler/pipeline/compiler.js +105 -0
  82. package/dist/compiler/pipeline/compiler.js.map +1 -0
  83. package/dist/compiler/pipeline/core-generator.d.ts +3 -0
  84. package/dist/compiler/pipeline/core-generator.js +483 -0
  85. package/dist/compiler/pipeline/core-generator.js.map +1 -0
  86. package/dist/compiler/pipeline/index.d.ts +5 -0
  87. package/dist/compiler/pipeline/index.js +6 -0
  88. package/dist/compiler/pipeline/index.js.map +1 -0
  89. package/dist/compiler/pipeline/registry.d.ts +7 -0
  90. package/dist/compiler/pipeline/registry.js +17 -0
  91. package/dist/compiler/pipeline/registry.js.map +1 -0
  92. package/dist/compiler/pipeline/requirements.d.ts +9 -0
  93. package/dist/compiler/pipeline/requirements.js +135 -0
  94. package/dist/compiler/pipeline/requirements.js.map +1 -0
  95. package/dist/compiler/pipeline/types.d.ts +65 -0
  96. package/dist/compiler/pipeline/types.js +2 -0
  97. package/dist/compiler/pipeline/types.js.map +1 -0
  98. package/dist/compiler/runtime/error.d.ts +6 -0
  99. package/dist/compiler/runtime/error.js +9 -0
  100. package/dist/compiler/runtime/error.js.map +1 -0
  101. package/dist/compiler/runtime/index.d.ts +1 -0
  102. package/dist/compiler/runtime/index.js +2 -0
  103. package/dist/compiler/runtime/index.js.map +1 -0
  104. package/dist/compiler/structured-data/index.d.ts +3 -0
  105. package/dist/compiler/structured-data/index.js +4 -0
  106. package/dist/compiler/structured-data/index.js.map +1 -0
  107. package/dist/compiler/structured-data/lowering.d.ts +30 -0
  108. package/dist/compiler/structured-data/lowering.js +202 -0
  109. package/dist/compiler/structured-data/lowering.js.map +1 -0
  110. package/dist/compiler/structured-data/path.d.ts +2 -0
  111. package/dist/compiler/structured-data/path.js +60 -0
  112. package/dist/compiler/structured-data/path.js.map +1 -0
  113. package/dist/compiler/structured-data/runtime.d.ts +20 -0
  114. package/dist/compiler/structured-data/runtime.js +210 -0
  115. package/dist/compiler/structured-data/runtime.js.map +1 -0
  116. package/dist/compiler/turbowarp-v2.d.ts +8 -0
  117. package/dist/compiler/turbowarp-v2.js +479 -0
  118. package/dist/compiler/turbowarp-v2.js.map +1 -0
  119. package/dist/compiler/validator/index.d.ts +4 -0
  120. package/dist/compiler/validator/index.js +5 -0
  121. package/dist/compiler/validator/index.js.map +1 -0
  122. package/dist/compiler/validator/ir-validator.d.ts +10 -0
  123. package/dist/compiler/validator/ir-validator.js +463 -0
  124. package/dist/compiler/validator/ir-validator.js.map +1 -0
  125. package/dist/compiler/validator/resource-lifetime.d.ts +18 -0
  126. package/dist/compiler/validator/resource-lifetime.js +106 -0
  127. package/dist/compiler/validator/resource-lifetime.js.map +1 -0
  128. package/dist/compiler/validator/turbowarp-subset.d.ts +3 -0
  129. package/dist/compiler/validator/turbowarp-subset.js +241 -0
  130. package/dist/compiler/validator/turbowarp-subset.js.map +1 -0
  131. package/dist/compiler/validator/types.d.ts +30 -0
  132. package/dist/compiler/validator/types.js +7 -0
  133. package/dist/compiler/validator/types.js.map +1 -0
  134. package/dist/config.d.ts +11 -0
  135. package/dist/config.js +12 -0
  136. package/dist/config.js.map +1 -0
  137. package/dist/digest-cli.js +0 -0
  138. package/dist/extension-manifest.json +102 -0
  139. package/dist/named-body.d.ts +57 -0
  140. package/dist/named-body.js +396 -0
  141. package/dist/named-body.js.map +1 -0
  142. package/dist/named-data-namespace.d.ts +3 -0
  143. package/dist/named-data-namespace.js +6 -0
  144. package/dist/named-data-namespace.js.map +1 -0
  145. package/dist/protocol.d.ts +13 -1
  146. package/dist/protocol.js +34 -0
  147. package/dist/protocol.js.map +1 -1
  148. package/dist/resource-named-body-provider.d.ts +8 -0
  149. package/dist/resource-named-body-provider.js +88 -0
  150. package/dist/resource-named-body-provider.js.map +1 -0
  151. package/dist/server.d.ts +10 -1
  152. package/dist/server.js +37 -7
  153. package/dist/server.js.map +1 -1
  154. package/dist/turbowarp-http-server.js +516 -1
  155. package/docs/binary-resource-semantics.ja.md +84 -0
  156. package/docs/cloudflare-worker-compiler.ja.md +90 -0
  157. package/docs/compiler-manifest-registry.ja.md +79 -0
  158. package/docs/compiler-platform-pipeline.ja.md +94 -0
  159. package/docs/deploy-ir-v2.ja.md +123 -0
  160. package/docs/fixed-input-editors.ja.md +23 -0
  161. package/docs/index.html +80 -0
  162. package/docs/ir-v2-conformance.ja.md +65 -0
  163. package/docs/named-response-body.ja.md +120 -0
  164. package/docs/platform-storage-adapters.ja.md +99 -0
  165. package/docs/server-executable-subset.ja.md +88 -0
  166. package/docs/structured-data-lowering.ja.md +63 -0
  167. package/examples/compiler/message-app.v2.ir.json +41 -0
  168. package/package.json +44 -20
  169. package/schemas/block-editor-fixed-inputs.schema.json +85 -0
  170. package/schemas/compiler-extension-manifest.schema.json +126 -0
  171. package/schemas/compiler-manifest-lock-v1.schema.json +48 -0
  172. package/schemas/deploy-ir-v2.schema.json +835 -0
  173. package/schemas/ir-v2-conformance-fixture.schema.json +44 -0
  174. package/src/block-definitions.json +76 -0
  175. package/src/cli.ts +136 -23
  176. package/src/compiler/adapters/cloudflare.ts +510 -0
  177. package/src/compiler/adapters/firebase.ts +538 -0
  178. package/src/compiler/adapters/index.ts +2 -0
  179. package/src/compiler/binary/codec.ts +61 -0
  180. package/src/compiler/binary/error.ts +25 -0
  181. package/src/compiler/binary/index.ts +4 -0
  182. package/src/compiler/binary/runtime.ts +133 -0
  183. package/src/compiler/binary/types.ts +26 -0
  184. package/src/compiler/feature-flags.ts +7 -0
  185. package/src/compiler/index.ts +114 -0
  186. package/src/compiler/ir-v2/canonical.ts +46 -0
  187. package/src/compiler/ir-v2/index.ts +9 -0
  188. package/src/compiler/ir-v2/parse.ts +921 -0
  189. package/src/compiler/ir-v2/strict-json.ts +129 -0
  190. package/src/compiler/ir-v2/types.ts +462 -0
  191. package/src/compiler/kvs/lowering.ts +88 -0
  192. package/src/compiler/manifest/error.ts +29 -0
  193. package/src/compiler/manifest/index.ts +17 -0
  194. package/src/compiler/manifest/operations.ts +175 -0
  195. package/src/compiler/manifest/parse.ts +390 -0
  196. package/src/compiler/manifest/registry.ts +74 -0
  197. package/src/compiler/manifest/resolve.ts +159 -0
  198. package/src/compiler/manifest/types.ts +112 -0
  199. package/src/compiler/named-body/index.ts +1 -0
  200. package/src/compiler/named-body/lowering.ts +186 -0
  201. package/src/compiler/pipeline/compiler.ts +138 -0
  202. package/src/compiler/pipeline/core-generator.ts +486 -0
  203. package/src/compiler/pipeline/index.ts +5 -0
  204. package/src/compiler/pipeline/registry.ts +18 -0
  205. package/src/compiler/pipeline/requirements.ts +139 -0
  206. package/src/compiler/pipeline/types.ts +59 -0
  207. package/src/compiler/runtime/error.ts +11 -0
  208. package/src/compiler/runtime/index.ts +1 -0
  209. package/src/compiler/structured-data/index.ts +3 -0
  210. package/src/compiler/structured-data/lowering.ts +314 -0
  211. package/src/compiler/structured-data/path.ts +53 -0
  212. package/src/compiler/structured-data/runtime.ts +221 -0
  213. package/src/compiler/turbowarp-v2.ts +610 -0
  214. package/src/compiler/validator/index.ts +4 -0
  215. package/src/compiler/validator/ir-validator.ts +812 -0
  216. package/src/compiler/validator/resource-lifetime.ts +153 -0
  217. package/src/compiler/validator/turbowarp-subset.ts +387 -0
  218. package/src/compiler/validator/types.ts +68 -0
  219. package/src/extension.ts +87 -1
  220. package/src/fixed-input-editors.ts +181 -0
  221. package/src/fixed-input-schema.ts +15 -0
  222. package/src/named-body.ts +495 -0
  223. package/src/named-data-namespace.ts +6 -0
  224. package/src/protocol.ts +50 -1
  225. package/src/resource-named-body-provider.ts +106 -0
  226. package/src/server.ts +88 -8
  227. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
  228. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
  229. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
  230. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
  231. package/docs/turbowarp-http-server.architecture.visual-check.html +0 -32
  232. package/docs/turbowarp-http-server.architecture.visual-check.json +0 -547
  233. package/schemas/extension-manifest.schema.json +0 -49
  234. package/src/extension-manifest.ts +0 -149
@@ -0,0 +1,159 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {lstat, readFile, realpath, stat} from 'node:fs/promises';
3
+ import {dirname, isAbsolute, relative, resolve, sep} from 'node:path';
4
+ import {CompilerManifestError} from './error.js';
5
+ import {
6
+ DEFAULT_COMPILER_MANIFEST_LIMITS,
7
+ parseCompilerExtensionManifestJson,
8
+ parseCompilerManifestLockJson,
9
+ type CompilerManifestLimits
10
+ } from './parse.js';
11
+ import {buildCompilerOpcodeRegistry} from './registry.js';
12
+ import type {
13
+ CompilerManifestLock,
14
+ CompilerOpcodeRegistry,
15
+ ResolvedCompilerManifest
16
+ } from './types.js';
17
+
18
+ export type BundledCompilerManifests = Readonly<Record<string, string | Uint8Array>>;
19
+
20
+ export interface ResolveCompilerManifestOptions {
21
+ bundled?: BundledCompilerManifests;
22
+ limits?: Readonly<CompilerManifestLimits>;
23
+ }
24
+
25
+ export interface ResolvedCompilerManifestLock {
26
+ lock: CompilerManifestLock;
27
+ manifests: readonly ResolvedCompilerManifest[];
28
+ registry: CompilerOpcodeRegistry;
29
+ }
30
+
31
+ export async function resolveCompilerManifestLock(
32
+ lockPath: string | undefined,
33
+ options: ResolveCompilerManifestOptions = {}
34
+ ): Promise<ResolvedCompilerManifestLock> {
35
+ if (lockPath === undefined || lockPath.length === 0) {
36
+ throw new CompilerManifestError(
37
+ 'TW2_MANIFEST_LOCK_REQUIRED',
38
+ 'IR v2 compilation with extension blocks requires an explicit manifest lock path.'
39
+ );
40
+ }
41
+ const limits = options.limits ?? DEFAULT_COMPILER_MANIFEST_LIMITS;
42
+ const absoluteLockPath = resolve(lockPath);
43
+ const lockBytes = await readLimitedFile(absoluteLockPath, limits.maxBytes, 'manifest lock');
44
+ const lock = parseCompilerManifestLockJson(decodeUtf8(lockBytes, 'manifest lock'), limits);
45
+ const lockDirectory = dirname(await realpathOrSourceError(absoluteLockPath));
46
+ const manifests: ResolvedCompilerManifest[] = [];
47
+ for (const entry of lock.extensions) {
48
+ const bytes =
49
+ entry.source.kind === 'bundled'
50
+ ? bundledBytes(entry.source.id, options.bundled)
51
+ : await readSafeLocalManifest(lockDirectory, entry.source.path, limits.maxBytes);
52
+ const exactIntegrity = manifestIntegrity(bytes);
53
+ if (exactIntegrity !== entry.integrity) {
54
+ throw new CompilerManifestError(
55
+ 'TW2_MANIFEST_INTEGRITY_MISMATCH',
56
+ `Manifest integrity mismatch for ${entry.extensionId}: expected ${entry.integrity}, received ${exactIntegrity}.`
57
+ );
58
+ }
59
+ const manifest = parseCompilerExtensionManifestJson(decodeUtf8(bytes, entry.extensionId), limits);
60
+ if (manifest.id !== entry.extensionId || manifest.formatVersion !== entry.manifestFormatVersion) {
61
+ throw new CompilerManifestError(
62
+ 'TW2_MANIFEST_LOCK_MISMATCH',
63
+ `Manifest ${entry.extensionId} does not match the extension ID and format version pinned by the lock.`
64
+ );
65
+ }
66
+ manifests.push({lock: entry, manifest, exactIntegrity});
67
+ }
68
+ manifests.sort((left, right) => lexicalCompare(left.manifest.id, right.manifest.id));
69
+ return {lock, manifests, registry: buildCompilerOpcodeRegistry(manifests)};
70
+ }
71
+
72
+ export function manifestIntegrity(bytes: string | Uint8Array): `sha256-${string}` {
73
+ return `sha256-${createHash('sha256').update(bytes).digest('base64')}`;
74
+ }
75
+
76
+ async function readSafeLocalManifest(root: string, sourcePath: string, maxBytes: number): Promise<Uint8Array> {
77
+ if (isAbsolute(sourcePath) || sourcePath.includes('\0')) unsafeSource(sourcePath, 'path must be relative');
78
+ const candidate = resolve(root, sourcePath);
79
+ assertContained(root, candidate, sourcePath);
80
+ const segments = relative(root, candidate).split(sep).filter((segment) => segment.length > 0);
81
+ let current = root;
82
+ for (const segment of segments) {
83
+ current = resolve(current, segment);
84
+ let info;
85
+ try {
86
+ info = await lstat(current);
87
+ } catch (error) {
88
+ sourceNotFound(sourcePath, error);
89
+ }
90
+ if (info.isSymbolicLink()) unsafeSource(sourcePath, `symbolic link component is not allowed: ${segment}`);
91
+ }
92
+ const resolvedCandidate = await realpathOrSourceError(candidate);
93
+ assertContained(root, resolvedCandidate, sourcePath);
94
+ return readLimitedFile(resolvedCandidate, maxBytes, `manifest ${sourcePath}`);
95
+ }
96
+
97
+ function bundledBytes(id: string, bundled: BundledCompilerManifests | undefined): Uint8Array {
98
+ const value = bundled?.[id];
99
+ if (value === undefined) {
100
+ throw new CompilerManifestError('TW2_MANIFEST_SOURCE_NOT_FOUND', `Bundled manifest is not registered: ${id}`);
101
+ }
102
+ return typeof value === 'string' ? Buffer.from(value, 'utf8') : value;
103
+ }
104
+
105
+ async function readLimitedFile(path: string, maxBytes: number, label: string): Promise<Uint8Array> {
106
+ let size: number;
107
+ try {
108
+ size = (await stat(path)).size;
109
+ } catch (error) {
110
+ sourceNotFound(path, error);
111
+ }
112
+ if (size > maxBytes) {
113
+ throw new CompilerManifestError('TW2_MANIFEST_TOO_LARGE', `${label} is ${size} bytes; limit is ${maxBytes}.`);
114
+ }
115
+ try {
116
+ return await readFile(path);
117
+ } catch (error) {
118
+ sourceNotFound(path, error);
119
+ }
120
+ }
121
+
122
+ function decodeUtf8(bytes: Uint8Array, label: string): string {
123
+ try {
124
+ return new TextDecoder('utf-8', {fatal: true}).decode(bytes);
125
+ } catch (error) {
126
+ throw new CompilerManifestError('TW2_MANIFEST_JSON_SYNTAX', `${label} is not valid UTF-8.`, error);
127
+ }
128
+ }
129
+
130
+ function assertContained(root: string, candidate: string, sourcePath: string): void {
131
+ const pathFromRoot = relative(root, candidate);
132
+ if (pathFromRoot === '..' || pathFromRoot.startsWith(`..${sep}`) || isAbsolute(pathFromRoot)) {
133
+ unsafeSource(sourcePath, 'path escapes the manifest lock directory');
134
+ }
135
+ }
136
+
137
+ async function realpathOrSourceError(path: string): Promise<string> {
138
+ try {
139
+ return await realpath(path);
140
+ } catch (error) {
141
+ sourceNotFound(path, error);
142
+ }
143
+ }
144
+
145
+ function unsafeSource(sourcePath: string, reason: string): never {
146
+ throw new CompilerManifestError('TW2_MANIFEST_SOURCE_UNSAFE', `Unsafe local manifest source ${sourcePath}: ${reason}.`);
147
+ }
148
+
149
+ function sourceNotFound(sourcePath: string, cause: unknown): never {
150
+ throw new CompilerManifestError(
151
+ 'TW2_MANIFEST_SOURCE_NOT_FOUND',
152
+ `Manifest source could not be read: ${sourcePath}`,
153
+ cause
154
+ );
155
+ }
156
+
157
+ function lexicalCompare(left: string, right: string): number {
158
+ return left < right ? -1 : left > right ? 1 : 0;
159
+ }
@@ -0,0 +1,112 @@
1
+ export const COMPILER_MANIFEST_FORMAT_VERSIONS = [1, 2] as const;
2
+ export const COMPILER_MANIFEST_LOCK_VERSION = 1 as const;
3
+
4
+ export type CompilerManifestFormatVersion = (typeof COMPILER_MANIFEST_FORMAT_VERSIONS)[number];
5
+
6
+ export type ManifestBlockType = 'COMMAND' | 'REPORTER' | 'BOOLEAN' | 'HAT' | 'LOOP';
7
+ export type ManifestArgumentType = 'STRING' | 'NUMBER' | 'BOOLEAN';
8
+ export type ManifestResultType =
9
+ | 'json'
10
+ | 'boolean'
11
+ | 'number'
12
+ | 'string'
13
+ | 'void'
14
+ /** A string whose content is serialized JSON or YAML, which 'string' alone would not record. */
15
+ | 'jsonText'
16
+ | 'yamlText';
17
+ export type ManifestEffect =
18
+ | 'pure'
19
+ | 'immutable'
20
+ | 'control'
21
+ | 'request-read'
22
+ | 'response-write'
23
+ | 'storage-read'
24
+ | 'storage-write'
25
+ | 'binary-read'
26
+ | 'binary-write'
27
+ /** Mutates extension-held data scoped to a target; storage-* means persistent storage instead. */
28
+ | 'state';
29
+
30
+ export interface CompilerManifestArgument {
31
+ id: string;
32
+ type: ManifestArgumentType;
33
+ menu?: string;
34
+ normalizesTo?: 'pathSegments';
35
+ staticLiteral?: boolean;
36
+ minimum?: number;
37
+ maximum?: number;
38
+ }
39
+
40
+ export interface CompilerManifestServerHint {
41
+ supported: boolean;
42
+ irOperation?: string;
43
+ }
44
+
45
+ export interface CompilerManifestBlock {
46
+ opcode: string;
47
+ blockType: ManifestBlockType;
48
+ arguments: CompilerManifestArgument[];
49
+ resultType?: ManifestResultType;
50
+ effect?: ManifestEffect;
51
+ immutable?: boolean;
52
+ errors?: string[];
53
+ server?: CompilerManifestServerHint;
54
+ }
55
+
56
+ export interface CompilerExtensionManifest {
57
+ formatVersion: CompilerManifestFormatVersion;
58
+ id: string;
59
+ blocks: CompilerManifestBlock[];
60
+ pathSegmentType?: {
61
+ kind: 'discriminatedUnion';
62
+ variants: [
63
+ {kind: 'key'; valueType: 'string'},
64
+ {kind: 'index'; valueType: 'nonNegativeInteger'}
65
+ ];
66
+ };
67
+ dataReferenceType?: {
68
+ kind: string;
69
+ scope: string;
70
+ lifetime: string;
71
+ valueType: string;
72
+ };
73
+ menus?: unknown[];
74
+ }
75
+
76
+ export type CompilerManifestSource =
77
+ | {kind: 'bundled'; id: string}
78
+ | {kind: 'local'; path: string};
79
+
80
+ export interface CompilerManifestLockEntry {
81
+ extensionId: string;
82
+ packageName: string;
83
+ packageVersion: string;
84
+ manifestFormatVersion: CompilerManifestFormatVersion;
85
+ integrity: `sha256-${string}`;
86
+ source: CompilerManifestSource;
87
+ }
88
+
89
+ export interface CompilerManifestLock {
90
+ lockVersion: typeof COMPILER_MANIFEST_LOCK_VERSION;
91
+ extensions: CompilerManifestLockEntry[];
92
+ }
93
+
94
+ export interface ResolvedCompilerManifest {
95
+ lock: CompilerManifestLockEntry;
96
+ manifest: CompilerExtensionManifest;
97
+ exactIntegrity: `sha256-${string}`;
98
+ }
99
+
100
+ export interface CompilerOpcodeRegistryEntry {
101
+ extensionId: string;
102
+ opcode: string;
103
+ projectOpcode: string;
104
+ packageName: string;
105
+ packageVersion: string;
106
+ block: CompilerManifestBlock;
107
+ }
108
+
109
+ export interface CompilerOpcodeRegistry {
110
+ entries: readonly CompilerOpcodeRegistryEntry[];
111
+ byProjectOpcode: ReadonlyMap<string, CompilerOpcodeRegistryEntry>;
112
+ }
@@ -0,0 +1 @@
1
+ export * from './lowering.js';
@@ -0,0 +1,186 @@
1
+ import {DEFAULT_MAX_BINARY_BYTES} from '../binary/types.js';
2
+ import {isNamedDataNamespace} from '../../named-data-namespace.js';
3
+ import type {
4
+ ExpressionIrV2,
5
+ NamedBodyRepresentationV2,
6
+ NamedDataKindV2,
7
+ NamedDataScopeV2,
8
+ SourceRefV2,
9
+ StatementIrV2
10
+ } from '../ir-v2/types.js';
11
+
12
+ export type NamedBodyLoweringDiagnosticCode =
13
+ | 'TW2_NAMED_DYNAMIC_DESCRIPTOR'
14
+ | 'TW2_NAMED_INVALID_DESCRIPTOR'
15
+ | 'TW2_NAMED_INVALID_MAX';
16
+
17
+ export interface NamedBodyLoweringDiagnostic {
18
+ severity: 'error';
19
+ code: NamedBodyLoweringDiagnosticCode;
20
+ message: string;
21
+ reason: string;
22
+ suggestion: string;
23
+ sourceRef: SourceRefV2;
24
+ }
25
+
26
+ export interface NamedBodyLoweringResult {
27
+ statement?: Extract<StatementIrV2, {kind: 'respond-named-body'}>;
28
+ diagnostics: NamedBodyLoweringDiagnostic[];
29
+ }
30
+
31
+ export type NamedBodyArguments = Readonly<Record<string, ExpressionIrV2>>;
32
+
33
+ const TARGET_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
34
+ const KINDS: readonly NamedDataKindV2[] = ['structured', 'document', 'binary', 'asset'];
35
+ const SCOPES: readonly NamedDataScopeV2[] = ['target', 'project'];
36
+ const REPRESENTATIONS: readonly NamedBodyRepresentationV2[] = ['json', 'yaml', 'html', 'markdown', 'raw'];
37
+
38
+ export function lowerNamedBodyResponse(
39
+ args: NamedBodyArguments,
40
+ sourceRef: SourceRefV2
41
+ ): NamedBodyLoweringResult {
42
+ const diagnostics: NamedBodyLoweringDiagnostic[] = [];
43
+ const namespace = literalString(args.NAMESPACE, 'NAMESPACE', sourceRef, diagnostics);
44
+ const name = literalString(args.NAME, 'NAME', sourceRef, diagnostics);
45
+ const kind = literalMember(args.KIND, 'KIND', KINDS, sourceRef, diagnostics);
46
+ const scope = literalMember(args.SCOPE, 'SCOPE', SCOPES, sourceRef, diagnostics);
47
+ const representation = literalMember(
48
+ args.REPRESENTATION,
49
+ 'REPRESENTATION',
50
+ REPRESENTATIONS,
51
+ sourceRef,
52
+ diagnostics
53
+ );
54
+ const maxBytes = literalMaximum(args.MAX_BYTES, sourceRef, diagnostics);
55
+ if (
56
+ namespace === undefined ||
57
+ name === undefined ||
58
+ kind === undefined ||
59
+ scope === undefined ||
60
+ representation === undefined ||
61
+ maxBytes === undefined
62
+ ) {
63
+ return {diagnostics};
64
+ }
65
+ if (!isNamedDataNamespace(namespace) || name.length < 1 || name.length > 256 || hasControlCharacter(name)) {
66
+ report(
67
+ diagnostics,
68
+ 'TW2_NAMED_INVALID_DESCRIPTOR',
69
+ 'Named response namespace or name is invalid.',
70
+ 'The canonical descriptor requires a safe logical namespace and a bounded non-control name.',
71
+ 'Use a canonical namespace such as asset and a name from 1 to 256 characters.',
72
+ sourceRef
73
+ );
74
+ return {diagnostics};
75
+ }
76
+
77
+ let targetId: string | undefined;
78
+ if (scope === 'target') {
79
+ targetId = literalString(args.TARGET_ID, 'TARGET_ID', sourceRef, diagnostics);
80
+ if (targetId === undefined) return {diagnostics};
81
+ if (!TARGET_ID.test(targetId)) {
82
+ report(
83
+ diagnostics,
84
+ 'TW2_NAMED_INVALID_DESCRIPTOR',
85
+ 'Target-scoped named response has an invalid target ID.',
86
+ 'Target scope requires a stable runtime-local identity.',
87
+ 'Use a non-empty target ID containing only letters, digits, dot, underscore, colon, or hyphen.',
88
+ inputSource(sourceRef, 'TARGET_ID')
89
+ );
90
+ return {diagnostics};
91
+ }
92
+ }
93
+
94
+ return {
95
+ statement: {
96
+ kind: 'respond-named-body',
97
+ reference: {namespace, name, kind, scope},
98
+ representation,
99
+ ...(targetId === undefined ? {} : {targetId}),
100
+ maxBytes,
101
+ sourceRef
102
+ },
103
+ diagnostics
104
+ };
105
+ }
106
+
107
+ function literalString(
108
+ expression: ExpressionIrV2 | undefined,
109
+ input: string,
110
+ sourceRef: SourceRefV2,
111
+ diagnostics: NamedBodyLoweringDiagnostic[]
112
+ ): string | undefined {
113
+ if (expression?.kind === 'literal' && expression.valueType === 'string' && typeof expression.value === 'string') {
114
+ return expression.value;
115
+ }
116
+ report(
117
+ diagnostics,
118
+ 'TW2_NAMED_DYNAMIC_DESCRIPTOR',
119
+ `Named response ${input} must be a compile-time string literal.`,
120
+ 'Static descriptors are required to validate provider capability and scope before generation.',
121
+ 'Replace the input with a literal value.',
122
+ inputSource(sourceRef, input)
123
+ );
124
+ }
125
+
126
+ function literalMember<T extends string>(
127
+ expression: ExpressionIrV2 | undefined,
128
+ input: string,
129
+ values: readonly T[],
130
+ sourceRef: SourceRefV2,
131
+ diagnostics: NamedBodyLoweringDiagnostic[]
132
+ ): T | undefined {
133
+ const value = literalString(expression, input, sourceRef, diagnostics);
134
+ if (value === undefined) return undefined;
135
+ const normalized = value.toLowerCase();
136
+ if (values.includes(normalized as T)) return normalized as T;
137
+ report(
138
+ diagnostics,
139
+ 'TW2_NAMED_INVALID_DESCRIPTOR',
140
+ `Named response ${input} is not supported.`,
141
+ `Accepted values are: ${values.join(', ')}.`,
142
+ 'Use one of the canonical descriptor values.',
143
+ inputSource(sourceRef, input)
144
+ );
145
+ }
146
+
147
+ function literalMaximum(
148
+ expression: ExpressionIrV2 | undefined,
149
+ sourceRef: SourceRefV2,
150
+ diagnostics: NamedBodyLoweringDiagnostic[]
151
+ ): number | undefined {
152
+ const value = expression?.kind === 'literal' && expression.valueType === 'number' ? expression.value : undefined;
153
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= DEFAULT_MAX_BINARY_BYTES) {
154
+ return value;
155
+ }
156
+ report(
157
+ diagnostics,
158
+ 'TW2_NAMED_INVALID_MAX',
159
+ `Named response MAX_BYTES must be an integer literal from 1 to ${DEFAULT_MAX_BINARY_BYTES}.`,
160
+ 'A static byte bound is required for target planning and runtime enforcement.',
161
+ 'Use a numeric literal within the compiler-wide binary limit.',
162
+ inputSource(sourceRef, 'MAX_BYTES')
163
+ );
164
+ }
165
+
166
+ function hasControlCharacter(value: string): boolean {
167
+ return [...value].some((character) => {
168
+ const point = character.codePointAt(0)!;
169
+ return point <= 0x1f || point === 0x7f;
170
+ });
171
+ }
172
+
173
+ function inputSource(sourceRef: SourceRefV2, input: string): SourceRefV2 {
174
+ return {...sourceRef, input};
175
+ }
176
+
177
+ function report(
178
+ diagnostics: NamedBodyLoweringDiagnostic[],
179
+ code: NamedBodyLoweringDiagnosticCode,
180
+ message: string,
181
+ reason: string,
182
+ suggestion: string,
183
+ sourceRef: SourceRefV2
184
+ ): void {
185
+ diagnostics.push({severity: 'error', code, message, reason, suggestion, sourceRef});
186
+ }
@@ -0,0 +1,138 @@
1
+ import {cloudflareWorkersAdapter} from '../adapters/cloudflare.js';
2
+ import {firebaseFunctionsAdapter} from '../adapters/firebase.js';
3
+ import {DEFAULT_COMPILER_FEATURE_FLAGS, type CompilerFeatureFlags} from '../feature-flags.js';
4
+ import type {DeployIrV2, StatementIrV2} from '../ir-v2/types.js';
5
+ import {validateDeployIrV2Subset} from '../validator/ir-validator.js';
6
+ import {generateHonoCore} from './core-generator.js';
7
+ import {PlatformAdapterRegistry} from './registry.js';
8
+ import {extractCapabilityRequirements} from './requirements.js';
9
+ import type {
10
+ GeneratedProject,
11
+ GeneratorOutputManifest,
12
+ PipelineDiagnostic,
13
+ PlatformAdapter
14
+ } from './types.js';
15
+
16
+ export interface CompileDeployIrV2Options {
17
+ target: string;
18
+ targetConfig?: unknown;
19
+ adapters?: readonly PlatformAdapter[];
20
+ featureFlags?: Partial<CompilerFeatureFlags>;
21
+ }
22
+
23
+ export type CompileDeployIrV2Result =
24
+ | {ok: true; files: GeneratedProject; manifest: GeneratorOutputManifest}
25
+ | {ok: false; diagnostics: PipelineDiagnostic[]};
26
+
27
+ export function compileDeployIrV2(
28
+ ir: DeployIrV2,
29
+ options: CompileDeployIrV2Options
30
+ ): CompileDeployIrV2Result {
31
+ const featureFlags: CompilerFeatureFlags = {
32
+ ...DEFAULT_COMPILER_FEATURE_FLAGS,
33
+ ...options.featureFlags
34
+ };
35
+ const targetNeutral = validateDeployIrV2Subset(ir, undefined, featureFlags);
36
+ if (targetNeutral.length > 0) return {ok: false, diagnostics: targetNeutral};
37
+
38
+ const registry = new PlatformAdapterRegistry();
39
+ for (const adapter of options.adapters ?? [cloudflareWorkersAdapter, firebaseFunctionsAdapter]) {
40
+ registry.register(adapter);
41
+ }
42
+ const adapter = registry.resolve(options.target);
43
+ if (adapter === undefined) {
44
+ return {
45
+ ok: false,
46
+ diagnostics: [
47
+ {
48
+ severity: 'error',
49
+ code: 'TW2_UNKNOWN_TARGET',
50
+ message: `Target ${options.target} is not registered.`,
51
+ reason: 'IR v2 never guesses a deployment target.',
52
+ suggestion: `Choose one of: ${registry.ids().join(', ') || '<none>'}.`,
53
+ targetId: options.target
54
+ }
55
+ ]
56
+ };
57
+ }
58
+ const targetLimitDiagnostics = validateTargetBinaryLimits(ir, adapter);
59
+ if (targetLimitDiagnostics.length > 0) return {ok: false, diagnostics: targetLimitDiagnostics};
60
+ const requirements = extractCapabilityRequirements(ir);
61
+ const planned = adapter.plan({ir, requirements, config: options.targetConfig});
62
+ if (!planned.ok) return planned;
63
+ const core = generateHonoCore(ir);
64
+ const generated = normalizeGeneratedProject(adapter.generate({ir, plan: planned.plan, core}));
65
+ const filePath = 'turbowarp-server.generated.json';
66
+ const fileNames = [...Object.keys(generated), filePath].sort();
67
+ const manifest: GeneratorOutputManifest = {
68
+ formatVersion: 1,
69
+ irVersion: 2,
70
+ adapter: {id: adapter.id, version: adapter.version},
71
+ requirements: requirements.keys,
72
+ plan: {
73
+ requirements: [...planned.plan.requirements].sort(),
74
+ bindings: Object.fromEntries(
75
+ Object.entries(planned.plan.bindings).sort(([left], [right]) =>
76
+ left < right ? -1 : left > right ? 1 : 0
77
+ )
78
+ )
79
+ },
80
+ files: fileNames
81
+ };
82
+ const files = normalizeGeneratedProject({
83
+ ...generated,
84
+ [filePath]: `${JSON.stringify(manifest, null, 2)}\n`
85
+ });
86
+ return {ok: true, files, manifest};
87
+ }
88
+
89
+ function validateTargetBinaryLimits(ir: DeployIrV2, adapter: PlatformAdapter): PipelineDiagnostic[] {
90
+ const maximum = adapter.capabilities().maxBinaryBytes;
91
+ if (maximum === undefined) return [];
92
+ const diagnostics: PipelineDiagnostic[] = [];
93
+ for (const route of ir.routes) visitStatements(route.body, route.id, maximum, adapter.id, diagnostics);
94
+ return diagnostics;
95
+ }
96
+
97
+ function visitStatements(
98
+ statements: readonly StatementIrV2[],
99
+ routeId: string,
100
+ maximum: number,
101
+ targetId: string,
102
+ diagnostics: PipelineDiagnostic[]
103
+ ): void {
104
+ for (const statement of statements) {
105
+ if (
106
+ (statement.kind === 'request-body-binary' ||
107
+ statement.kind === 'asset-object-get' ||
108
+ statement.kind === 'asset-object-put' ||
109
+ statement.kind === 'respond-named-body') &&
110
+ statement.maxBytes > maximum
111
+ ) {
112
+ diagnostics.push({
113
+ severity: 'error',
114
+ code: 'TW2_TARGET_BINARY_LIMIT_EXCEEDED',
115
+ message: `Binary limit ${statement.maxBytes} exceeds the ${targetId} target limit ${maximum}.`,
116
+ reason: 'The selected platform cannot safely satisfy this binary operation limit.',
117
+ suggestion: `Set maxBytes to ${maximum} or less, or choose a target with a larger declared limit.`,
118
+ targetId,
119
+ routeId,
120
+ ...(statement.sourceRef === undefined ? {} : {sourceRef: statement.sourceRef})
121
+ });
122
+ }
123
+ if (statement.kind === 'if') {
124
+ visitStatements(statement.then, routeId, maximum, targetId, diagnostics);
125
+ visitStatements(statement.else ?? [], routeId, maximum, targetId, diagnostics);
126
+ } else if (statement.kind === 'bounded-loop' || statement.kind === 'json-for-each') {
127
+ visitStatements(statement.body, routeId, maximum, targetId, diagnostics);
128
+ }
129
+ }
130
+ }
131
+
132
+ function normalizeGeneratedProject(files: GeneratedProject): GeneratedProject {
133
+ return Object.fromEntries(
134
+ Object.entries(files)
135
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
136
+ .map(([path, source]) => [path, `${source.replace(/\r\n?/gu, '\n').replace(/\n*$/u, '')}\n`])
137
+ );
138
+ }