@module-federation/treeshake-server 0.0.1-alpha.0

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