@bleedingdev/modern-js-app-tools 3.5.0-ultramodern.3 → 3.5.0-ultramodern.31

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 (133) hide show
  1. package/dist/cjs/builder/generator/getBuilderEnvironments.js +1 -0
  2. package/dist/cjs/index.js +50 -44
  3. package/dist/cjs/plugins/backend-federation/codegen.js +208 -0
  4. package/dist/cjs/plugins/backend-federation/config.js +217 -0
  5. package/dist/cjs/plugins/backend-federation/emit.js +139 -0
  6. package/dist/cjs/plugins/backendFederationBuild.js +53 -0
  7. package/dist/cjs/plugins/deploy/platforms/cloudflare/artifacts.js +127 -0
  8. package/dist/cjs/plugins/deploy/platforms/cloudflare/constants.js +137 -0
  9. package/dist/cjs/plugins/deploy/platforms/cloudflare/delivery-unit.js +118 -0
  10. package/dist/cjs/plugins/deploy/platforms/cloudflare/i18n-worker.js +135 -0
  11. package/dist/cjs/plugins/deploy/platforms/cloudflare/index.js +126 -0
  12. package/dist/cjs/plugins/deploy/platforms/cloudflare/security-policies.js +223 -0
  13. package/dist/cjs/plugins/deploy/platforms/cloudflare/types.js +18 -0
  14. package/dist/cjs/plugins/deploy/platforms/cloudflare/utils.js +66 -0
  15. package/dist/cjs/plugins/deploy/platforms/cloudflare/worker-manifest.js +178 -0
  16. package/dist/cjs/plugins/deploy/platforms/cloudflare/wrangler-config.js +189 -0
  17. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-contract.js +91 -0
  18. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-plan.js +93 -0
  19. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/identity.js +83 -0
  20. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/index.js +184 -0
  21. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/issues.js +54 -0
  22. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/manifest.js +83 -0
  23. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.js +158 -0
  24. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.js +137 -0
  25. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier.js +62 -0
  26. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +2 -502
  27. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  28. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  29. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  30. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  31. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  32. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  33. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +1 -0
  34. package/dist/esm/index.mjs +2 -0
  35. package/dist/esm/plugins/backend-federation/codegen.mjs +157 -0
  36. package/dist/esm/plugins/backend-federation/config.mjs +141 -0
  37. package/dist/esm/plugins/backend-federation/emit.mjs +88 -0
  38. package/dist/esm/plugins/backendFederationBuild.mjs +1 -0
  39. package/dist/esm/plugins/deploy/platforms/cloudflare/artifacts.mjs +64 -0
  40. package/dist/esm/plugins/deploy/platforms/cloudflare/constants.mjs +33 -0
  41. package/dist/esm/plugins/deploy/platforms/cloudflare/delivery-unit.mjs +67 -0
  42. package/dist/esm/plugins/deploy/platforms/cloudflare/i18n-worker.mjs +97 -0
  43. package/dist/esm/plugins/deploy/platforms/cloudflare/index.mjs +78 -0
  44. package/dist/esm/plugins/deploy/platforms/cloudflare/security-policies.mjs +167 -0
  45. package/dist/esm/plugins/deploy/platforms/cloudflare/types.mjs +0 -0
  46. package/dist/esm/plugins/deploy/platforms/cloudflare/utils.mjs +12 -0
  47. package/dist/esm/plugins/deploy/platforms/cloudflare/worker-manifest.mjs +118 -0
  48. package/dist/esm/plugins/deploy/platforms/cloudflare/wrangler-config.mjs +135 -0
  49. package/dist/esm/plugins/deploy/platforms/cloudflare-output-contract.mjs +17 -0
  50. package/dist/esm/plugins/deploy/platforms/cloudflare-output-plan.mjs +45 -0
  51. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/identity.mjs +45 -0
  52. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +129 -0
  53. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/issues.mjs +10 -0
  54. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/manifest.mjs +45 -0
  55. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.mjs +97 -0
  56. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +68 -0
  57. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier.mjs +1 -0
  58. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +1 -492
  59. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  60. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  61. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  62. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  63. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  64. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  65. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +1 -0
  66. package/dist/esm-node/index.mjs +2 -0
  67. package/dist/esm-node/plugins/backend-federation/codegen.mjs +158 -0
  68. package/dist/esm-node/plugins/backend-federation/config.mjs +142 -0
  69. package/dist/esm-node/plugins/backend-federation/emit.mjs +89 -0
  70. package/dist/esm-node/plugins/backendFederationBuild.mjs +2 -0
  71. package/dist/esm-node/plugins/deploy/platforms/cloudflare/artifacts.mjs +65 -0
  72. package/dist/esm-node/plugins/deploy/platforms/cloudflare/constants.mjs +34 -0
  73. package/dist/esm-node/plugins/deploy/platforms/cloudflare/delivery-unit.mjs +68 -0
  74. package/dist/esm-node/plugins/deploy/platforms/cloudflare/i18n-worker.mjs +98 -0
  75. package/dist/esm-node/plugins/deploy/platforms/cloudflare/index.mjs +79 -0
  76. package/dist/esm-node/plugins/deploy/platforms/cloudflare/security-policies.mjs +168 -0
  77. package/dist/esm-node/plugins/deploy/platforms/cloudflare/types.mjs +1 -0
  78. package/dist/esm-node/plugins/deploy/platforms/cloudflare/utils.mjs +13 -0
  79. package/dist/esm-node/plugins/deploy/platforms/cloudflare/worker-manifest.mjs +119 -0
  80. package/dist/esm-node/plugins/deploy/platforms/cloudflare/wrangler-config.mjs +136 -0
  81. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-contract.mjs +18 -0
  82. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-plan.mjs +46 -0
  83. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/identity.mjs +46 -0
  84. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +130 -0
  85. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/issues.mjs +11 -0
  86. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/manifest.mjs +46 -0
  87. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.mjs +98 -0
  88. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.mjs +69 -0
  89. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier.mjs +2 -0
  90. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +1 -492
  91. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.mjs +22 -0
  92. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.mjs +0 -0
  93. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.mjs +0 -0
  94. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.mjs +0 -0
  95. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.mjs +0 -0
  96. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.006-fetch-handler.mjs +32 -0
  97. package/dist/types/plugins/backend-federation/codegen.d.ts +82 -0
  98. package/dist/types/plugins/backend-federation/config.d.ts +103 -0
  99. package/dist/types/plugins/backend-federation/emit.d.ts +13 -0
  100. package/dist/types/plugins/backendFederationBuild.d.ts +2 -0
  101. package/dist/types/plugins/deploy/platforms/cloudflare/artifacts.d.ts +15 -0
  102. package/dist/types/plugins/deploy/platforms/cloudflare/constants.d.ts +23 -0
  103. package/dist/types/plugins/deploy/platforms/cloudflare/delivery-unit.d.ts +23 -0
  104. package/dist/types/plugins/deploy/platforms/cloudflare/i18n-worker.d.ts +21 -0
  105. package/dist/types/plugins/deploy/platforms/cloudflare/index.d.ts +2 -0
  106. package/dist/types/plugins/deploy/platforms/cloudflare/security-policies.d.ts +88 -0
  107. package/dist/types/plugins/deploy/platforms/cloudflare/types.d.ts +5 -0
  108. package/dist/types/plugins/deploy/platforms/cloudflare/utils.d.ts +6 -0
  109. package/dist/types/plugins/deploy/platforms/cloudflare/worker-manifest.d.ts +100 -0
  110. package/dist/types/plugins/deploy/platforms/cloudflare/wrangler-config.d.ts +39 -0
  111. package/dist/types/plugins/deploy/platforms/cloudflare-output-contract.d.ts +13 -0
  112. package/dist/types/plugins/deploy/platforms/cloudflare-output-plan.d.ts +33 -0
  113. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/identity.d.ts +4 -0
  114. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/index.d.ts +18 -0
  115. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/issues.d.ts +14 -0
  116. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/manifest.d.ts +2 -0
  117. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/mutation-policy.d.ts +13 -0
  118. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/worker-bundles.d.ts +16 -0
  119. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier.d.ts +1 -0
  120. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +1 -2
  121. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.001-bootstrap-security.d.mts +1 -0
  122. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.002-assets-routes.d.mts +1 -0
  123. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.003-i18n-locales.d.mts +1 -0
  124. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.004-rendering-css.d.mts +1 -0
  125. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.005-worker-dispatch.d.mts +1 -0
  126. package/dist/types/types/config/cloudflareDeploy.d.ts +22 -0
  127. package/dist/types/types/config/deploy.d.ts +15 -2
  128. package/lib/types.d.ts +2 -3
  129. package/package.json +17 -11
  130. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -576
  131. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -576
  132. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +0 -576
  133. /package/dist/types/plugins/deploy/platforms/templates/{cloudflare-entry.d.mts → cloudflare-entry.006-fetch-handler.d.mts} +0 -0
