@bleedingdev/modern-js-app-tools 3.5.0-ultramodern.27 → 3.5.0-ultramodern.29

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 (28) hide show
  1. package/dist/cjs/index.js +50 -44
  2. package/dist/cjs/plugins/backendFederationBuild.js +347 -0
  3. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-contract.js +91 -0
  4. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-plan.js +93 -0
  5. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier.js +402 -0
  6. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +158 -30
  7. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  8. package/dist/esm/index.mjs +2 -0
  9. package/dist/esm/plugins/backendFederationBuild.mjs +296 -0
  10. package/dist/esm/plugins/deploy/platforms/cloudflare-output-contract.mjs +17 -0
  11. package/dist/esm/plugins/deploy/platforms/cloudflare-output-plan.mjs +45 -0
  12. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier.mjs +347 -0
  13. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +158 -30
  14. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  15. package/dist/esm-node/index.mjs +2 -0
  16. package/dist/esm-node/plugins/backendFederationBuild.mjs +297 -0
  17. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-contract.mjs +18 -0
  18. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-plan.mjs +46 -0
  19. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier.mjs +348 -0
  20. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +158 -30
  21. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +30 -19
  22. package/dist/types/plugins/backendFederationBuild.d.ts +11 -0
  23. package/dist/types/plugins/deploy/platforms/cloudflare-output-contract.d.ts +13 -0
  24. package/dist/types/plugins/deploy/platforms/cloudflare-output-plan.d.ts +33 -0
  25. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier.d.ts +32 -0
  26. package/dist/types/types/config/cloudflareDeploy.d.ts +11 -0
  27. package/dist/types/types/config/deploy.d.ts +11 -3
  28. package/package.json +17 -11
