@module-federation/treeshake-server 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +71 -0
  2. package/dist/adapters/createAdapterDeps.d.ts +10 -0
  3. package/dist/adapters/local/adapter.d.ts +10 -0
  4. package/dist/adapters/local/index.d.ts +3 -0
  5. package/dist/adapters/local/localObjectStore.d.ts +12 -0
  6. package/dist/adapters/registry.d.ts +7 -0
  7. package/dist/adapters/types.d.ts +70 -0
  8. package/dist/app.d.ts +18 -0
  9. package/dist/cli/ossEnv.d.ts +18 -0
  10. package/dist/domain/build/constant.d.ts +1 -0
  11. package/dist/domain/build/normalize-config.d.ts +21 -0
  12. package/dist/domain/build/retrieve-global-name.d.ts +1 -0
  13. package/dist/domain/build/schema.d.ts +31 -0
  14. package/dist/domain/upload/constant.d.ts +2 -0
  15. package/dist/domain/upload/retrieve-cdn-path.d.ts +4 -0
  16. package/dist/frontend/adapter/index.d.ts +13 -0
  17. package/dist/frontend/adapter/index.js +128 -0
  18. package/dist/frontend/adapter/index.mjs +83 -0
  19. package/dist/frontend/favicon.ico +0 -0
  20. package/dist/frontend/index.html +1 -0
  21. package/dist/frontend/static/css/index.16175e0f.css +1 -0
  22. package/dist/frontend/static/js/954.dfe166a3.js +2 -0
  23. package/dist/frontend/static/js/954.dfe166a3.js.LICENSE.txt +16 -0
  24. package/dist/frontend/static/js/async/873.6ccd5409.js +2 -0
  25. package/dist/frontend/static/js/async/951.ec9191e2.js +12 -0
  26. package/dist/frontend/static/js/async/951.ec9191e2.js.LICENSE.txt +6 -0
  27. package/dist/frontend/static/js/async/987.6bf8e9b0.js +2 -0
  28. package/dist/frontend/static/js/async/987.6bf8e9b0.js.LICENSE.txt +6 -0
  29. package/dist/frontend/static/js/index.db4e73c6.js +88 -0
  30. package/dist/frontend/static/js/lib-react.c59642e3.js +2 -0
  31. package/dist/frontend/static/js/lib-react.c59642e3.js.LICENSE.txt +39 -0
  32. package/dist/frontend/static/js/lib-router.75e1e689.js +4 -0
  33. package/dist/frontend/static/js/lib-router.75e1e689.js.LICENSE.txt +10 -0
  34. package/dist/http/env.d.ts +10 -0
  35. package/dist/http/middlewares/di.middleware.d.ts +4 -0
  36. package/dist/http/middlewares/logger.middleware.d.ts +3 -0
  37. package/dist/http/routes/build.d.ts +3 -0
  38. package/dist/http/routes/index.d.ts +2 -0
  39. package/dist/http/routes/maintenance.d.ts +3 -0
  40. package/dist/http/routes/static.d.ts +5 -0
  41. package/dist/index.d.ts +10 -0
  42. package/dist/index.js +958 -0
  43. package/dist/index.mjs +889 -0
  44. package/dist/infra/logger.d.ts +6 -0
  45. package/dist/nodeServer.d.ts +7 -0
  46. package/dist/ports/objectStore.d.ts +1 -0
  47. package/dist/ports/projectPublisher.d.ts +1 -0
  48. package/dist/server.d.ts +2 -0
  49. package/dist/server.js +1090 -0
  50. package/dist/server.mjs +1058 -0
  51. package/dist/services/buildService.d.ts +8 -0
  52. package/dist/services/cacheService.d.ts +15 -0
  53. package/dist/services/pnpmMaintenance.d.ts +4 -0
  54. package/dist/services/uploadService.d.ts +36 -0
  55. package/dist/template/re-shake-share/Collect.js +115 -0
  56. package/dist/template/re-shake-share/EmitManifest.js +49 -0
  57. package/dist/template/re-shake-share/index.ts +1 -0
  58. package/dist/template/re-shake-share/package.json +23 -0
  59. package/dist/template/re-shake-share/rspack.config.ts +33 -0
  60. package/dist/utils/runCommand.d.ts +20 -0
  61. package/dist/utils/runtimeEnv.d.ts +3 -0
  62. package/dist/utils/uploadSdk.d.ts +10 -0
  63. package/package.json +61 -0
