@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.10 → 3.2.0-ultramodern.100

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 (44) hide show
  1. package/bin/modern.js +0 -0
  2. package/dist/cjs/baseline.js +43 -1
  3. package/dist/cjs/builder/generator/getBuilderEnvironments.js +191 -8
  4. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +41 -5
  5. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +3 -1
  6. package/dist/cjs/plugins/deploy/index.js +17 -6
  7. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +222 -0
  8. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  9. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  10. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  11. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  12. package/dist/cjs/rsbuild.js +3 -0
  13. package/dist/esm/baseline.mjs +33 -1
  14. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +180 -8
  15. package/dist/esm/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  16. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  17. package/dist/esm/plugins/deploy/index.mjs +10 -4
  18. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +178 -0
  19. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  20. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  21. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  22. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  23. package/dist/esm/rsbuild.mjs +5 -2
  24. package/dist/esm-node/baseline.mjs +33 -1
  25. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +185 -9
  26. package/dist/esm-node/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  27. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  28. package/dist/esm-node/plugins/deploy/index.mjs +10 -4
  29. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +179 -0
  30. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  31. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  32. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  33. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  34. package/dist/esm-node/rsbuild.mjs +5 -2
  35. package/dist/types/locale/en.d.ts +1 -1
  36. package/dist/types/locale/zh.d.ts +1 -1
  37. package/dist/types/plugins/deploy/index.d.ts +4 -1
  38. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +2 -0
  39. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +4 -0
  40. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.d.mts +5 -0
  41. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.d.mts +48 -0
  42. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-path.d.mts +21 -0
  43. package/dist/types/types/config/deploy.d.ts +8 -0
  44. package/package.json +18 -17
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ createCloudflarePreset: ()=>createCloudflarePreset
37
+ });
38
+ const external_node_path_namespaceObject = require("node:path");
39
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
40
+ const utils_namespaceObject = require("@modern-js/utils");
41
+ const index_js_namespaceObject = require("../utils/index.js");
42
+ const WORKER_ENTRY = 'server/index.mjs';
43
+ const WORKER_MANIFEST = 'server/modern-worker-manifest.json';
44
+ const ASSETS_BINDING = 'ASSETS';
45
+ const ROUTE_SPEC_FILE = 'route.json';
46
+ const ROUTE_SPEC_OUTPUT = `server/${ROUTE_SPEC_FILE}`;
47
+ const LOADABLE_STATS_FILE = 'loadable-stats.json';
48
+ const ROUTE_MANIFEST_FILE = 'routes-manifest.json';
49
+ const PUBLIC_ASSETS_DIRECTORY = 'public';
50
+ const WORKER_BUNDLE_DIRECTORY = 'worker';
51
+ const SERVER_BUNDLE_DIRECTORY = 'bundles';
52
+ const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
53
+ const getCompatibilityDate = ()=>new Date().toISOString().slice(0, 10);
54
+ const getWorkerName = (appDirectory)=>{
55
+ const basename = external_node_path_default().basename(appDirectory);
56
+ return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
57
+ };
58
+ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
59
+ const configuredName = modernConfig.deploy?.worker?.name?.trim();
60
+ return configuredName || getWorkerName(appDirectory);
61
+ };
62
+ const readRouteSpec = async (outputDirectory)=>{
63
+ const routeSpecPath = external_node_path_default().join(outputDirectory, ROUTE_SPEC_OUTPUT);
64
+ if (!await utils_namespaceObject.fs.pathExists(routeSpecPath)) return {
65
+ routes: []
66
+ };
67
+ const routeSpec = await utils_namespaceObject.fs.readJSON(routeSpecPath);
68
+ return {
69
+ ...routeSpec,
70
+ routes: Array.isArray(routeSpec.routes) ? routeSpec.routes : []
71
+ };
72
+ };
73
+ const createWorkerManifest = async (outputDirectory, modernConfig)=>{
74
+ const routeSpec = await readRouteSpec(outputDirectory);
75
+ const routes = await Promise.all(routeSpec.routes.map(async (route)=>{
76
+ const worker = 'string' == typeof route.worker ? route.worker : void 0;
77
+ return {
78
+ urlPath: route.urlPath,
79
+ entryName: route.entryName,
80
+ entryPath: route.entryPath,
81
+ isSSR: Boolean(route.isSSR),
82
+ worker,
83
+ workerExists: worker ? await utils_namespaceObject.fs.pathExists(external_node_path_default().join(outputDirectory, worker)) : false
84
+ };
85
+ }));
86
+ const bffPrefix = modernConfig.bff?.prefix;
87
+ const primaryBffPrefix = Array.isArray(bffPrefix) ? bffPrefix[0] : bffPrefix;
88
+ const isEffectBff = Boolean(modernConfig.bff) && modernConfig.bff?.runtimeFramework !== 'hono';
89
+ const effectBffWorkerExists = await utils_namespaceObject.fs.pathExists(external_node_path_default().join(outputDirectory, BFF_EFFECT_WORKER_ENTRY));
90
+ return {
91
+ version: 1,
92
+ runtime: {
93
+ type: 'cloudflare-module-worker',
94
+ entry: WORKER_ENTRY,
95
+ fetchExport: true,
96
+ nodeListen: false
97
+ },
98
+ assets: {
99
+ binding: ASSETS_BINDING,
100
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
101
+ runWorkerFirst: true
102
+ },
103
+ routeSpec: {
104
+ file: ROUTE_SPEC_OUTPUT,
105
+ routes
106
+ },
107
+ workerBundles: {
108
+ directory: WORKER_BUNDLE_DIRECTORY,
109
+ format: 'commonjs',
110
+ importableFromModuleWorker: true,
111
+ requestHandlerExport: 'requestHandler'
112
+ },
113
+ resources: {
114
+ loadableStats: LOADABLE_STATS_FILE,
115
+ routeManifest: ROUTE_MANIFEST_FILE
116
+ },
117
+ bff: isEffectBff && primaryBffPrefix && effectBffWorkerExists ? {
118
+ runtimeFramework: 'effect',
119
+ prefix: primaryBffPrefix,
120
+ worker: BFF_EFFECT_WORKER_ENTRY
121
+ } : void 0
122
+ };
123
+ };
124
+ const createWorkerModuleLoaders = (manifest)=>{
125
+ const imports = new Map();
126
+ for (const route of manifest.routeSpec.routes)if (route.worker && route.workerExists) {
127
+ const importPath = `../${String(route.worker).replace(/^\/+/u, '')}`;
128
+ imports.set(route.worker, `() => import(${JSON.stringify(importPath)})`);
129
+ }
130
+ if (manifest.bff?.worker) {
131
+ const importPath = `../${String(manifest.bff.worker).replace(/^\/+/u, '')}`;
132
+ imports.set(manifest.bff.worker, `() => import(${JSON.stringify(importPath)})`);
133
+ }
134
+ if (0 === imports.size) return '{}';
135
+ const loaders = [
136
+ ...imports.entries()
137
+ ].map(([worker, loader])=>`${JSON.stringify(worker)}: ${loader}`);
138
+ return `{\n${loaders.join(',\n')}\n}`;
139
+ };
140
+ const shouldCopyToPublicAssets = (src, distDirectory)=>{
141
+ const relativePath = external_node_path_default().relative(distDirectory, src);
142
+ if (!relativePath) return true;
143
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
144
+ const [topLevelDirectory] = normalizedRelativePath.split('/');
145
+ return normalizedRelativePath !== ROUTE_SPEC_FILE && topLevelDirectory !== WORKER_BUNDLE_DIRECTORY && topLevelDirectory !== SERVER_BUNDLE_DIRECTORY;
146
+ };
147
+ const shouldCopyToWorkerBundle = (src, workerBundleDirectory)=>{
148
+ const relativePath = external_node_path_default().relative(workerBundleDirectory, src);
149
+ if (!relativePath) return true;
150
+ const normalizedRelativePath = relativePath.replace(/\\/g, '/');
151
+ const basename = external_node_path_default().basename(normalizedRelativePath);
152
+ if (basename.startsWith('.') || normalizedRelativePath.includes('/.')) return false;
153
+ if (utils_namespaceObject.fs.statSync(src).isDirectory()) return true;
154
+ return [
155
+ '.cjs',
156
+ '.js',
157
+ '.mjs'
158
+ ].includes(external_node_path_default().extname(normalizedRelativePath));
159
+ };
160
+ const createCloudflarePreset = ({ appContext, modernConfig })=>{
161
+ const { appDirectory, distDirectory } = appContext;
162
+ const outputDirectory = external_node_path_default().join(appDirectory, '.output');
163
+ const publicDirectory = external_node_path_default().join(outputDirectory, PUBLIC_ASSETS_DIRECTORY);
164
+ const workerEntryPath = external_node_path_default().join(outputDirectory, WORKER_ENTRY);
165
+ const workerManifestPath = external_node_path_default().join(outputDirectory, WORKER_MANIFEST);
166
+ const routeSpecOutputPath = external_node_path_default().join(outputDirectory, ROUTE_SPEC_OUTPUT);
167
+ const wranglerConfigPath = external_node_path_default().join(outputDirectory, 'wrangler.json');
168
+ const workerName = getConfiguredWorkerName(appDirectory, modernConfig);
169
+ return {
170
+ async prepare () {
171
+ await utils_namespaceObject.fs.remove(outputDirectory);
172
+ },
173
+ async writeOutput () {
174
+ await utils_namespaceObject.fs.copy(distDirectory, publicDirectory, {
175
+ filter: (src)=>shouldCopyToPublicAssets(src, distDirectory)
176
+ });
177
+ await utils_namespaceObject.fs.ensureDir(external_node_path_default().dirname(workerEntryPath));
178
+ await utils_namespaceObject.fs.ensureDir(external_node_path_default().dirname(workerManifestPath));
179
+ const routeSpecSourcePath = external_node_path_default().join(distDirectory, ROUTE_SPEC_FILE);
180
+ if (await utils_namespaceObject.fs.pathExists(routeSpecSourcePath)) await utils_namespaceObject.fs.copy(routeSpecSourcePath, routeSpecOutputPath);
181
+ const workerBundleSourceDirectory = external_node_path_default().join(distDirectory, WORKER_BUNDLE_DIRECTORY);
182
+ if (await utils_namespaceObject.fs.pathExists(workerBundleSourceDirectory)) await utils_namespaceObject.fs.copy(workerBundleSourceDirectory, external_node_path_default().join(outputDirectory, WORKER_BUNDLE_DIRECTORY), {
183
+ filter: (src)=>shouldCopyToWorkerBundle(src, workerBundleSourceDirectory)
184
+ });
185
+ await utils_namespaceObject.fs.writeJSON(wranglerConfigPath, {
186
+ $schema: 'node_modules/wrangler/config-schema.json',
187
+ name: workerName,
188
+ main: WORKER_ENTRY,
189
+ compatibility_date: getCompatibilityDate(),
190
+ compatibility_flags: [
191
+ 'nodejs_compat',
192
+ 'global_fetch_strictly_public'
193
+ ],
194
+ assets: {
195
+ directory: `./${PUBLIC_ASSETS_DIRECTORY}`,
196
+ binding: ASSETS_BINDING,
197
+ run_worker_first: true
198
+ }
199
+ }, {
200
+ spaces: 2
201
+ });
202
+ await utils_namespaceObject.fs.writeJSON(workerManifestPath, await createWorkerManifest(outputDirectory, modernConfig), {
203
+ spaces: 2
204
+ });
205
+ await utils_namespaceObject.fs.writeJSON(external_node_path_default().join(outputDirectory, 'package.json'), {
206
+ type: 'commonjs'
207
+ });
208
+ },
209
+ async genEntry () {
210
+ const template = await (0, index_js_namespaceObject.readTemplate)('cloudflare-entry.mjs');
211
+ const manifest = await utils_namespaceObject.fs.readJSON(workerManifestPath);
212
+ await utils_namespaceObject.fs.writeFile(workerEntryPath, template.replace('p_workerManifest', JSON.stringify(manifest, null, 2)).replace('p_workerModuleLoaders', createWorkerModuleLoaders(manifest)));
213
+ }
214
+ };
215
+ };
216
+ exports.createCloudflarePreset = __webpack_exports__.createCloudflarePreset;
217
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
218
+ "createCloudflarePreset"
219
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
220
+ Object.defineProperty(exports, '__esModule', {
221
+ value: true
222
+ });
@@ -0,0 +1,438 @@
1
+ const ASSETS_BINDING = 'ASSETS';
2
+ const MODERN_WORKER_MANIFEST = p_workerManifest;
3
+ const WORKER_MODULE_LOADERS = p_workerModuleLoaders;
4
+ const workerModulePromises = new Map();
5
+ const remoteJsonPromises = new Map();
6
+ const CORS_HEADERS = {
7
+ 'access-control-allow-headers': '*',
8
+ 'access-control-allow-methods': 'GET, HEAD, OPTIONS',
9
+ 'access-control-allow-origin': '*'
10
+ };
11
+ globalThis.__dirname ??= '/';
12
+ globalThis.__filename ??= '/index.js';
13
+ function withCorsHeaders(response) {
14
+ const headers = new Headers(response.headers);
15
+ for (const [name, value] of Object.entries(CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
16
+ return new Response(response.body, {
17
+ headers,
18
+ status: response.status,
19
+ statusText: response.statusText
20
+ });
21
+ }
22
+ function isFingerprintedAssetPathname(pathname) {
23
+ return /(?:^|\/)[^/]+\.[a-f0-9]{8,}\.(?:css|js|mjs|json|svg|png|jpe?g|webp|avif|gif|woff2?|ttf)$/iu.test(pathname);
24
+ }
25
+ function withAssetHeaders(response, request) {
26
+ const corsResponse = withCorsHeaders(response);
27
+ const headers = new Headers(corsResponse.headers);
28
+ const { pathname } = new URL(request.url);
29
+ if (isFingerprintedAssetPathname(pathname)) headers.set('cache-control', 'public, max-age=31536000, immutable');
30
+ return new Response(corsResponse.body, {
31
+ headers,
32
+ status: corsResponse.status,
33
+ statusText: corsResponse.statusText
34
+ });
35
+ }
36
+ function createCorsPreflightResponse(request) {
37
+ if ('OPTIONS' !== request.method) return null;
38
+ return new Response(null, {
39
+ headers: CORS_HEADERS,
40
+ status: 204
41
+ });
42
+ }
43
+ async function fetchAsset(request, env) {
44
+ const assets = env?.[ASSETS_BINDING];
45
+ if (!assets || 'function' != typeof assets.fetch) return null;
46
+ const response = await assets.fetch(request);
47
+ if (404 === response.status) return null;
48
+ return withAssetHeaders(response, request);
49
+ }
50
+ async function fetchAssetByPath(pathname, request, env) {
51
+ const url = new URL(request.url);
52
+ url.pathname = `/${pathname.replace(/^\/+/u, '')}`;
53
+ return fetchAsset(new Request(url, request), env);
54
+ }
55
+ async function fetchAssetByPathFollowingRedirects(pathname, request, env, visited = new Set()) {
56
+ const normalizedPathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
57
+ if (visited.has(normalizedPathname)) return null;
58
+ visited.add(normalizedPathname);
59
+ const response = await fetchAssetByPath(normalizedPathname, request, env);
60
+ if (response && response.status >= 300 && response.status < 400 && response.headers.has('location')) {
61
+ const location = response.headers.get('location');
62
+ if (location) {
63
+ const nextUrl = new URL(location, request.url);
64
+ const currentUrl = new URL(request.url);
65
+ if (nextUrl.origin === currentUrl.origin) return fetchAssetByPathFollowingRedirects(nextUrl.pathname, request, env, visited);
66
+ }
67
+ }
68
+ return response;
69
+ }
70
+ async function readAssetText(pathname, request, env) {
71
+ const response = await fetchAssetByPathFollowingRedirects(pathname, request, env);
72
+ if (!response || !response.ok) return;
73
+ return response.text();
74
+ }
75
+ async function readAssetJson(pathname, request, env) {
76
+ const text = await readAssetText(pathname, request, env);
77
+ if (!text) return {};
78
+ return JSON.parse(text);
79
+ }
80
+ function normalizeRoutePath(pathname) {
81
+ if ('/' === pathname) return pathname;
82
+ return pathname.replace(/\/+$/u, '');
83
+ }
84
+ function getPathExtension(pathname) {
85
+ const lastSegment = pathname.split('/').pop() || '';
86
+ const dotIndex = lastSegment.lastIndexOf('.');
87
+ if (dotIndex <= 0 || dotIndex === lastSegment.length - 1) return '';
88
+ return lastSegment.slice(dotIndex).toLowerCase();
89
+ }
90
+ function isAssetLikePathname(pathname) {
91
+ const extension = getPathExtension(pathname);
92
+ return '' !== extension && '.html' !== extension && '.htm' !== extension;
93
+ }
94
+ function routeMatchesExactly(route, pathname) {
95
+ if ('string' != typeof route?.urlPath) return false;
96
+ return normalizeRoutePath(route.urlPath) === normalizeRoutePath(pathname);
97
+ }
98
+ function routeMatches(route, pathname) {
99
+ if ('string' != typeof route.urlPath) return false;
100
+ const routePath = normalizeRoutePath(route.urlPath);
101
+ const requestPath = normalizeRoutePath(pathname);
102
+ return routePath === requestPath || '/' === routePath && route.isSSR || requestPath.startsWith(`${routePath}/`);
103
+ }
104
+ function findRoute(request) {
105
+ const { pathname } = new URL(request.url);
106
+ const routes = MODERN_WORKER_MANIFEST.routeSpec.routes;
107
+ return [
108
+ ...routes
109
+ ].sort((left, right)=>{
110
+ const leftLength = left.urlPath?.length || 0;
111
+ const rightLength = right.urlPath?.length || 0;
112
+ return rightLength - leftLength;
113
+ }).find((route)=>routeMatches(route, pathname));
114
+ }
115
+ async function fetchRouteHtml(route, request, env) {
116
+ if (!route?.entryPath) return null;
117
+ return fetchAssetByPath(route.entryPath, request, env);
118
+ }
119
+ function createNoopMonitors() {
120
+ const noop = ()=>{};
121
+ return {
122
+ debug: noop,
123
+ error: noop,
124
+ info: noop,
125
+ warn: noop
126
+ };
127
+ }
128
+ function createRequestHandlerOptions({ route, htmlTemplate, routeManifest, loadableStats }) {
129
+ const monitors = createNoopMonitors();
130
+ return {
131
+ resource: {
132
+ route,
133
+ routeManifest,
134
+ loadableStats,
135
+ htmlTemplate,
136
+ entryName: route.entryName
137
+ },
138
+ params: {},
139
+ loaderContext: {},
140
+ config: {},
141
+ locals: {},
142
+ staticGenerate: false,
143
+ monitors,
144
+ onError (error) {
145
+ monitors.error(error);
146
+ },
147
+ onTiming () {},
148
+ reporter: {
149
+ reportTiming: ()=>{}
150
+ }
151
+ };
152
+ }
153
+ function collectRouteCssAssets(route, routeManifest) {
154
+ const routeAssets = routeManifest?.routeAssets || {};
155
+ const candidateKeys = [
156
+ route.entryName,
157
+ `async-${route.entryName}`
158
+ ].filter(Boolean);
159
+ const assets = new Set();
160
+ for (const key of candidateKeys){
161
+ const routeAsset = routeAssets[key];
162
+ const cssAssets = [
163
+ ...Array.isArray(routeAsset?.referenceCssAssets) ? routeAsset.referenceCssAssets : [],
164
+ ...Array.isArray(routeAsset?.assets) ? routeAsset.assets : []
165
+ ];
166
+ for (const asset of cssAssets)if ('string' == typeof asset && asset.endsWith('.css')) assets.add(asset);
167
+ }
168
+ return [
169
+ ...assets
170
+ ];
171
+ }
172
+ function collectRenderedFederatedExposes(html) {
173
+ const renderedExposes = [];
174
+ const tagPattern = /<[^>]*data-modern-(?:boundary-id|mf-expose)=["'][^"']+["'][^>]*>/g;
175
+ const attributePattern = /\s(data-modern-(?:boundary-id|mf-expose))=["']([^"']+)["']/g;
176
+ for (const [tag] of html.matchAll(tagPattern)){
177
+ const attributes = {};
178
+ for (const [, name, value] of tag.matchAll(attributePattern))attributes[name] = value;
179
+ const boundaryId = attributes['data-modern-boundary-id'];
180
+ const expose = attributes['data-modern-mf-expose'];
181
+ if (boundaryId && expose) renderedExposes.push({
182
+ boundaryId,
183
+ expose
184
+ });
185
+ }
186
+ return renderedExposes;
187
+ }
188
+ function getRemoteManifestUrl(remote, request) {
189
+ const entry = remote?.entry;
190
+ if ('string' != typeof entry || 0 === entry.length) return;
191
+ return new URL(entry, request.url).toString();
192
+ }
193
+ async function fetchRemoteJson(jsonUrl) {
194
+ if (!remoteJsonPromises.has(jsonUrl)) remoteJsonPromises.set(jsonUrl, fetch(jsonUrl).then((response)=>{
195
+ if (!response.ok) {
196
+ remoteJsonPromises.delete(jsonUrl);
197
+ return {};
198
+ }
199
+ return response.json().catch(()=>{
200
+ remoteJsonPromises.delete(jsonUrl);
201
+ return {};
202
+ });
203
+ }).catch(()=>{
204
+ remoteJsonPromises.delete(jsonUrl);
205
+ return {};
206
+ }));
207
+ return remoteJsonPromises.get(jsonUrl);
208
+ }
209
+ function findRemoteExpose(remoteManifest, exposePath) {
210
+ const exposes = Array.isArray(remoteManifest?.exposes) ? remoteManifest.exposes : [];
211
+ const normalizedExpose = exposePath.replace(/^\.\//u, '');
212
+ return exposes.find((expose)=>{
213
+ if (!expose || 'object' != typeof expose) return false;
214
+ return expose.path === exposePath || expose.path === `./${normalizedExpose}` || expose.name === normalizedExpose;
215
+ });
216
+ }
217
+ function collectCssAssetEntries(assets) {
218
+ const cssAssets = assets?.css;
219
+ return [
220
+ ...Array.isArray(cssAssets?.sync) ? cssAssets.sync : [],
221
+ ...Array.isArray(cssAssets?.async) ? cssAssets.async : []
222
+ ].filter((asset)=>'string' == typeof asset && asset.endsWith('.css'));
223
+ }
224
+ function collectRouteManifestCssAssets(routeManifest) {
225
+ const routeAssets = routeManifest?.routeAssets || {};
226
+ const assets = new Set();
227
+ for (const routeAsset of Object.values(routeAssets)){
228
+ const cssAssets = [
229
+ ...Array.isArray(routeAsset?.referenceCssAssets) ? routeAsset.referenceCssAssets : [],
230
+ ...Array.isArray(routeAsset?.assets) ? routeAsset.assets : []
231
+ ];
232
+ for (const asset of cssAssets)if ('string' == typeof asset && asset.endsWith('.css')) assets.add(asset);
233
+ }
234
+ return [
235
+ ...assets
236
+ ];
237
+ }
238
+ async function collectRenderedRemoteCssHrefs(html, request, env) {
239
+ const renderedExposes = collectRenderedFederatedExposes(html);
240
+ if (0 === renderedExposes.length) return [];
241
+ const hostManifest = await readAssetJson('mf-manifest.json', request, env);
242
+ const remotes = Array.isArray(hostManifest?.remotes) ? hostManifest.remotes : [];
243
+ const remoteByBoundary = new Map();
244
+ const hrefs = new Set();
245
+ for (const remote of remotes){
246
+ if ('string' == typeof remote?.alias) remoteByBoundary.set(remote.alias, remote);
247
+ if ('string' == typeof remote?.federationContainerName) remoteByBoundary.set(remote.federationContainerName, remote);
248
+ }
249
+ await Promise.all(renderedExposes.map(async ({ boundaryId, expose })=>{
250
+ const remote = remoteByBoundary.get(boundaryId);
251
+ const manifestUrl = remote ? getRemoteManifestUrl(remote, request) : void 0;
252
+ if (!manifestUrl) return;
253
+ const remoteManifest = await fetchRemoteJson(manifestUrl);
254
+ const remoteExpose = findRemoteExpose(remoteManifest, expose);
255
+ const publicPath = 'string' == typeof remoteManifest?.metaData?.publicPath ? remoteManifest.metaData.publicPath : manifestUrl;
256
+ const remoteRouteManifest = await fetchRemoteJson(new URL('routes-manifest.json', publicPath).toString());
257
+ for (const asset of collectCssAssetEntries(remoteExpose?.assets))hrefs.add(new URL(asset, publicPath).toString());
258
+ for (const asset of collectRouteManifestCssAssets(remoteRouteManifest))hrefs.add(new URL(asset, publicPath).toString());
259
+ }));
260
+ return [
261
+ ...hrefs
262
+ ];
263
+ }
264
+ function escapeAttribute(value) {
265
+ return String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
266
+ }
267
+ async function withRouteCssLinks(response, route, routeManifest, request, env) {
268
+ const contentType = response.headers.get('content-type') || '';
269
+ if (!contentType.includes('text/html')) return response;
270
+ const html = await response.text();
271
+ const cssHrefs = [
272
+ ...collectRouteCssAssets(route, routeManifest).map((asset)=>new URL(asset, request.url).toString()),
273
+ ...await collectRenderedRemoteCssHrefs(html, request, env)
274
+ ];
275
+ if (0 === cssHrefs.length) return response;
276
+ const uniqueCssHrefs = [
277
+ ...new Set(cssHrefs)
278
+ ];
279
+ const headers = new Headers(response.headers);
280
+ for (const href of uniqueCssHrefs)headers.append('link', `<${href}>; rel=preload; as=style`);
281
+ const links = uniqueCssHrefs.filter((href)=>!html.includes(href)).map((href)=>`<link rel="stylesheet" href="${escapeAttribute(href)}">`);
282
+ if (0 === links.length || !html.includes('</head>')) return new Response(html, {
283
+ headers,
284
+ status: response.status,
285
+ statusText: response.statusText
286
+ });
287
+ return new Response(html.replace('</head>', `${links.join('')}</head>`), {
288
+ headers,
289
+ status: response.status,
290
+ statusText: response.statusText
291
+ });
292
+ }
293
+ async function getRequestHandlerOptions(route, request, env) {
294
+ const [htmlTemplate, routeManifest, loadableStats] = await Promise.all([
295
+ readAssetText(route.entryPath, request, env),
296
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.routeManifest, request, env),
297
+ readAssetJson(MODERN_WORKER_MANIFEST.resources.loadableStats, request, env)
298
+ ]);
299
+ return createRequestHandlerOptions({
300
+ route,
301
+ htmlTemplate: htmlTemplate || '',
302
+ routeManifest,
303
+ loadableStats
304
+ });
305
+ }
306
+ async function loadWorkerModule(workerPath) {
307
+ const loader = WORKER_MODULE_LOADERS[workerPath];
308
+ if (!loader) return;
309
+ if (!workerModulePromises.has(workerPath)) workerModulePromises.set(workerPath, loader());
310
+ return workerModulePromises.get(workerPath);
311
+ }
312
+ function getRuntimeModule(workerModule) {
313
+ const defaultExport = workerModule.default;
314
+ const nestedDefaultExport = defaultExport && 'object' == typeof defaultExport ? defaultExport.default : void 0;
315
+ return defaultExport && 'object' == typeof defaultExport ? {
316
+ ...workerModule,
317
+ ...defaultExport,
318
+ ...nestedDefaultExport && 'object' == typeof nestedDefaultExport ? nestedDefaultExport : {}
319
+ } : workerModule;
320
+ }
321
+ function getFetchHandler(workerModule) {
322
+ const defaultExport = workerModule.default;
323
+ const runtime = getRuntimeModule(workerModule);
324
+ return 'function' == typeof runtime.fetch && runtime.fetch.bind(runtime) || 'function' == typeof defaultExport && defaultExport.fetch?.bind?.(defaultExport);
325
+ }
326
+ async function getRequestHandler(workerModule) {
327
+ const defaultExport = workerModule.default;
328
+ const runtime = getRuntimeModule(workerModule);
329
+ return await workerModule.requestHandler || await runtime.requestHandler || ('function' == typeof defaultExport ? defaultExport : void 0);
330
+ }
331
+ async function dispatchRouteWorker(route, request, env, ctx) {
332
+ const workerPath = route.worker;
333
+ if (!workerPath) return new Response('Worker bundle not configured for SSR route', {
334
+ status: 500,
335
+ headers: {
336
+ 'content-type': 'text/plain; charset=utf-8'
337
+ }
338
+ });
339
+ const workerModule = await loadWorkerModule(workerPath);
340
+ if (!workerModule) return new Response(`Worker bundle not found: ${workerPath}`, {
341
+ status: 500,
342
+ headers: {
343
+ 'content-type': 'text/plain; charset=utf-8',
344
+ 'x-modern-js-route-worker': workerPath
345
+ }
346
+ });
347
+ const fetchHandler = getFetchHandler(workerModule);
348
+ if (fetchHandler) return fetchHandler(request, env, ctx);
349
+ const requestHandler = await getRequestHandler(workerModule);
350
+ if ('function' == typeof requestHandler) {
351
+ const requestHandlerOptions = await getRequestHandlerOptions(route, request, env);
352
+ return withRouteCssLinks(await requestHandler(request, requestHandlerOptions), route, requestHandlerOptions.resource.routeManifest, request, env);
353
+ }
354
+ return new Response(`Worker bundle has no fetch or requestHandler export: ${workerPath}`, {
355
+ status: 500,
356
+ headers: {
357
+ 'content-type': 'text/plain; charset=utf-8',
358
+ 'x-modern-js-route-worker': workerPath
359
+ }
360
+ });
361
+ }
362
+ function matchesPrefix(pathname, prefix) {
363
+ if (!prefix || '/' === prefix) return true;
364
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
365
+ return pathname === normalized || pathname.startsWith(`${normalized}/`);
366
+ }
367
+ function createRequestForMountedPrefix(request, prefix) {
368
+ if (!prefix || '/' === prefix) return request;
369
+ const url = new URL(request.url);
370
+ const normalized = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
371
+ if (!matchesPrefix(url.pathname, normalized)) return request;
372
+ const nextPath = url.pathname.slice(normalized.length) || '/';
373
+ url.pathname = nextPath.startsWith('/') ? nextPath : `/${nextPath}`;
374
+ return new Request(url, request);
375
+ }
376
+ function createEffectContext(originalRequest, mountedRequest, env) {
377
+ const url = new URL(originalRequest.url);
378
+ return {
379
+ request: mountedRequest,
380
+ env: env || {},
381
+ path: url.pathname,
382
+ method: originalRequest.method,
383
+ operationContext: {
384
+ request: mountedRequest,
385
+ env: env || {},
386
+ path: url.pathname,
387
+ method: originalRequest.method
388
+ }
389
+ };
390
+ }
391
+ async function dispatchBffRequest(request, env) {
392
+ const bff = MODERN_WORKER_MANIFEST.bff;
393
+ if (!bff?.worker || !matchesPrefix(new URL(request.url).pathname, bff.prefix)) return null;
394
+ const workerModule = await loadWorkerModule(bff.worker);
395
+ if (!workerModule) return new Response(`BFF worker bundle not found: ${bff.worker}`, {
396
+ status: 500,
397
+ headers: {
398
+ 'content-type': 'text/plain; charset=utf-8',
399
+ 'x-modern-js-bff-worker': bff.worker
400
+ }
401
+ });
402
+ const mountedRequest = createRequestForMountedPrefix(request, bff.prefix);
403
+ const effectContext = createEffectContext(request, mountedRequest, env);
404
+ const defaultExport = workerModule.default;
405
+ const runtime = getRuntimeModule(workerModule);
406
+ const directHandler = 'function' == typeof runtime.handler && runtime.handler || 'function' == typeof defaultExport && defaultExport;
407
+ const createdHandler = 'function' == typeof runtime.createHandler ? runtime.createHandler().handler : void 0;
408
+ const handler = directHandler || createdHandler;
409
+ if ('function' != typeof handler) return new Response(`BFF worker bundle has no handler export: ${bff.worker}`, {
410
+ status: 500,
411
+ headers: {
412
+ 'content-type': 'text/plain; charset=utf-8',
413
+ 'x-modern-js-bff-worker': bff.worker
414
+ }
415
+ });
416
+ return handler.length > 1 ? handler(mountedRequest, effectContext) : handler(mountedRequest);
417
+ }
418
+ export default {
419
+ async fetch (request, env, ctx) {
420
+ const corsPreflightResponse = createCorsPreflightResponse(request);
421
+ if (corsPreflightResponse) return corsPreflightResponse;
422
+ const assetResponse = await fetchAsset(request, env);
423
+ if (assetResponse) return assetResponse;
424
+ const bffResponse = await dispatchBffRequest(request, env);
425
+ if (bffResponse) return withCorsHeaders(bffResponse);
426
+ const route = findRoute(request);
427
+ const { pathname } = new URL(request.url);
428
+ if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return withCorsHeaders(new Response('Not found', {
429
+ status: 404
430
+ }));
431
+ if (route?.worker) return withCorsHeaders(await dispatchRouteWorker(route, request, env, ctx));
432
+ const htmlResponse = await fetchRouteHtml(route, request, env);
433
+ if (htmlResponse) return htmlResponse;
434
+ return withCorsHeaders(new Response('Not found', {
435
+ status: 404
436
+ }));
437
+ }
438
+ };
@@ -0,0 +1,7 @@
1
+ const unavailable = (method)=>async ()=>{
2
+ throw new Error(`node:fs/promises.${method} is unavailable in Cloudflare Worker SSR`);
3
+ };
4
+ export const readFile = unavailable('readFile');
5
+ export default {
6
+ readFile
7
+ };