@@ -0,0 +1,347 @@
1
+ import promises from "node:fs/promises";
2
+ import node_path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_ENTRY } from "./cloudflare-output-contract.mjs";
5
+ import { createCloudflareOutputPlan } from "./cloudflare-output-plan.mjs";
6
+ const SOURCE_SCAN_FILE_PATTERN = /\.(?:[cm]?[jt]s|json)$/u;
7
+ const SOURCE_SCAN_IGNORED_DIRECTORY_NAMES = new Set([
8
+ '.codex',
9
+ '.fastcontext',
10
+ '.git',
11
+ '.mf',
12
+ '.modernjs',
13
+ '.output',
14
+ 'coverage',
15
+ 'dist',
16
+ 'dist-cloudflare',
17
+ 'node_modules',
18
+ 'repos',
19
+ 'topology'
20
+ ]);
21
+ const FORBIDDEN_MUTATION_PATTERNS = [
22
+ {
23
+ code: 'forbidden-mutation-pattern',
24
+ message: "Generated Cloudflare server worker output must not be rewritten by app scripts.",
25
+ pattern: /\.output\/server\/index\.mjs/u
26
+ },
27
+ {
28
+ code: 'forbidden-mutation-pattern',
29
+ message: "Generated Cloudflare server worker output must not be rewritten by app scripts.",
30
+ pattern: /path\.join\(\s*['"`]\.output['"`]\s*,\s*['"`]server['"`]\s*,\s*['"`]index\.mjs['"`]\s*\)/u
31
+ },
32
+ {
33
+ code: 'forbidden-mutation-pattern',
34
+ message: "Generated Cloudflare BFF worker bundles must not be rewritten by app scripts.",
35
+ pattern: /\.output\/worker\/[^'"`]*\.(?:mjs|cjs|js)/u
36
+ },
37
+ {
38
+ code: 'forbidden-mutation-pattern',
39
+ message: "Generated Cloudflare BFF worker bundles must not be rewritten by app scripts.",
40
+ pattern: /path\.join\(\s*['"`]\.output['"`]\s*,\s*['"`]worker['"`]\s*,\s*['"`][^'"`]+\.(?:mjs|cjs|js)['"`]\s*\)/u
41
+ },
42
+ {
43
+ code: 'forbidden-mutation-pattern',
44
+ message: "Drizzle entityKind worker bundle markers must be fixed in the framework toolchain, not post-build scripts.",
45
+ pattern: /replaceAll\(\s*['"`];entityKind(?:,entityKind)?;/u
46
+ },
47
+ {
48
+ code: 'forbidden-mutation-pattern',
49
+ message: "Effect BFF Cloudflare dispatch must not depend on duck-typed runtime helper probing in app scripts.",
50
+ pattern: /(?:typeof\s+[^;\n]*dispatchEffectBffRequest|['"`]dispatchEffectBffRequest['"`]\s+in\s+|\.dispatchEffectBffRequest\b)/u
51
+ },
52
+ {
53
+ code: 'forbidden-mutation-pattern',
54
+ message: "Effect BFF Cloudflare dispatch must not branch on handler.length in app scripts.",
55
+ pattern: /\bhandler\s*\.\s*length\b/u
56
+ }
57
+ ];
58
+ const pathExists = async (filePath)=>{
59
+ try {
60
+ await promises.access(filePath);
61
+ return true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ };
66
+ const readJson = async (filePath)=>JSON.parse(await promises.readFile(filePath, 'utf-8'));
67
+ const addIssue = (issues, issue)=>{
68
+ issues.push(issue);
69
+ };
70
+ const assertEqual = (issues, actual, expected, issue)=>{
71
+ if (actual !== expected) addIssue(issues, issue);
72
+ };
73
+ const assertFlag = (issues, flags, flag, issue)=>{
74
+ if (!Array.isArray(flags) || !flags.includes(flag)) addIssue(issues, issue);
75
+ };
76
+ const getReferencedRouteWorkers = (manifest)=>Array.isArray(manifest?.routeSpec?.routes) ? manifest.routeSpec.routes.map((route)=>'string' == typeof route?.worker && route.worker.length > 0 ? route.worker : void 0).filter((worker)=>'string' == typeof worker) : [];
77
+ const getEffectBffWorker = (manifest)=>manifest?.bff?.runtimeFramework === 'effect' && 'string' == typeof manifest.bff.worker ? manifest.bff.worker : void 0;
78
+ const getWorkerBundleReferences = (manifest)=>{
79
+ const effectBffWorker = getEffectBffWorker(manifest);
80
+ return [
81
+ ...effectBffWorker ? [
82
+ {
83
+ kind: 'effect-bff',
84
+ reference: effectBffWorker
85
+ }
86
+ ] : [],
87
+ ...getReferencedRouteWorkers(manifest).map((reference)=>({
88
+ kind: 'route',
89
+ reference
90
+ }))
91
+ ];
92
+ };
93
+ const resolveWorkerBundleReference = (issues, outputDirectory, reference, manifestPath)=>{
94
+ const workerRoot = node_path.resolve(outputDirectory, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY);
95
+ const workerPath = node_path.resolve(outputDirectory, reference.reference);
96
+ const relativeToWorkerRoot = node_path.relative(workerRoot, workerPath);
97
+ if (node_path.isAbsolute(reference.reference) || relativeToWorkerRoot.startsWith('..') || node_path.isAbsolute(relativeToWorkerRoot)) {
98
+ addIssue(issues, {
99
+ code: 'invalid-manifest',
100
+ message: 'Cloudflare output manifest worker bundle references must stay under worker/.',
101
+ path: manifestPath
102
+ });
103
+ return null;
104
+ }
105
+ return {
106
+ ...reference,
107
+ path: workerPath
108
+ };
109
+ };
110
+ const missingWorkerBundleMessage = (reference)=>'effect-bff' === reference.kind ? 'Cloudflare Effect BFF manifest points to a missing worker bundle.' : 'Cloudflare route worker manifest points to a missing worker bundle.';
111
+ const DELIVERY_UNIT_IDENTITY_FIELDS = [
112
+ 'unitId',
113
+ 'buildMarker',
114
+ 'sourceRevision'
115
+ ];
116
+ const verifyDeliveryUnitIdentity = (issues, manifest, manifestPath, declared)=>{
117
+ const stamped = manifest?.deliveryUnit;
118
+ const hasStamp = Boolean(stamped) && 'object' == typeof stamped;
119
+ if (declared) {
120
+ if (!hasStamp) return void addIssue(issues, {
121
+ code: 'missing-delivery-unit',
122
+ message: `Cloudflare worker manifest is missing the delivery-unit identity declared by the workspace topology (expected unitId ${declared.unitId}, buildMarker ${declared.buildMarker}).`,
123
+ path: manifestPath
124
+ });
125
+ for (const field of DELIVERY_UNIT_IDENTITY_FIELDS)assertEqual(issues, stamped[field], declared[field], {
126
+ code: 'delivery-unit-drift',
127
+ message: `Cloudflare worker manifest deliveryUnit.${field} must match the topology delivery-unit record (expected ${declared[field]}, received ${stamped[field] ?? 'undefined'}).`,
128
+ path: manifestPath
129
+ });
130
+ }
131
+ if (hasStamp && stamped.surfaces && 'object' == typeof stamped.surfaces) for (const surface of [
132
+ 'ui',
133
+ 'api'
134
+ ]){
135
+ const marker = stamped.surfaces[surface];
136
+ if (!marker || 'object' != typeof marker) {
137
+ addIssue(issues, {
138
+ code: 'missing-delivery-unit',
139
+ message: `Cloudflare worker manifest is missing the ${surface} delivery-unit surface marker.`,
140
+ path: manifestPath
141
+ });
142
+ continue;
143
+ }
144
+ for (const field of DELIVERY_UNIT_IDENTITY_FIELDS)assertEqual(issues, marker[field], stamped[field], {
145
+ code: 'delivery-unit-drift',
146
+ message: `Cloudflare worker manifest ${surface} surface deliveryUnit.${field} must derive from one delivery-unit record (expected ${stamped[field] ?? 'undefined'}, received ${marker[field] ?? 'undefined'}).`,
147
+ path: manifestPath
148
+ });
149
+ }
150
+ };
151
+ const verifyManifestShape = (issues, manifest, manifestPath)=>{
152
+ assertEqual(issues, manifest.runtime?.type, CLOUDFLARE_RUNTIME_TYPE, {
153
+ code: 'invalid-manifest',
154
+ message: 'Cloudflare output manifest runtime.type must be cloudflare-module-worker.',
155
+ path: manifestPath
156
+ });
157
+ assertEqual(issues, manifest.runtime?.entry, CLOUDFLARE_WORKER_ENTRY, {
158
+ code: 'invalid-manifest',
159
+ message: `Cloudflare output manifest runtime.entry must be ${CLOUDFLARE_WORKER_ENTRY}.`,
160
+ path: manifestPath
161
+ });
162
+ assertEqual(issues, manifest.runtime?.fetchExport, true, {
163
+ code: 'invalid-manifest',
164
+ message: 'Cloudflare output manifest runtime.fetchExport must be true.',
165
+ path: manifestPath
166
+ });
167
+ assertEqual(issues, manifest.runtime?.nodeListen, false, {
168
+ code: 'invalid-manifest',
169
+ message: 'Cloudflare output manifest runtime.nodeListen must be false.',
170
+ path: manifestPath
171
+ });
172
+ assertEqual(issues, manifest.assets?.binding, CLOUDFLARE_ASSETS_BINDING, {
173
+ code: 'invalid-manifest',
174
+ message: 'Cloudflare output manifest assets.binding must be ASSETS.',
175
+ path: manifestPath
176
+ });
177
+ assertEqual(issues, manifest.assets?.directory, `./${CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY}`, {
178
+ code: 'invalid-manifest',
179
+ message: 'Cloudflare output manifest assets.directory must be ./public.',
180
+ path: manifestPath
181
+ });
182
+ assertEqual(issues, manifest.assets?.runWorkerFirst, true, {
183
+ code: 'invalid-manifest',
184
+ message: 'Cloudflare output manifest assets.runWorkerFirst must be true.',
185
+ path: manifestPath
186
+ });
187
+ };
188
+ const walkFiles = async (root)=>{
189
+ if (!await pathExists(root)) return [];
190
+ const entries = await promises.readdir(root, {
191
+ withFileTypes: true
192
+ });
193
+ const files = [];
194
+ for (const entry of entries){
195
+ if (SOURCE_SCAN_IGNORED_DIRECTORY_NAMES.has(entry.name)) continue;
196
+ const entryPath = node_path.join(root, entry.name);
197
+ if (entry.isDirectory()) {
198
+ files.push(...await walkFiles(entryPath));
199
+ continue;
200
+ }
201
+ if (SOURCE_SCAN_FILE_PATTERN.test(entry.name)) files.push(entryPath);
202
+ }
203
+ return files;
204
+ };
205
+ const verifyCloudflareOutputMutationPolicy = async (options)=>{
206
+ const issues = [];
207
+ const files = (await Promise.all(options.scanRoots.map((scanRoot)=>walkFiles(node_path.resolve(scanRoot))))).flat();
208
+ for (const file of files){
209
+ const source = await promises.readFile(file, 'utf-8');
210
+ for (const forbidden of FORBIDDEN_MUTATION_PATTERNS)if (forbidden.pattern.test(source)) addIssue(issues, {
211
+ code: forbidden.code,
212
+ message: forbidden.message,
213
+ path: file
214
+ });
215
+ }
216
+ return {
217
+ ok: 0 === issues.length,
218
+ issues
219
+ };
220
+ };
221
+ const verifyWorkerImport = async (issues, entryPath)=>{
222
+ try {
223
+ const worker = (await import(`${pathToFileURL(entryPath).href}?t=${Date.now()}`)).default;
224
+ if (!worker || 'function' != typeof worker.fetch) addIssue(issues, {
225
+ code: 'worker-import-failed',
226
+ message: 'Cloudflare server entry must default-export a Worker with fetch.',
227
+ path: entryPath
228
+ });
229
+ } catch (error) {
230
+ addIssue(issues, {
231
+ code: 'worker-import-failed',
232
+ message: `Cloudflare server entry could not be imported: ${error instanceof Error ? error.message : String(error)}`,
233
+ path: entryPath
234
+ });
235
+ }
236
+ };
237
+ const verifyCloudflareOutput = async (options)=>{
238
+ const outputDirectory = node_path.resolve(options.outputDirectory);
239
+ const issues = [];
240
+ const outputPlan = createCloudflareOutputPlan(outputDirectory);
241
+ for (const relativePath of outputPlan.requiredFiles){
242
+ const filePath = node_path.join(outputDirectory, relativePath);
243
+ if (!await pathExists(filePath)) addIssue(issues, {
244
+ code: 'missing-file',
245
+ message: `Cloudflare output is missing ${relativePath}.`,
246
+ path: filePath
247
+ });
248
+ }
249
+ const manifestPath = outputPlan.paths.workerManifest;
250
+ const wranglerPath = outputPlan.paths.wranglerConfig;
251
+ const packagePath = outputPlan.paths.outputPackage;
252
+ const workerPackagePath = outputPlan.paths.workerPackage;
253
+ const manifest = await pathExists(manifestPath) ? await readJson(manifestPath) : void 0;
254
+ const wrangler = await pathExists(wranglerPath) ? await readJson(wranglerPath) : void 0;
255
+ const outputPackage = await pathExists(packagePath) ? await readJson(packagePath) : void 0;
256
+ const workerPackage = await pathExists(workerPackagePath) ? await readJson(workerPackagePath) : void 0;
257
+ if (manifest) {
258
+ verifyManifestShape(issues, manifest, manifestPath);
259
+ verifyDeliveryUnitIdentity(issues, manifest, manifestPath, options.deliveryUnit);
260
+ const workerReferences = getWorkerBundleReferences(manifest);
261
+ if (workerReferences.length > 0 && !await pathExists(workerPackagePath)) addIssue(issues, {
262
+ code: 'missing-file',
263
+ message: 'Cloudflare output is missing worker/package.json for referenced worker bundles.',
264
+ path: workerPackagePath
265
+ });
266
+ if (manifest.bff?.runtimeFramework === 'effect' && !getEffectBffWorker(manifest)) addIssue(issues, {
267
+ code: 'missing-worker-bundle',
268
+ message: 'Cloudflare Effect BFF manifest points to a missing worker bundle.'
269
+ });
270
+ for (const workerReference of workerReferences){
271
+ const resolvedWorker = resolveWorkerBundleReference(issues, outputDirectory, workerReference, manifestPath);
272
+ if (!resolvedWorker) continue;
273
+ const workerExists = await pathExists(resolvedWorker.path);
274
+ if (!workerExists) addIssue(issues, {
275
+ code: 'missing-worker-bundle',
276
+ message: missingWorkerBundleMessage(workerReference),
277
+ path: resolvedWorker.path
278
+ });
279
+ if (workerExists && 'effect-bff' === resolvedWorker.kind) {
280
+ const workerSource = await promises.readFile(resolvedWorker.path, 'utf-8');
281
+ if (workerSource.includes(';entityKind;') || workerSource.includes(';entityKind,entityKind;')) addIssue(issues, {
282
+ code: 'invalid-worker-bundle',
283
+ message: 'Cloudflare Effect BFF worker bundle contains invalid Drizzle entityKind marker references.',
284
+ path: resolvedWorker.path
285
+ });
286
+ }
287
+ }
288
+ }
289
+ if (wrangler) {
290
+ assertEqual(issues, wrangler.main, outputPlan.wrangler.main, {
291
+ code: 'invalid-wrangler',
292
+ message: `wrangler.json main must be ${outputPlan.wrangler.main}.`,
293
+ path: wranglerPath
294
+ });
295
+ assertEqual(issues, wrangler.assets?.binding, outputPlan.wrangler.assets.binding, {
296
+ code: 'invalid-wrangler',
297
+ message: 'wrangler.json assets.binding must be ASSETS.',
298
+ path: wranglerPath
299
+ });
300
+ assertEqual(issues, wrangler.assets?.directory, outputPlan.wrangler.assets.directory, {
301
+ code: 'invalid-wrangler',
302
+ message: 'wrangler.json assets.directory must be ./public.',
303
+ path: wranglerPath
304
+ });
305
+ assertEqual(issues, wrangler.assets?.run_worker_first, outputPlan.wrangler.assets.run_worker_first, {
306
+ code: 'invalid-wrangler',
307
+ message: 'wrangler.json assets.run_worker_first must be true.',
308
+ path: wranglerPath
309
+ });
310
+ for (const flag of outputPlan.wrangler.requiredCompatibilityFlags)assertFlag(issues, wrangler.compatibility_flags, flag, {
311
+ code: 'invalid-wrangler',
312
+ message: `wrangler.json compatibility_flags must include ${flag}.`,
313
+ path: wranglerPath
314
+ });
315
+ }
316
+ if (outputPackage) assertEqual(issues, outputPackage.type, outputPlan.packages.output.type, {
317
+ code: 'invalid-package',
318
+ message: '.output/package.json must declare type module.',
319
+ path: packagePath
320
+ });
321
+ if (workerPackage) assertEqual(issues, workerPackage.type, outputPlan.packages.worker.type, {
322
+ code: 'invalid-package',
323
+ message: '.output/worker/package.json must declare type commonjs.',
324
+ path: workerPackagePath
325
+ });
326
+ for (const leakedPath of outputPlan.publicLeakDirectories){
327
+ const publicPath = node_path.join(outputPlan.paths.publicAssets, leakedPath);
328
+ if (await pathExists(publicPath)) addIssue(issues, {
329
+ code: 'public-output-leak',
330
+ message: `Framework-owned ${leakedPath} output leaked into public assets.`,
331
+ path: publicPath
332
+ });
333
+ }
334
+ if (false !== options.importWorker && await pathExists(outputPlan.paths.workerEntry)) await verifyWorkerImport(issues, outputPlan.paths.workerEntry);
335
+ return {
336
+ ok: 0 === issues.length,
337
+ issues
338
+ };
339
+ };
340
+ const assertCloudflareOutput = async (options)=>{
341
+ const result = await verifyCloudflareOutput(options);
342
+ if (!result.ok) throw new Error([
343
+ 'Cloudflare output verification failed:',
344
+ ...result.issues.map((issue)=>`- ${issue.code}: ${issue.message}${issue.path ? ` (${issue.path})` : ''}`)
345
+ ].join('\n'));
346
+ };
347
+ export { assertCloudflareOutput, verifyCloudflareOutput, verifyCloudflareOutputMutationPolicy };
@@ -1,17 +1,19 @@
1
1
  import node_path from "node:path";
2
2
  import { fs } from "@modern-js/utils";
3
3
  import { readTemplate } from "../utils/index.mjs";
4
- const WORKER_ENTRY = 'server/index.mjs';
5
- const WORKER_MANIFEST = 'server/modern-worker-manifest.json';
6
- const WRANGLER_CONFIG_FILE = 'wrangler.json';
7
- const OUTPUT_PACKAGE_FILE = 'package.json';
8
- const ASSETS_BINDING = 'ASSETS';
4
+ import { CLOUDFLARE_ASSETS_BINDING, CLOUDFLARE_OUTPUT_PACKAGE_FILE, CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY, CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_DIRECTORY, CLOUDFLARE_WORKER_BUNDLE_FORMAT, CLOUDFLARE_WORKER_ENTRY, CLOUDFLARE_WRANGLER_CONFIG_FILE } from "./cloudflare-output-contract.mjs";
5
+ import { createCloudflareOutputPlan } from "./cloudflare-output-plan.mjs";
6
+ import { assertCloudflareOutput } from "./cloudflare-output-verifier.mjs";
7
+ const WORKER_ENTRY = CLOUDFLARE_WORKER_ENTRY;
8
+ const WRANGLER_CONFIG_FILE = CLOUDFLARE_WRANGLER_CONFIG_FILE;
9
+ const OUTPUT_PACKAGE_FILE = CLOUDFLARE_OUTPUT_PACKAGE_FILE;
10
+ const ASSETS_BINDING = CLOUDFLARE_ASSETS_BINDING;
9
11
  const ROUTE_SPEC_FILE = 'route.json';
10
12
  const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
11
13
  const LOADABLE_STATS_FILE = 'loadable-stats.json';
12
14
  const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
13
- const PUBLIC_ASSETS_DIRECTORY = 'public';
14
- const WORKER_BUNDLE_DIRECTORY = 'worker';
15
+ const PUBLIC_ASSETS_DIRECTORY = CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY;
16
+ const WORKER_BUNDLE_DIRECTORY = CLOUDFLARE_WORKER_BUNDLE_DIRECTORY;
15
17
  const SERVER_BUNDLE_DIRECTORY = 'bundles';
16
18
  const SERVER_OUTPUT_DIRECTORY = 'server';
17
19
  const DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES = [
@@ -22,10 +24,7 @@ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.
22
24
  const EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE = 'Ensure the Effect API entry exists at api/index.ts or bff.effect.entry, and import Cloudflare edge handlers from @modern-js/plugin-bff/effect-edge instead of lambda/Hono server helpers.';
23
25
  const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
24
26
  const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
25
- const REQUIRED_COMPATIBILITY_FLAGS = [
26
- 'nodejs_compat',
27
- 'global_fetch_strictly_public'
28
- ];
27
+ const REQUIRED_COMPATIBILITY_FLAGS = CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS;
29
28
  const RESERVED_ARTIFACT_DESTINATION_FILES = new Set([
30
29
  WRANGLER_CONFIG_FILE,
31
30
  OUTPUT_PACKAGE_FILE
@@ -219,11 +218,12 @@ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
219
218
  const configuredName = modernConfig.deploy?.worker?.name?.trim();
220
219
  return configuredName || getWorkerName(appDirectory);
221
220
  };
222
- const normalizeRelativePath = (value, label, scope = 'app output')=>{
221
+ const normalizeRelativePath = (value, label, scope = 'app output', options = {})=>{
223
222
  if ('string' != typeof value) throw new Error(`${label} must be a relative path inside the ${scope}.`);
224
223
  const normalized = value.trim().replace(/\\/g, '/').replace(/^\.\/+/u, '').replace(/\/+$/u, '');
225
224
  const segments = normalized.split('/');
226
- if (!normalized || node_path.isAbsolute(normalized) || '.' === normalized || segments.includes('..')) throw new Error(`${label} must be a relative path inside the ${scope}.`);
225
+ const isRootDestination = '.' === normalized;
226
+ if (!normalized || node_path.isAbsolute(normalized) || !options.allowRoot && isRootDestination || segments.includes('..')) throw new Error(`${label} must be a relative path inside the ${scope}.`);
227
227
  return normalized;
228
228
  };
229
229
  const normalizeDirectiveValues = (value)=>{
@@ -378,9 +378,48 @@ const createWranglerD1Databases = (modernConfig, configuredWranglerD1)=>{
378
378
  if (!Array.isArray(d1Databases)) throw new Error('deploy.worker.d1Databases must be an array.');
379
379
  return d1Databases.map(normalizeD1Database);
380
380
  };
381
+ const normalizeServiceBinding = (service, index)=>{
382
+ const binding = assertNonEmptyString(service.binding, `deploy.worker.services[${index}].binding`);
383
+ const serviceName = assertNonEmptyString(service.service, `deploy.worker.services[${index}].service`);
384
+ const prefix = void 0 === service.prefix ? void 0 : assertNonEmptyString(service.prefix, `deploy.worker.services[${index}].prefix`);
385
+ return {
386
+ binding,
387
+ service: serviceName,
388
+ ...void 0 === prefix ? {} : {
389
+ prefix
390
+ }
391
+ };
392
+ };
393
+ const createWorkerServiceBindings = (modernConfig, configuredWranglerServices)=>{
394
+ const services = modernConfig.deploy?.worker?.services;
395
+ if (void 0 === services) return configuredWranglerServices;
396
+ if (void 0 !== configuredWranglerServices) throw new Error('Use deploy.worker.services or deploy.worker.wrangler.services, not both.');
397
+ if (!Array.isArray(services)) throw new Error('deploy.worker.services must be an array.');
398
+ return services.map(normalizeServiceBinding);
399
+ };
400
+ const createWranglerServices = (serviceBindings)=>{
401
+ if (!Array.isArray(serviceBindings)) return serviceBindings;
402
+ if (!serviceBindings.every(isJsonRecord)) return serviceBindings;
403
+ return serviceBindings.map((service)=>{
404
+ const { prefix, ...wranglerService } = service;
405
+ return wranglerService;
406
+ });
407
+ };
408
+ const createWorkerManifestServiceBindings = (serviceBindings)=>{
409
+ if (!Array.isArray(serviceBindings)) return;
410
+ const dispatchBindings = serviceBindings.filter((service)=>isJsonRecord(service) && 'string' == typeof service.binding && 'string' == typeof service.service && 'string' == typeof service.prefix).map((service)=>({
411
+ binding: service.binding,
412
+ service: service.service,
413
+ prefix: service.prefix,
414
+ interface: 'fetch'
415
+ }));
416
+ return dispatchBindings.length > 0 ? dispatchBindings : void 0;
417
+ };
381
418
  const createWranglerConfig = (appDirectory, modernConfig)=>{
382
419
  const wrangler = getConfiguredWrangler(modernConfig);
383
420
  const d1Databases = createWranglerD1Databases(modernConfig, wrangler.d1_databases);
421
+ const serviceBindings = createWorkerServiceBindings(modernConfig, wrangler.services);
422
+ const wranglerServices = createWranglerServices(serviceBindings);
384
423
  return {
385
424
  $schema: 'node_modules/wrangler/config-schema.json',
386
425
  name: getConfiguredWorkerName(appDirectory, modernConfig),
@@ -391,6 +430,9 @@ const createWranglerConfig = (appDirectory, modernConfig)=>{
391
430
  assets: createWranglerAssetsConfig(wrangler.assets),
392
431
  ...void 0 === d1Databases ? {} : {
393
432
  d1_databases: d1Databases
433
+ },
434
+ ...void 0 === wranglerServices ? {} : {
435
+ services: wranglerServices
394
436
  }
395
437
  };
396
438
  };
@@ -409,7 +451,9 @@ const normalizeCloudflareArtifact = (artifact, index)=>{
409
451
  const getCloudflareArtifacts = (modernConfig)=>(modernConfig.deploy?.worker?.artifacts ?? []).map(normalizeCloudflareArtifact);
410
452
  const normalizeCloudflarePublicAsset = (asset, index)=>{
411
453
  const from = normalizeRelativePath(asset.from, `deploy.worker.publicAssets[${index}].from`, 'app root');
412
- const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output');
454
+ const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output', {
455
+ allowRoot: true
456
+ });
413
457
  return {
414
458
  from,
415
459
  to,
@@ -451,8 +495,79 @@ const readRouteSpec = async (outputDirectory)=>{
451
495
  routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
452
496
  };
453
497
  };
498
+ const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
499
+ const ULTRAMODERN_BUILD_MODULE = 'shared/ultramodern-build.ts';
500
+ const nonEmptyString = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
501
+ const toDeliveryUnitIdentity = (value)=>{
502
+ if (!isRecord(value)) return;
503
+ const unitId = nonEmptyString(value.unitId);
504
+ const buildMarker = nonEmptyString(value.buildMarker);
505
+ const sourceRevision = nonEmptyString(value.sourceRevision);
506
+ if (!unitId || !buildMarker || !sourceRevision) return;
507
+ return {
508
+ unitId,
509
+ buildMarker,
510
+ sourceRevision
511
+ };
512
+ };
513
+ const findWorkspaceRoot = async (appDirectory)=>{
514
+ let current = node_path.resolve(appDirectory);
515
+ for(;;){
516
+ if (await fs.pathExists(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
517
+ const parent = node_path.dirname(current);
518
+ if (parent === current) return;
519
+ current = parent;
520
+ }
521
+ };
522
+ const resolveTopologyDeliveryUnit = async (appDirectory)=>{
523
+ const workspaceRoot = await findWorkspaceRoot(appDirectory);
524
+ if (!workspaceRoot) return;
525
+ let compactConfig;
526
+ try {
527
+ compactConfig = await fs.readJSON(node_path.join(workspaceRoot, COMPACT_CONFIG_PATH));
528
+ } catch {
529
+ return;
530
+ }
531
+ if (!isRecord(compactConfig)) return;
532
+ const topology = isRecord(compactConfig.topology) ? compactConfig.topology : void 0;
533
+ const apps = Array.isArray(topology?.apps) ? topology.apps : [];
534
+ const resolvedAppDirectory = node_path.resolve(appDirectory);
535
+ for (const app of apps){
536
+ if (!isRecord(app)) continue;
537
+ const appPath = nonEmptyString(app.path);
538
+ if (appPath && node_path.resolve(workspaceRoot, appPath.replace(/^\.\/+/u, '')) === resolvedAppDirectory) return toDeliveryUnitIdentity(app.deliveryUnit);
539
+ }
540
+ return toDeliveryUnitIdentity(compactConfig.deliveryUnit);
541
+ };
542
+ const resolveWorkerDeliveryUnitStamp = async (appDirectory)=>{
543
+ const buildModulePath = node_path.join(appDirectory, ULTRAMODERN_BUILD_MODULE);
544
+ if (!await fs.pathExists(buildModulePath)) return;
545
+ const source = await fs.readFile(buildModulePath, 'utf8');
546
+ const buildMarker = source.match(/\bbuild:\s*['"]([^'"]+)['"]/u)?.[1];
547
+ const unitId = source.match(/\bunitId:\s*['"]([^'"]+)['"]/u)?.[1];
548
+ const sourceRevision = source.match(/\bsourceRevision:\s*['"]([^'"]+)['"]/u)?.[1];
549
+ if (!buildMarker || !unitId || !sourceRevision) return;
550
+ const identity = {
551
+ unitId,
552
+ buildMarker,
553
+ sourceRevision
554
+ };
555
+ return {
556
+ ...identity,
557
+ surfaces: {
558
+ ui: {
559
+ ...identity,
560
+ surface: 'ui'
561
+ },
562
+ api: {
563
+ ...identity,
564
+ surface: 'api'
565
+ }
566
+ }
567
+ };
568
+ };
454
569
  const createMissingEffectBffWorkerError = (outputDirectory, worker)=>new Error(`Cloudflare Effect API runtime is configured, but the BFF worker bundle is missing: ${node_path.join(outputDirectory, worker)}. ${EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE}`);
455
- const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>{
570
+ const createWorkerManifest = async (outputDirectory, modernConfig, appContext, deliveryUnitStamp)=>{
456
571
  const routeSpec = await readRouteSpec(outputDirectory);
457
572
  const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
458
573
  const worker = 'string' == typeof route.worker ? route.worker : void 0;
@@ -469,11 +584,12 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
469
584
  const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
470
585
  const isEffectApi = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
471
586
  const effectApiWorkerExists = await fs.pathExists(node_path.join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
587
+ const serviceBindings = createWorkerManifestServiceBindings(createWorkerServiceBindings(modernConfig, void 0));
472
588
  if (isEffectApi && primaryBffPrefix && !effectApiWorkerExists) throw createMissingEffectBffWorkerError(outputDirectory, BFF_EFFECT_WORKER_ENTRY);
473
589
  return {
474
590
  version: 1,
475
591
  runtime: {
476
- type: 'cloudflare-module-worker',
592
+ type: CLOUDFLARE_RUNTIME_TYPE,
477
593
  entry: WORKER_ENTRY,
478
594
  fetchExport: true,
479
595
  nodeListen: false
@@ -489,7 +605,7 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
489
605
  },
490
606
  workerBundles: {
491
607
  directory: WORKER_BUNDLE_DIRECTORY,
492
- format: 'commonjs',
608
+ format: CLOUDFLARE_WORKER_BUNDLE_FORMAT,
493
609
  importableFromModuleWorker: true,
494
610
  requestHandlerExport: 'requestHandler'
495
611
  },
@@ -498,12 +614,18 @@ const createWorkerManifest = async (outputDirectory, modernConfig, appContext)=>
498
614
  routeManifest: ROUTE_MANIFEST_FILE
499
615
  },
500
616
  security: createCloudflareWorkerSecurityPolicy(modernConfig),
617
+ ...deliveryUnitStamp ? {
618
+ deliveryUnit: deliveryUnitStamp
619
+ } : {},
501
620
  i18n: createI18nWorkerManifest(routeSpec, appContext),
502
621
  bff: isEffectApi && primaryBffPrefix && effectApiWorkerExists ? {
503
622
  runtimeFramework: 'effect',
504
623
  prefix: primaryBffPrefix,
505
624
  worker: BFF_EFFECT_WORKER_ENTRY
506
- } : void 0
625
+ } : void 0,
626
+ ...void 0 === serviceBindings ? {} : {
627
+ serviceBindings
628
+ }
507
629
  };
508
630
  };
509
631
  const createWorkerModuleLoaders = (manifest)=>{
@@ -555,11 +677,12 @@ const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
555
677
  const createCloudflarePreset = ({ appContext, modernConfig })=>{
556
678
  const { appDirectory, distDirectory } = appContext;
557
679
  const outputDirectory = node_path.join(appDirectory, '.output');
558
- const publicDirectory = node_path.join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
559
- const workerEntryPath = node_path.join(outputDirectory, WORKER_ENTRY);
560
- const workerManifestPath = node_path.join(outputDirectory, WORKER_MANIFEST);
680
+ const outputPlan = createCloudflareOutputPlan(outputDirectory);
681
+ const publicDirectory = outputPlan.paths.publicAssets;
682
+ const workerEntryPath = outputPlan.paths.workerEntry;
683
+ const workerManifestPath = outputPlan.paths.workerManifest;
561
684
  const routeSpecOutputPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
562
- const wranglerConfigPath = node_path.join(outputDirectory, WRANGLER_CONFIG_FILE);
685
+ const wranglerConfigPath = outputPlan.paths.wranglerConfig;
563
686
  const cloudflareArtifacts = getCloudflareArtifacts(modernConfig);
564
687
  const publicAssetExcludes = getPublicAssetExcludes(appDirectory, modernConfig);
565
688
  return {
@@ -575,14 +698,12 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
575
698
  const routeSpecSourcePath = node_path.join(distDirectory, ROUTE_SPEC_FILE);
576
699
  if (await fs.pathExists(routeSpecSourcePath)) await fs.copy(routeSpecSourcePath, routeSpecOutputPath);
577
700
  const workerBundleSourceDirectory = node_path.join(distDirectory, WORKER_BUNDLE_DIRECTORY);
578
- const workerBundleOutputDirectory = node_path.join(outputDirectory, WORKER_BUNDLE_DIRECTORY);
701
+ const workerBundleOutputDirectory = outputPlan.paths.workerBundle;
579
702
  if (await fs.pathExists(workerBundleSourceDirectory)) {
580
703
  await fs.copy(workerBundleSourceDirectory, workerBundleOutputDirectory, {
581
704
  filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
582
705
  });
583
- await fs.writeJSON(node_path.join(workerBundleOutputDirectory, 'package.json'), {
584
- type: 'commonjs'
585
- });
706
+ await fs.writeJSON(outputPlan.paths.workerPackage, outputPlan.packages.worker);
586
707
  }
587
708
  await copyCloudflareArtifacts(appDirectory, outputDirectory, cloudflareArtifacts);
588
709
  await copyCloudflarePublicAssets(appDirectory, publicDirectory, getCloudflarePublicAssets(modernConfig));
@@ -590,17 +711,24 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
590
711
  await fs.writeJSON(wranglerConfigPath, createWranglerConfig(appDirectory, modernConfig), {
591
712
  spaces: 2
592
713
  });
593
- await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig, appContext), {
714
+ const deliveryUnitStamp = await resolveWorkerDeliveryUnitStamp(appDirectory);
715
+ await fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig, appContext, deliveryUnitStamp), {
594
716
  spaces: 2
595
717
  });
596
- await fs.writeJSON(node_path.join(outputDirectory, OUTPUT_PACKAGE_FILE), {
597
- type: 'module'
598
- });
718
+ await fs.writeJSON(outputPlan.paths.outputPackage, outputPlan.packages.output);
599
719
  },
600
720
  async genEntry () {
601
721
  const template = await readTemplate('cloudflare-entry.mjs');
602
722
  const manifest = await fs.readJSON(workerManifestPath);
603
723
  await fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
724
+ const topologyDeliveryUnit = await resolveTopologyDeliveryUnit(appDirectory);
725
+ await assertCloudflareOutput({
726
+ outputDirectory,
727
+ importWorker: false,
728
+ ...topologyDeliveryUnit ? {
729
+ deliveryUnit: topologyDeliveryUnit
730
+ } : {}
731
+ });
604
732
  }
605
733
  };
606
734
  };