@blinkk/root 1.0.0-alpha.11 → 1.0.0-alpha.13

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,31 @@
1
+ // src/core/plugin.ts
2
+ async function configureServerPlugins(server, callback, plugins, options) {
3
+ const postHooks = [];
4
+ for (const plugin of plugins) {
5
+ if (plugin.configureServer) {
6
+ const postHook = await plugin.configureServer(server, options);
7
+ if (postHook) {
8
+ postHooks.push(postHook);
9
+ }
10
+ }
11
+ }
12
+ callback();
13
+ for (const postHook of postHooks) {
14
+ await postHook();
15
+ }
16
+ }
17
+ function getVitePlugins(plugins) {
18
+ const vitePlugins = [];
19
+ for (const plugin of plugins) {
20
+ if (plugin.vitePlugins) {
21
+ vitePlugins.push(...plugin.vitePlugins);
22
+ }
23
+ }
24
+ return vitePlugins;
25
+ }
26
+
27
+ export {
28
+ configureServerPlugins,
29
+ getVitePlugins
30
+ };
31
+ //# sourceMappingURL=chunk-ZB7R6ZOY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/plugin.ts"],"sourcesContent":["import {PluginOption as VitePlugin} from 'vite';\nimport {Server} from './types';\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ConfigureServerHook = (\n server: Server,\n options: ConfigureServerOptions\n) => MaybePromise<void> | MaybePromise<() => void>;\n\nexport interface ConfigureServerOptions {\n type: 'dev' | 'preview' | 'prod';\n}\n\nexport interface Plugin {\n name?: string;\n\n /** Configures the root.js express server . */\n configureServer?: ConfigureServerHook;\n\n /** Adds vite plugins. */\n vitePlugins?: VitePlugin[];\n}\n\n/**\n * Runs the pre-hook configureServer method of every plugin, calls a callback\n * function, and then runs the configureServer's post-hook if provided. Plugins\n * provide a post-hook by returning a callback function from configureServer.\n */\nexport async function configureServerPlugins(\n server: Server,\n callback: () => Promise<void>,\n plugins: Plugin[],\n options: ConfigureServerOptions\n) {\n const postHooks: Array<() => void> = [];\n\n // Call the `configureServer()` method for each plugin.\n for (const plugin of plugins) {\n if (plugin.configureServer) {\n const postHook = await plugin.configureServer(server, options);\n if (postHook) {\n postHooks.push(postHook);\n }\n }\n }\n\n // Register any built-in middleware.\n callback();\n\n // Run any post hooks returned by `plugin.configureServer()`.\n for (const postHook of postHooks) {\n await postHook();\n }\n}\n\nexport function getVitePlugins(plugins: Plugin[]): VitePlugin[] {\n const vitePlugins: VitePlugin[] = [];\n for (const plugin of plugins) {\n if (plugin.vitePlugins) {\n vitePlugins.push(...plugin.vitePlugins);\n }\n }\n return vitePlugins;\n}\n"],"mappings":";AA6BA,eAAsB,uBACpB,QACA,UACA,SACA,SACA;AACA,QAAM,YAA+B,CAAC;AAGtC,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,iBAAiB;AAC1B,YAAM,WAAW,MAAM,OAAO,gBAAgB,QAAQ,OAAO;AAC7D,UAAI,UAAU;AACZ,kBAAU,KAAK,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAGA,WAAS;AAGT,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS;AAAA,EACjB;AACF;AAEO,SAAS,eAAe,SAAiC;AAC9D,QAAM,cAA4B,CAAC;AACnC,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,aAAa;AACtB,kBAAY,KAAK,GAAG,OAAO,WAAW;AAAA,IACxC;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/cli.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ configureServerPlugins,
3
+ getVitePlugins
4
+ } from "./chunk-ZB7R6ZOY.js";
5
+
1
6
  // src/cli/commands/dev.ts
2
7
  import path4 from "node:path";
3
8
  import { fileURLToPath } from "node:url";