package/dist/server.js ADDED
@@ -0,0 +1,1090 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __webpack_require__ = {};
4
+ (()=>{
5
+ __webpack_require__.n = (module)=>{
6
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
7
+ __webpack_require__.d(getter, {
8
+ a: getter
9
+ });
10
+ return getter;
11
+ };
12
+ })();
13
+ (()=>{
14
+ __webpack_require__.d = (exports1, definition)=>{
15
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
+ enumerable: true,
17
+ get: definition[key]
18
+ });
19
+ };
20
+ })();
21
+ (()=>{
22
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ const external_node_fs_namespaceObject = require("node:fs");
26
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
27
+ const external_node_path_namespaceObject = require("node:path");
28
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
29
+ const SERVER_VERSION = 'v0-011501';
30
+ const UPLOADED_DIR = '_shared-tree-shaking';
31
+ const external_pino_namespaceObject = require("pino");
32
+ var external_pino_default = /*#__PURE__*/ __webpack_require__.n(external_pino_namespaceObject);
33
+ const createLogger = (opts)=>external_pino_default()({
34
+ level: (null == opts ? void 0 : opts.level) ?? 'info',
35
+ formatters: {
36
+ level (label) {
37
+ return {
38
+ level: label
39
+ };
40
+ }
41
+ }
42
+ });
43
+ let logger_logger = createLogger();
44
+ const setLogger = (next)=>{
45
+ logger_logger = next;
46
+ };
47
+ async function createAdapterDeps(params) {
48
+ const adapterId = params.adapterId;
49
+ const adapter = params.registry.getAdapterById(adapterId);
50
+ return adapter.create(params.adapterConfig ?? {}, {
51
+ logger: params.logger ?? logger_logger,
52
+ uploadedDir: params.uploadedDir ?? UPLOADED_DIR
53
+ });
54
+ }
55
+ function _define_property(obj, key, value) {
56
+ if (key in obj) Object.defineProperty(obj, key, {
57
+ value: value,
58
+ enumerable: true,
59
+ configurable: true,
60
+ writable: true
61
+ });
62
+ else obj[key] = value;
63
+ return obj;
64
+ }
65
+ class LocalObjectStore {
66
+ async exists(key) {
67
+ const filePath = external_node_path_default().join(this.rootDir, key.replace(/^\//, ''));
68
+ try {
69
+ const stat = await external_node_fs_default().promises.stat(filePath);
70
+ return stat.isFile();
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ async uploadFile(localPath, key) {
76
+ const rel = key.replace(/^\//, '');
77
+ const dest = external_node_path_default().join(this.rootDir, rel);
78
+ await external_node_fs_default().promises.mkdir(external_node_path_default().dirname(dest), {
79
+ recursive: true
80
+ });
81
+ await external_node_fs_default().promises.copyFile(localPath, dest);
82
+ }
83
+ publicUrl(key) {
84
+ return `${this.publicBaseUrl}${key.replace(/^\//, '')}`;
85
+ }
86
+ constructor(opts){
87
+ _define_property(this, "rootDir", void 0);
88
+ _define_property(this, "publicBaseUrl", void 0);
89
+ this.rootDir = (null == opts ? void 0 : opts.rootDir) ?? external_node_path_default().join(process.cwd(), 'log', 'static');
90
+ const base = (null == opts ? void 0 : opts.publicBaseUrl) ?? '/';
91
+ this.publicBaseUrl = base.endsWith('/') ? base : `${base}/`;
92
+ }
93
+ }
94
+ function adapter_define_property(obj, key, value) {
95
+ if (key in obj) Object.defineProperty(obj, key, {
96
+ value: value,
97
+ enumerable: true,
98
+ configurable: true,
99
+ writable: true
100
+ });
101
+ else obj[key] = value;
102
+ return obj;
103
+ }
104
+ function envStr(env, name, fallback) {
105
+ const v = env[name];
106
+ if (void 0 === v || '' === v) return fallback;
107
+ return v;
108
+ }
109
+ class LocalAdapter {
110
+ fromEnv(env) {
111
+ return {
112
+ rootDir: envStr(env, 'LOCAL_STORE_DIR', external_node_path_default().join(process.cwd(), 'log', 'static')),
113
+ publicBaseUrl: envStr(env, 'LOCAL_STORE_BASE_URL', '/')
114
+ };
115
+ }
116
+ async create(config, _context) {
117
+ const objectStore = new LocalObjectStore({
118
+ rootDir: config.rootDir,
119
+ publicBaseUrl: config.publicBaseUrl
120
+ });
121
+ return {
122
+ objectStore
123
+ };
124
+ }
125
+ constructor(){
126
+ adapter_define_property(this, "id", 'local');
127
+ }
128
+ }
129
+ function createAdapterRegistry(adapters) {
130
+ return {
131
+ adapters,
132
+ getAdapterById: (id)=>{
133
+ const found = adapters.find((a)=>a.id === id);
134
+ if (!found) throw new Error(`Unknown ADAPTER_ID: ${id}`);
135
+ return found;
136
+ }
137
+ };
138
+ }
139
+ function createOssAdapterRegistry() {
140
+ return createAdapterRegistry([
141
+ new LocalAdapter()
142
+ ]);
143
+ }
144
+ const external_hono_namespaceObject = require("hono");
145
+ function contentTypeByExt(filePath) {
146
+ if (filePath.endsWith('.js')) return "application/javascript";
147
+ if (filePath.endsWith('.json')) return 'application/json';
148
+ return 'application/octet-stream';
149
+ }
150
+ const DEFAULT_STATIC_ROOT = external_node_path_default().join(process.cwd(), 'log', 'static');
151
+ async function serveLocalFile(c, rootDir) {
152
+ let requestPath = c.req.path;
153
+ try {
154
+ requestPath = decodeURIComponent(requestPath);
155
+ } catch {
156
+ return c.text('Not Found', 404);
157
+ }
158
+ const relPath = requestPath.replace(/^\/+/, '');
159
+ const rootResolved = external_node_path_default().resolve(rootDir);
160
+ const filePath = external_node_path_default().resolve(rootResolved, relPath);
161
+ if (filePath !== rootResolved && !filePath.startsWith(`${rootResolved}${external_node_path_default().sep}`)) return c.text('Not Found', 404);
162
+ try {
163
+ const buf = await external_node_fs_default().promises.readFile(filePath);
164
+ return new Response(buf, {
165
+ status: 200,
166
+ headers: {
167
+ 'Content-Type': contentTypeByExt(filePath)
168
+ }
169
+ });
170
+ } catch {
171
+ return c.text('Not Found', 404);
172
+ }
173
+ }
174
+ function createStaticRoute(opts) {
175
+ const staticRoute = new external_hono_namespaceObject.Hono();
176
+ const rootDir = (null == opts ? void 0 : opts.rootDir) ?? DEFAULT_STATIC_ROOT;
177
+ staticRoute.get('/tree-shaking-shared/*', async (c)=>serveLocalFile(c, rootDir));
178
+ return staticRoute;
179
+ }
180
+ const DEFAULT_PRUNE_INTERVAL_MS = 3600000;
181
+ function ossEnv_envStr(env, name, fallback) {
182
+ const v = env[name];
183
+ if (void 0 === v || '' === v) return fallback;
184
+ return v;
185
+ }
186
+ function envNum(env, name, fallback) {
187
+ const v = ossEnv_envStr(env, name);
188
+ if (!v) return fallback;
189
+ const n = Number(v);
190
+ return Number.isFinite(n) ? n : fallback;
191
+ }
192
+ function resolveOssEnv(params) {
193
+ const adapterId = ossEnv_envStr(params.env, 'ADAPTER_ID', params.defaultAdapterId) ?? 'local';
194
+ const adapter = params.registry.getAdapterById(adapterId);
195
+ const adapterConfig = adapter.fromEnv ? adapter.fromEnv(params.env) : {};
196
+ return {
197
+ adapterId,
198
+ adapterConfig,
199
+ corsOrigin: ossEnv_envStr(params.env, 'CORS_ORIGIN', '*') ?? '*',
200
+ staticRootDir: ossEnv_envStr(params.env, 'LOCAL_STORE_DIR', DEFAULT_STATIC_ROOT) ?? DEFAULT_STATIC_ROOT,
201
+ logLevel: ossEnv_envStr(params.env, 'LOG_LEVEL', 'info') ?? 'info',
202
+ port: envNum(params.env, 'PORT', 3000),
203
+ hostname: ossEnv_envStr(params.env, 'HOST', '0.0.0.0') ?? '0.0.0.0',
204
+ pruneIntervalMs: envNum(params.env, 'PNPM_PRUNE_INTERVAL_MS', DEFAULT_PRUNE_INTERVAL_MS),
205
+ runtimeEnv: params.env
206
+ };
207
+ }
208
+ const cors_namespaceObject = require("hono/cors");
209
+ function createDiMiddleware(deps) {
210
+ return async (c, next)=>{
211
+ c.set('objectStore', deps.objectStore);
212
+ if (deps.projectPublisher) c.set('projectPublisher', deps.projectPublisher);
213
+ await next();
214
+ };
215
+ }
216
+ const loggerMiddleware = async (c, next)=>{
217
+ const category = c.req.path.split('/')[1] || 'root';
218
+ const child = logger_logger.child({
219
+ category,
220
+ path: c.req.path,
221
+ method: c.req.method
222
+ });
223
+ c.set('logger', child);
224
+ await next();
225
+ };
226
+ const zod_validator_namespaceObject = require("@hono/zod-validator");
227
+ const external_nanoid_namespaceObject = require("nanoid");
228
+ const parseNormalizedKey = (key)=>{
229
+ const res = key.split('@');
230
+ return {
231
+ name: res.slice(0, -1).join('@'),
232
+ version: res[res.length - 1]
233
+ };
234
+ };
235
+ const normalizedKey = (name, v)=>`${name}@${v}`;
236
+ function normalizeConfig(config) {
237
+ const { shared, plugins, target, libraryType, hostName, uploadOptions } = config;
238
+ const commonNormalizedConfig = {
239
+ plugins: (null == plugins ? void 0 : plugins.sort(([a], [b])=>a.localeCompare(b))) ?? [],
240
+ target: Array.isArray(target) ? [
241
+ ...target
242
+ ].sort() : [
243
+ target
244
+ ],
245
+ uploadOptions,
246
+ libraryType,
247
+ hostName
248
+ };
249
+ const normalizedConfig = {};
250
+ shared.forEach(([sharedName, version, usedExports], index)=>{
251
+ const key = normalizedKey(sharedName, version);
252
+ normalizedConfig[key] = {
253
+ ...commonNormalizedConfig,
254
+ shared: shared.slice(0, index).concat(shared.slice(index + 1)).sort(([s, v, u], [b, v2, u2])=>`${s}${v}${u.sort().join('')}`.localeCompare(`${b}${v2}${u2.sort().join('')}`)),
255
+ usedExports
256
+ };
257
+ });
258
+ return normalizedConfig;
259
+ }
260
+ function extractBuildConfig(config, type) {
261
+ const { shared, plugins, target, libraryType, usedExports } = config;
262
+ return {
263
+ shared,
264
+ plugins,
265
+ target,
266
+ libraryType,
267
+ usedExports,
268
+ type
269
+ };
270
+ }
271
+ const external_zod_namespaceObject = require("zod");
272
+ const UploadOptionsSchema = external_zod_namespaceObject.z.object({
273
+ scmName: external_zod_namespaceObject.z.string(),
274
+ bucketName: external_zod_namespaceObject.z.string(),
275
+ publicFilePath: external_zod_namespaceObject.z.string(),
276
+ publicPath: external_zod_namespaceObject.z.string(),
277
+ cdnRegion: external_zod_namespaceObject.z.string()
278
+ });
279
+ const BasicSchema = external_zod_namespaceObject.z.object({
280
+ shared: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.tuple([
281
+ external_zod_namespaceObject.z.string(),
282
+ external_zod_namespaceObject.z.string(),
283
+ external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())
284
+ ])).describe('List of plugins: [name, version, usedExports]'),
285
+ plugins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.tuple([
286
+ external_zod_namespaceObject.z.string(),
287
+ external_zod_namespaceObject.z.string().optional()
288
+ ])).describe('Specify extra build plugin names, support specify version in second item').optional(),
289
+ target: external_zod_namespaceObject.z.union([
290
+ external_zod_namespaceObject.z.string(),
291
+ external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())
292
+ ]).describe('Used to configure the target environment of Rspack output and the ECMAScript version of Rspack runtime code, the same with rspack#target'),
293
+ libraryType: external_zod_namespaceObject.z.string(),
294
+ hostName: external_zod_namespaceObject.z.string().describe('The name of the host app / mf')
295
+ });
296
+ const ConfigSchema = BasicSchema.extend({
297
+ uploadOptions: UploadOptionsSchema.optional()
298
+ });
299
+ const CheckTreeShakingSchema = ConfigSchema.extend({
300
+ uploadOptions: UploadOptionsSchema.optional()
301
+ });
302
+ const external_node_crypto_namespaceObject = require("node:crypto");
303
+ const external_node_os_namespaceObject = require("node:os");
304
+ var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
305
+ const STATS_NAME = 'mf-stats.json';
306
+ const external_node_child_process_namespaceObject = require("node:child_process");
307
+ let runtimeEnv = {};
308
+ const setRuntimeEnv = (env)=>{
309
+ runtimeEnv = env;
310
+ };
311
+ const getRuntimeEnv = ()=>runtimeEnv;
312
+ function runCommand_define_property(obj, key, value) {
313
+ if (key in obj) Object.defineProperty(obj, key, {
314
+ value: value,
315
+ enumerable: true,
316
+ configurable: true,
317
+ writable: true
318
+ });
319
+ else obj[key] = value;
320
+ return obj;
321
+ }
322
+ class CommandExecutionError extends Error {
323
+ constructor(command, exitCode, stdout, stderr){
324
+ super(`Command "${command}" exited with code ${exitCode}`), runCommand_define_property(this, "command", void 0), runCommand_define_property(this, "exitCode", void 0), runCommand_define_property(this, "stdout", void 0), runCommand_define_property(this, "stderr", void 0);
325
+ this.name = 'CommandExecutionError';
326
+ this.command = command;
327
+ this.exitCode = exitCode;
328
+ this.stdout = stdout;
329
+ this.stderr = stderr;
330
+ }
331
+ }
332
+ const runCommand = (command, options = {})=>new Promise((resolve, reject)=>{
333
+ const stdoutChunks = [];
334
+ const stderrChunks = [];
335
+ const child = (0, external_node_child_process_namespaceObject.spawn)(command, {
336
+ cwd: options.cwd,
337
+ env: {
338
+ ...getRuntimeEnv(),
339
+ ...options.env
340
+ },
341
+ shell: true,
342
+ stdio: [
343
+ 'ignore',
344
+ 'pipe',
345
+ 'pipe'
346
+ ]
347
+ });
348
+ child.stdout.on('data', (chunk)=>{
349
+ stdoutChunks.push(chunk.toString());
350
+ });
351
+ child.stderr.on('data', (chunk)=>{
352
+ stderrChunks.push(chunk.toString());
353
+ });
354
+ child.on('error', (error)=>{
355
+ reject(error);
356
+ });
357
+ child.on('close', (exitCode)=>{
358
+ const stdout = stdoutChunks.join('');
359
+ const stderr = stderrChunks.join('');
360
+ if (0 === exitCode) return void resolve({
361
+ stdout,
362
+ stderr,
363
+ exitCode
364
+ });
365
+ reject(new CommandExecutionError(command, exitCode ?? -1, stdout, stderr));
366
+ });
367
+ });
368
+ let installs = 0;
369
+ let pruneScheduled = false;
370
+ let pruning = false;
371
+ const DEFAULT_INTERVAL = 3600000;
372
+ const markInstallStart = ()=>{
373
+ installs++;
374
+ };
375
+ const markInstallEnd = ()=>{
376
+ installs = Math.max(0, installs - 1);
377
+ schedulePruneSoon();
378
+ };
379
+ const schedulePruneSoon = (delay = 30000)=>{
380
+ if (pruneScheduled) return;
381
+ pruneScheduled = true;
382
+ setTimeout(()=>{
383
+ pruneScheduled = false;
384
+ maybePrune();
385
+ }, delay);
386
+ };
387
+ const maybePrune = async ()=>{
388
+ if (pruning || installs > 0) return void schedulePruneSoon(60000);
389
+ pruning = true;
390
+ try {
391
+ await runCommand('pnpm store prune');
392
+ } catch {} finally{
393
+ pruning = false;
394
+ }
395
+ };
396
+ const startPeriodicPrune = (intervalMs = DEFAULT_INTERVAL)=>{
397
+ if (intervalMs <= 0) return;
398
+ setInterval(()=>{
399
+ maybePrune();
400
+ }, intervalMs);
401
+ };
402
+ const createUniqueTempDirByKey = (key)=>{
403
+ const base = external_node_path_default().join(external_node_os_default().tmpdir(), `re-shake-share-${key}`);
404
+ let candidate = base;
405
+ for(;;)try {
406
+ external_node_fs_default().mkdirSync(candidate, {
407
+ recursive: false
408
+ });
409
+ return candidate;
410
+ } catch {
411
+ const rand = Math.floor(1e9 * Math.random());
412
+ candidate = `${base}-${rand}`;
413
+ }
414
+ };
415
+ const prepareProject = (config, excludeShared)=>{
416
+ const key = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify(config)).digest('hex');
417
+ const dir = createUniqueTempDirByKey(key);
418
+ const templateDir = external_node_path_default().join(__dirname, '..', 'template', 're-shake-share');
419
+ external_node_fs_default().cpSync(templateDir, dir, {
420
+ recursive: true
421
+ });
422
+ const pkgPath = external_node_path_default().join(dir, 'package.json');
423
+ const pkg = JSON.parse(external_node_fs_default().readFileSync(pkgPath, 'utf-8'));
424
+ const deps = {
425
+ ...pkg.dependencies || {}
426
+ };
427
+ const shared = {};
428
+ const mfConfig = {
429
+ name: 're_shake',
430
+ library: {
431
+ type: 'global'
432
+ },
433
+ manifest: true,
434
+ shared
435
+ };
436
+ let pluginImportStr = '';
437
+ let pluginOptionStr = '[\n';
438
+ let sharedImport = '';
439
+ Object.entries(config).forEach(([key, { plugins = [], libraryType, usedExports, hostName }], index)=>{
440
+ const { name, version } = parseNormalizedKey(key);
441
+ deps[name] = version;
442
+ if (!index) {
443
+ plugins.forEach(([pluginName, pluginVersion], pIndex)=>{
444
+ deps[pluginName] = pluginVersion ?? 'latest';
445
+ const pluginImportName = `plugin_${pIndex}`;
446
+ pluginImportStr += `import ${pluginImportName} from '${pluginName}';\n`;
447
+ pluginOptionStr += `new ${pluginImportName}(),`;
448
+ });
449
+ mfConfig.library.type = libraryType;
450
+ mfConfig.name = hostName;
451
+ }
452
+ shared[name] = {
453
+ requiredVersion: version,
454
+ version,
455
+ treeShaking: excludeShared.some(([n, v])=>n === name && v === version) ? void 0 : {
456
+ usedExports,
457
+ mode: 'server-calc'
458
+ }
459
+ };
460
+ sharedImport += `import shared_${index} from '${name}';\n`;
461
+ });
462
+ pluginOptionStr += '\n]';
463
+ pkg.dependencies = deps;
464
+ external_node_fs_default().writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
465
+ const sharedImportPlaceholder = "${SHARED_IMPORT}";
466
+ const pluginsPlaceholder = "${ PLUGINS }";
467
+ const mfConfigPlaceholder = "${ MF_CONFIG }";
468
+ const indexPath = external_node_path_default().join(dir, 'index.ts');
469
+ const indexContent = external_node_fs_default().readFileSync(indexPath, 'utf-8');
470
+ external_node_fs_default().writeFileSync(indexPath, indexContent.replace(sharedImportPlaceholder, sharedImport));
471
+ const rspackConfigPath = external_node_path_default().join(dir, 'rspack.config.ts');
472
+ let cfg = external_node_fs_default().readFileSync(rspackConfigPath, 'utf-8');
473
+ cfg += pluginImportStr;
474
+ cfg = cfg.replace(pluginsPlaceholder, pluginOptionStr);
475
+ cfg = cfg.replace(mfConfigPlaceholder, JSON.stringify(mfConfig, null, 2));
476
+ external_node_fs_default().writeFileSync(rspackConfigPath, cfg);
477
+ return dir;
478
+ };
479
+ const installDependencies = async (cwd)=>{
480
+ markInstallStart();
481
+ try {
482
+ await runCommand('pnpm i', {
483
+ cwd,
484
+ env: {
485
+ npm_config_registry: 'https://registry.npmjs.org/'
486
+ }
487
+ });
488
+ } finally{
489
+ markInstallEnd();
490
+ }
491
+ };
492
+ const buildProject = async (cwd, type)=>{
493
+ const scripts = [];
494
+ if ('re-shake' === type) scripts.push('pnpm build');
495
+ else scripts.push('pnpm build:full');
496
+ await Promise.all(scripts.map((script)=>runCommand(script, {
497
+ cwd
498
+ })));
499
+ };
500
+ const retrieveSharedFilepaths = (projectDir, type)=>{
501
+ const sharedFilepaths = [];
502
+ const collectSharedFilepaths = (t)=>{
503
+ const dir = 'full' === t ? 'full-shared' : 'dist';
504
+ const distDir = external_node_path_default().join(projectDir, dir);
505
+ const stats = JSON.parse(external_node_fs_default().readFileSync(external_node_path_default().join(distDir, STATS_NAME), 'utf-8'));
506
+ stats.shared.forEach((s)=>{
507
+ const { name, version, fallback, fallbackName } = s;
508
+ if (fallback && fallbackName) {
509
+ var _s_usedExports;
510
+ const filepath = external_node_path_default().join(distDir, fallback);
511
+ sharedFilepaths.push({
512
+ name,
513
+ version,
514
+ filepath,
515
+ globalName: fallbackName,
516
+ type: t,
517
+ modules: s.usedExports,
518
+ canTreeShaking: s.canTreeShaking ?? (null == (_s_usedExports = s.usedExports) ? void 0 : _s_usedExports.length) !== 0
519
+ });
520
+ }
521
+ });
522
+ };
523
+ collectSharedFilepaths(type);
524
+ return sharedFilepaths;
525
+ };
526
+ const runBuild = async (normalizedConfig, excludeShared, type)=>{
527
+ const tmpDir = prepareProject(normalizedConfig, excludeShared);
528
+ await installDependencies(tmpDir);
529
+ await buildProject(tmpDir, type);
530
+ const sharedFilePaths = retrieveSharedFilepaths(tmpDir, type);
531
+ return {
532
+ sharedFilePaths,
533
+ dir: tmpDir
534
+ };
535
+ };
536
+ function cleanUp(tmpDir) {
537
+ if (!tmpDir) return;
538
+ external_node_fs_default().rmSync(tmpDir, {
539
+ recursive: true,
540
+ force: true
541
+ });
542
+ }
543
+ const external_json_stable_stringify_namespaceObject = require("json-stable-stringify");
544
+ var external_json_stable_stringify_default = /*#__PURE__*/ __webpack_require__.n(external_json_stable_stringify_namespaceObject);
545
+ const encodeName = function(name, prefix = '', withExt = false) {
546
+ const ext = withExt ? '.js' : '';
547
+ return `${prefix}${name.replace(/@/g, 'scope_').replace(/-/g, '_').replace(/\//g, '__').replace(/\./g, '')}${ext}`;
548
+ };
549
+ function retrieveGlobalName(mfName, sharedName, version) {
550
+ return encodeName(`${mfName}_${sharedName}_${version}`);
551
+ }
552
+ function createCacheHash(config, type) {
553
+ const relevant = extractBuildConfig({
554
+ ...config,
555
+ usedExports: 'full' === type ? [] : config.usedExports
556
+ }, type);
557
+ const json = external_json_stable_stringify_default()(relevant);
558
+ if (!json) throw new Error('Can not stringify build config!');
559
+ return (0, external_node_crypto_namespaceObject.createHash)('sha256').update(json).digest('hex');
560
+ }
561
+ function retrieveCDNPath({ config, sharedKey, type }) {
562
+ const configHash = createCacheHash(config, type);
563
+ return `tree-shaking-shared/${SERVER_VERSION}/${sharedKey}/${configHash}.js`;
564
+ }
565
+ async function cacheService_hitCache(sharedKey, config, type, store) {
566
+ const cdnPath = retrieveCDNPath({
567
+ config,
568
+ sharedKey,
569
+ type
570
+ });
571
+ const exists = await store.exists(cdnPath);
572
+ return exists ? store.publicUrl(cdnPath) : null;
573
+ }
574
+ const retrieveCacheItems = async (normalizedConfig, type, store)=>{
575
+ const cacheItems = [];
576
+ const restConfig = {};
577
+ const excludeShared = [];
578
+ for (const [sharedKey, config] of Object.entries(normalizedConfig)){
579
+ let cache = false;
580
+ const { name, version } = parseNormalizedKey(sharedKey);
581
+ const cdnUrl = await cacheService_hitCache(sharedKey, config, type, store);
582
+ if (cdnUrl) {
583
+ cache = true;
584
+ cacheItems.push({
585
+ type,
586
+ name,
587
+ version,
588
+ cdnUrl,
589
+ globalName: retrieveGlobalName(config.hostName, name, version)
590
+ });
591
+ }
592
+ if (cache) excludeShared.push([
593
+ name,
594
+ version
595
+ ]);
596
+ else if (config.usedExports.length || 're-shake' !== type) restConfig[sharedKey] = config;
597
+ else excludeShared.push([
598
+ name,
599
+ version
600
+ ]);
601
+ }
602
+ return {
603
+ cacheItems,
604
+ excludeShared,
605
+ restConfig
606
+ };
607
+ };
608
+ async function uploadToCacheStore(sharedFilePaths, normalizedConfig, store) {
609
+ const results = [];
610
+ for (const file of sharedFilePaths){
611
+ const { name, version, filepath, globalName, type, modules, canTreeShaking } = file;
612
+ try {
613
+ const sharedKey = normalizedKey(name, version);
614
+ logger_logger.info(`Uploading ${sharedKey} to CDN`);
615
+ const config = normalizedConfig[sharedKey];
616
+ const cdnPath = retrieveCDNPath({
617
+ config,
618
+ sharedKey,
619
+ type
620
+ });
621
+ const t0 = Date.now();
622
+ await store.uploadFile(filepath, cdnPath);
623
+ const tUpload = Date.now() - t0;
624
+ const cdnUrl = store.publicUrl(cdnPath);
625
+ const res = {
626
+ name: name,
627
+ version: version,
628
+ globalName: globalName,
629
+ cdnUrl,
630
+ type,
631
+ modules,
632
+ canTreeShaking
633
+ };
634
+ try {
635
+ const jsonFilePath = filepath.replace(/\.js$/, '.json');
636
+ const jsonFile = JSON.stringify(res);
637
+ const jsonCdnUrl = cdnPath.replace(/\.js$/, '.json');
638
+ external_node_fs_default().writeFileSync(jsonFilePath, jsonFile);
639
+ await store.uploadFile(jsonFilePath, jsonCdnUrl);
640
+ } catch (error) {
641
+ logger_logger.error(`Failed to upload ${name}@${version} json file: ${error}`);
642
+ }
643
+ results.push(res);
644
+ logger_logger.info(`Successfully uploaded ${name}@${version} to ${cdnUrl} in ${tUpload}ms`);
645
+ } catch (error) {
646
+ logger_logger.error(`Failed to upload ${name}@${version}: ${error}`);
647
+ throw error;
648
+ }
649
+ }
650
+ return results;
651
+ }
652
+ const downloadToFile = async (url, destPath)=>{
653
+ const res = await fetch(url);
654
+ if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText} - ${url}`);
655
+ const buf = Buffer.from(await res.arrayBuffer());
656
+ await external_node_fs_default().promises.mkdir(external_node_path_default().dirname(destPath), {
657
+ recursive: true
658
+ });
659
+ await external_node_fs_default().promises.writeFile(destPath, buf);
660
+ return destPath;
661
+ };
662
+ async function uploadProject(uploadResults, sharedFilePaths, normalizedConfig, publisher) {
663
+ const tmpDir = createUniqueTempDirByKey(`upload-project${Date.now().toString()}`);
664
+ const uploaded = [];
665
+ try {
666
+ for (const item of uploadResults)try {
667
+ const config = normalizedConfig[normalizedKey(item.name, item.version)];
668
+ if (!config) {
669
+ logger_logger.error(`No config found for ${item.name}`);
670
+ continue;
671
+ }
672
+ const { uploadOptions } = config;
673
+ if (!uploadOptions) throw new Error(`No uploadOptions found for ${item.name}`);
674
+ const filename = external_node_path_default().basename(new URL(item.cdnUrl).pathname);
675
+ const localPath = external_node_path_default().join(tmpDir, filename);
676
+ const hash = createCacheHash({
677
+ ...config,
678
+ plugins: config.plugins || []
679
+ }, item.type);
680
+ const cdnUrl = publisher.publicUrl({
681
+ sharedName: item.name,
682
+ hash,
683
+ fileName: filename,
684
+ options: uploadOptions
685
+ });
686
+ const hitCache = await publisher.exists(cdnUrl);
687
+ if (hitCache) {
688
+ logger_logger.info(`Hit cache for ${item.name}@${item.version} -> ${cdnUrl}`);
689
+ uploaded.push({
690
+ ...item,
691
+ cdnUrl
692
+ });
693
+ continue;
694
+ }
695
+ logger_logger.info(`Downloading ${item.name}@${item.version} -> ${localPath}`);
696
+ const t0 = Date.now();
697
+ await downloadToFile(item.cdnUrl, localPath);
698
+ const tDownload = Date.now() - t0;
699
+ logger_logger.info(`Downloaded ${item.name}@${item.version} in ${tDownload}ms`);
700
+ const newCdnUrl = await publisher.publishFile({
701
+ localPath,
702
+ sharedName: item.name,
703
+ hash,
704
+ options: uploadOptions
705
+ });
706
+ uploaded.push({
707
+ ...item,
708
+ cdnUrl: newCdnUrl
709
+ });
710
+ } catch (error) {
711
+ logger_logger.error(`Failed to upload ${item.name}@${item.version}: ${error}`);
712
+ }
713
+ for (const s of sharedFilePaths)try {
714
+ const config = normalizedConfig[normalizedKey(s.name, s.version)];
715
+ if (!config) {
716
+ logger_logger.error(`No config found for ${s.name}`);
717
+ continue;
718
+ }
719
+ const { uploadOptions } = config;
720
+ if (!uploadOptions) throw new Error(`No uploadOptions found for ${s.name}`);
721
+ const hash = createCacheHash({
722
+ ...config,
723
+ plugins: config.plugins || []
724
+ }, s.type);
725
+ const cdnUrl = await publisher.publishFile({
726
+ localPath: s.filepath,
727
+ sharedName: s.name,
728
+ hash,
729
+ options: uploadOptions
730
+ });
731
+ uploaded.push({
732
+ name: s.name,
733
+ version: s.version,
734
+ globalName: s.globalName,
735
+ cdnUrl,
736
+ type: s.type
737
+ });
738
+ } catch (error) {
739
+ logger_logger.error(`Failed to upload ${s.name}@${s.version}: ${error}`);
740
+ }
741
+ return uploaded;
742
+ } finally{
743
+ external_node_fs_default().rmSync(tmpDir, {
744
+ recursive: true,
745
+ force: true
746
+ });
747
+ }
748
+ }
749
+ async function upload(sharedFilePaths, uploadResults, normalizedConfig, uploadOptions, store, publisher) {
750
+ const cacheUploaded = await uploadToCacheStore(sharedFilePaths, normalizedConfig, store);
751
+ if (!uploadOptions) {
752
+ const hydrated = await Promise.all(uploadResults.map(async (item)=>{
753
+ if ('full' !== item.type) return item;
754
+ const tmpDir = createUniqueTempDirByKey(`download-full-json${Date.now().toString()}`);
755
+ const jsonPath = external_node_path_default().join(tmpDir, `${item.name}-${item.version}.json`);
756
+ try {
757
+ const tJson0 = Date.now();
758
+ await downloadToFile(item.cdnUrl.replace('.js', '.json'), jsonPath);
759
+ const tJson = Date.now() - tJson0;
760
+ logger_logger.info(`Downloaded ${item.name}@${item.version} json in ${tJson}ms`);
761
+ const jsonContent = JSON.parse(external_node_fs_default().readFileSync(jsonPath, 'utf8'));
762
+ return {
763
+ ...item,
764
+ canTreeShaking: jsonContent.canTreeShaking,
765
+ modules: jsonContent.modules
766
+ };
767
+ } catch (jsonError) {
768
+ logger_logger.error(`Failed to download ${item.name}@${item.version} json: ${jsonError}`);
769
+ return {
770
+ ...item,
771
+ canTreeShaking: item.canTreeShaking ?? true
772
+ };
773
+ } finally{
774
+ external_node_fs_default().rmSync(tmpDir, {
775
+ recursive: true,
776
+ force: true
777
+ });
778
+ }
779
+ }));
780
+ return [
781
+ ...cacheUploaded,
782
+ ...hydrated
783
+ ];
784
+ }
785
+ if (!publisher) throw new Error('uploadOptions provided but no projectPublisher configured (configure the selected adapter to enable it or omit uploadOptions)');
786
+ const projectUploadResults = await uploadProject(uploadResults, sharedFilePaths, normalizedConfig, publisher);
787
+ return projectUploadResults;
788
+ }
789
+ const buildRoute = new external_hono_namespaceObject.Hono();
790
+ buildRoute.post('/', (0, zod_validator_namespaceObject.zValidator)('json', ConfigSchema), async (c)=>{
791
+ const logger = c.get('logger');
792
+ const startTime = Date.now();
793
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
794
+ logger.info(jobId);
795
+ const body = c.req.valid('json');
796
+ logger.info(JSON.stringify(body));
797
+ const normalizedConfig = normalizeConfig(body);
798
+ const store = c.get('objectStore');
799
+ const publisher = c.get('projectPublisher');
800
+ try {
801
+ const { cacheItems, excludeShared, restConfig } = await retrieveCacheItems(normalizedConfig, 're-shake', store);
802
+ let sharedFilePaths = [];
803
+ let dir;
804
+ if (Object.keys(restConfig).length > 0) {
805
+ const buildResult = await runBuild(normalizedConfig, excludeShared, 're-shake');
806
+ sharedFilePaths = buildResult.sharedFilePaths;
807
+ dir = buildResult.dir;
808
+ }
809
+ const uploadResults = await upload(sharedFilePaths, cacheItems, normalizedConfig, body.uploadOptions, store, publisher);
810
+ cleanUp(dir);
811
+ return c.json({
812
+ jobId,
813
+ status: 'success',
814
+ data: uploadResults,
815
+ cached: cacheItems,
816
+ duration: Date.now() - startTime
817
+ });
818
+ } catch (error) {
819
+ if (error instanceof CommandExecutionError) {
820
+ if (137 === error.exitCode) maybePrune();
821
+ return c.json({
822
+ jobId,
823
+ status: 'failed',
824
+ error: error.message,
825
+ command: error.command,
826
+ exitCode: error.exitCode,
827
+ stdout: error.stdout,
828
+ stderr: error.stderr
829
+ });
830
+ }
831
+ return c.json({
832
+ jobId,
833
+ status: 'failed',
834
+ error: error instanceof Error ? error.message : 'Unknown error'
835
+ });
836
+ }
837
+ });
838
+ async function handleCheckTreeshake(c, body) {
839
+ const logger = c.get('logger');
840
+ const startTime = Date.now();
841
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
842
+ logger.info(jobId);
843
+ logger.info(JSON.stringify(body));
844
+ const normalizedConfig = normalizeConfig(body);
845
+ const store = c.get('objectStore');
846
+ const publisher = c.get('projectPublisher');
847
+ try {
848
+ const { cacheItems, excludeShared, restConfig } = await retrieveCacheItems(normalizedConfig, 'full', store);
849
+ let sharedFilePaths = [];
850
+ let dir;
851
+ if (Object.keys(restConfig).length > 0) {
852
+ const buildResult = await runBuild(normalizedConfig, excludeShared, 'full');
853
+ sharedFilePaths = buildResult.sharedFilePaths;
854
+ dir = buildResult.dir;
855
+ }
856
+ const uploadResults = await upload(sharedFilePaths, cacheItems, normalizedConfig, body.uploadOptions, store, publisher);
857
+ cleanUp(dir);
858
+ return c.json({
859
+ jobId,
860
+ status: 'success',
861
+ data: uploadResults,
862
+ cached: cacheItems,
863
+ duration: Date.now() - startTime
864
+ });
865
+ } catch (error) {
866
+ if (error instanceof CommandExecutionError) {
867
+ if (137 === error.exitCode) maybePrune();
868
+ return c.json({
869
+ jobId,
870
+ status: 'failed',
871
+ error: error.message,
872
+ command: error.command,
873
+ exitCode: error.exitCode,
874
+ stdout: error.stdout,
875
+ stderr: error.stderr
876
+ });
877
+ }
878
+ return c.json({
879
+ jobId,
880
+ status: 'failed',
881
+ error: error instanceof Error ? error.message : 'Unknown error'
882
+ });
883
+ }
884
+ }
885
+ buildRoute.post('/check-tree-shaking', (0, zod_validator_namespaceObject.zValidator)('json', CheckTreeShakingSchema), async (c)=>handleCheckTreeshake(c, c.req.valid('json')));
886
+ const maintenanceRoute = new external_hono_namespaceObject.Hono();
887
+ maintenanceRoute.post('/', async (c)=>{
888
+ const logger = c.get('logger');
889
+ const jobId = (0, external_nanoid_namespaceObject.nanoid)();
890
+ const startTime = Date.now();
891
+ logger.info(jobId);
892
+ await maybePrune();
893
+ return c.json({
894
+ jobId,
895
+ status: 'success',
896
+ duration: Date.now() - startTime
897
+ });
898
+ });
899
+ const routes = new external_hono_namespaceObject.Hono();
900
+ routes.route('/build', buildRoute);
901
+ routes.route('/clean-cache', maintenanceRoute);
902
+ function createApp(deps, opts) {
903
+ var _opts_appExtensions, _opts_frontendAdapters;
904
+ if (null == opts ? void 0 : opts.logger) setLogger(opts.logger);
905
+ setRuntimeEnv((null == opts ? void 0 : opts.runtimeEnv) ?? process.env);
906
+ const app = new external_hono_namespaceObject.Hono();
907
+ const corsOrigin = (null == opts ? void 0 : opts.corsOrigin) ?? '*';
908
+ const staticRootDir = (null == opts ? void 0 : opts.staticRootDir) ?? DEFAULT_STATIC_ROOT;
909
+ app.use('*', (0, cors_namespaceObject.cors)({
910
+ origin: corsOrigin,
911
+ allowMethods: [
912
+ 'GET',
913
+ 'POST',
914
+ 'OPTIONS'
915
+ ],
916
+ allowHeaders: [
917
+ 'Content-Type',
918
+ 'Authorization'
919
+ ]
920
+ }));
921
+ app.use('*', loggerMiddleware);
922
+ app.use('*', createDiMiddleware(deps));
923
+ if (null == opts ? void 0 : null == (_opts_appExtensions = opts.appExtensions) ? void 0 : _opts_appExtensions.length) for (const extend of opts.appExtensions)extend(app);
924
+ app.get('/tree-shaking-shared/healthz', (c)=>c.json({
925
+ status: 'ok',
926
+ timestamp: new Date().toISOString()
927
+ }));
928
+ app.route('/tree-shaking-shared', routes);
929
+ app.route('/', createStaticRoute({
930
+ rootDir: staticRootDir
931
+ }));
932
+ if (null == opts ? void 0 : null == (_opts_frontendAdapters = opts.frontendAdapters) ? void 0 : _opts_frontendAdapters.length) for (const adapter of opts.frontendAdapters)adapter.register(app);
933
+ startPeriodicPrune(null == opts ? void 0 : opts.pruneIntervalMs);
934
+ return app;
935
+ }
936
+ const defaultBasePath = '/tree-shaking';
937
+ const embeddedAdapter_contentTypeByExt = (filePath)=>{
938
+ if (filePath.endsWith('.html')) return 'text/html; charset=utf-8';
939
+ if (filePath.endsWith('.js')) return "application/javascript";
940
+ if (filePath.endsWith('.css')) return 'text/css';
941
+ if (filePath.endsWith('.json')) return 'application/json';
942
+ if (filePath.endsWith('.svg')) return 'image/svg+xml';
943
+ if (filePath.endsWith('.png')) return 'image/png';
944
+ if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) return 'image/jpeg';
945
+ if (filePath.endsWith('.webp')) return 'image/webp';
946
+ if (filePath.endsWith('.ico')) return 'image/x-icon';
947
+ return 'application/octet-stream';
948
+ };
949
+ const safeResolve = (rootDir, requestPath)=>{
950
+ const rootResolved = external_node_path_default().resolve(rootDir);
951
+ const rel = requestPath.replace(/^\/+/, '');
952
+ const filePath = external_node_path_default().resolve(rootResolved, rel);
953
+ if (filePath !== rootResolved && !filePath.startsWith(`${rootResolved}${external_node_path_default().sep}`)) return null;
954
+ return filePath;
955
+ };
956
+ function createEmbeddedFrontendAdapter(opts) {
957
+ const basePath = opts.basePath ?? defaultBasePath;
958
+ const normalizedBase = '/' === basePath ? '' : basePath.replace(/\/$/, '');
959
+ const distDir = opts.distDir;
960
+ const indexFile = opts.indexFile ?? 'index.html';
961
+ const spaFallback = opts.spaFallback ?? true;
962
+ const handler = async (c)=>{
963
+ let requestPath = c.req.path;
964
+ try {
965
+ requestPath = decodeURIComponent(requestPath);
966
+ } catch {
967
+ return c.text('Not Found', 404);
968
+ }
969
+ let relPath = requestPath;
970
+ if (normalizedBase && requestPath.startsWith(normalizedBase)) relPath = requestPath.slice(normalizedBase.length);
971
+ if (!relPath || '/' === relPath) relPath = `/${indexFile}`;
972
+ const filePath = safeResolve(distDir, relPath);
973
+ if (filePath) try {
974
+ const stat = await external_node_fs_default().promises.stat(filePath);
975
+ if (stat.isFile()) {
976
+ const buf = await external_node_fs_default().promises.readFile(filePath);
977
+ return new Response(buf, {
978
+ status: 200,
979
+ headers: {
980
+ 'Content-Type': embeddedAdapter_contentTypeByExt(filePath)
981
+ }
982
+ });
983
+ }
984
+ } catch {}
985
+ if (!spaFallback) return c.text('Not Found', 404);
986
+ const fallbackPath = safeResolve(distDir, `/${indexFile}`);
987
+ if (!fallbackPath) return c.text('Not Found', 404);
988
+ try {
989
+ const buf = await external_node_fs_default().promises.readFile(fallbackPath);
990
+ return new Response(buf, {
991
+ status: 200,
992
+ headers: {
993
+ 'Content-Type': embeddedAdapter_contentTypeByExt(fallbackPath)
994
+ }
995
+ });
996
+ } catch {
997
+ return c.text('Not Found', 404);
998
+ }
999
+ };
1000
+ return {
1001
+ id: 'treeshake-embedded-frontend',
1002
+ register (app) {
1003
+ const base = normalizedBase || '/';
1004
+ app.get(base, handler);
1005
+ app.get(`${base}/*`, handler);
1006
+ }
1007
+ };
1008
+ }
1009
+ const node_server_namespaceObject = require("@hono/node-server");
1010
+ function createServer(opts) {
1011
+ const port = opts.port ?? 3000;
1012
+ const hostname = opts.hostname ?? '0.0.0.0';
1013
+ return (0, node_server_namespaceObject.serve)({
1014
+ fetch: opts.app.fetch,
1015
+ port,
1016
+ hostname
1017
+ });
1018
+ }
1019
+ const hasIndexHtml = (dir)=>Boolean(dir && external_node_fs_default().existsSync(external_node_path_default().join(dir, 'index.html')));
1020
+ const resolveFrontendDistDir = ()=>{
1021
+ const envDir = process.env.TREESHAKE_FRONTEND_DIST;
1022
+ if (envDir) {
1023
+ if (hasIndexHtml(envDir)) return envDir;
1024
+ throw new Error(`TREESHAKE_FRONTEND_DIST is set but index.html is missing: ${envDir}`);
1025
+ }
1026
+ const candidates = [
1027
+ external_node_path_default().resolve(__dirname, 'frontend'),
1028
+ external_node_path_default().resolve(__dirname, '..', 'frontend')
1029
+ ];
1030
+ for (const candidate of candidates)if (hasIndexHtml(candidate)) return candidate;
1031
+ const workspaceCandidates = [
1032
+ external_node_path_default().resolve(process.cwd(), 'packages', 'treeshake-frontend', 'dist'),
1033
+ external_node_path_default().resolve(process.cwd(), 'treeshake-frontend', 'dist')
1034
+ ];
1035
+ for (const candidate of workspaceCandidates)if (hasIndexHtml(candidate)) return candidate;
1036
+ };
1037
+ async function main() {
1038
+ const registry = createOssAdapterRegistry();
1039
+ const resolved = resolveOssEnv({
1040
+ env: {
1041
+ ...process.env,
1042
+ ADAPTER_ID: 'local'
1043
+ },
1044
+ registry,
1045
+ defaultAdapterId: 'local'
1046
+ });
1047
+ const logger = createLogger({
1048
+ level: resolved.logLevel
1049
+ });
1050
+ const deps = await createAdapterDeps({
1051
+ registry,
1052
+ adapterId: resolved.adapterId,
1053
+ adapterConfig: resolved.adapterConfig,
1054
+ logger
1055
+ });
1056
+ const frontendAdapters = [];
1057
+ const distDir = resolveFrontendDistDir();
1058
+ if (!distDir) throw new Error('Treeshake UI dist not found. Rebuild the CLI bundle or set TREESHAKE_FRONTEND_DIST.');
1059
+ frontendAdapters.push(createEmbeddedFrontendAdapter({
1060
+ basePath: process.env.TREESHAKE_FRONTEND_BASE_PATH ?? '/tree-shaking',
1061
+ distDir,
1062
+ spaFallback: '0' !== process.env.TREESHAKE_FRONTEND_SPA_FALLBACK && 'false' !== process.env.TREESHAKE_FRONTEND_SPA_FALLBACK
1063
+ }));
1064
+ const app = createApp(deps, {
1065
+ corsOrigin: resolved.corsOrigin,
1066
+ staticRootDir: resolved.staticRootDir,
1067
+ pruneIntervalMs: resolved.pruneIntervalMs,
1068
+ logger,
1069
+ runtimeEnv: resolved.runtimeEnv,
1070
+ frontendAdapters
1071
+ });
1072
+ createServer({
1073
+ app,
1074
+ port: resolved.port,
1075
+ hostname: resolved.hostname
1076
+ });
1077
+ console.log(`Build service listening on http://${resolved.hostname}:${resolved.port}`);
1078
+ if (frontendAdapters.length) {
1079
+ const basePath = process.env.TREESHAKE_FRONTEND_BASE_PATH ?? '/tree-shaking';
1080
+ console.log(`Treeshake UI available at http://${resolved.hostname}:${resolved.port}${basePath}`);
1081
+ }
1082
+ }
1083
+ main().catch((err)=>{
1084
+ console.error(err);
1085
+ process.exit(1);
1086
+ });
1087
+ for(var __webpack_i__ in __webpack_exports__)exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
1088
+ Object.defineProperty(exports, '__esModule', {
1089
+ value: true
1090
+ });