@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,510 @@
1
+ import type {DeployIrV2} from '../ir-v2/types.js';
2
+ import type {
3
+ PipelineDiagnostic,
4
+ PlatformAdapter,
5
+ PlatformPlan
6
+ } from '../pipeline/types.js';
7
+ import {findCapabilityOrigin} from '../pipeline/requirements.js';
8
+
9
+ export const cloudflareWorkersAdapter: PlatformAdapter = {
10
+ id: 'cloudflare-workers',
11
+ version: '1.5.0',
12
+ capabilities: () => ({
13
+ keys: [
14
+ 'auth:external-jwt',
15
+ 'auth:trusted-access-jwt',
16
+ 'key-value-store',
17
+ 'object-storage',
18
+ 'record-store',
19
+ 'request-metadata:client-address',
20
+ 'streaming-body'
21
+ ],
22
+ maxBinaryBytes: 16 * 1024 * 1024
23
+ }),
24
+ plan({ir, requirements, config}) {
25
+ const unsupported = requirements.keys.filter(
26
+ (requirement) => !cloudflareWorkersAdapter.capabilities().keys.includes(requirement)
27
+ );
28
+ if (unsupported.length > 0) {
29
+ return {
30
+ ok: false,
31
+ diagnostics: unsupported.map((requirement) => capabilityDiagnostic(requirement, ir))
32
+ };
33
+ }
34
+ const parsed = parseConfig(config);
35
+ if ('diagnostic' in parsed) return {ok: false, diagnostics: [parsed.diagnostic]};
36
+ return {
37
+ ok: true,
38
+ plan: {
39
+ targetId: cloudflareWorkersAdapter.id,
40
+ adapterVersion: cloudflareWorkersAdapter.version,
41
+ requirements: requirements.keys,
42
+ bindings: {
43
+ ...(
44
+ requirements.keys.includes('record-store') || requirements.keys.includes('key-value-store')
45
+ ? {recordDatabase: parsed.recordDatabaseBinding}
46
+ : {}
47
+ ),
48
+ ...(requirements.keys.includes('object-storage') ? {objectBucket: parsed.objectBucketBinding} : {})
49
+ }
50
+ }
51
+ };
52
+ },
53
+ generate({ir, plan, core}) {
54
+ return {
55
+ ...core.files,
56
+ 'package.json': packageJson(ir),
57
+ 'tsconfig.json': tsconfig(),
58
+ 'src/index.ts': indexSource(ir, plan),
59
+ 'src/platform.ts': platformSource(),
60
+ ...(authScheme(ir) === undefined ? {} : {'src/auth.ts': authSource()}),
61
+ 'wrangler.jsonc': wrangler(ir, plan),
62
+ ...(plan.bindings.recordDatabase === undefined ? {} : {'migrations/0001_init.sql': migration(plan)}),
63
+ 'README.md': generatedReadme(ir, plan)
64
+ };
65
+ }
66
+ };
67
+
68
+ function parseConfig(config: unknown):
69
+ | {recordDatabaseBinding: string; objectBucketBinding: string}
70
+ | {diagnostic: PipelineDiagnostic} {
71
+ if (config === undefined || config === null) return {recordDatabaseBinding: 'DB', objectBucketBinding: 'OBJECTS'};
72
+ if (typeof config !== 'object' || Array.isArray(config)) return {diagnostic: configDiagnostic()};
73
+ const record = config as Record<string, unknown>;
74
+ if (Object.keys(record).some((key) => key !== 'recordDatabaseBinding' && key !== 'objectBucketBinding')) {
75
+ return {diagnostic: configDiagnostic()};
76
+ }
77
+ const recordDatabaseBinding = record.recordDatabaseBinding ?? 'DB';
78
+ const objectBucketBinding = record.objectBucketBinding ?? 'OBJECTS';
79
+ if (
80
+ typeof recordDatabaseBinding !== 'string' ||
81
+ typeof objectBucketBinding !== 'string' ||
82
+ !/^[A-Z][A-Z0-9_]*$/u.test(recordDatabaseBinding) ||
83
+ !/^[A-Z][A-Z0-9_]*$/u.test(objectBucketBinding) ||
84
+ recordDatabaseBinding === objectBucketBinding
85
+ ) {
86
+ return {diagnostic: configDiagnostic()};
87
+ }
88
+ return {recordDatabaseBinding, objectBucketBinding};
89
+ }
90
+
91
+ function capabilityDiagnostic(requirement: string, ir: DeployIrV2): PipelineDiagnostic {
92
+ const origin = findCapabilityOrigin(ir, requirement);
93
+ return {
94
+ severity: 'error',
95
+ code: 'TW2_TARGET_CAPABILITY_UNSUPPORTED',
96
+ message: `Target cloudflare-workers does not support capability ${requirement}.`,
97
+ reason: 'The selected adapter cannot satisfy a target-neutral IR requirement.',
98
+ suggestion: 'Choose a registered capable target or remove the requiring operation.',
99
+ targetId: 'cloudflare-workers',
100
+ ...(origin === undefined ? {} : {routeId: origin.routeId}),
101
+ ...(origin?.sourceRef === undefined ? {} : {sourceRef: origin.sourceRef})
102
+ };
103
+ }
104
+
105
+ function configDiagnostic(): PipelineDiagnostic {
106
+ return {
107
+ severity: 'error',
108
+ code: 'TW2_TARGET_CONFIG_INVALID',
109
+ message: 'Cloudflare target config is invalid.',
110
+ reason: 'Only distinct, non-secret D1 and R2 binding identifiers are accepted.',
111
+ suggestion: 'Use {"recordDatabaseBinding":"DB","objectBucketBinding":"OBJECTS"}.',
112
+ targetId: 'cloudflare-workers'
113
+ };
114
+ }
115
+
116
+ function indexSource(ir: DeployIrV2, plan: PlatformPlan): string {
117
+ const recordBinding = plan.bindings.recordDatabase;
118
+ const objectBinding = plan.bindings.objectBucket;
119
+ const selectedAuthScheme = authScheme(ir);
120
+ const bindingMembers = [
121
+ ...(recordBinding === undefined ? [] : [`${recordBinding}: D1Database`]),
122
+ ...(objectBinding === undefined ? [] : [`${objectBinding}: R2Bucket`]),
123
+ ...(selectedAuthScheme === 'trusted-access-jwt'
124
+ ? ['CF_ACCESS_TEAM_DOMAIN: string', 'CF_ACCESS_AUD: string']
125
+ : selectedAuthScheme === 'external-jwt'
126
+ ? ['JWT_ISSUER: string', 'JWT_AUDIENCE: string', 'JWT_JWKS_URL: string']
127
+ : [])
128
+ ].join('; ');
129
+ const services = [
130
+ ...(selectedAuthScheme === undefined
131
+ ? []
132
+ : [`authenticate: (context) => {
133
+ const current = context as {req: {raw: Request}; env: Bindings};
134
+ return authenticateRequest(current.req.raw, current.env, '${selectedAuthScheme}');
135
+ }`]),
136
+ ...(recordBinding === undefined || !plan.requirements.includes('record-store')
137
+ ? []
138
+ : [`records: (context) => createRecordStore((context as {env: Bindings}).env.${recordBinding})`]),
139
+ ...(recordBinding === undefined || !plan.requirements.includes('key-value-store')
140
+ ? []
141
+ : [`keyValues: (context) => createKeyValueStore((context as {env: Bindings}).env.${recordBinding})`]),
142
+ ...(objectBinding === undefined
143
+ ? []
144
+ : [`objects: (context) => createObjectStore((context as {env: Bindings}).env.${objectBinding})`]),
145
+ "clientAddress: (context) => (context as {req: {header(name: string): string | undefined}}).req.header('cf-connecting-ip') ?? ''"
146
+ ].join(',\n ');
147
+ return `import {Hono} from 'hono';
148
+ import {registerCoreRoutes} from './core.generated.js';
149
+ import {createKeyValueStore, createObjectStore, createRecordStore} from './platform.js';
150
+ ${selectedAuthScheme === undefined ? '' : "import {authenticateRequest} from './auth.js';"}
151
+
152
+ type Bindings = {${bindingMembers}};
153
+ const app = new Hono<{Bindings: Bindings}>();
154
+ registerCoreRoutes(app, {
155
+ ${services}
156
+ });
157
+ export default app;
158
+ `;
159
+ }
160
+
161
+ function authScheme(ir: DeployIrV2): 'external-jwt' | 'trusted-access-jwt' | undefined {
162
+ return ir.auth.kind === 'jwt' ? ir.auth.scheme : undefined;
163
+ }
164
+
165
+ function authSource(): string {
166
+ return `import {createRemoteJWKSet, jwtVerify} from 'jose';
167
+ import type {AuthIdentity, AuthScheme} from './core.generated.js';
168
+
169
+ type AuthEnv = {
170
+ CF_ACCESS_TEAM_DOMAIN?: string;
171
+ CF_ACCESS_AUD?: string;
172
+ JWT_ISSUER?: string;
173
+ JWT_AUDIENCE?: string;
174
+ JWT_JWKS_URL?: string;
175
+ };
176
+
177
+ export async function authenticateRequest(
178
+ request: Request,
179
+ env: AuthEnv,
180
+ scheme: AuthScheme
181
+ ): Promise<AuthIdentity | null> {
182
+ const token = scheme === 'trusted-access-jwt'
183
+ ? request.headers.get('cf-access-jwt-assertion')
184
+ : bearerToken(request.headers.get('authorization'));
185
+ if (token === null) return null;
186
+ const issuer = scheme === 'trusted-access-jwt'
187
+ ? optional(env.CF_ACCESS_TEAM_DOMAIN)?.replace(/\\/$/u, '')
188
+ : optional(env.JWT_ISSUER);
189
+ const audience = scheme === 'trusted-access-jwt'
190
+ ? optional(env.CF_ACCESS_AUD)
191
+ : optional(env.JWT_AUDIENCE);
192
+ const jwksText = scheme === 'trusted-access-jwt'
193
+ ? issuer === undefined ? undefined : new URL('/cdn-cgi/access/certs', issuer).href
194
+ : optional(env.JWT_JWKS_URL);
195
+ if (issuer === undefined || audience === undefined || jwksText === undefined) return null;
196
+ try {
197
+ const {payload} = await jwtVerify(token, createRemoteJWKSet(new URL(jwksText)), {issuer, audience});
198
+ return typeof payload.sub === 'string' ? {id: payload.sub, claims: {...payload}} : null;
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
204
+ function bearerToken(value: string | null): string | null {
205
+ const match = value?.match(/^Bearer\\s+(.+)$/iu);
206
+ return match?.[1] ?? null;
207
+ }
208
+
209
+ function optional(value: string | undefined): string | undefined {
210
+ return value === undefined || value.length === 0 ? undefined : value;
211
+ }
212
+ `;
213
+ }
214
+
215
+ function platformSource(): string {
216
+ return `import type {BinaryBodySource, BinaryLocator, BinaryMetadata, BinaryObjectStore, BinaryRef, KeyValueStore, RecordStore} from './core.generated.js';
217
+
218
+ type RecordRow = {id: string; collection: string; data_json: string; created_at: string; updated_at: string};
219
+ export function createRecordStore(database: D1Database): RecordStore {
220
+ return {
221
+ async create(collection, data) {
222
+ const id = crypto.randomUUID();
223
+ const now = new Date().toISOString();
224
+ await database.prepare('INSERT INTO records (id, collection, data_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').bind(id, collection, JSON.stringify(data), now, now).run();
225
+ return {id, collection, data, createdAt: now, updatedAt: now};
226
+ },
227
+ async list(collection) {
228
+ const result = await database.prepare('SELECT id, collection, data_json, created_at, updated_at FROM records WHERE collection = ? ORDER BY created_at DESC LIMIT 100').bind(collection).all<RecordRow>();
229
+ return result.results.map(fromRow);
230
+ },
231
+ async get(id) {
232
+ const row = await database.prepare('SELECT id, collection, data_json, created_at, updated_at FROM records WHERE id = ?').bind(id).first<RecordRow>();
233
+ return row ? fromRow(row) : null;
234
+ },
235
+ async delete(id) {
236
+ const result = await database.prepare('DELETE FROM records WHERE id = ?').bind(id).run();
237
+ return result.meta.changes > 0;
238
+ }
239
+ };
240
+ }
241
+ function fromRow(row: RecordRow): Record<string, unknown> {
242
+ return {id: row.id, collection: row.collection, data: JSON.parse(row.data_json), createdAt: row.created_at, updatedAt: row.updated_at};
243
+ }
244
+
245
+ export function createKeyValueStore(database: D1Database): KeyValueStore {
246
+ return {
247
+ async set(namespace, key, value) {
248
+ const locator = kvsLocator(namespace, key);
249
+ await kvsStorage(() => database.prepare('INSERT INTO kvs (namespace, key, value_text, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(namespace, key) DO UPDATE SET value_text = excluded.value_text, updated_at = excluded.updated_at').bind(locator.namespace, locator.key, value, new Date().toISOString()).run());
250
+ },
251
+ async get(namespace, key) {
252
+ const locator = kvsLocator(namespace, key);
253
+ const row = await kvsStorage(() => database.prepare('SELECT value_text FROM kvs WHERE namespace = ? AND key = ?').bind(locator.namespace, locator.key).first<{value_text: string}>());
254
+ return row?.value_text ?? null;
255
+ },
256
+ async has(namespace, key) {
257
+ const locator = kvsLocator(namespace, key);
258
+ return await kvsStorage(() => database.prepare('SELECT 1 AS present FROM kvs WHERE namespace = ? AND key = ?').bind(locator.namespace, locator.key).first()) !== null;
259
+ },
260
+ async delete(namespace, key) {
261
+ const locator = kvsLocator(namespace, key);
262
+ const result = await kvsStorage(() => database.prepare('DELETE FROM kvs WHERE namespace = ? AND key = ?').bind(locator.namespace, locator.key).run());
263
+ return result.meta.changes > 0;
264
+ },
265
+ async list(namespace) {
266
+ const locator = kvsLocator(namespace, 'placeholder');
267
+ const result = await kvsStorage(() => database.prepare('SELECT key FROM kvs WHERE namespace = ? ORDER BY key ASC').bind(locator.namespace).all<{key: string}>());
268
+ return result.results.map((row) => row.key);
269
+ }
270
+ };
271
+ }
272
+ function kvsLocator(namespaceValue: string, keyValue: string): {namespace: string; key: string} {
273
+ const namespace = namespaceValue.normalize('NFC');
274
+ const key = keyValue.normalize('NFC');
275
+ if (!/^[a-z][a-z0-9.-]{0,63}$/u.test(namespace)) throw Object.assign(new Error('KVS_NAMESPACE_INVALID'), {code: 'KVS_NAMESPACE_INVALID'});
276
+ if (key.length === 0 || key.length > 512 || key.includes('\\0') || key.split('/').some((part) => part === '.' || part === '..')) throw Object.assign(new Error('KVS_KEY_INVALID'), {code: 'KVS_KEY_INVALID'});
277
+ return {namespace, key};
278
+ }
279
+ async function kvsStorage<T>(operation: () => Promise<T>): Promise<T> {
280
+ try {return await operation();}
281
+ catch (error) {if (isKvsFault(error)) throw error; throw Object.assign(new Error('KVS_STORAGE_FAILURE'), {code: 'KVS_STORAGE_FAILURE'});}
282
+ }
283
+ function isKvsFault(error: unknown): error is Error & {code: string} {return error instanceof Error && 'code' in error && typeof error.code === 'string' && error.code.startsWith('KVS_')}
284
+
285
+ export function createObjectStore(bucket: R2Bucket): BinaryObjectStore {
286
+ return {
287
+ async resolve(locator) {
288
+ try {
289
+ const object = await bucket.head(storageKey(locator));
290
+ return object === null || isTombstone(object) ? null : objectRef(locator, object);
291
+ } catch (error) {if (isBinaryFault(error)) throw error; throw binaryFault('BINARY_STORAGE_FAILURE')}
292
+ },
293
+ async get(ref) {
294
+ try {
295
+ const key = storageKey(ref);
296
+ let object: R2ObjectBody | R2Object | null;
297
+ let expected: R2Revision | undefined;
298
+ if (ref.revision === undefined) {
299
+ object = await bucket.get(key);
300
+ } else {
301
+ expected = parseR2Revision(ref.revision);
302
+ if (expected === undefined) return null;
303
+ object = await bucket.get(key, {onlyIf: revisionCondition(expected)});
304
+ }
305
+ if (object === null || !hasR2Body(object) || isTombstone(object)) return null;
306
+ if (expected !== undefined && !matchesRevision(object, expected)) return null;
307
+ return {
308
+ chunks: readableChunks(object.body),
309
+ size: object.size,
310
+ ...(object.httpMetadata?.contentType === undefined ? {} : {contentType: object.httpMetadata.contentType})
311
+ };
312
+ } catch (error) {if (isBinaryFault(error)) throw error; throw binaryFault('BINARY_STORAGE_FAILURE')}
313
+ },
314
+ async put(locator, source, metadata, maxBytes) {
315
+ try {
316
+ if (source.size !== undefined && source.size > maxBytes) throw binaryFault('BINARY_TOO_LARGE');
317
+ const body = await collectBytes(source.chunks, maxBytes);
318
+ if (metadata.size !== undefined && metadata.size !== body.byteLength) throw binaryFault('BINARY_INTEGRITY_MISMATCH');
319
+ const integrity = metadata.integrity?.startsWith('sha256:') === true ? metadata.integrity.slice(7) : undefined;
320
+ const object = await bucket.put(storageKey(locator), body, {
321
+ ...(metadata.contentType === undefined ? {} : {httpMetadata: {contentType: metadata.contentType}}),
322
+ ...(metadata.integrity === undefined ? {} : {customMetadata: {twIntegrity: metadata.integrity}}),
323
+ ...(integrity === undefined ? {} : {sha256: integrity})
324
+ });
325
+ if (object === null) throw binaryFault('BINARY_STORAGE_FAILURE');
326
+ return objectRef(locator, object);
327
+ } catch (error) {
328
+ if (isBinaryFault(error)) throw error;
329
+ throw binaryFault(metadata.integrity !== undefined && isR2BadDigest(error) ? 'BINARY_INTEGRITY_MISMATCH' : 'BINARY_STORAGE_FAILURE');
330
+ }
331
+ },
332
+ async delete(target) {
333
+ try {
334
+ const key = storageKey(target);
335
+ if ('revision' in target && target.revision !== undefined) {
336
+ const expected = parseR2Revision(target.revision);
337
+ if (expected === undefined) return false;
338
+ const current = await bucket.head(key);
339
+ if (current === null || isTombstone(current) || !matchesRevision(current, expected)) return false;
340
+ return putTombstone(bucket, key, current);
341
+ }
342
+ for (let attempt = 0; attempt < 8; attempt += 1) {
343
+ const current = await bucket.head(key);
344
+ if (current === null || isTombstone(current)) return false;
345
+ if (await putTombstone(bucket, key, current)) return true;
346
+ }
347
+ throw binaryFault('BINARY_STORAGE_FAILURE');
348
+ } catch (error) {if (isBinaryFault(error)) throw error; throw binaryFault('BINARY_STORAGE_FAILURE')}
349
+ }
350
+ };
351
+ }
352
+ function storageKey(locator: BinaryLocator): string {
353
+ if (!/^[a-z][a-z0-9.-]{0,63}$/u.test(locator.namespace) || locator.key.length > 512 || locator.key.includes('\\0') || locator.key.startsWith('/') || locator.key.includes('\\\\') || locator.key.split('/').some((part) => part.length === 0 || part === '.' || part === '..')) {
354
+ throw binaryFault('BINARY_INVALID_REF');
355
+ }
356
+ return 'v1/' + locator.namespace + '/' + locator.key;
357
+ }
358
+ function objectRef(locator: BinaryLocator, object: R2Object): BinaryRef {
359
+ const integrity = object.customMetadata?.twIntegrity;
360
+ const contentType = object.httpMetadata?.contentType;
361
+ return {
362
+ ...locator,
363
+ size: object.size,
364
+ revision: encodeR2Revision(object),
365
+ ...(contentType === undefined ? {} : {contentType}),
366
+ ...(integrity === undefined ? {} : {integrity})
367
+ };
368
+ }
369
+ interface R2Revision {version: string; etag: string; uploaded: number}
370
+ function isTombstone(object: R2Object): boolean {return object.customMetadata?.twDeleted === '1'}
371
+ function encodeR2Revision(object: R2Object): string {
372
+ const revision = 'r2:' + JSON.stringify([object.version, object.etag, object.uploaded.getTime()]);
373
+ if (revision.length > 256) throw binaryFault('BINARY_STORAGE_FAILURE');
374
+ return revision;
375
+ }
376
+ function parseR2Revision(value: string): R2Revision | undefined {
377
+ if (!value.startsWith('r2:')) return undefined;
378
+ try {
379
+ const parsed: unknown = JSON.parse(value.slice(3));
380
+ if (!Array.isArray(parsed) || parsed.length !== 3 || typeof parsed[0] !== 'string' || parsed[0].length === 0 || typeof parsed[1] !== 'string' || parsed[1].length === 0 || typeof parsed[2] !== 'number' || !Number.isSafeInteger(parsed[2]) || new Date(parsed[2] - 1).getTime() !== parsed[2] - 1 || new Date(parsed[2]).getTime() !== parsed[2] || new Date(parsed[2] + 1).getTime() !== parsed[2] + 1) return undefined;
381
+ return {version: parsed[0], etag: parsed[1], uploaded: parsed[2]};
382
+ } catch {return undefined}
383
+ }
384
+ function matchesRevision(object: R2Object, revision: R2Revision): boolean {
385
+ return object.version === revision.version && object.etag === revision.etag && object.uploaded.getTime() === revision.uploaded;
386
+ }
387
+ function revisionCondition(revision: R2Revision): R2Conditional {
388
+ return {
389
+ etagMatches: revision.etag,
390
+ uploadedAfter: new Date(revision.uploaded - 1),
391
+ uploadedBefore: new Date(revision.uploaded + 1)
392
+ };
393
+ }
394
+ async function putTombstone(bucket: R2Bucket, key: string, current: R2Object): Promise<boolean> {
395
+ const revision = {version: current.version, etag: current.etag, uploaded: current.uploaded.getTime()};
396
+ return await bucket.put(key, new Uint8Array(), {
397
+ onlyIf: revisionCondition(revision),
398
+ customMetadata: {twDeleted: '1'}
399
+ }) !== null;
400
+ }
401
+ function hasR2Body(object: R2Object): object is R2ObjectBody {return 'body' in object}
402
+ async function* readableChunks(stream: ReadableStream<Uint8Array>): AsyncIterable<Uint8Array> {
403
+ const reader = stream.getReader();
404
+ try {while (true) {const item = await reader.read(); if (item.done) return; yield item.value;}}
405
+ finally {reader.releaseLock()}
406
+ }
407
+ async function collectBytes(chunks: AsyncIterable<Uint8Array>, maximum: number): Promise<Uint8Array> {
408
+ const collected: Uint8Array[] = [];
409
+ let size = 0;
410
+ for await (const chunk of chunks) {
411
+ size += chunk.byteLength;
412
+ if (size > maximum) throw binaryFault('BINARY_TOO_LARGE');
413
+ collected.push(chunk);
414
+ }
415
+ const result = new Uint8Array(size);
416
+ let offset = 0;
417
+ for (const chunk of collected) {result.set(chunk, offset); offset += chunk.byteLength}
418
+ return result;
419
+ }
420
+ function binaryFault(code: string): Error & {code: string} {return Object.assign(new Error(code), {code})}
421
+ function isBinaryFault(error: unknown): error is Error & {code: string} {return error instanceof Error && 'code' in error && typeof error.code === 'string' && error.code.startsWith('BINARY_')}
422
+ function isR2BadDigest(error: unknown): boolean {return error instanceof Error && /\\(10037\\)$/u.test(error.message)}
423
+ `;
424
+ }
425
+
426
+ function packageJson(ir: DeployIrV2): string {
427
+ const usesAuth = ir.auth.kind === 'jwt';
428
+ return `${JSON.stringify(
429
+ {
430
+ name: ir.name.toLowerCase().replace(/[^a-z0-9._-]+/gu, '-'),
431
+ private: true,
432
+ type: 'module',
433
+ scripts: {dev: 'wrangler dev', deploy: 'wrangler deploy', typecheck: 'tsc --noEmit'},
434
+ dependencies: {hono: '^4.13.8', ...(usesAuth ? {jose: '^6.1.0'} : {})},
435
+ devDependencies: {'@cloudflare/workers-types': '^5.20260919.1', typescript: '^5.9.3', wrangler: '^4.135.0'}
436
+ },
437
+ null,
438
+ 2
439
+ )}\n`;
440
+ }
441
+
442
+ function tsconfig(): string {
443
+ return `${JSON.stringify(
444
+ {
445
+ compilerOptions: {
446
+ target: 'ES2022', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2022'],
447
+ strict: true, noEmit: true, skipLibCheck: true, types: ['@cloudflare/workers-types']
448
+ },
449
+ include: ['src/**/*.ts']
450
+ },
451
+ null,
452
+ 2
453
+ )}\n`;
454
+ }
455
+
456
+ function wrangler(ir: DeployIrV2, plan: PlatformPlan): string {
457
+ const recordBinding = plan.bindings.recordDatabase;
458
+ const objectBinding = plan.bindings.objectBucket;
459
+ const config = {
460
+ name: ir.name,
461
+ main: 'src/index.ts',
462
+ compatibility_date: '2026-09-01',
463
+ ...(recordBinding === undefined ? {} : {d1_databases: [{binding: recordBinding, database_name: `${ir.name}-db`, database_id: 'replace-me'}]}),
464
+ ...(objectBinding === undefined ? {} : {r2_buckets: [{binding: objectBinding, bucket_name: `${ir.name}-objects`}]})
465
+ };
466
+ return `// Generated by turbowarp-http-server.\n${JSON.stringify(config, null, 2)}\n`;
467
+ }
468
+
469
+ function migration(plan: PlatformPlan): string {
470
+ return [
471
+ ...(plan.requirements.includes('record-store')
472
+ ? ['CREATE TABLE IF NOT EXISTS records (id TEXT PRIMARY KEY, collection TEXT NOT NULL, data_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);']
473
+ : []),
474
+ ...(plan.requirements.includes('key-value-store')
475
+ ? ['CREATE TABLE IF NOT EXISTS kvs (namespace TEXT NOT NULL, key TEXT NOT NULL, value_text TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (namespace, key));']
476
+ : [])
477
+ ].join('\n') + '\n';
478
+ }
479
+
480
+ function generatedReadme(ir: DeployIrV2, plan: PlatformPlan): string {
481
+ const resources = [
482
+ ...(
483
+ plan.requirements.includes('record-store') || plan.requirements.includes('key-value-store')
484
+ ? [`the D1 database \`${ir.name}-db\``]
485
+ : []
486
+ ),
487
+ ...(plan.requirements.includes('object-storage') ? [`the R2 bucket \`${ir.name}-objects\``] : [])
488
+ ];
489
+ const setup = resources.length === 0
490
+ ? 'review the generated `wrangler.jsonc`'
491
+ : `create ${resources.join(' and ')} named in \`wrangler.jsonc\``;
492
+ const migration = plan.requirements.includes('record-store') || plan.requirements.includes('key-value-store')
493
+ ? ` Apply \`migrations/0001_init.sql\` with Wrangler before serving storage-backed routes.`
494
+ : '';
495
+ const auth = authScheme(ir) === 'trusted-access-jwt'
496
+ ? ' Configure `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUD` as deployment variables or secrets.'
497
+ : authScheme(ir) === 'external-jwt'
498
+ ? ' Configure `JWT_ISSUER`, `JWT_AUDIENCE`, and `JWT_JWKS_URL` as deployment variables or secrets.'
499
+ : '';
500
+ return `# Generated Cloudflare Workers application
501
+
502
+ Run \`npm install\`, ${setup}, replace only placeholder resource IDs, then run \`npm run dev\` or \`npm run deploy\`.${migration}${auth}
503
+
504
+ R2 stores binary bytes under the versioned \`v1/<namespace>/<key>\` prefix. Revisions combine R2's unique upload version, ETag, and upload timestamp. Deletes use ETag-and-time-conditional zero-byte \`twDeleted\` tombstones that resolve/get treat as absent; locator deletes retry when a concurrent write wins, and a later put replaces the tombstone. D1 stores queryable records and KVS text entries; KVS key listing is lexicographically ordered. Cloudflare KV is deliberately not used because this contract requires read-after-write consistency.
505
+
506
+ ## Rollback and cleanup
507
+
508
+ Stop traffic or roll back the Worker deployment first. Generated code never deletes cloud resources automatically. Export required data, inspect D1/R2 bindings and dependent services, then delete resources manually only when no deployment references them.
509
+ `;
510
+ }