@@ -302,34 +307,68 @@ async function htmlMinify(html) {
302
307
  // src/cli/commands/dev.ts
303
308
  import glob2 from "tiny-glob";
304
309
  import { dim } from "kleur/colors";
310
+
311
+ // src/core/middleware.ts
312
+ function rootProjectMiddleware(options) {
313
+ return (req, _, next) => {
314
+ req.rootConfig = Object.assign({}, options.rootConfig, {
315
+ rootDir: options.rootDir
316
+ });
317
+ next();
318
+ };
319
+ }
320
+
321
+ // src/cli/commands/dev.ts
305
322
  var __dirname = path4.dirname(fileURLToPath(import.meta.url));
306
- async function createServer(options) {
307
- const rootDir = (options == null ? void 0 : options.rootDir) || process.cwd();
308
- const app = express();
309
- app.disable("x-powered-by");
310
- app.use(express.static("public"));
311
- const middlewares = await getMiddlewares({ rootDir });
312
- middlewares.forEach((middleware) => app.use(middleware));
323
+ async function dev(rootProjectDir) {
324
+ process.env.NODE_ENV = "development";
325
+ const rootDir = path4.resolve(rootProjectDir || process.cwd());
326
+ const server = await createServer({ rootDir });
313
327
  const port = parseInt(process.env.PORT || "4007");
314
328
  console.log();
315
329
  console.log(`${dim("\u2503")} project: ${rootDir}`);
316
330
  console.log(`${dim("\u2503")} server: http://localhost:${port}`);
331
+ console.log(`${dim("\u2503")} mode: development`);
317
332
  console.log();
318
- app.listen(port);
333
+ server.listen(port);
319
334
  }
320
- async function getMiddlewares(options) {
321
- var _a, _b, _c;
335
+ async function createServer(options) {
322
336
  const rootDir = path4.resolve((options == null ? void 0 : options.rootDir) || process.cwd());
323
337
  const rootConfig = await loadRootConfig(rootDir);
338
+ const server = express();
339
+ server.disable("x-powered-by");
340
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
341
+ server.use(await viteServerMiddleware({ rootDir, rootConfig }));
342
+ server.use(rootDevRendererMiddleware());
343
+ const plugins = rootConfig.plugins || [];
344
+ await configureServerPlugins(
345
+ server,
346
+ async () => {
347
+ var _a;
348
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
349
+ for (const middleware of userMiddlewares) {
350
+ server.use(middleware);
351
+ }
352
+ server.use(rootDevServerMiddleware());
353
+ server.use(rootDevServer404Middleware());
354
+ },
355
+ plugins,
356
+ { type: "dev" }
357
+ );
358
+ return server;
359
+ }
360
+ async function viteServerMiddleware(options) {
361
+ var _a, _b, _c;
362
+ const rootDir = options.rootDir;
363
+ const rootConfig = options.rootConfig;
324
364
  const viteConfig = rootConfig.vite || {};
325
- const renderModulePath = path4.resolve(__dirname, "./render.js");
326
- const pages = [];
365
+ const routeFiles = [];
327
366
  if (await isDirectory(path4.join(rootDir, "routes"))) {
328
367
  const pageFiles = await glob2("routes/**/*", { cwd: rootDir });
329
368
  pageFiles.forEach((file) => {
330
369
  const parts = path4.parse(file);
331
370
  if (!parts.name.startsWith("_") && isJsFile(parts.base)) {
332
- pages.push(file);
371
+ routeFiles.push(file);
333
372
  }
334
373
  });
335
374
  }
@@ -374,14 +413,25 @@ async function getMiddlewares(options) {
374
413
  }
375
414
  });
376
415
  }
416
+ const vitePlugins = [
417
+ pluginRoot({ rootDir, rootConfig }),
418
+ ...viteConfig.plugins || [],
419
+ ...getVitePlugins(rootConfig.plugins || [])
420
+ ];
377
421
  const viteServer = await createViteServer({
378
422
  ...viteConfig,
379
423
  mode: "development",
380
424
  root: rootDir,
425
+ publicDir: path4.join(rootDir, "public"),
381
426
  server: { middlewareMode: true },
382
427
  appType: "custom",
383
428
  optimizeDeps: {
384
- include: [...pages, ...elements, ...bundleScripts]
429
+ include: [
430
+ ...routeFiles,
431
+ ...elements,
432
+ ...bundleScripts,
433
+ ...((_c = viteConfig.optimizeDeps) == null ? void 0 : _c.include) || []
434
+ ]
385
435
  },
386
436
  ssr: {
387
437
  noExternal: ["@blinkk/root"]
@@ -390,18 +440,32 @@ async function getMiddlewares(options) {
390
440
  jsx: "automatic",
391
441
  jsxImportSource: "preact"
392
442
  },
393
- plugins: [...viteConfig.plugins || [], pluginRoot({ rootDir, rootConfig })]
443
+ plugins: vitePlugins
394
444
  });
395
- const rootMiddleware = async (req, res, next) => {
445
+ return async (req, res, next) => {
446
+ req.viteServer = viteServer;
447
+ viteServer.middlewares(req, res, next);
448
+ };
449
+ }
450
+ function rootDevRendererMiddleware() {
451
+ const renderModulePath = path4.resolve(__dirname, "./render.js");
452
+ return async (req, _, next) => {
453
+ const rootConfig = req.rootConfig;
454
+ const viteServer = req.viteServer;
455
+ const render = await viteServer.ssrLoadModule(renderModulePath);
456
+ const assetMap = new DevServerAssetMap(viteServer.moduleGraph);
457
+ req.renderer = new render.Renderer(rootConfig, { assetMap });
458
+ next();
459
+ };
460
+ }
461
+ function rootDevServerMiddleware() {
462
+ return async (req, res, next) => {
396
463
  const url = req.originalUrl;
397
- let renderer = null;
464
+ const renderer = req.renderer;
465
+ const viteServer = req.viteServer;
466
+ const rootConfig = req.rootConfig;
398
467
  try {
399
- const render = await viteServer.ssrLoadModule(renderModulePath);
400
- renderer = new render.Renderer(rootConfig);
401
- const assetMap = new DevServerAssetMap(viteServer.moduleGraph);
402
- const data = await renderer.render(url, {
403
- assetMap
404
- });
468
+ const data = await renderer.render(url);
405
469
  if (data.notFound || !data.html) {
406
470
  next();
407
471
  return;
@@ -428,31 +492,20 @@ async function getMiddlewares(options) {
428
492
  }
429
493
  }
430
494
  };
431
- const notFoundMiddleware = async (req, res) => {
495
+ }
496
+ function rootDevServer404Middleware() {
497
+ return async (req, res) => {
432
498
  const url = req.originalUrl;
433
499
  const ext = path4.extname(url);
500
+ const renderer = req.renderer;
434
501
  if (!ext) {
435
- const render = await viteServer.ssrLoadModule(renderModulePath);
436
- const renderer = new render.Renderer(rootConfig);
437
- const data = await renderer.renderDevNotFound();
502
+ const data = await renderer.renderDevServer404();
438
503
  const html = data.html || "";
439
504
  res.status(404).set({ "Content-Type": "text/html" }).end(html);
440
505
  return;
441
506
  }
442
507
  res.status(404).set({ "Content-Type": "text/plain" }).end("404");
443
508
  };
444
- const userMiddlewares = ((_c = rootConfig.server) == null ? void 0 : _c.middlewares) || [];
445
- return [
446
- ...userMiddlewares,
447
- viteServer.middlewares,
448
- rootMiddleware,
449
- notFoundMiddleware
450
- ];
451
- }
452
- async function dev(rootProjectDir) {
453
- process.env.NODE_ENV = "development";
454
- const rootDir = path4.resolve(rootProjectDir || process.cwd());
455
- await createServer({ rootDir });
456
509
  }
457
510
 
458
511
  // src/cli/commands/build.ts
@@ -657,6 +710,11 @@ async function build(rootProjectDir, options) {
657
710
  });
658
711
  }
659
712
  const viteConfig = rootConfig.vite || {};
713
+ const vitePlugins = [
714
+ pluginRoot({ rootDir, rootConfig }),
715
+ ...viteConfig.plugins || [],
716
+ ...getVitePlugins(rootConfig.plugins || [])
717
+ ];
660
718
  const baseConfig = {
661
719
  ...viteConfig,
662
720
  root: rootDir,
@@ -666,7 +724,7 @@ async function build(rootProjectDir, options) {
666
724
  jsxImportSource: "preact",
667
725
  treeShaking: true
668
726
  },
669
- plugins: [...viteConfig.plugins || [], pluginRoot({ rootDir, rootConfig })]
727
+ plugins: vitePlugins
670
728
  };
671
729
  await viteBuild({
672
730
  ...baseConfig,
@@ -735,13 +793,12 @@ async function build(rootProjectDir, options) {
735
793
  copyDir(path5.join(distDir, "client/chunks"), path5.join(buildDir, "chunks"));
736
794
  if (!ssrOnly) {
737
795
  const render = await import(path5.join(distDir, "server/render.js"));
738
- const renderer = new render.Renderer(rootConfig);
796
+ const renderer = new render.Renderer(rootConfig, { assetMap });
739
797
  const sitemap = await renderer.getSitemap();
740
798
  await Promise.all(
741
799
  Object.keys(sitemap).map(async (urlPath) => {
742
800
  const { route, params } = sitemap[urlPath];
743
801
  const data = await renderer.renderRoute(route, {
744
- assetMap,
745
802
  routeParams: params
746
803
  });
747
804
  let outPath = path5.join(distDir, `html${urlPath}`, "index.html");
@@ -761,14 +818,50 @@ async function build(rootProjectDir, options) {
761
818
  import path6 from "node:path";
762
819
  import { default as express2 } from "express";
763
820
  import { dim as dim3 } from "kleur/colors";
821
+ import sirv from "sirv";
822
+ import compression from "compression";
764
823
  async function preview(rootProjectDir) {
765
- var _a;
766
824
  process.env.NODE_ENV = "development";
767
825
  const rootDir = path6.resolve(rootProjectDir || process.cwd());
826
+ const server = await createServer2({ rootDir });
827
+ const port = parseInt(process.env.PORT || "4007");
828
+ console.log();
829
+ console.log(`${dim3("\u2503")} project: ${rootDir}`);
830
+ console.log(`${dim3("\u2503")} server: http://localhost:${port}`);
831
+ console.log(`${dim3("\u2503")} mode: staging`);
832
+ console.log();
833
+ server.listen(port);
834
+ }
835
+ async function createServer2(options) {
836
+ const rootDir = options.rootDir;
768
837
  const rootConfig = await loadRootConfig(rootDir);
769
838
  const distDir = path6.join(rootDir, "dist");
839
+ const server = express2();
840
+ server.disable("x-powered-by");
841
+ server.use(compression());
842
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
843
+ server.use(await rootPreviewRendererMiddleware({ rootConfig, distDir }));
844
+ const plugins = rootConfig.plugins || [];
845
+ configureServerPlugins(
846
+ server,
847
+ async () => {
848
+ var _a;
849
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
850
+ userMiddlewares.forEach((middleware) => {
851
+ server.use(middleware);
852
+ });
853
+ const publicDir = path6.join(distDir, "html");
854
+ server.use(sirv(publicDir, { dev: false }));
855
+ server.use(rootPreviewServerMiddleware());
856
+ },
857
+ plugins,
858
+ { type: "preview" }
859
+ );
860
+ return server;
861
+ }
862
+ async function rootPreviewRendererMiddleware(options) {
863
+ const { distDir, rootConfig } = options;
770
864
  const render = await import(path6.join(distDir, "server/render.js"));
771
- const renderer = new render.Renderer(rootConfig);
772
865
  const manifestPath = path6.join(distDir, "client/root-manifest.json");
773
866
  if (!await fileExists(manifestPath)) {
774
867
  throw new Error(
@@ -777,20 +870,19 @@ async function preview(rootProjectDir) {
777
870
  }
778
871
  const rootManifest = await loadJson(manifestPath);
779
872
  const assetMap = BuildAssetMap.fromRootManifest(rootManifest);
780
- const app = express2();
781
- app.disable("x-powered-by");
782
- const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
783
- userMiddlewares.forEach((middleware) => {
784
- app.use(middleware);
785
- });
786
- const publicDir = path6.join(distDir, "html");
787
- app.use(express2.static(publicDir));
788
- app.use(async (req, res, next) => {
873
+ const renderer = new render.Renderer(rootConfig, { assetMap });
874
+ return async (req, _, next) => {
875
+ req.renderer = renderer;
876
+ next();
877
+ };
878
+ }
879
+ function rootPreviewServerMiddleware() {
880
+ return async (req, res, next) => {
881
+ const rootConfig = req.rootConfig;
882
+ const renderer = req.renderer;
789
883
  try {
790
884
  const url = req.originalUrl;
791
- const data = await renderer.render(url, {
792
- assetMap
793
- });
885
+ const data = await renderer.render(url);
794
886
  if (data.notFound || !data.html) {
795
887
  next();
796
888
  return;
@@ -810,49 +902,78 @@ async function preview(rootProjectDir) {
810
902
  next(e);
811
903
  }
812
904
  }
813
- });
814
- const port = parseInt(process.env.PORT || "4007");
815
- console.log();
816
- console.log(`${dim3("\u2503")} project: ${rootDir}`);
817
- console.log(`${dim3("\u2503")} server: http://localhost:${port}`);
818
- console.log();
819
- app.listen(port);
905
+ };
820
906
  }
821
907
 
822
908
  // src/cli/commands/start.ts
823
909
  import path7 from "node:path";
824
910
  import { default as express3 } from "express";
825
911
  import { dim as dim4 } from "kleur/colors";
912
+ import sirv2 from "sirv";
913
+ import compression2 from "compression";
826
914
  async function start(rootProjectDir) {
827
- var _a;
828
915
  process.env.NODE_ENV = "production";
829
916
  const rootDir = path7.resolve(rootProjectDir || process.cwd());
917
+ const server = await createServer3({ rootDir });
918
+ const port = parseInt(process.env.PORT || "4007");
919
+ console.log();
920
+ console.log(`${dim4("\u2503")} project: ${rootDir}`);
921
+ console.log(`${dim4("\u2503")} server: http://localhost:${port}`);
922
+ console.log(`${dim4("\u2503")} mode: production`);
923
+ console.log();
924
+ server.listen(port);
925
+ }
926
+ async function createServer3(options) {
927
+ const rootDir = options.rootDir;
830
928
  const rootConfig = await loadRootConfig(rootDir);
831
929
  const distDir = path7.join(rootDir, "dist");
930
+ const server = express3();
931
+ server.disable("x-powered-by");
932
+ server.use(compression2());
933
+ server.use(rootProjectMiddleware({ rootDir, rootConfig }));
934
+ server.use(await rootProdRendererMiddleware({ rootConfig, distDir }));
935
+ const plugins = rootConfig.plugins || [];
936
+ configureServerPlugins(
937
+ server,
938
+ async () => {
939
+ var _a;
940
+ const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
941
+ userMiddlewares.forEach((middleware) => {
942
+ server.use(middleware);
943
+ });
944
+ const publicDir = path7.join(distDir, "html");
945
+ server.use(sirv2(publicDir, { dev: false }));
946
+ server.use(rootProdServerMiddleware());
947
+ },
948
+ plugins,
949
+ { type: "prod" }
950
+ );
951
+ return server;
952
+ }
953
+ async function rootProdRendererMiddleware(options) {
954
+ const { distDir, rootConfig } = options;
832
955
  const render = await import(path7.join(distDir, "server/render.js"));
833
- const renderer = new render.Renderer(rootConfig);
834
956
  const manifestPath = path7.join(distDir, "client/root-manifest.json");
835
957
  if (!await fileExists(manifestPath)) {
836
958
  throw new Error(
837
- `could not find ${manifestPath}. run \`root build\` before \`root start\`.`
959
+ `could not find ${manifestPath}. run \`root build\` before \`root preview\`.`
838
960
  );
839
961
  }
840
962
  const rootManifest = await loadJson(manifestPath);
841
963
  const assetMap = BuildAssetMap.fromRootManifest(rootManifest);
842
- const app = express3();
843
- app.disable("x-powered-by");
844
- const userMiddlewares = ((_a = rootConfig.server) == null ? void 0 : _a.middlewares) || [];
845
- userMiddlewares.forEach((middleware) => {
846
- app.use(middleware);
847
- });
848
- const publicDir = path7.join(distDir, "html");
849
- app.use(express3.static(publicDir));
850
- app.use(async (req, res, next) => {
964
+ const renderer = new render.Renderer(rootConfig, { assetMap });
965
+ return async (req, _, next) => {
966
+ req.renderer = renderer;
967
+ next();
968
+ };
969
+ }
970
+ function rootProdServerMiddleware() {
971
+ return async (req, res, next) => {
972
+ const rootConfig = req.rootConfig;
973
+ const renderer = req.renderer;
851
974
  try {
852
975
  const url = req.originalUrl;
853
- const data = await renderer.render(url, {
854
- assetMap
855
- });
976
+ const data = await renderer.render(url);
856
977
  if (data.notFound || !data.html) {
857
978
  next();
858
979
  return;
@@ -872,13 +993,7 @@ async function start(rootProjectDir) {
872
993
  next(e);
873
994
  }
874
995
  }
875
- });
876
- const port = parseInt(process.env.PORT || "4007");
877
- console.log();
878
- console.log(`${dim4("\u2503")} project: ${rootDir}`);
879
- console.log(`${dim4("\u2503")} server: http://localhost:${port}`);
880
- console.log();
881
- app.listen(port);
996
+ };
882
997
  }
883
998
  export {
884
999
  build,