@@ -0,0 +1,157 @@
1
+ import node_path from "node:path";
2
+ import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, formatBackendFederationValidationErrors, validateBackendFederationManifest } from "@modern-js/utils/universal";
3
+ import { normalizeRelativePath } from "./config.mjs";
4
+ const createRelativeImportSpecifier = (fromDirectory, toFile)=>{
5
+ const relativePath = normalizeRelativePath(node_path.relative(fromDirectory, toFile));
6
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
7
+ };
8
+ const createPublicPath = (containerEntry, fallbackPort)=>{
9
+ try {
10
+ return new URL('.', containerEntry).href;
11
+ } catch {
12
+ const slashIndex = containerEntry.lastIndexOf('/');
13
+ if (slashIndex >= 0) return containerEntry.slice(0, slashIndex + 1);
14
+ return `http://localhost:${fallbackPort}/`;
15
+ }
16
+ };
17
+ const createBackendRemoteEntrySource = (workspaceRoot, app, effectApiPath, entryPath)=>{
18
+ const effectApiSpecifier = createRelativeImportSpecifier(node_path.dirname(entryPath), effectApiPath);
19
+ return `// Generated by Modern.js backend federation build.
20
+ const exposedModules = {
21
+ ${JSON.stringify(BACKEND_FEDERATION_EFFECT_EXPOSE)}: () =>
22
+ import(new URL(${JSON.stringify(effectApiSpecifier)}, import.meta.url).href),
23
+ };
24
+
25
+ export const __modernjsBackendFederation = ${JSON.stringify({
26
+ buildVersion: app.buildVersion,
27
+ expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
28
+ name: app.backendName,
29
+ packageName: app.packageName,
30
+ remoteType: app.remoteType,
31
+ source: normalizeRelativePath(node_path.relative(workspaceRoot, effectApiPath)),
32
+ version: app.version,
33
+ ...app.unitId ? {
34
+ unitId: app.unitId
35
+ } : {},
36
+ ...app.sourceRevision ? {
37
+ sourceRevision: app.sourceRevision
38
+ } : {}
39
+ }, null, 2)};
40
+
41
+ export function init() {}
42
+
43
+ export function get(id) {
44
+ const load = exposedModules[id];
45
+ if (!load) {
46
+ throw new Error(\`Unexpected backend federation expose: \${id}\`);
47
+ }
48
+
49
+ return async () => load();
50
+ }
51
+
52
+ export default { get, init };
53
+ `;
54
+ };
55
+ const createBackendManifest = (workspaceRoot, distDirectory, app)=>{
56
+ const sourceModule = `${app.directory}/api/effect-api.ts`;
57
+ const publicPath = createPublicPath(app.containerEntry, app.port);
58
+ const manifest = {
59
+ schemaVersion: 1,
60
+ id: app.backendName,
61
+ name: app.backendName,
62
+ version: app.version,
63
+ buildVersion: app.buildVersion,
64
+ metaData: {
65
+ name: app.backendName,
66
+ type: 'backend',
67
+ buildInfo: {
68
+ buildVersion: app.buildVersion,
69
+ buildName: app.packageName
70
+ },
71
+ remoteEntry: {
72
+ name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
73
+ path: '',
74
+ type: app.remoteType
75
+ },
76
+ globalName: app.backendName,
77
+ publicPath,
78
+ ssrRemoteEntry: {
79
+ name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
80
+ path: '',
81
+ type: app.remoteType
82
+ },
83
+ ssrPublicPath: publicPath
84
+ },
85
+ entry: {
86
+ file: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
87
+ path: normalizeRelativePath(node_path.relative(workspaceRoot, node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE))),
88
+ type: app.remoteType,
89
+ url: app.containerEntry
90
+ },
91
+ exposes: [
92
+ {
93
+ id: `${app.backendName}:${BACKEND_FEDERATION_EFFECT_EXPOSE}`,
94
+ name: BACKEND_FEDERATION_EFFECT_EXPOSE,
95
+ path: '',
96
+ assets: {
97
+ js: {
98
+ async: [],
99
+ sync: [
100
+ BACKEND_FEDERATION_REMOTE_ENTRY_FILE
101
+ ]
102
+ },
103
+ css: {
104
+ async: [],
105
+ sync: []
106
+ }
107
+ }
108
+ }
109
+ ],
110
+ shared: [],
111
+ backendFederation: {
112
+ role: 'microvertical-server',
113
+ name: app.backendName,
114
+ runtimeFramework: 'effect',
115
+ strictEffectApproach: true,
116
+ contractVersion: BACKEND_FEDERATION_CONTRACT_VERSION,
117
+ nodeAdapterVersion: BACKEND_FEDERATION_NODE_ADAPTER_VERSION,
118
+ remoteType: app.remoteType,
119
+ expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
120
+ manifestUrl: app.manifestUrl,
121
+ containerEntry: app.containerEntry,
122
+ source: {
123
+ module: sourceModule
124
+ },
125
+ readinessPath: `${app.apiPrefix}/${app.apiStem}/readiness`,
126
+ openapiPath: `${app.apiPrefix}/openapi.json`,
127
+ ...app.deliveryUnit ? {
128
+ deliveryUnit: app.deliveryUnit
129
+ } : {},
130
+ versionBoundary: {
131
+ invariant: 'web-and-api-same-build',
132
+ packageName: app.packageName,
133
+ version: app.version,
134
+ buildVersion: app.buildVersion,
135
+ ...app.uiManifestUrl ? {
136
+ uiManifestUrl: app.uiManifestUrl
137
+ } : {},
138
+ ...app.deliveryUnit ? {
139
+ deliveryUnit: {
140
+ unitId: app.deliveryUnit.unitId,
141
+ buildMarker: app.deliveryUnit.buildMarker,
142
+ sourceRevision: app.deliveryUnit.sourceRevision
143
+ }
144
+ } : {}
145
+ }
146
+ }
147
+ };
148
+ const validation = validateBackendFederationManifest(manifest, {
149
+ path: 'backendFederationManifest',
150
+ requireEffectExpose: true,
151
+ requireEffectRuntime: true,
152
+ requireVersionFields: true
153
+ });
154
+ if (!validation.ok) throw new Error(`[backend-federation-build] Invalid backend federation manifest: ${formatBackendFederationValidationErrors(validation.errors)}.`);
155
+ return manifest;
156
+ };
157
+ export { createBackendManifest, createBackendRemoteEntrySource };
@@ -0,0 +1,141 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import promises from "node:fs/promises";
4
+ import node_path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, DELIVERY_UNIT_DEPLOY_PROFILE, DELIVERY_UNIT_KIND, DELIVERY_UNIT_SCHEMA_VERSION, ULTRAMODERN_BUILD_ARTIFACT_FILE, ULTRAMODERN_BUILD_ARTIFACT_PATH, ULTRAMODERN_BUILD_MODULE_PATH, deliveryUnitContractBlock, validateDeliveryUnitRecord, validateUltramodernBuildArtifact } from "@modern-js/utils/universal";
7
+ const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
8
+ const execFileAsync = promisify(execFile);
9
+ const normalizeRelativePath = (value)=>value.replace(/\\/gu, '/').replace(/^\.\/+/u, '');
10
+ const isRecord = (value)=>'object' == typeof value && null !== value;
11
+ const readJsonFile = async (filePath)=>JSON.parse(await promises.readFile(filePath, 'utf8'));
12
+ const buildArtifactPathFor = (appDirectory)=>node_path.join(appDirectory, ULTRAMODERN_BUILD_ARTIFACT_PATH);
13
+ const buildModulePathFor = (appDirectory)=>node_path.join(appDirectory, ULTRAMODERN_BUILD_MODULE_PATH);
14
+ const readBuildIdentity = async (appDirectory)=>{
15
+ const buildArtifactPath = buildArtifactPathFor(appDirectory);
16
+ if (existsSync(buildArtifactPath)) {
17
+ const artifact = await readJsonFile(buildArtifactPath);
18
+ const artifactValidation = validateUltramodernBuildArtifact(artifact, buildArtifactPath);
19
+ if (!artifactValidation.ok) throw new Error(`[backend-federation-build] Invalid delivery-unit build artifact at ${buildArtifactPath}.`);
20
+ const deliveryUnit = artifact.deliveryUnit;
21
+ return {
22
+ artifact,
23
+ appId: deliveryUnit.appId,
24
+ buildVersion: deliveryUnit.buildMarker,
25
+ packageName: deliveryUnit.packageName,
26
+ version: deliveryUnit.version,
27
+ unitId: deliveryUnit.unitId,
28
+ sourceRevision: deliveryUnit.sourceRevision
29
+ };
30
+ }
31
+ const buildModulePath = buildModulePathFor(appDirectory);
32
+ if (!existsSync(buildModulePath)) return {};
33
+ console.warn(`[backend-federation-build] ${buildArtifactPath} missing; falling back to legacy regex parsing of ${buildModulePath}. Regenerate the workspace to emit ${ULTRAMODERN_BUILD_ARTIFACT_FILE}.`);
34
+ const source = await promises.readFile(buildModulePath, 'utf8');
35
+ return {
36
+ appId: source.match(/\bappId:\s*['"]([^'"]+)['"]/u)?.[1],
37
+ buildVersion: source.match(/\bbuild:\s*['"]([^'"]+)['"]/u)?.[1],
38
+ packageName: source.match(/\bpackageName:\s*['"]([^'"]+)['"]/u)?.[1],
39
+ version: source.match(/\bversion:\s*['"]([^'"]+)['"]/u)?.[1],
40
+ unitId: source.match(/\bunitId:\s*['"]([^'"]+)['"]/u)?.[1],
41
+ sourceRevision: source.match(/\bsourceRevision:\s*['"]([^'"]+)['"]/u)?.[1]
42
+ };
43
+ };
44
+ const toPascalCase = (value)=>value.split(/[^a-zA-Z0-9]+/u).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
45
+ const stringValue = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
46
+ const createBackendName = (app, id)=>{
47
+ const configuredName = stringValue(app.backendFederation?.name) ?? stringValue(app.backendFederation?.executionSurfaces?.node?.remoteName) ?? stringValue(app.serverExecution?.node?.remoteName);
48
+ if (configuredName) return configuredName;
49
+ const mfName = stringValue(app.moduleFederation?.name);
50
+ return mfName ? `${mfName}Backend` : `vertical${toPascalCase(id)}Backend`;
51
+ };
52
+ const findWorkspaceRoot = (appDirectory)=>{
53
+ let current = appDirectory;
54
+ while(true){
55
+ if (existsSync(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
56
+ const parent = node_path.dirname(current);
57
+ if (parent === current) return;
58
+ current = parent;
59
+ }
60
+ };
61
+ const resolveWorkspaceSourceRevision = async (workspaceRoot)=>{
62
+ const envRevision = process.env.ULTRAMODERN_SOURCE_REVISION?.trim();
63
+ if (envRevision) return envRevision;
64
+ try {
65
+ const { stdout } = await execFileAsync('git', [
66
+ '-C',
67
+ workspaceRoot,
68
+ 'rev-parse',
69
+ 'HEAD'
70
+ ]);
71
+ const revision = stdout.trim();
72
+ if (revision.length > 0) return revision;
73
+ } catch {}
74
+ console.warn('[backend-federation-build] Could not resolve git source revision; stamping sourceRevision as "workspace". Set ULTRAMODERN_SOURCE_REVISION to override.');
75
+ return 'workspace';
76
+ };
77
+ const createStampedDeliveryUnit = (input)=>{
78
+ if (!input.unitId || !input.buildMarker || !input.packageName || !input.version) return;
79
+ const record = {
80
+ schemaVersion: DELIVERY_UNIT_SCHEMA_VERSION,
81
+ kind: DELIVERY_UNIT_KIND,
82
+ appId: input.appId,
83
+ unitId: input.unitId,
84
+ packageName: input.packageName,
85
+ version: input.version,
86
+ buildMarker: input.buildMarker,
87
+ sourceRevision: input.sourceRevision,
88
+ deployProfile: DELIVERY_UNIT_DEPLOY_PROFILE
89
+ };
90
+ const validation = validateDeliveryUnitRecord(record);
91
+ if (!validation.ok) return;
92
+ return deliveryUnitContractBlock(record);
93
+ };
94
+ const createAppFromCompactMetadata = (workspaceRoot, appDirectory, compactApp)=>{
95
+ const id = stringValue(compactApp.id);
96
+ const appPath = stringValue(compactApp.path);
97
+ if (!id || 'vertical' !== compactApp.kind || !isRecord(compactApp.api)) return;
98
+ const directory = appPath ? normalizeRelativePath(appPath) : `verticals/${id}`;
99
+ if (node_path.resolve(workspaceRoot, directory) !== node_path.resolve(appDirectory)) return;
100
+ const port = 'number' == typeof compactApp.port ? compactApp.port : void 0;
101
+ if (void 0 === port) return;
102
+ const apiPrefix = stringValue(compactApp.api.prefix) ?? `/${id}-api`;
103
+ const apiStem = stringValue(compactApp.api.stem) ?? id;
104
+ const backendName = createBackendName(compactApp, id);
105
+ const manifestUrl = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.manifestUrl) ?? stringValue(compactApp.serverExecution?.node?.manifestUrl) ?? `http://localhost:${port}/${BACKEND_FEDERATION_MANIFEST_FILE}`;
106
+ const containerEntry = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.containerEntry) ?? stringValue(compactApp.serverExecution?.node?.containerEntry) ?? `http://localhost:${port}/${BACKEND_FEDERATION_REMOTE_ENTRY_FILE}`;
107
+ const remoteType = stringValue(compactApp.backendFederation?.executionSurfaces?.node?.remoteType) ?? stringValue(compactApp.serverExecution?.node?.remoteType) ?? 'module';
108
+ const packageName = stringValue(compactApp.package);
109
+ const uiManifestUrl = stringValue(compactApp.backendFederation?.versionBoundary?.ui?.manifestUrl) ?? stringValue(compactApp.moduleFederation?.manifestUrl);
110
+ const compactDeliveryUnit = isRecord(compactApp.deliveryUnit) ? {
111
+ unitId: stringValue(compactApp.deliveryUnit.unitId),
112
+ buildMarker: stringValue(compactApp.deliveryUnit.buildMarker),
113
+ sourceRevision: stringValue(compactApp.deliveryUnit.sourceRevision),
114
+ packageName: stringValue(compactApp.deliveryUnit.packageName),
115
+ version: stringValue(compactApp.deliveryUnit.version)
116
+ } : void 0;
117
+ return {
118
+ id,
119
+ directory,
120
+ packageName,
121
+ port,
122
+ apiPrefix,
123
+ apiStem,
124
+ backendName,
125
+ manifestUrl,
126
+ containerEntry,
127
+ remoteType,
128
+ uiManifestUrl,
129
+ compactDeliveryUnit
130
+ };
131
+ };
132
+ const findBackendFederationApp = async (workspaceRoot, appDirectory)=>{
133
+ const compactConfigPath = node_path.join(workspaceRoot, COMPACT_CONFIG_PATH);
134
+ const compactConfig = await readJsonFile(compactConfigPath);
135
+ const apps = Array.isArray(compactConfig.topology?.apps) ? compactConfig.topology.apps : [];
136
+ for (const app of apps){
137
+ const resolved = createAppFromCompactMetadata(workspaceRoot, appDirectory, app);
138
+ if (resolved) return resolved;
139
+ }
140
+ };
141
+ export { COMPACT_CONFIG_PATH, buildArtifactPathFor, buildModulePathFor, createAppFromCompactMetadata, createStampedDeliveryUnit, findBackendFederationApp, findWorkspaceRoot, normalizeRelativePath, readBuildIdentity, resolveWorkspaceSourceRevision };
@@ -0,0 +1,88 @@
1
+ import { existsSync } from "node:fs";
2
+ import promises from "node:fs/promises";
3
+ import node_path from "node:path";
4
+ import { BACKEND_FEDERATION_MANIFEST_FILE, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, ULTRAMODERN_BUILD_ARTIFACT_FILE, stampUltramodernBuildArtifactSourceRevision } from "@modern-js/utils/universal";
5
+ import { createBackendManifest, createBackendRemoteEntrySource } from "./codegen.mjs";
6
+ import { COMPACT_CONFIG_PATH, buildArtifactPathFor, buildModulePathFor, createStampedDeliveryUnit, findBackendFederationApp, findWorkspaceRoot, readBuildIdentity, resolveWorkspaceSourceRevision } from "./config.mjs";
7
+ const emitBackendFederationArtifacts = async (appDirectory, distDirectory)=>{
8
+ const workspaceRoot = findWorkspaceRoot(appDirectory);
9
+ if (!workspaceRoot) return;
10
+ const effectApiPath = node_path.join(appDirectory, 'api/effect-api.ts');
11
+ const backendFederationConfigPath = node_path.join(appDirectory, 'backend-federation.config.ts');
12
+ if (!existsSync(effectApiPath) || !existsSync(backendFederationConfigPath)) return;
13
+ const app = await findBackendFederationApp(workspaceRoot, appDirectory);
14
+ if (!app) return;
15
+ const buildIdentity = await readBuildIdentity(appDirectory);
16
+ const compactDeliveryUnit = app.compactDeliveryUnit;
17
+ const hasCompactDeliveryUnit = void 0 !== compactDeliveryUnit && (void 0 !== compactDeliveryUnit.unitId || void 0 !== compactDeliveryUnit.buildMarker || void 0 !== compactDeliveryUnit.packageName || void 0 !== compactDeliveryUnit.version);
18
+ const hasBuildIdentity = void 0 !== buildIdentity.unitId || void 0 !== buildIdentity.buildVersion || void 0 !== buildIdentity.packageName || void 0 !== buildIdentity.version;
19
+ if (hasBuildIdentity) {
20
+ const compactConfigPath = node_path.join(workspaceRoot, COMPACT_CONFIG_PATH);
21
+ const buildIdentityPath = existsSync(buildArtifactPathFor(appDirectory)) ? buildArtifactPathFor(appDirectory) : buildModulePathFor(appDirectory);
22
+ const mismatches = [];
23
+ const compare = (label, a, b, leftLabel = 'deliveryUnit')=>{
24
+ if (void 0 !== a && void 0 !== b && a !== b) mismatches.push(`${label}: ${leftLabel}=${a} vs ultramodern-build=${b}`);
25
+ };
26
+ compare('appId', app.id, buildIdentity.appId, 'topology');
27
+ if (hasCompactDeliveryUnit) {
28
+ compare('unitId', compactDeliveryUnit?.unitId, buildIdentity.unitId);
29
+ compare('buildMarker/build', compactDeliveryUnit?.buildMarker, buildIdentity.buildVersion);
30
+ compare('packageName', compactDeliveryUnit?.packageName, buildIdentity.packageName);
31
+ compare('version', compactDeliveryUnit?.version, buildIdentity.version);
32
+ }
33
+ if (mismatches.length > 0) throw new Error(`[backend-federation-build] Delivery-unit identity drift between ${compactConfigPath} (topology) and ${buildIdentityPath}: ${mismatches.join('; ')}`);
34
+ }
35
+ const unitId = compactDeliveryUnit?.unitId ?? buildIdentity.unitId;
36
+ const buildVersion = compactDeliveryUnit?.buildMarker ?? buildIdentity.buildVersion;
37
+ const sourceRevision = await resolveWorkspaceSourceRevision(workspaceRoot);
38
+ const packageName = compactDeliveryUnit?.packageName ?? buildIdentity.packageName ?? app.packageName;
39
+ const version = compactDeliveryUnit?.version ?? buildIdentity.version;
40
+ const deliveryUnit = createStampedDeliveryUnit({
41
+ appId: app.id,
42
+ unitId,
43
+ buildMarker: buildVersion,
44
+ packageName,
45
+ version,
46
+ sourceRevision
47
+ });
48
+ const stampedBuildArtifact = buildIdentity.artifact ? stampUltramodernBuildArtifactSourceRevision(buildIdentity.artifact, sourceRevision) : void 0;
49
+ const resolvedApp = {
50
+ ...app,
51
+ packageName,
52
+ version,
53
+ buildVersion,
54
+ unitId,
55
+ sourceRevision,
56
+ deliveryUnit
57
+ };
58
+ const manifestPath = node_path.join(distDirectory, BACKEND_FEDERATION_MANIFEST_FILE);
59
+ const entryPath = node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE);
60
+ const deliveryUnitArtifactPath = stampedBuildArtifact ? node_path.join(distDirectory, ULTRAMODERN_BUILD_ARTIFACT_FILE) : void 0;
61
+ await promises.mkdir(distDirectory, {
62
+ recursive: true
63
+ });
64
+ await promises.writeFile(entryPath, createBackendRemoteEntrySource(workspaceRoot, resolvedApp, effectApiPath, entryPath));
65
+ await promises.writeFile(manifestPath, `${JSON.stringify(createBackendManifest(workspaceRoot, distDirectory, resolvedApp), null, 2)}\n`);
66
+ if (stampedBuildArtifact && deliveryUnitArtifactPath) await promises.writeFile(deliveryUnitArtifactPath, `${JSON.stringify(stampedBuildArtifact, null, 2)}\n`);
67
+ return {
68
+ appId: resolvedApp.id,
69
+ manifestPath,
70
+ containerPath: entryPath,
71
+ ...deliveryUnitArtifactPath ? {
72
+ deliveryUnitArtifactPath
73
+ } : {},
74
+ remoteName: resolvedApp.backendName,
75
+ remoteType: resolvedApp.remoteType
76
+ };
77
+ };
78
+ const emit = ()=>({
79
+ name: '@modern-js/backend-federation-build',
80
+ setup (api) {
81
+ api.onAfterBuild(async ()=>{
82
+ const { appDirectory, distDirectory } = api.getAppContext();
83
+ await emitBackendFederationArtifacts(appDirectory, distDirectory);
84
+ });
85
+ }
86
+ });
87
+ export default emit;
88
+ export { emitBackendFederationArtifacts };
@@ -0,0 +1 @@
1
+ export { default, emitBackendFederationArtifacts } from "./backend-federation/emit.mjs";
@@ -0,0 +1,64 @@
1
+ import node_path from "node:path";
2
+ import { fs } from "@modern-js/utils";
3
+ import { RESERVED_ARTIFACT_DESTINATION_DIRECTORIES, RESERVED_ARTIFACT_DESTINATION_FILES, ROUTE_SPEC_OUTPUT } from "./constants.mjs";
4
+ import { normalizeRelativePath } from "./utils.mjs";
5
+ const normalizeCloudflareArtifact = (artifact, index)=>{
6
+ const from = normalizeRelativePath(artifact.from, `deploy.worker.artifacts[${index}].from`, 'app root');
7
+ const to = normalizeRelativePath(artifact.to, `deploy.worker.artifacts[${index}].to`, 'Cloudflare output');
8
+ const [topLevelDestination] = to.split('/');
9
+ const reservedDestination = RESERVED_ARTIFACT_DESTINATION_FILES.has(to) ? to : topLevelDestination;
10
+ if (RESERVED_ARTIFACT_DESTINATION_FILES.has(to) || RESERVED_ARTIFACT_DESTINATION_DIRECTORIES.has(topLevelDestination)) throw new Error(`deploy.worker.artifacts[${index}].to must not target generated Cloudflare output path ${JSON.stringify(reservedDestination)}.`);
11
+ return {
12
+ from,
13
+ to,
14
+ index
15
+ };
16
+ };
17
+ const getCloudflareArtifacts = (modernConfig)=>(modernConfig.deploy?.worker?.artifacts ?? []).map(normalizeCloudflareArtifact);
18
+ const normalizeCloudflarePublicAsset = (asset, index)=>{
19
+ const from = normalizeRelativePath(asset.from, `deploy.worker.publicAssets[${index}].from`, 'app root');
20
+ const to = normalizeRelativePath(asset.to, `deploy.worker.publicAssets[${index}].to`, 'Cloudflare public output', {
21
+ allowRoot: true
22
+ });
23
+ return {
24
+ from,
25
+ to,
26
+ index
27
+ };
28
+ };
29
+ const getCloudflarePublicAssets = (modernConfig)=>(modernConfig.deploy?.worker?.publicAssets ?? []).map(normalizeCloudflarePublicAsset);
30
+ const copyCloudflareArtifacts = async (appDirectory, outputDirectory, artifacts)=>{
31
+ for (const artifact of artifacts){
32
+ const sourcePath = node_path.join(appDirectory, artifact.from);
33
+ if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.artifacts[${artifact.index}].from does not exist: ${artifact.from}`);
34
+ await fs.copy(sourcePath, node_path.join(outputDirectory, artifact.to));
35
+ }
36
+ };
37
+ const copyCloudflarePublicAssets = async (appDirectory, publicDirectory, publicAssets)=>{
38
+ for (const asset of publicAssets){
39
+ const sourcePath = node_path.join(appDirectory, asset.from);
40
+ if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.publicAssets[${asset.index}].from does not exist: ${asset.from}`);
41
+ await fs.copy(sourcePath, node_path.join(publicDirectory, asset.to));
42
+ }
43
+ };
44
+ const copyCloudflareD1Migrations = async (appDirectory, outputDirectory, modernConfig)=>{
45
+ for (const [index, database] of (modernConfig.deploy?.worker?.d1Databases ?? []).entries()){
46
+ if (!database.migrationsDir) continue;
47
+ const migrationsDir = normalizeRelativePath(database.migrationsDir, `deploy.worker.d1Databases[${index}].migrationsDir`, 'app root');
48
+ const sourcePath = node_path.join(appDirectory, migrationsDir);
49
+ if (!await fs.pathExists(sourcePath)) throw new Error(`deploy.worker.d1Databases[${index}].migrationsDir does not exist: ${migrationsDir}`);
50
+ await fs.copy(sourcePath, node_path.join(outputDirectory, migrationsDir));
51
+ }
52
+ };
53
+ const readRouteSpec = async (outputDirectory)=>{
54
+ const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
55
+ if (!await fs.pathExists(routeSpecPath)) return {
56
+ routes: []
57
+ };
58
+ const routeSpec = await fs.readJSON(routeSpecPath);
59
+ return {
60
+ ...routeSpec,
61
+ routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
62
+ };
63
+ };
64
+ export { copyCloudflareArtifacts, copyCloudflareD1Migrations, copyCloudflarePublicAssets, getCloudflareArtifacts, getCloudflarePublicAssets, readRouteSpec };
@@ -0,0 +1,33 @@
1
+ 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_WORKER_MANIFEST, CLOUDFLARE_WRANGLER_CONFIG_FILE } from "../cloudflare-output-contract.mjs";
2
+ const WORKER_ENTRY = CLOUDFLARE_WORKER_ENTRY;
3
+ const WORKER_MANIFEST = CLOUDFLARE_WORKER_MANIFEST;
4
+ const WRANGLER_CONFIG_FILE = CLOUDFLARE_WRANGLER_CONFIG_FILE;
5
+ const OUTPUT_PACKAGE_FILE = CLOUDFLARE_OUTPUT_PACKAGE_FILE;
6
+ const ASSETS_BINDING = CLOUDFLARE_ASSETS_BINDING;
7
+ const ROUTE_SPEC_FILE = 'route.json';
8
+ const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
9
+ const LOADABLE_STATS_FILE = 'loadable-stats.json';
10
+ const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
11
+ const PUBLIC_ASSETS_DIRECTORY = CLOUDFLARE_PUBLIC_ASSETS_DIRECTORY;
12
+ const WORKER_BUNDLE_DIRECTORY = CLOUDFLARE_WORKER_BUNDLE_DIRECTORY;
13
+ const SERVER_BUNDLE_DIRECTORY = 'bundles';
14
+ const SERVER_OUTPUT_DIRECTORY = 'server';
15
+ const DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES = [
16
+ 'api',
17
+ 'shared'
18
+ ];
19
+ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
20
+ 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.';
21
+ const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
22
+ const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
23
+ const REQUIRED_COMPATIBILITY_FLAGS = CLOUDFLARE_REQUIRED_COMPATIBILITY_FLAGS;
24
+ const RESERVED_ARTIFACT_DESTINATION_FILES = new Set([
25
+ WRANGLER_CONFIG_FILE,
26
+ OUTPUT_PACKAGE_FILE
27
+ ]);
28
+ const RESERVED_ARTIFACT_DESTINATION_DIRECTORIES = new Set([
29
+ PUBLIC_ASSETS_DIRECTORY,
30
+ SERVER_OUTPUT_DIRECTORY,
31
+ WORKER_BUNDLE_DIRECTORY
32
+ ]);
33
+ export { ASSETS_BINDING, BFF_EFFECT_WORKER_ENTRY, CLOUDFLARE_RUNTIME_TYPE, CLOUDFLARE_WORKER_BUNDLE_FORMAT, COMPATIBILITY_DATE_PATTERN, DEFAULT_COMPATIBILITY_DATE, DEFAULT_SERVER_ONLY_PUBLIC_ASSET_EXCLUDES, EFFECT_BFF_CLOUDFLARE_IMPORT_GUIDANCE, LOADABLE_STATS_FILE, OUTPUT_PACKAGE_FILE, PUBLIC_ASSETS_DIRECTORY, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_ARTIFACT_DESTINATION_DIRECTORIES, RESERVED_ARTIFACT_DESTINATION_FILES, ROUTE_MANIFEST_FILE, ROUTE_SPEC_FILE, ROUTE_SPEC_OUTPUT, SERVER_BUNDLE_DIRECTORY, SERVER_OUTPUT_DIRECTORY, WORKER_BUNDLE_DIRECTORY, WORKER_ENTRY, WORKER_MANIFEST, WRANGLER_CONFIG_FILE };
@@ -0,0 +1,67 @@
1
+ import node_path from "node:path";
2
+ import { fs } from "@modern-js/utils";
3
+ import { ULTRAMODERN_BUILD_ARTIFACT_PATH, ULTRAMODERN_BUILD_MODULE_PATH, isUltramodernBuildArtifact, nonEmptyString, toDeliveryUnitIdentity } from "@modern-js/utils/universal";
4
+ import { isRecord } from "./utils.mjs";
5
+ const COMPACT_CONFIG_PATH = '.modernjs/ultramodern.json';
6
+ const findWorkspaceRoot = async (appDirectory)=>{
7
+ let current = node_path.resolve(appDirectory);
8
+ for(;;){
9
+ if (await fs.pathExists(node_path.join(current, COMPACT_CONFIG_PATH))) return current;
10
+ const parent = node_path.dirname(current);
11
+ if (parent === current) return;
12
+ current = parent;
13
+ }
14
+ };
15
+ const resolveTopologyDeliveryUnit = async (appDirectory)=>{
16
+ const workspaceRoot = await findWorkspaceRoot(appDirectory);
17
+ if (!workspaceRoot) return;
18
+ let compactConfig;
19
+ try {
20
+ compactConfig = await fs.readJSON(node_path.join(workspaceRoot, COMPACT_CONFIG_PATH));
21
+ } catch {
22
+ return;
23
+ }
24
+ if (!isRecord(compactConfig)) return;
25
+ const topology = isRecord(compactConfig.topology) ? compactConfig.topology : void 0;
26
+ const apps = Array.isArray(topology?.apps) ? topology.apps : [];
27
+ const resolvedAppDirectory = node_path.resolve(appDirectory);
28
+ for (const app of apps){
29
+ if (!isRecord(app)) continue;
30
+ const appPath = nonEmptyString(app.path);
31
+ if (appPath && node_path.resolve(workspaceRoot, appPath.replace(/^\.\/+/u, '')) === resolvedAppDirectory) return toDeliveryUnitIdentity(app.deliveryUnit);
32
+ }
33
+ return toDeliveryUnitIdentity(compactConfig.deliveryUnit);
34
+ };
35
+ const resolveWorkerDeliveryUnitStamp = async (appDirectory)=>{
36
+ const buildArtifactPath = node_path.join(appDirectory, ULTRAMODERN_BUILD_ARTIFACT_PATH);
37
+ const buildModulePath = node_path.join(appDirectory, ULTRAMODERN_BUILD_MODULE_PATH);
38
+ let identity;
39
+ if (await fs.pathExists(buildArtifactPath)) {
40
+ const artifact = await fs.readJSON(buildArtifactPath);
41
+ if (!isUltramodernBuildArtifact(artifact)) return;
42
+ identity = toDeliveryUnitIdentity(artifact.deliveryUnit);
43
+ } else if (await fs.pathExists(buildModulePath)) {
44
+ console.warn(`[cloudflare] ${buildArtifactPath} missing; falling back to legacy regex parsing of ${buildModulePath}. Regenerate the workspace to emit ultramodern-build.json.`);
45
+ const source = await fs.readFile(buildModulePath, 'utf8');
46
+ identity = toDeliveryUnitIdentity({
47
+ buildMarker: source.match(/\bbuild:\s*['"]([^'"]+)['"]/u)?.[1],
48
+ unitId: source.match(/\bunitId:\s*['"]([^'"]+)['"]/u)?.[1],
49
+ sourceRevision: source.match(/\bsourceRevision:\s*['"]([^'"]+)['"]/u)?.[1]
50
+ });
51
+ }
52
+ if (!identity) return;
53
+ return {
54
+ ...identity,
55
+ surfaces: {
56
+ ui: {
57
+ ...identity,
58
+ surface: 'ui'
59
+ },
60
+ api: {
61
+ ...identity,
62
+ surface: 'api'
63
+ }
64
+ }
65
+ };
66
+ };
67
+ export { resolveTopologyDeliveryUnit, resolveWorkerDeliveryUnitStamp };
@@ -0,0 +1,97 @@
1
+ import { isRecord } from "./utils.mjs";
2
+ const I18N_SERVER_PLUGIN_NAME = 'plugin-i18n/server';
3
+ const DEFAULT_I18NEXT_DETECTION_OPTIONS = {
4
+ order: [
5
+ 'querystring',
6
+ 'cookie',
7
+ 'localStorage',
8
+ 'header',
9
+ 'navigator',
10
+ 'htmlTag',
11
+ 'path',
12
+ 'subdomain'
13
+ ],
14
+ lookupQuerystring: 'lng',
15
+ lookupCookie: 'i18next',
16
+ lookupHeader: 'accept-language'
17
+ };
18
+ const SERVER_SIDE_I18N_DETECTORS = new Set([
19
+ 'querystring',
20
+ 'cookie',
21
+ 'header'
22
+ ]);
23
+ const toStringArray = (value)=>Array.isArray(value) ? value.filter((entry)=>'string' == typeof entry) : [];
24
+ const getI18nServerPlugin = (appContext)=>appContext.serverPlugins?.find((plugin)=>plugin.name.includes(I18N_SERVER_PLUGIN_NAME));
25
+ const removeLocaleDetectionByEntry = (config)=>{
26
+ const { localeDetectionByEntry: _localeDetectionByEntry, ...rest } = config;
27
+ return rest;
28
+ };
29
+ const getEntryLocaleDetection = (entryName, localeDetection)=>{
30
+ const byEntry = isRecord(localeDetection.localeDetectionByEntry) ? localeDetection.localeDetectionByEntry : void 0;
31
+ const entryConfig = byEntry?.[entryName];
32
+ const globalConfig = removeLocaleDetectionByEntry(localeDetection);
33
+ return isRecord(entryConfig) ? {
34
+ ...globalConfig,
35
+ ...entryConfig
36
+ } : globalConfig;
37
+ };
38
+ const normalizeI18nDetection = (detection)=>{
39
+ const configured = isRecord(detection) ? detection : {};
40
+ const rawOrder = Array.isArray(configured.order) ? configured.order : DEFAULT_I18NEXT_DETECTION_OPTIONS.order;
41
+ const order = rawOrder.filter((entry)=>'string' == typeof entry && SERVER_SIDE_I18N_DETECTORS.has(entry));
42
+ return {
43
+ order: order.length > 0 ? order : [
44
+ 'querystring',
45
+ 'cookie',
46
+ 'header'
47
+ ],
48
+ lookupQuerystring: 'string' == typeof configured.lookupQuerystring && configured.lookupQuerystring ? configured.lookupQuerystring : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupQuerystring,
49
+ lookupCookie: 'string' == typeof configured.lookupCookie && configured.lookupCookie ? configured.lookupCookie : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupCookie,
50
+ lookupHeader: 'string' == typeof configured.lookupHeader && configured.lookupHeader ? configured.lookupHeader : DEFAULT_I18NEXT_DETECTION_OPTIONS.lookupHeader
51
+ };
52
+ };
53
+ const normalizeLocalisedUrls = (localisedUrls)=>{
54
+ if (!isRecord(localisedUrls) || 0 === Object.keys(localisedUrls).length) return;
55
+ const normalized = {};
56
+ for (const [canonicalPath, languageMap] of Object.entries(localisedUrls)){
57
+ if (!isRecord(languageMap)) continue;
58
+ const normalizedLanguageMap = Object.fromEntries(Object.entries(languageMap).filter((entry)=>'string' == typeof entry[1] && entry[1].length > 0));
59
+ if (Object.keys(normalizedLanguageMap).length > 0) normalized[canonicalPath] = normalizedLanguageMap;
60
+ }
61
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
62
+ };
63
+ const normalizeWorkerI18nEntry = (entryName, localeDetection, staticRoutePrefixes)=>{
64
+ const entryConfig = getEntryLocaleDetection(entryName, localeDetection);
65
+ const languages = toStringArray(entryConfig.languages);
66
+ if (true !== entryConfig.localePathRedirect || 0 === languages.length) return;
67
+ const fallbackLanguage = 'string' == typeof entryConfig.fallbackLanguage && entryConfig.fallbackLanguage ? entryConfig.fallbackLanguage : 'en';
68
+ const ignoreRedirectRoutes = Array.isArray(entryConfig.ignoreRedirectRoutes) ? toStringArray(entryConfig.ignoreRedirectRoutes) : [];
69
+ const localisedUrls = normalizeLocalisedUrls(entryConfig.localisedUrls);
70
+ return {
71
+ i18nextDetector: false !== entryConfig.i18nextDetector,
72
+ languages,
73
+ fallbackLanguage,
74
+ detection: normalizeI18nDetection(entryConfig.detection),
75
+ ignoreRedirectRoutes,
76
+ staticRoutePrefixes,
77
+ ...localisedUrls ? {
78
+ localisedUrls
79
+ } : {}
80
+ };
81
+ };
82
+ const createI18nWorkerManifest = (routeSpec, appContext)=>{
83
+ const i18nServerPlugin = getI18nServerPlugin(appContext);
84
+ const localeDetection = i18nServerPlugin?.options?.localeDetection;
85
+ if (!isRecord(localeDetection)) return;
86
+ const staticRoutePrefixes = toStringArray(i18nServerPlugin?.options?.staticRoutePrefixes);
87
+ const entries = {};
88
+ for (const route of routeSpec.routes){
89
+ if ('string' != typeof route.entryName || entries[route.entryName]) continue;
90
+ const entry = normalizeWorkerI18nEntry(route.entryName, localeDetection, staticRoutePrefixes);
91
+ if (entry) entries[route.entryName] = entry;
92
+ }
93
+ return Object.keys(entries).length > 0 ? {
94
+ entries
95
+ } : void 0;
96
+ };
97
+ export { createI18nWorkerManifest };