@blinkk/root 1.0.0-beta.30 → 1.0.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1184 @@
1
+ import {
2
+ copyGlob,
3
+ createViteServer,
4
+ directoryContains,
5
+ fileExists,
6
+ isDirectory,
7
+ isJsFile,
8
+ loadJson,
9
+ loadRootConfig,
10
+ makeDir,
11
+ rmDir,
12
+ writeFile
13
+ } from "./chunk-XGD3RBFM.js";
14
+ import {
15
+ configureServerPlugins,
16
+ getVitePlugins
17
+ } from "./chunk-QKBMWK5B.js";
18
+ import {
19
+ htmlMinify,
20
+ htmlPretty,
21
+ isValidTagName,
22
+ parseTagNames
23
+ } from "./chunk-DXD5LKU3.js";
24
+
25
+ // src/cli/commands/build.ts
26
+ import path3 from "node:path";
27
+ import { fileURLToPath } from "node:url";
28
+ import fsExtra from "fs-extra";
29
+ import { dim, cyan } from "kleur/colors";
30
+ import glob2 from "tiny-glob";
31
+ import { build as viteBuild } from "vite";
32
+
33
+ // src/node/element-graph.ts
34
+ import fs from "node:fs";
35
+ import path from "node:path";
36
+ import glob from "tiny-glob";
37
+ import { searchForWorkspaceRoot } from "vite";
38
+ var ElementGraph = class {
39
+ constructor(sourceFiles) {
40
+ this.sourceFiles = {};
41
+ this.deps = {};
42
+ this.sourceFiles = sourceFiles;
43
+ }
44
+ toJson() {
45
+ for (const tagName in this.sourceFiles) {
46
+ this.deps[tagName] ??= this.parseDepsFromSource(tagName);
47
+ }
48
+ return {
49
+ sourceFiles: this.sourceFiles,
50
+ deps: this.deps
51
+ };
52
+ }
53
+ static fromJson(data) {
54
+ const graph = new ElementGraph(data.sourceFiles);
55
+ graph.deps = data.deps;
56
+ return graph;
57
+ }
58
+ getDeps(tagName, visited) {
59
+ visited ??= /* @__PURE__ */ new Set();
60
+ if (visited.has(tagName)) {
61
+ return [];
62
+ }
63
+ visited.add(tagName);
64
+ this.deps[tagName] ??= this.parseDepsFromSource(tagName);
65
+ const deps = new Set(this.deps[tagName]);
66
+ for (const depTagName of this.deps[tagName]) {
67
+ for (const childDep of this.getDeps(depTagName, visited)) {
68
+ deps.add(childDep);
69
+ }
70
+ }
71
+ return Array.from(deps);
72
+ }
73
+ parseDepsFromSource(tagName) {
74
+ const srcFile = this.sourceFiles[tagName];
75
+ if (!srcFile) {
76
+ throw new Error(`could not find file path for tagName <${tagName}>`);
77
+ }
78
+ const src = fs.readFileSync(srcFile.filePath, "utf-8");
79
+ const tagNames = parseTagNames(src);
80
+ const deps = /* @__PURE__ */ new Set();
81
+ for (const depTagName of tagNames) {
82
+ if (depTagName !== tagName && depTagName in this.sourceFiles) {
83
+ deps.add(depTagName);
84
+ }
85
+ }
86
+ return Array.from(deps);
87
+ }
88
+ };
89
+ async function getElements(rootConfig) {
90
+ var _a;
91
+ const rootDir = rootConfig.rootDir;
92
+ const elementsDirs = getElementsDirs(rootConfig);
93
+ const excludePatterns = ((_a = rootConfig.elements) == null ? void 0 : _a.exclude) || [];
94
+ const excludeElement = (moduleId) => {
95
+ return excludePatterns.some((pattern) => Boolean(moduleId.match(pattern)));
96
+ };
97
+ const elementFilePaths = {};
98
+ for (const dirPath of elementsDirs) {
99
+ if (await isDirectory(dirPath)) {
100
+ const files = await glob("**/*", { cwd: dirPath });
101
+ files.forEach((file) => {
102
+ const parts = path.parse(file);
103
+ if (isJsFile(parts.base) && isValidTagName(parts.name)) {
104
+ const tagName = parts.name;
105
+ const filePath = path.join(dirPath, file);
106
+ const relPath = path.relative(rootDir, filePath);
107
+ if (!excludeElement(relPath)) {
108
+ elementFilePaths[tagName] = { filePath, relPath };
109
+ }
110
+ }
111
+ });
112
+ }
113
+ }
114
+ const graph = new ElementGraph(elementFilePaths);
115
+ return graph;
116
+ }
117
+ function getElementsDirs(rootConfig) {
118
+ var _a;
119
+ const rootDir = rootConfig.rootDir;
120
+ const workspaceRoot = searchForWorkspaceRoot(rootDir);
121
+ const elementsDirs = [path.join(rootDir, "elements")];
122
+ const elementsInclude = ((_a = rootConfig.elements) == null ? void 0 : _a.include) || [];
123
+ for (const dirPath of elementsInclude) {
124
+ const elementsDir = path.resolve(rootDir, dirPath);
125
+ if (!directoryContains(rootDir, elementsDir)) {
126
+ throw new Error(
127
+ `the elements dir (${dirPath}) should be within the project's workspace (${workspaceRoot})`
128
+ );
129
+ }
130
+ elementsDirs.push(elementsDir);
131
+ }
132
+ return elementsDirs;
133
+ }
134
+
135
+ // src/render/asset-map/build-asset-map.ts
136
+ import fs2 from "node:fs";
137
+ import path2 from "node:path";
138
+ var BuildAssetMap = class {
139
+ constructor(rootConfig) {
140
+ this.rootConfig = rootConfig;
141
+ this.srcToAsset = /* @__PURE__ */ new Map();
142
+ }
143
+ async get(src) {
144
+ const asset = this.srcToAsset.get(src);
145
+ if (asset) {
146
+ return asset;
147
+ }
148
+ const realSrc = realPathRelativeTo(this.rootConfig.rootDir, src);
149
+ if (realSrc !== src) {
150
+ const asset2 = this.srcToAsset.get(realSrc);
151
+ if (asset2) {
152
+ return asset2;
153
+ }
154
+ }
155
+ console.log(`could not find build asset: ${src}`);
156
+ return null;
157
+ }
158
+ add(asset) {
159
+ this.srcToAsset.set(asset.src, asset);
160
+ }
161
+ toJson() {
162
+ const result = {};
163
+ for (const src of this.srcToAsset.keys()) {
164
+ result[src] = this.srcToAsset.get(src).toJson();
165
+ }
166
+ return result;
167
+ }
168
+ static fromViteManifest(rootConfig, clientManifest, elementsGraph) {
169
+ const assetMap = new BuildAssetMap(rootConfig);
170
+ const elementFiles = /* @__PURE__ */ new Set();
171
+ Object.values(elementsGraph.sourceFiles).forEach((elementSource) => {
172
+ elementFiles.add(elementSource.relPath);
173
+ const realSrc = realPathRelativeTo(
174
+ rootConfig.rootDir,
175
+ elementSource.relPath
176
+ );
177
+ if (realSrc !== elementSource.filePath) {
178
+ elementFiles.add(realSrc);
179
+ }
180
+ });
181
+ Object.keys(clientManifest).forEach((manifestKey) => {
182
+ const src = manifestKey;
183
+ const manifestChunk = clientManifest[manifestKey];
184
+ const isElement = elementFiles.has(src);
185
+ const assetUrl = src.startsWith("routes/") && isJsFile(src) ? "" : `/${manifestChunk.file}`;
186
+ const assetData = {
187
+ src,
188
+ assetUrl,
189
+ importedModules: manifestChunk.imports || [],
190
+ importedCss: (manifestChunk.css || []).map((relPath) => `/${relPath}`),
191
+ isElement
192
+ };
193
+ assetMap.add(new BuildAsset(assetMap, assetData));
194
+ });
195
+ return assetMap;
196
+ }
197
+ static fromRootManifest(rootConfig, rootManifest) {
198
+ const assetMap = new BuildAssetMap(rootConfig);
199
+ Object.keys(rootManifest).forEach((moduleId) => {
200
+ const assetData = rootManifest[moduleId];
201
+ assetMap.add(new BuildAsset(assetMap, assetData));
202
+ });
203
+ return assetMap;
204
+ }
205
+ };
206
+ function realPathRelativeTo(rootDir, src) {
207
+ const fullPath = path2.resolve(rootDir, src);
208
+ if (!fs2.existsSync(fullPath)) {
209
+ return src;
210
+ }
211
+ const realpath = fs2.realpathSync(path2.resolve(rootDir, src));
212
+ return path2.relative(rootDir, realpath);
213
+ }
214
+ var BuildAsset = class {
215
+ constructor(assetMap, assetData) {
216
+ this.assetMap = assetMap;
217
+ this.src = assetData.src;
218
+ this.assetUrl = assetData.assetUrl;
219
+ this.importedModules = assetData.importedModules;
220
+ this.importedCss = assetData.importedCss;
221
+ this.isElement = assetData.isElement;
222
+ }
223
+ async getCssDeps() {
224
+ const visited = /* @__PURE__ */ new Set();
225
+ const deps = /* @__PURE__ */ new Set();
226
+ await this.collectCss(this, deps, visited);
227
+ return Array.from(deps);
228
+ }
229
+ async getJsDeps() {
230
+ const visited = /* @__PURE__ */ new Set();
231
+ const deps = /* @__PURE__ */ new Set();
232
+ await this.collectJs(this, deps, visited);
233
+ return Array.from(deps);
234
+ }
235
+ async collectJs(asset, urls, visited) {
236
+ if (!asset) {
237
+ return;
238
+ }
239
+ if (!asset.src) {
240
+ return;
241
+ }
242
+ if (visited.has(asset.src)) {
243
+ return;
244
+ }
245
+ visited.add(asset.src);
246
+ if (asset.isElement) {
247
+ urls.add(asset.assetUrl);
248
+ }
249
+ await Promise.all(
250
+ asset.importedModules.map(async (src) => {
251
+ const importedAsset = await this.assetMap.get(src);
252
+ this.collectJs(importedAsset, urls, visited);
253
+ })
254
+ );
255
+ }
256
+ async collectCss(asset, urls, visited) {
257
+ if (!asset) {
258
+ return;
259
+ }
260
+ if (!asset.src) {
261
+ return;
262
+ }
263
+ if (visited.has(asset.src)) {
264
+ return;
265
+ }
266
+ visited.add(asset.src);
267
+ if (asset.importedCss) {
268
+ asset.importedCss.forEach((cssUrl) => urls.add(cssUrl));
269
+ }
270
+ await Promise.all(
271
+ asset.importedModules.map(async (moduleId) => {
272
+ const importedAsset = await this.assetMap.get(moduleId);
273
+ this.collectCss(importedAsset, urls, visited);
274
+ })
275
+ );
276
+ }
277
+ toJson() {
278
+ return {
279
+ src: this.src,
280
+ assetUrl: this.assetUrl,
281
+ importedModules: this.importedModules,
282
+ importedCss: this.importedCss,
283
+ isElement: this.isElement
284
+ };
285
+ }
286
+ };
287
+
288
+ // src/cli/commands/build.ts
289
+ var __dirname = path3.dirname(fileURLToPath(import.meta.url));
290
+ async function build(rootProjectDir, options) {
291
+ var _a, _b, _c, _d, _e, _f, _g, _h;
292
+ const mode = (options == null ? void 0 : options.mode) || "production";
293
+ process.env.NODE_ENV = mode;
294
+ const rootDir = path3.resolve(rootProjectDir || process.cwd());
295
+ const rootConfig = await loadRootConfig(rootDir, { command: "build" });
296
+ const distDir = path3.join(rootDir, "dist");
297
+ const ssrOnly = (options == null ? void 0 : options.ssrOnly) || false;
298
+ console.log();
299
+ console.log(`${dim("\u2503")} project: ${rootDir}`);
300
+ console.log(`${dim("\u2503")} output: ${distDir}/html`);
301
+ console.log(`${dim("\u2503")} mode: ${mode}`);
302
+ console.log();
303
+ await rmDir(distDir);
304
+ await makeDir(distDir);
305
+ const routeFiles = [];
306
+ if (await isDirectory(path3.join(rootDir, "routes"))) {
307
+ const pageFiles = await glob2("routes/**/*", { cwd: rootDir });
308
+ pageFiles.forEach((file) => {
309
+ const parts = path3.parse(file);
310
+ if (!parts.name.startsWith("_") && isJsFile(parts.base)) {
311
+ routeFiles.push(path3.resolve(rootDir, file));
312
+ }
313
+ });
314
+ }
315
+ const elementGraph = await getElements(rootConfig);
316
+ const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {
317
+ return sourceFile.filePath;
318
+ });
319
+ const bundleScripts = [];
320
+ if (await isDirectory(path3.join(rootDir, "bundles"))) {
321
+ const bundleFiles = await glob2("bundles/*", { cwd: rootDir });
322
+ bundleFiles.forEach((file) => {
323
+ const parts = path3.parse(file);
324
+ if (isJsFile(parts.base)) {
325
+ bundleScripts.push(path3.resolve(rootDir, file));
326
+ }
327
+ });
328
+ }
329
+ const rootPlugins = rootConfig.plugins || [];
330
+ const viteConfig = rootConfig.vite || {};
331
+ const vitePlugins = [
332
+ ...viteConfig.plugins || [],
333
+ ...getVitePlugins(rootPlugins)
334
+ ];
335
+ const baseConfig = {
336
+ ...viteConfig,
337
+ root: rootDir,
338
+ mode,
339
+ esbuild: {
340
+ ...viteConfig.esbuild,
341
+ jsx: "automatic",
342
+ jsxImportSource: "preact",
343
+ treeShaking: true
344
+ },
345
+ plugins: vitePlugins
346
+ };
347
+ const ssrInput = {
348
+ render: path3.resolve(__dirname, "./render.js")
349
+ };
350
+ rootPlugins.forEach((plugin) => {
351
+ if (plugin.ssrInput) {
352
+ Object.assign(ssrInput, plugin.ssrInput());
353
+ }
354
+ });
355
+ const noExternalConfig = (_a = viteConfig.ssr) == null ? void 0 : _a.noExternal;
356
+ const noExternal = [];
357
+ if (noExternalConfig) {
358
+ if (Array.isArray(noExternalConfig)) {
359
+ noExternal.push(...noExternalConfig);
360
+ } else {
361
+ noExternal.push(noExternalConfig);
362
+ }
363
+ }
364
+ await viteBuild({
365
+ ...baseConfig,
366
+ publicDir: false,
367
+ build: {
368
+ ...viteConfig == null ? void 0 : viteConfig.build,
369
+ rollupOptions: {
370
+ ...(_b = viteConfig == null ? void 0 : viteConfig.build) == null ? void 0 : _b.rollupOptions,
371
+ input: ssrInput,
372
+ output: {
373
+ format: "esm",
374
+ chunkFileNames: "chunks/[hash].min.js",
375
+ assetFileNames: "assets/[name].[hash][extname]",
376
+ sanitizeFileName
377
+ }
378
+ },
379
+ outDir: path3.join(distDir, "server"),
380
+ ssr: true,
381
+ ssrManifest: false,
382
+ cssCodeSplit: true,
383
+ target: "esnext",
384
+ minify: false,
385
+ modulePreload: { polyfill: false },
386
+ reportCompressedSize: false
387
+ },
388
+ ssr: {
389
+ ...viteConfig.ssr,
390
+ target: "node",
391
+ noExternal: ["@blinkk/root", ...noExternal]
392
+ }
393
+ });
394
+ await viteBuild({
395
+ ...baseConfig,
396
+ publicDir: false,
397
+ build: {
398
+ ...viteConfig == null ? void 0 : viteConfig.build,
399
+ rollupOptions: {
400
+ ...(_c = viteConfig == null ? void 0 : viteConfig.build) == null ? void 0 : _c.rollupOptions,
401
+ input: [...routeFiles],
402
+ output: {
403
+ format: "esm",
404
+ entryFileNames: "assets/[name].[hash].min.js",
405
+ assetFileNames: "assets/[name].[hash][extname]",
406
+ chunkFileNames: "chunks/[hash].min.js",
407
+ sanitizeFileName,
408
+ ...(_e = (_d = viteConfig == null ? void 0 : viteConfig.build) == null ? void 0 : _d.rollupOptions) == null ? void 0 : _e.output
409
+ }
410
+ },
411
+ outDir: path3.join(distDir, "routes"),
412
+ ssr: false,
413
+ ssrManifest: false,
414
+ manifest: true,
415
+ cssCodeSplit: true,
416
+ target: "esnext",
417
+ minify: true,
418
+ modulePreload: { polyfill: false },
419
+ reportCompressedSize: false
420
+ }
421
+ });
422
+ const clientInput = [...elements, ...bundleScripts];
423
+ if (clientInput.length > 0) {
424
+ await viteBuild({
425
+ ...baseConfig,
426
+ publicDir: false,
427
+ build: {
428
+ ...viteConfig == null ? void 0 : viteConfig.build,
429
+ rollupOptions: {
430
+ ...(_f = viteConfig == null ? void 0 : viteConfig.build) == null ? void 0 : _f.rollupOptions,
431
+ input: [...elements, ...bundleScripts],
432
+ output: {
433
+ format: "esm",
434
+ entryFileNames: "assets/[name].[hash].min.js",
435
+ assetFileNames: "assets/[name].[hash][extname]",
436
+ chunkFileNames: "chunks/[hash].min.js",
437
+ sanitizeFileName,
438
+ ...(_h = (_g = viteConfig == null ? void 0 : viteConfig.build) == null ? void 0 : _g.rollupOptions) == null ? void 0 : _h.output
439
+ }
440
+ },
441
+ outDir: path3.join(distDir, "client"),
442
+ ssr: false,
443
+ ssrManifest: false,
444
+ manifest: true,
445
+ cssCodeSplit: true,
446
+ target: "esnext",
447
+ minify: true,
448
+ modulePreload: { polyfill: false },
449
+ reportCompressedSize: false
450
+ }
451
+ });
452
+ } else {
453
+ await writeFile(path3.join(distDir, "client/manifest.json"), "{}");
454
+ }
455
+ await copyGlob(
456
+ "**/*.css",
457
+ path3.join(distDir, "routes"),
458
+ path3.join(distDir, "client")
459
+ );
460
+ const routesManifest = await loadJson(
461
+ path3.join(distDir, "routes/manifest.json")
462
+ );
463
+ const clientManifest = await loadJson(
464
+ path3.join(distDir, "client/manifest.json")
465
+ );
466
+ function collectRouteCss(asset, cssDeps, visited) {
467
+ if (!asset || !asset.file || visited.has(asset.file)) {
468
+ return;
469
+ }
470
+ visited.add(asset.file);
471
+ if (asset.css) {
472
+ asset.css.forEach((dep) => cssDeps.add(dep));
473
+ }
474
+ if (asset.imports) {
475
+ asset.imports.forEach((manifestKey) => {
476
+ collectRouteCss(routesManifest[manifestKey], cssDeps, visited);
477
+ });
478
+ }
479
+ }
480
+ Object.keys(routesManifest).forEach((manifestKey) => {
481
+ const asset = routesManifest[manifestKey];
482
+ if (asset.isEntry) {
483
+ const visited = /* @__PURE__ */ new Set();
484
+ const cssDeps = /* @__PURE__ */ new Set();
485
+ collectRouteCss(asset, cssDeps, visited);
486
+ asset.css = Array.from(cssDeps);
487
+ asset.imports = [];
488
+ clientManifest[manifestKey] = asset;
489
+ } else if (asset.file.endsWith(".css")) {
490
+ clientManifest[manifestKey] = asset;
491
+ }
492
+ });
493
+ const assetMap = BuildAssetMap.fromViteManifest(
494
+ rootConfig,
495
+ clientManifest,
496
+ elementGraph
497
+ );
498
+ const rootManifest = assetMap.toJson();
499
+ await writeFile(
500
+ path3.join(distDir, "client/root-manifest.json"),
501
+ JSON.stringify(rootManifest, null, 2)
502
+ );
503
+ const elementGraphJson = elementGraph.toJson();
504
+ await writeFile(
505
+ path3.join(distDir, "client/root-element-graph.json"),
506
+ JSON.stringify(elementGraphJson, null, 2)
507
+ );
508
+ const buildDir = path3.join(distDir, "html");
509
+ const publicDir = path3.join(rootDir, "public");
510
+ if (fsExtra.existsSync(path3.join(rootDir, "public"))) {
511
+ fsExtra.copySync(publicDir, buildDir, { dereference: true });
512
+ } else {
513
+ await makeDir(buildDir);
514
+ }
515
+ console.log("\njs/css output:");
516
+ await Promise.all(
517
+ Object.keys(rootManifest).map(async (src) => {
518
+ if (isRouteFile(src)) {
519
+ return;
520
+ }
521
+ const assetData = rootManifest[src];
522
+ if (!assetData.assetUrl) {
523
+ return;
524
+ }
525
+ const assetRelPath = assetData.assetUrl.slice(1);
526
+ const assetFrom = path3.join(distDir, "client", assetRelPath);
527
+ const assetTo = path3.join(buildDir, assetRelPath);
528
+ if (!await fileExists(assetFrom)) {
529
+ console.log(`${assetFrom} does not exist`);
530
+ return;
531
+ }
532
+ await fsExtra.copy(assetFrom, assetTo);
533
+ printFileOutput(fileSize(assetTo), "dist/html/", assetRelPath);
534
+ })
535
+ );
536
+ if (!ssrOnly) {
537
+ const render = await import(path3.join(distDir, "server/render.js"));
538
+ const renderer = new render.Renderer(rootConfig, { assetMap, elementGraph });
539
+ const sitemap = await renderer.getSitemap();
540
+ console.log("\nhtml output:");
541
+ await Promise.all(
542
+ Object.keys(sitemap).map(async (urlPath) => {
543
+ const { route, params } = sitemap[urlPath];
544
+ const data = await renderer.renderRoute(route, {
545
+ routeParams: params
546
+ });
547
+ if (data.notFound) {
548
+ return;
549
+ }
550
+ let outFilePath = path3.join(urlPath.slice(1), "index.html");
551
+ if (outFilePath.endsWith("404/index.html")) {
552
+ outFilePath = outFilePath.replace("404/index.html", "404.html");
553
+ }
554
+ const outPath = path3.join(buildDir, outFilePath);
555
+ let html = data.html || "";
556
+ if (rootConfig.prettyHtml !== false) {
557
+ html = await htmlPretty(html, rootConfig.prettyHtmlOptions);
558
+ }
559
+ if (rootConfig.minifyHtml !== false) {
560
+ html = await htmlMinify(html, rootConfig.minifyHtmlOptions);
561
+ }
562
+ await writeFile(outPath, html);
563
+ printFileOutput(fileSize(outPath), "dist/html/", outFilePath);
564
+ })
565
+ );
566
+ }
567
+ }
568
+ function isRouteFile(filepath) {
569
+ return filepath.startsWith("routes") && isJsFile(filepath);
570
+ }
571
+ function fileSize(filepath) {
572
+ const stats = fsExtra.statSync(filepath);
573
+ const bytes = stats.size;
574
+ const k = 1024;
575
+ if (bytes < k) {
576
+ return (bytes / k).toFixed(2) + " kB";
577
+ }
578
+ const units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
579
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
580
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + units[i];
581
+ }
582
+ function printFileOutput(fileSize2, outputDir, outputFile) {
583
+ const indent = " ".repeat(2);
584
+ const paddedSize = fileSize2.padStart(9, " ");
585
+ console.log(
586
+ `${indent}${dim(paddedSize)} ${dim(outputDir)}${cyan(outputFile)}`
587
+ );
588
+ }
589
+ function sanitizeFileName(name) {
590
+ return name.replaceAll("...", "").replaceAll("_", "").replaceAll("[", "").replaceAll("]", "").replace(/[^\x00-\x7F]/g, "").replace(/\x00/g, "").toLowerCase();
591
+ }
592
+
593
+ // src/cli/commands/dev.ts
594
+ import path5 from "node:path";
595
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
596
+ import { default as express } from "express";
597
+ import { dim as dim2 } from "kleur/colors";
598
+ import glob3 from "tiny-glob";
599
+
600
+ // src/core/middleware.ts
601
+ function rootProjectMiddleware(options) {
602
+ return (req, _, next) => {
603
+ req.rootConfig = options.rootConfig;
604
+ next();
605
+ };
606
+ }
607
+
608
+ // src/render/asset-map/dev-asset-map.ts
609
+ import path4 from "node:path";
610
+ import { searchForWorkspaceRoot as searchForWorkspaceRoot2 } from "vite";
611
+ var DevServerAssetMap = class {
612
+ constructor(rootConfig, moduleGraph) {
613
+ this.rootConfig = rootConfig;
614
+ this.moduleGraph = moduleGraph;
615
+ }
616
+ async get(src) {
617
+ const file = path4.resolve(this.rootConfig.rootDir, src);
618
+ const viteModules = this.moduleGraph.getModulesByFile(file);
619
+ if (viteModules && viteModules.size > 0) {
620
+ const [viteModule] = viteModules;
621
+ return new DevServerAsset(src, {
622
+ assetMap: this,
623
+ viteModule
624
+ });
625
+ }
626
+ if (file.startsWith(this.rootConfig.rootDir)) {
627
+ const assetUrl = file.slice(this.rootConfig.rootDir.length);
628
+ return {
629
+ src,
630
+ assetUrl,
631
+ getCssDeps: async () => [],
632
+ getJsDeps: async () => [assetUrl]
633
+ };
634
+ }
635
+ const workspaceRoot = searchForWorkspaceRoot2(this.rootConfig.rootDir);
636
+ if (await directoryContains(workspaceRoot, file)) {
637
+ const assetUrl = `/@fs/${file}`;
638
+ return {
639
+ src,
640
+ assetUrl,
641
+ getCssDeps: async () => [],
642
+ getJsDeps: async () => [assetUrl]
643
+ };
644
+ }
645
+ console.log(`could not find asset in asset map: ${src}`);
646
+ return null;
647
+ }
648
+ filePathToSrc(file) {
649
+ return path4.relative(this.rootConfig.rootDir, file);
650
+ }
651
+ };
652
+ var DevServerAsset = class {
653
+ constructor(src, options) {
654
+ this.src = src;
655
+ this.assetMap = options.assetMap;
656
+ this.viteModule = options.viteModule;
657
+ this.moduleId = this.viteModule.id;
658
+ this.assetUrl = this.viteModule.url;
659
+ }
660
+ async getCssDeps() {
661
+ const visited = /* @__PURE__ */ new Set();
662
+ const deps = /* @__PURE__ */ new Set();
663
+ this.collectCss(this, deps, visited);
664
+ return Array.from(deps);
665
+ }
666
+ async getJsDeps() {
667
+ const visited = /* @__PURE__ */ new Set();
668
+ const deps = /* @__PURE__ */ new Set();
669
+ this.collectJs(this, deps, visited);
670
+ return Array.from(deps);
671
+ }
672
+ getImportedModules() {
673
+ return this.viteModule.importedModules;
674
+ }
675
+ collectJs(asset, urls, visited) {
676
+ if (!asset) {
677
+ return;
678
+ }
679
+ if (!asset.moduleId) {
680
+ return;
681
+ }
682
+ if (visited.has(asset.moduleId)) {
683
+ return;
684
+ }
685
+ visited.add(asset.moduleId);
686
+ const parts = path4.parse(asset.assetUrl);
687
+ if ([".js", ".jsx", ".ts", ".tsx"].includes(parts.ext) && asset.moduleId.includes("/elements/")) {
688
+ urls.add(asset.assetUrl);
689
+ }
690
+ asset.getImportedModules().forEach((viteModule) => {
691
+ if (viteModule.file) {
692
+ const src = this.assetMap.filePathToSrc(viteModule.file);
693
+ const importedAsset = new DevServerAsset(src, {
694
+ assetMap: this.assetMap,
695
+ viteModule
696
+ });
697
+ this.collectJs(importedAsset, urls, visited);
698
+ }
699
+ });
700
+ }
701
+ collectCss(asset, urls, visited) {
702
+ if (!asset) {
703
+ return;
704
+ }
705
+ if (!asset.assetUrl) {
706
+ return;
707
+ }
708
+ if (visited.has(asset.assetUrl)) {
709
+ return;
710
+ }
711
+ visited.add(asset.assetUrl);
712
+ if (asset.src.endsWith(".scss")) {
713
+ const parts = path4.parse(asset.src);
714
+ if (!parts.name.startsWith("_")) {
715
+ urls.add(asset.assetUrl);
716
+ }
717
+ }
718
+ asset.getImportedModules().forEach((viteModule) => {
719
+ if (viteModule.file) {
720
+ const src = this.assetMap.filePathToSrc(viteModule.file);
721
+ const importedAsset = new DevServerAsset(src, {
722
+ assetMap: this.assetMap,
723
+ viteModule
724
+ });
725
+ this.collectCss(importedAsset, urls, visited);
726
+ }
727
+ });
728
+ }
729
+ };
730
+
731
+ // src/utils/ports.ts
732
+ import { createServer } from "node:net";
733
+ function isPortOpen(port) {
734
+ return new Promise((resolve, reject) => {
735
+ const server = createServer();
736
+ server.on("error", (err) => {
737
+ if (err.code === "EADDRINUSE") {
738
+ resolve(false);
739
+ return;
740
+ }
741
+ reject(err);
742
+ });
743
+ server.on("close", () => {
744
+ resolve(true);
745
+ });
746
+ server.listen(port, () => {
747
+ server.close((err) => {
748
+ if (err) {
749
+ console.log(`error closing server: ${err}`);
750
+ reject(err);
751
+ }
752
+ });
753
+ });
754
+ });
755
+ }
756
+ async function findOpenPort(min, max) {
757
+ let port = min;
758
+ while (port <= max) {
759
+ const isOpen = await isPortOpen(port);
760
+ if (isOpen) {
761
+ return port;
762
+ }
763
+ port += 1;
764
+ }
765
+ throw new Error(`no ports open between ${min} and ${max}`);
766
+ }
767
+
768
+ // src/cli/commands/dev.ts
769
+ var __dirname2 = path5.dirname(fileURLToPath2(import.meta.url));
770
+ async function dev(rootProjectDir, options) {
771
+ process.env.NODE_ENV = "development";
772
+ const rootDir = path5.resolve(rootProjectDir || process.cwd());
773
+ const defaultPort = parseInt(process.env.PORT || "4007");
774
+ const host = (options == null ? void 0 : options.host) || "localhost";
775
+ const port = await findOpenPort(defaultPort, defaultPort + 10);
776
+ console.log();
777
+ console.log(`${dim2("\u2503")} project: ${rootDir}`);
778
+ console.log(`${dim2("\u2503")} server: http://${host}:${port}`);
779
+ console.log(`${dim2("\u2503")} mode: development`);
780
+ console.log();
781
+ const server = await createDevServer({ rootDir, port });
782
+ server.listen(port, host);
783
+ }
784
+ async function createDevServer(options) {
785
+ const rootDir = path5.resolve((options == null ? void 0 : options.rootDir) || process.cwd());
786
+ const rootConfig = await loadRootConfig(rootDir, { command: "dev" });
787
+ const port = options == null ? void 0 : options.port;
788
+ const server = express();
789
+ server.disable("x-powered-by");
790
+ server.use(rootProjectMiddleware({ rootConfig }));
791
+ server.use(await viteServerMiddleware({ rootConfig, port }));
792
+ const plugins = rootConfig.plugins || [];
793
+ await configureServerPlugins(
794
+ server,
795
+ async () => {
796
+ var _a;
797
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
798
+ for (const middleware of userMiddlewares) {
799
+ server.use(middleware);
800
+ }
801
+ server.use(rootDevServerMiddleware());
802
+ server.use(rootDevServer404Middleware());
803
+ server.use(rootDevServer500Middleware());
804
+ },
805
+ plugins,
806
+ { type: "dev", rootConfig }
807
+ );
808
+ return server;
809
+ }
810
+ async function viteServerMiddleware(options) {
811
+ const rootConfig = options.rootConfig;
812
+ const rootDir = rootConfig.rootDir;
813
+ let elementGraph = await getElements(rootConfig);
814
+ const elements = Object.values(elementGraph.sourceFiles).map((sourceFile) => {
815
+ return sourceFile.relPath;
816
+ });
817
+ const bundleScripts = [];
818
+ if (await isDirectory(path5.join(rootDir, "bundles"))) {
819
+ const bundleFiles = await glob3("bundles/*", { cwd: rootDir });
820
+ bundleFiles.forEach((file) => {
821
+ const parts = path5.parse(file);
822
+ if (isJsFile(parts.base)) {
823
+ bundleScripts.push(file);
824
+ }
825
+ });
826
+ }
827
+ const optimizeDeps = [...elements, ...bundleScripts];
828
+ const viteServer = await createViteServer(rootConfig, {
829
+ port: options.port,
830
+ optimizeDeps
831
+ });
832
+ function isInElementsDir(changedFilePath) {
833
+ const filePath = path5.resolve(changedFilePath);
834
+ const elementsDirs = getElementsDirs(rootConfig);
835
+ return elementsDirs.some((dirPath) => filePath.startsWith(dirPath));
836
+ }
837
+ viteServer.watcher.on("add", async (filePath) => {
838
+ if (isInElementsDir(filePath)) {
839
+ elementGraph = await getElements(rootConfig);
840
+ }
841
+ });
842
+ viteServer.watcher.on("unlink", async (filePath) => {
843
+ if (isInElementsDir(filePath)) {
844
+ elementGraph = await getElements(rootConfig);
845
+ }
846
+ });
847
+ return async (req, res, next) => {
848
+ try {
849
+ req.viteServer = viteServer;
850
+ const renderModulePath = path5.resolve(__dirname2, "./render.js");
851
+ const render = await viteServer.ssrLoadModule(
852
+ renderModulePath
853
+ );
854
+ const assetMap = new DevServerAssetMap(
855
+ rootConfig,
856
+ viteServer.moduleGraph
857
+ );
858
+ req.renderer = new render.Renderer(rootConfig, { assetMap, elementGraph });
859
+ viteServer.middlewares(req, res, next);
860
+ } catch (e) {
861
+ next(e);
862
+ }
863
+ };
864
+ }
865
+ function rootDevServerMiddleware() {
866
+ return async (req, res, next) => {
867
+ const renderer = req.renderer;
868
+ const viteServer = req.viteServer;
869
+ try {
870
+ await renderer.handle(req, res, next);
871
+ } catch (err) {
872
+ viteServer.ssrFixStacktrace(err);
873
+ next(err);
874
+ }
875
+ };
876
+ }
877
+ function rootDevServer404Middleware() {
878
+ return async (req, res) => {
879
+ console.error(`\u2753 404 ${req.originalUrl}`);
880
+ if (req.renderer) {
881
+ const url = req.path;
882
+ const ext = path5.extname(url);
883
+ if (!ext) {
884
+ const renderer = req.renderer;
885
+ const data = await renderer.renderDevServer404(req);
886
+ const html = data.html || "";
887
+ res.status(404).set({ "Content-Type": "text/html" }).end(html);
888
+ return;
889
+ }
890
+ }
891
+ res.status(404).set({ "Content-Type": "text/plain" }).end("404");
892
+ };
893
+ }
894
+ function rootDevServer500Middleware() {
895
+ return async (err, req, res, next) => {
896
+ console.error(`\u2757 500 ${req.originalUrl}`);
897
+ console.error(String(err.stack || err));
898
+ if (req.renderer) {
899
+ const url = req.path;
900
+ const ext = path5.extname(url);
901
+ if (!ext) {
902
+ const renderer = req.renderer;
903
+ const data = await renderer.renderDevServer500(req, err);
904
+ const html = data.html || "";
905
+ res.status(500).set({ "Content-Type": "text/html" }).end(html);
906
+ return;
907
+ }
908
+ }
909
+ next(err);
910
+ };
911
+ }
912
+
913
+ // src/cli/commands/preview.ts
914
+ import path6 from "node:path";
915
+ import compression from "compression";
916
+ import { default as express2 } from "express";
917
+ import { dim as dim3 } from "kleur/colors";
918
+ import sirv from "sirv";
919
+ async function preview(rootProjectDir, options) {
920
+ process.env.NODE_ENV = "development";
921
+ const rootDir = path6.resolve(rootProjectDir || process.cwd());
922
+ const server = await createPreviewServer({ rootDir });
923
+ const port = parseInt(process.env.PORT || "4007");
924
+ const host = (options == null ? void 0 : options.host) || "localhost";
925
+ console.log();
926
+ console.log(`${dim3("\u2503")} project: ${rootDir}`);
927
+ console.log(`${dim3("\u2503")} server: http://${host}:${port}`);
928
+ console.log(`${dim3("\u2503")} mode: preview`);
929
+ console.log();
930
+ server.listen(port, host);
931
+ }
932
+ async function createPreviewServer(options) {
933
+ const rootDir = options.rootDir;
934
+ const rootConfig = await loadRootConfig(rootDir, { command: "preview" });
935
+ const distDir = path6.join(rootDir, "dist");
936
+ const server = express2();
937
+ server.disable("x-powered-by");
938
+ server.use(compression());
939
+ server.use(rootProjectMiddleware({ rootConfig }));
940
+ server.use(await rootPreviewRendererMiddleware({ rootConfig, distDir }));
941
+ const plugins = rootConfig.plugins || [];
942
+ configureServerPlugins(
943
+ server,
944
+ async () => {
945
+ var _a;
946
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
947
+ userMiddlewares.forEach((middleware) => {
948
+ server.use(middleware);
949
+ });
950
+ const publicDir = path6.join(distDir, "html");
951
+ server.use(sirv(publicDir, { dev: false }));
952
+ server.use(rootPreviewServerMiddleware());
953
+ server.use(rootPreviewServer404Middleware());
954
+ server.use(rootPreviewServer500Middleware());
955
+ },
956
+ plugins,
957
+ { type: "preview", rootConfig }
958
+ );
959
+ return server;
960
+ }
961
+ async function rootPreviewRendererMiddleware(options) {
962
+ const { distDir, rootConfig } = options;
963
+ const render = await import(path6.join(distDir, "server/render.js"));
964
+ const manifestPath = path6.join(distDir, "client/root-manifest.json");
965
+ if (!await fileExists(manifestPath)) {
966
+ throw new Error(
967
+ `could not find ${manifestPath}. run \`root build\` before \`root preview\`.`
968
+ );
969
+ }
970
+ const elementGraphJsonPath = path6.join(
971
+ distDir,
972
+ "client/root-element-graph.json"
973
+ );
974
+ if (!await fileExists(elementGraphJsonPath)) {
975
+ throw new Error(
976
+ `could not find ${elementGraphJsonPath}. run \`root build\` before \`root start\`.`
977
+ );
978
+ }
979
+ const rootManifest = await loadJson(manifestPath);
980
+ const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);
981
+ const elementGraphJson = await loadJson(elementGraphJsonPath);
982
+ const elementGraph = ElementGraph.fromJson(elementGraphJson);
983
+ const renderer = new render.Renderer(rootConfig, { assetMap, elementGraph });
984
+ return async (req, _, next) => {
985
+ req.renderer = renderer;
986
+ next();
987
+ };
988
+ }
989
+ function rootPreviewServerMiddleware() {
990
+ return async (req, res, next) => {
991
+ const renderer = req.renderer;
992
+ try {
993
+ await renderer.handle(req, res, next);
994
+ } catch (e) {
995
+ try {
996
+ console.error(`error rendering ${req.originalUrl}`);
997
+ console.error(e.stack || e);
998
+ const { html } = await renderer.renderError(e);
999
+ res.status(500).set({ "Content-Type": "text/html" }).end(html);
1000
+ } catch (e2) {
1001
+ console.error("failed to render custom error");
1002
+ console.error(e2);
1003
+ next(e);
1004
+ }
1005
+ }
1006
+ };
1007
+ }
1008
+ function rootPreviewServer404Middleware() {
1009
+ return async (req, res) => {
1010
+ console.error(`\u2753 404 ${req.originalUrl}`);
1011
+ if (req.renderer) {
1012
+ const url = req.path;
1013
+ const ext = path6.extname(url);
1014
+ if (!ext) {
1015
+ const renderer = req.renderer;
1016
+ const data = await renderer.renderDevServer404(req);
1017
+ const html = data.html || "";
1018
+ res.status(404).set({ "Content-Type": "text/html" }).end(html);
1019
+ return;
1020
+ }
1021
+ }
1022
+ res.status(404).set({ "Content-Type": "text/plain" }).end("404");
1023
+ };
1024
+ }
1025
+ function rootPreviewServer500Middleware() {
1026
+ return async (err, req, res, next) => {
1027
+ console.error(`\u2757 500 ${req.originalUrl}`);
1028
+ console.error(String(err.stack || err));
1029
+ if (req.renderer) {
1030
+ const url = req.path;
1031
+ const ext = path6.extname(url);
1032
+ if (!ext) {
1033
+ const renderer = req.renderer;
1034
+ const data = await renderer.renderDevServer500(req, err);
1035
+ const html = data.html || "";
1036
+ res.status(500).set({ "Content-Type": "text/html" }).end(html);
1037
+ return;
1038
+ }
1039
+ }
1040
+ next(err);
1041
+ };
1042
+ }
1043
+
1044
+ // src/cli/commands/start.ts
1045
+ import path7 from "node:path";
1046
+ import compression2 from "compression";
1047
+ import { default as express3 } from "express";
1048
+ import { dim as dim4 } from "kleur/colors";
1049
+ import sirv2 from "sirv";
1050
+ async function start(rootProjectDir, options) {
1051
+ process.env.NODE_ENV = "production";
1052
+ const rootDir = path7.resolve(rootProjectDir || process.cwd());
1053
+ const server = await createProdServer({ rootDir });
1054
+ const port = parseInt(process.env.PORT || "4007");
1055
+ const host = (options == null ? void 0 : options.host) || "localhost";
1056
+ console.log();
1057
+ console.log(`${dim4("\u2503")} project: ${rootDir}`);
1058
+ console.log(`${dim4("\u2503")} server: http://${host}:${port}`);
1059
+ console.log(`${dim4("\u2503")} mode: production`);
1060
+ console.log();
1061
+ server.listen(port, host);
1062
+ }
1063
+ async function createProdServer(options) {
1064
+ const rootDir = options.rootDir;
1065
+ const rootConfig = await loadRootConfig(rootDir, { command: "start" });
1066
+ const distDir = path7.join(rootDir, "dist");
1067
+ const server = express3();
1068
+ server.disable("x-powered-by");
1069
+ server.use(compression2());
1070
+ server.use(rootProjectMiddleware({ rootConfig }));
1071
+ server.use(await rootProdRendererMiddleware({ rootConfig, distDir }));
1072
+ const plugins = rootConfig.plugins || [];
1073
+ configureServerPlugins(
1074
+ server,
1075
+ async () => {
1076
+ var _a;
1077
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
1078
+ userMiddlewares.forEach((middleware) => {
1079
+ server.use(middleware);
1080
+ });
1081
+ const publicDir = path7.join(distDir, "html");
1082
+ server.use(sirv2(publicDir, { dev: false }));
1083
+ server.use(rootProdServerMiddleware());
1084
+ server.use(rootProdServer404Middleware());
1085
+ server.use(rootProdServer500Middleware());
1086
+ },
1087
+ plugins,
1088
+ { type: "prod", rootConfig }
1089
+ );
1090
+ return server;
1091
+ }
1092
+ async function rootProdRendererMiddleware(options) {
1093
+ const { distDir, rootConfig } = options;
1094
+ const render = await import(path7.join(distDir, "server/render.js"));
1095
+ const manifestPath = path7.join(distDir, "client/root-manifest.json");
1096
+ if (!await fileExists(manifestPath)) {
1097
+ throw new Error(
1098
+ `could not find ${manifestPath}. run \`root build\` before \`root start\`.`
1099
+ );
1100
+ }
1101
+ const elementGraphJsonPath = path7.join(
1102
+ distDir,
1103
+ "client/root-element-graph.json"
1104
+ );
1105
+ if (!await fileExists(elementGraphJsonPath)) {
1106
+ throw new Error(
1107
+ `could not find ${elementGraphJsonPath}. run \`root build\` before \`root start\`.`
1108
+ );
1109
+ }
1110
+ const rootManifest = await loadJson(manifestPath);
1111
+ const assetMap = BuildAssetMap.fromRootManifest(rootConfig, rootManifest);
1112
+ const elementGraphJson = await loadJson(elementGraphJsonPath);
1113
+ const elementGraph = ElementGraph.fromJson(elementGraphJson);
1114
+ const renderer = new render.Renderer(rootConfig, { assetMap, elementGraph });
1115
+ return async (req, _, next) => {
1116
+ req.renderer = renderer;
1117
+ next();
1118
+ };
1119
+ }
1120
+ function rootProdServerMiddleware() {
1121
+ return async (req, res, next) => {
1122
+ const renderer = req.renderer;
1123
+ try {
1124
+ await renderer.handle(req, res, next);
1125
+ } catch (e) {
1126
+ try {
1127
+ console.error(`error rendering ${req.originalUrl}`);
1128
+ console.error(e.stack || e);
1129
+ const { html } = await renderer.renderError(e);
1130
+ res.status(500).set({ "Content-Type": "text/html" }).end(html);
1131
+ } catch (e2) {
1132
+ console.error("failed to render custom error");
1133
+ console.error(e2);
1134
+ next(e);
1135
+ }
1136
+ }
1137
+ };
1138
+ }
1139
+ function rootProdServer404Middleware() {
1140
+ return async (req, res) => {
1141
+ console.error(`\u2753 404 ${req.originalUrl}`);
1142
+ if (req.renderer) {
1143
+ const url = req.path;
1144
+ const ext = path7.extname(url);
1145
+ if (!ext) {
1146
+ const renderer = req.renderer;
1147
+ const data = await renderer.render404();
1148
+ const html = data.html || "";
1149
+ res.status(404).set({ "Content-Type": "text/html" }).end(html);
1150
+ return;
1151
+ }
1152
+ }
1153
+ res.status(404).set({ "Content-Type": "text/plain" }).end("404");
1154
+ };
1155
+ }
1156
+ function rootProdServer500Middleware() {
1157
+ return async (err, req, res, next) => {
1158
+ console.error(`\u2757 500 ${req.originalUrl}`);
1159
+ console.error(String(err.stack || err));
1160
+ if (req.renderer) {
1161
+ const url = req.path;
1162
+ const ext = path7.extname(url);
1163
+ if (!ext) {
1164
+ const renderer = req.renderer;
1165
+ const data = await renderer.renderError(err);
1166
+ const html = data.html || "";
1167
+ res.status(500).set({ "Content-Type": "text/html" }).end(html);
1168
+ return;
1169
+ }
1170
+ }
1171
+ next(err);
1172
+ };
1173
+ }
1174
+
1175
+ export {
1176
+ build,
1177
+ dev,
1178
+ createDevServer,
1179
+ preview,
1180
+ createPreviewServer,
1181
+ start,
1182
+ createProdServer
1183
+ };
1184
+ //# sourceMappingURL=chunk-4NAXAI6M.js.map