@monkeyplus/flow 5.0.0-rc.90 → 5.0.0-rc.91

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.
@@ -6,47 +6,66 @@ import { genObjectFromRawEntries, genDynamicImport } from 'knitwork';
6
6
  import fse from 'fs-extra';
7
7
  import { debounce } from 'perfect-debounce';
8
8
  import { isIgnoredFlow, logger } from '@monkeyplus/flow-kit';
9
- import { h as hashId, c as createIsExternal, u as uniq, i as isCSS } from './external.mjs';
10
- import { withTrailingSlash, withoutLeadingSlash } from 'ufo';
11
- import escapeRE from 'escape-string-regexp';
12
- import { normalizeViteManifest } from 'vue-bundle-renderer';
13
- import 'ohash';
14
- import 'externality';
9
+ import { h as hashId, u as uniq, i as isCSS } from './index.mjs';
10
+ import { ExternalsDefaults, isExternal } from 'externality';
11
+ import { joinURL } from 'ufo';
12
+ import 'hookable';
13
+ import 'url';
14
+ import 'unimport';
15
+ import 'unplugin';
16
+ import 'fs';
17
+ import 'escape-string-regexp';
18
+ import 'scule';
19
+ import 'consola';
20
+ import 'vite';
21
+ import 'nitropack';
22
+ import 'defu';
23
+ import 'h3';
24
+ import 'chokidar';
25
+ import 'untyped';
26
+ import 'mlly';
27
+ import '@rollup/plugin-replace';
28
+ import 'node:crypto';
15
29
 
16
- async function writeManifest(ctx, css = []) {
17
- const clientDist = resolve(ctx.nuxt.options.buildDir, "dist/client");
18
- const serverDist = resolve(ctx.nuxt.options.buildDir, "dist/server");
19
- const devClientManifest = {
20
- "@vite/client": {
21
- isEntry: true,
22
- file: "@vite/client",
23
- css,
24
- module: true,
25
- resourceType: "script"
26
- },
27
- [ctx.entry]: {
28
- isEntry: true,
29
- file: ctx.entry,
30
- module: true,
31
- resourceType: "script"
30
+ function createIsExternal(viteServer, rootDir) {
31
+ const externalOpts = {
32
+ inline: [
33
+ /virtual:/,
34
+ /\.ts$/,
35
+ ...ExternalsDefaults.inline,
36
+ ...viteServer.config.ssr.noExternal
37
+ ],
38
+ external: [
39
+ ...viteServer.config.ssr.external,
40
+ /node_modules/
41
+ ],
42
+ resolve: {
43
+ type: "module",
44
+ extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
32
45
  }
33
46
  };
34
- const clientManifest = ctx.nuxt.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
35
- const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(ctx.nuxt.options.app.buildAssetsDir));
36
- const BASE_RE = new RegExp(`^${escapeRE(buildAssetsDir)}`);
37
- for (const key in clientManifest) {
38
- if (clientManifest[key].file)
39
- clientManifest[key].file = clientManifest[key].file.replace(BASE_RE, "");
40
- for (const item of ["css", "assets"]) {
41
- if (clientManifest[key][item])
42
- clientManifest[key][item] = clientManifest[key][item].map((i) => i.replace(BASE_RE, ""));
43
- }
44
- }
47
+ return (id) => isExternal(id, rootDir, externalOpts);
48
+ }
49
+
50
+ async function writeManifest(ctx, extraEntries = []) {
51
+ const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
52
+ const serverDist = resolve(ctx.flow.options.buildDir, "dist/server");
53
+ const entries = [
54
+ "@vite/client",
55
+ "entry.mjs",
56
+ ...extraEntries
57
+ ];
58
+ const devClientManifest = {
59
+ publicPath: joinURL(ctx.flow.options.app.baseURL, ctx.flow.options.app.buildAssetsDir),
60
+ all: entries,
61
+ initial: entries,
62
+ async: [],
63
+ modules: {}
64
+ };
65
+ const clientManifest = ctx.flow.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
45
66
  await fse.mkdirp(serverDist);
46
- const manifest = normalizeViteManifest(clientManifest);
47
- await ctx.nuxt.callHook("build:manifest", manifest);
48
- await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
49
- await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), `export default ${JSON.stringify(manifest, null, 2)}`, "utf8");
67
+ await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(clientManifest, null, 2), "utf8");
68
+ await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), `export default ${JSON.stringify(clientManifest, null, 2)}`, "utf8");
50
69
  }
51
70
 
52
71
  async function transformRequest(opts, id) {
@@ -223,17 +242,19 @@ async function initViteDevBundler(ctx, onBuild) {
223
242
  const _doBuild = async () => {
224
243
  const start = Date.now();
225
244
  const { code, ids } = await bundleRequest(options, ctx.entry);
226
- await fse.ensureFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"));
245
+ await fse.ensureFile(resolve(ctx.flow.options.buildDir, "dist/server/server.mjs"));
227
246
  await fse.writeFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
228
247
  await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
229
248
  const time = Date.now() - start;
230
249
  logger.success(`Vite server built in ${time}ms`);
231
250
  await onBuild();
232
- ctx.nuxt.callHook("bundler:change", {});
251
+ ctx.flow.callHook("bundler:change", {});
233
252
  };
234
253
  const doBuild = debounce(_doBuild);
235
254
  await _doBuild();
236
255
  viteServer.watcher.on("all", (_event, file) => {
256
+ if (file.includes("/pages/"))
257
+ return;
237
258
  file = normalize(file);
238
259
  if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnoredFlow(file))
239
260
  return;
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'url';
5
5
  import { defineUnimportPreset, createUnimport, toImports, scanDirExports } from 'unimport';
6
6
  import { pathToFileURL } from 'node:url';
7
7
  import { createUnplugin } from 'unplugin';
8
- import { parseURL, parseQuery, joinURL } from 'ufo';
8
+ import { parseURL, parseQuery, joinURL, withoutTrailingSlash } from 'ufo';
9
9
  import fs from 'fs';
10
10
  import escapeRE from 'escape-string-regexp';
11
11
  import { camelCase, pascalCase } from 'scule';
@@ -15,18 +15,18 @@ import logger$1 from 'consola';
15
15
  import * as vite from 'vite';
16
16
  import { createServer, build as build$1 } from 'vite';
17
17
  import { debounce } from 'perfect-debounce';
18
- import { existsSync, promises } from 'node:fs';
18
+ import { existsSync, promises, readdirSync, statSync } from 'node:fs';
19
19
  import { createNitro, scanHandlers, writeTypes, build as build$2, prepare, copyPublicAssets, prerender, createDevServer } from 'nitropack';
20
20
  import defu from 'defu';
21
21
  import { dynamicEventHandler, toEventHandler } from 'h3';
22
22
  import { createRequire } from 'node:module';
23
23
  import chokidar from 'chokidar';
24
24
  import { generateTypes, resolveSchema } from 'untyped';
25
- import replace from '@rollup/plugin-replace';
26
25
  import { sanitizeFilePath } from 'mlly';
27
- import { resolveTSConfig } from 'pkg-types';
26
+ import replace from '@rollup/plugin-replace';
27
+ import { createHash } from 'node:crypto';
28
28
 
29
- const version = "5.0.0-rc.90";
29
+ const version = "5.0.0-rc.91";
30
30
 
31
31
  let _distDir = dirname(fileURLToPath(import.meta.url));
32
32
  if (_distDir.endsWith("chunks"))
@@ -379,7 +379,7 @@ const builClient = async (flow) => {
379
379
  root: flow.options.rootDir,
380
380
  mode: "production",
381
381
  build: {
382
- outDir: "node_modules/.vite_flow",
382
+ outDir: ".vite",
383
383
  manifest: true
384
384
  }
385
385
  });
@@ -418,7 +418,7 @@ const viteModule = defineFlowModule({
418
418
  }
419
419
  });
420
420
  } else {
421
- const file = resolve(flow.options.rootDir, "node_modules/.vite_flow/manifest.json");
421
+ const file = resolve(flow.options.rootDir, ".vite/manifest.json");
422
422
  addTemplate({
423
423
  filename: "viteManifest.mjs",
424
424
  async getContents() {
@@ -438,7 +438,7 @@ const viteModule = defineFlowModule({
438
438
  logger$1.success(`Client build in ${Date.now() - start}ms`);
439
439
  });
440
440
  flow.hook("generate:before", async () => {
441
- const files = resolve(flow.options.rootDir, "node_modules/.vite_flow/assets");
441
+ const files = resolve(flow.options.rootDir, ".vite/assets");
442
442
  await fse.copy(files, resolve(flow.options.generate.dir, "assets"));
443
443
  });
444
444
  }
@@ -487,9 +487,6 @@ async function initNitro(flow) {
487
487
  nodeModulesDirs: flow.options.modulesDir,
488
488
  handlers,
489
489
  devHandlers: [],
490
- output: {
491
- dir: resolve(flow.options.buildDir, "output")
492
- },
493
490
  baseURL: flow.options.app.baseURL,
494
491
  runtimeConfig: {
495
492
  ...flow.options.runtimeConfig,
@@ -853,49 +850,6 @@ function uniqueBy(arr, key) {
853
850
  return res;
854
851
  }
855
852
 
856
- const PREFIX = "virtual:nuxt:";
857
- function virtual(vfs) {
858
- const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
859
- const resolveWithExt = (id) => {
860
- for (const ext of extensions) {
861
- const rId = id + ext;
862
- if (rId in vfs)
863
- return rId;
864
- }
865
- return null;
866
- };
867
- return {
868
- name: "virtual",
869
- resolveId(id, importer) {
870
- if (process.platform === "win32" && isAbsolute(id)) {
871
- id = resolve(id);
872
- }
873
- const resolvedId = resolveWithExt(id);
874
- if (resolvedId)
875
- return PREFIX + resolvedId;
876
- if (importer && !isAbsolute(id)) {
877
- const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
878
- const importedDir = dirname(importerNoPrefix);
879
- const resolved = resolveWithExt(join(importedDir, id));
880
- if (resolved)
881
- return PREFIX + resolved;
882
- }
883
- return null;
884
- },
885
- load(id) {
886
- if (!id.startsWith(PREFIX))
887
- return null;
888
- const idNoPrefix = id.slice(PREFIX.length);
889
- if (idNoPrefix in vfs) {
890
- return {
891
- code: vfs[idNoPrefix],
892
- map: null
893
- };
894
- }
895
- }
896
- };
897
- }
898
-
899
853
  async function warmupViteServer(server, entries) {
900
854
  const warmedUrls = /* @__PURE__ */ new Set();
901
855
  const warmup = async (url) => {
@@ -914,11 +868,6 @@ async function warmupViteServer(server, entries) {
914
868
  await Promise.all(entries.map((entry) => warmup(entry)));
915
869
  }
916
870
 
917
- const wpfs = {
918
- ...fse,
919
- join
920
- };
921
-
922
871
  function cacheDirPlugin(rootDir, name) {
923
872
  const optimizeCacheDir = resolve(rootDir, "node_modules/.cache/vite", name);
924
873
  return {
@@ -929,27 +878,54 @@ function cacheDirPlugin(rootDir, name) {
929
878
  };
930
879
  }
931
880
 
932
- async function buildServer(ctx) {
881
+ const wpfs = {
882
+ ...fse,
883
+ join
884
+ };
885
+
886
+ function uniq(arr) {
887
+ return Array.from(new Set(arr));
888
+ }
889
+ const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
890
+ function isCSS(file) {
891
+ return IS_CSS_RE.test(file);
892
+ }
893
+ function hashId(id) {
894
+ return `$id_${hash(id)}`;
895
+ }
896
+ function hash(input, length = 8) {
897
+ return createHash("sha256").update(input).digest("hex").slice(0, length);
898
+ }
899
+ function readDirRecursively(dir) {
900
+ return readdirSync(dir).reduce((files, file) => {
901
+ const name = join(dir, file);
902
+ const isDirectory2 = statSync(name).isDirectory();
903
+ return isDirectory2 ? [...files, ...readDirRecursively(name)] : [...files, name];
904
+ }, []);
905
+ }
906
+ async function isDirectory(path) {
907
+ try {
908
+ return (await promises.stat(path)).isDirectory();
909
+ } catch (_err) {
910
+ return false;
911
+ }
912
+ }
913
+
914
+ const buildServer = async (ctx) => {
933
915
  const serverConfig = vite.mergeConfig(ctx.config, {
934
- base: ctx.nuxt.options.dev ? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", ctx.nuxt.options.app.buildAssetsDir) : void 0,
916
+ configFile: false,
935
917
  define: {
936
918
  "process.server": true,
937
- "process.client": false,
938
919
  "typeof window": '"undefined"',
939
920
  "typeof document": '"undefined"',
940
921
  "typeof navigator": '"undefined"',
941
922
  "typeof location": '"undefined"',
942
923
  "typeof XMLHttpRequest": '"undefined"'
943
924
  },
944
- resolve: {
945
- alias: {
946
- "#build/plugins": resolve(ctx.nuxt.options.buildDir, "plugins/server")
947
- }
948
- },
949
925
  ssr: {
950
- external: ["#internal/nitro", "#internal/nitro/utils"],
926
+ external: ctx.nuxt.options.experimental.externalVue ? ["#internal/nitro", "#internal/nitro/utils", "vue", "vue-router"] : ["#internal/nitro", "#internal/nitro/utils"],
951
927
  noExternal: [
952
- ...ctx.nuxt.options.build.transpile,
928
+ ...ctx.flow.options.build.transpile,
953
929
  /\/esm\/.*\.js$/,
954
930
  /\.(es|esm|esm-browser|esm-bundler).js$/,
955
931
  "/__vue-jsx",
@@ -962,14 +938,13 @@ async function buildServer(ctx) {
962
938
  ]
963
939
  },
964
940
  build: {
965
- outDir: resolve(ctx.nuxt.options.buildDir, "dist/server"),
941
+ outDir: resolve(ctx.flow.options.buildDir, "dist/server"),
966
942
  ssr: true,
967
943
  rollupOptions: {
968
944
  external: ["#internal/nitro"],
969
945
  output: {
970
946
  entryFileNames: "server.mjs",
971
947
  preferConst: true,
972
- inlineDynamicImports: !ctx.nuxt.options.experimental.viteServerDynamicImports,
973
948
  format: "module"
974
949
  },
975
950
  onwarn(warning, rollupWarn) {
@@ -980,23 +955,38 @@ async function buildServer(ctx) {
980
955
  },
981
956
  server: {
982
957
  preTransformRequests: false,
983
- hmr: false
958
+ cors: true
984
959
  },
985
960
  plugins: [
986
- cacheDirPlugin(ctx.nuxt.options.rootDir, "server")
961
+ cacheDirPlugin(ctx.flow.options.rootDir, "server")
987
962
  ]
988
963
  });
989
- if (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev) {
990
- const checker = await import('vite-plugin-checker').then((r) => r.default);
991
- serverConfig.plugins.push(checker({
992
- vueTsc: {
993
- tsconfigPath: await resolveTSConfig(ctx.nuxt.options.rootDir)
964
+ await ctx.flow.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
965
+ ctx.flow.hook("nitro:build:before", async () => {
966
+ if (ctx.flow.options.dev)
967
+ return;
968
+ const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
969
+ const publicDir = join(ctx.flow.options.srcDir, ctx.flow.options.dir.public);
970
+ let publicFiles = [];
971
+ if (await isDirectory(publicDir)) {
972
+ publicFiles = readDirRecursively(publicDir).map((r) => r.replace(publicDir, ""));
973
+ for (const file of publicFiles) {
974
+ try {
975
+ fse.rmSync(join(clientDist, file));
976
+ } catch {
977
+ }
994
978
  }
995
- }));
996
- }
997
- await ctx.nuxt.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
998
- const onBuild = () => ctx.nuxt.callHook("build:resources", wpfs);
999
- if (!ctx.nuxt.options.dev) {
979
+ }
980
+ if (await isDirectory(clientDist)) {
981
+ const nestedAssetsPath = withoutTrailingSlash(join(clientDist, ctx.flow.options.app.buildAssetsDir));
982
+ if (await isDirectory(nestedAssetsPath)) {
983
+ await fse.copy(nestedAssetsPath, clientDist, { recursive: true });
984
+ await fse.remove(nestedAssetsPath);
985
+ }
986
+ }
987
+ });
988
+ const onBuild = () => ctx.flow.callHook("build:resources", wpfs);
989
+ if (!ctx.flow.options.dev) {
1000
990
  const start = Date.now();
1001
991
  logger.info("Building server...");
1002
992
  await vite.build(serverConfig);
@@ -1004,93 +994,125 @@ async function buildServer(ctx) {
1004
994
  logger.success(`Server built in ${Date.now() - start}ms`);
1005
995
  return;
1006
996
  }
1007
- if (!ctx.nuxt.options.ssr) {
1008
- await onBuild();
1009
- return;
1010
- }
1011
997
  const viteServer = await vite.createServer(serverConfig);
1012
998
  ctx.ssrServer = viteServer;
1013
- await ctx.nuxt.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
1014
- ctx.nuxt.hook("close", () => viteServer.close());
999
+ await ctx.flow.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
1000
+ ctx.flow.hook("close", () => viteServer.close());
1015
1001
  await viteServer.pluginContainer.buildStart({});
1016
- if (ctx.nuxt.options.experimental.viteNode) {
1002
+ if (ctx.nuxt.options.experimental.viteNode)
1017
1003
  logger.info("Vite server using experimental `vite-node`...");
1018
- await import('./vite-node.mjs').then((r) => r.initViteNodeServer(ctx));
1019
- } else {
1004
+ else
1020
1005
  await import('./dev-bundler.mjs').then((r) => r.initViteDevBundler(ctx, onBuild));
1021
- }
1006
+ };
1007
+
1008
+ const PREFIX = "virtual:";
1009
+ function virtual(vfs) {
1010
+ const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
1011
+ const resolveWithExt = (id) => {
1012
+ for (const ext of extensions) {
1013
+ const rId = id + ext;
1014
+ if (rId in vfs)
1015
+ return rId;
1016
+ }
1017
+ return null;
1018
+ };
1019
+ return {
1020
+ name: "virtual",
1021
+ resolveId(id, importer) {
1022
+ if (process.platform === "win32" && isAbsolute(id)) {
1023
+ id = resolve(id);
1024
+ }
1025
+ const resolvedId = resolveWithExt(id);
1026
+ if (resolvedId)
1027
+ return PREFIX + resolvedId;
1028
+ if (importer && !isAbsolute(id)) {
1029
+ const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
1030
+ const importedDir = dirname(importerNoPrefix);
1031
+ const resolved = resolveWithExt(join(importedDir, id));
1032
+ if (resolved)
1033
+ return PREFIX + resolved;
1034
+ }
1035
+ return null;
1036
+ },
1037
+ load(id) {
1038
+ if (!id.startsWith(PREFIX))
1039
+ return null;
1040
+ const idNoPrefix = id.slice(PREFIX.length);
1041
+ return {
1042
+ code: vfs[idNoPrefix],
1043
+ map: null
1044
+ };
1045
+ }
1046
+ };
1022
1047
  }
1023
1048
 
1024
- async function bundle$1(nuxt) {
1025
- const entry = resolve(nuxt.options.appDir, nuxt.options.experimental.asyncEntry ? "entry.async" : "entry");
1049
+ async function bundleVite(flow) {
1050
+ const entry = resolve(flow.options.appDir, flow.options.experimental.asyncEntry ? "entry.async" : "entry");
1026
1051
  const ctx = {
1027
- nuxt,
1052
+ nuxt: flow,
1053
+ flow,
1028
1054
  entry,
1029
- config: vite.mergeConfig(
1030
- {
1031
- configFile: false,
1032
- resolve: {
1033
- alias: {
1034
- ...nuxt.options.alias,
1035
- "#app": nuxt.options.appDir,
1036
- "#build/plugins": "",
1037
- "#build": nuxt.options.buildDir,
1038
- "web-streams-polyfill/ponyfill/es2018": "unenv/runtime/mock/empty",
1039
- "abort-controller": "unenv/runtime/mock/empty"
1040
- }
1041
- },
1042
- optimizeDeps: {
1043
- entries: [entry],
1044
- include: []
1045
- },
1046
- build: {
1047
- rollupOptions: {
1048
- output: { sanitizeFileName: sanitizeFilePath },
1049
- input: resolve(nuxt.options.appDir, "entry")
1050
- },
1051
- watch: {
1052
- exclude: nuxt.options.ignore
1053
- }
1054
- },
1055
- plugins: [
1056
- replace({
1057
- ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
1058
- preventAssignment: true
1059
- }),
1060
- virtual(nuxt.vfs)
1055
+ config: vite.mergeConfig({
1056
+ configFile: false,
1057
+ resolve: {
1058
+ alias: {
1059
+ ...flow.options.alias,
1060
+ "#app": flow.options.appDir,
1061
+ "#build/plugins": resolve(flow.options.buildDir, "plugins/server"),
1062
+ "#build": flow.options.buildDir
1063
+ }
1064
+ },
1065
+ optimizeDeps: {
1066
+ entries: [
1067
+ entry
1061
1068
  ],
1062
- vue: {
1063
- reactivityTransform: nuxt.options.experimental.reactivityTransform
1069
+ include: ["vue"]
1070
+ },
1071
+ build: {
1072
+ rollupOptions: {
1073
+ output: { sanitizeFileName: sanitizeFilePath },
1074
+ input: resolve(flow.options.appDir, "entry")
1064
1075
  },
1065
- server: {
1066
- watch: { ignored: isIgnoredFlow },
1067
- fs: {
1068
- allow: [
1069
- nuxt.options.appDir
1070
- ]
1071
- },
1072
- hmr: false
1076
+ watch: {
1077
+ exclude: flow.options.ignore
1073
1078
  }
1074
1079
  },
1075
- nuxt.options.vite
1076
- )
1080
+ plugins: [
1081
+ replace({
1082
+ ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
1083
+ preventAssignment: true
1084
+ }),
1085
+ virtual(flow.vfs)
1086
+ ],
1087
+ server: {
1088
+ watch: {
1089
+ ignored: isIgnoredFlow
1090
+ },
1091
+ hmr: false,
1092
+ fs: {
1093
+ allow: [
1094
+ flow.options.appDir
1095
+ ]
1096
+ }
1097
+ }
1098
+ }, flow.options.vite)
1077
1099
  };
1078
- if (!nuxt.options.dev) {
1100
+ if (!flow.options.dev) {
1079
1101
  ctx.config.server.watch = void 0;
1080
1102
  ctx.config.build.watch = void 0;
1081
1103
  }
1082
- await nuxt.callHook("vite:extend", ctx);
1083
- nuxt.hook("vite:serverCreated", (server, env) => {
1104
+ await flow.callHook("vite:extend", ctx);
1105
+ flow.hook("vite:serverCreated", (server) => {
1084
1106
  ctx.nuxt.hook("app:templatesGenerated", () => {
1085
1107
  for (const [id, mod] of server.moduleGraph.idToModuleMap) {
1086
1108
  if (id.includes("pages."))
1087
1109
  server.moduleGraph.invalidateModule(mod);
1088
- if (id.startsWith("\virtual:"))
1110
+ if (id.startsWith("\0virtual:"))
1089
1111
  server.moduleGraph.invalidateModule(mod);
1090
1112
  }
1091
1113
  });
1092
1114
  const start = Date.now();
1093
- warmupViteServer(server, [join("/@fs/", ctx.entry)]).then(() => logger.info(`Vite ${env.isClient ? "client" : "server"} warmed up in ${Date.now() - start}ms`)).catch(logger.error);
1115
+ warmupViteServer(server, ["/entry.mjs"]).then(() => logger.info(`Vite server warmed up in ${Date.now() - start}ms`)).catch(logger.error);
1094
1116
  });
1095
1117
  await buildServer(ctx);
1096
1118
  }
@@ -1132,11 +1154,11 @@ function watch(flow) {
1132
1154
  }
1133
1155
  async function bundle(nuxt) {
1134
1156
  try {
1135
- return bundle$1(nuxt);
1157
+ return bundleVite(nuxt);
1136
1158
  } catch (error) {
1137
1159
  await nuxt.callHook("build:error", error);
1138
1160
  throw error;
1139
1161
  }
1140
1162
  }
1141
1163
 
1142
- export { defineFlowConfig as a, build as b, createFlow as c, distDir as d, loadFlow as l };
1164
+ export { build as b, createFlow as c, defineFlowConfig as d, hashId as h, isCSS as i, loadFlow as l, uniq as u };
@@ -1,5 +1,6 @@
1
1
  import { defineFlowPlugin } from "#app";
2
2
  export default defineFlowPlugin((flow) => {
3
3
  flow._useHead = (_meta) => {
4
+ console.log(_meta);
4
5
  };
5
6
  });
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { b as build, c as createFlow, a as defineFlowConfig, l as loadFlow } from './chunks/index.mjs';
1
+ export { b as build, c as createFlow, d as defineFlowConfig, l as loadFlow } from './chunks/index.mjs';
2
2
  import 'hookable';
3
3
  import 'pathe';
4
4
  import '@monkeyplus/flow-kit';
@@ -22,6 +22,6 @@ import 'h3';
22
22
  import 'node:module';
23
23
  import 'chokidar';
24
24
  import 'untyped';
25
- import '@rollup/plugin-replace';
26
25
  import 'mlly';
27
- import 'pkg-types';
26
+ import '@rollup/plugin-replace';
27
+ import 'node:crypto';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monkeyplus/flow",
3
- "version": "5.0.0-rc.90",
3
+ "version": "5.0.0-rc.91",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -25,11 +25,12 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@monkeyplus/flow-cli": "5.0.0-rc.90",
29
- "@monkeyplus/flow-kit": "5.0.0-rc.90",
30
- "@monkeyplus/flow-schema": "5.0.0-rc.90",
28
+ "@monkeyplus/flow-cli": "5.0.0-rc.91",
29
+ "@monkeyplus/flow-kit": "5.0.0-rc.91",
30
+ "@monkeyplus/flow-schema": "5.0.0-rc.91",
31
31
  "@rollup/plugin-replace": "^4.0.0",
32
32
  "@vueuse/head": "^0.7.6",
33
+ "pkg-types": "^0.3.4",
33
34
  "c12": "^0.2.8",
34
35
  "chokidar": "^3.5.3",
35
36
  "consola": "^2.15.3",
@@ -45,7 +46,6 @@
45
46
  "h3": "^0.7.16",
46
47
  "hookable": "^5.1.1",
47
48
  "jiti": "^1.14.0",
48
- "ohash": "^0.1.5",
49
49
  "knitwork": "^0.1.2",
50
50
  "listhen": "^0.2.13",
51
51
  "magic-string": "^0.26.2",
@@ -65,12 +65,9 @@
65
65
  "unctx": "^2.0.1",
66
66
  "unimport": "^0.4.5",
67
67
  "unplugin": "^0.9.4",
68
- "untyped": "^0.4.5",
69
- "pkg-types": "^0.3.3",
70
- "vite": "2.9.15",
71
- "vite-node": "^0.22.1",
72
- "vite-plugin-checker": "^0.4.9",
73
- "vue-bundle-renderer": "^0.4.2",
68
+ "std-env": "^3.1.1",
69
+ "untyped": "^0.4.4",
70
+ "vite": "^3.0.9",
74
71
  "vue": "^3.2.37"
75
72
  },
76
73
  "devDependencies": {
@@ -1,3 +0,0 @@
1
- import type { RuntimeConfig } from '@monkeyplus/flow-schema';
2
- declare const _default: (ctx?: RuntimeConfig) => Promise<any>;
3
- export default _default;
@@ -1 +0,0 @@
1
- export default (ctx) => import("#app/entry").then((m) => m.default(ctx));
@@ -1,37 +0,0 @@
1
- import 'node:fs';
2
- import { hash } from 'ohash';
3
- import 'pathe';
4
- import { ExternalsDefaults, isExternal } from 'externality';
5
-
6
- function uniq(arr) {
7
- return Array.from(new Set(arr));
8
- }
9
- const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
10
- function isCSS(file) {
11
- return IS_CSS_RE.test(file);
12
- }
13
- function hashId(id) {
14
- return `$id_${hash(id)}`;
15
- }
16
-
17
- function createIsExternal(viteServer, rootDir) {
18
- const externalOpts = {
19
- inline: [
20
- /virtual:/,
21
- /\.ts$/,
22
- ...ExternalsDefaults.inline || [],
23
- ...viteServer.config.ssr.noExternal
24
- ],
25
- external: [
26
- ...viteServer.config.ssr.external || [],
27
- /node_modules/
28
- ],
29
- resolve: {
30
- type: "module",
31
- extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
32
- }
33
- };
34
- return (id) => isExternal(id, rootDir, externalOpts);
35
- }
36
-
37
- export { createIsExternal as c, hashId as h, isCSS as i, uniq as u };
@@ -1,155 +0,0 @@
1
- import { pathToFileURL } from 'node:url';
2
- import { createApp, defineEventHandler, defineLazyEventHandler, createError } from 'h3';
3
- import { ViteNodeServer } from 'vite-node/server';
4
- import fse from 'fs-extra';
5
- import { resolve as resolve$1 } from 'pathe';
6
- import { addServerMiddleware } from '@monkeyplus/flow-kit';
7
- import { normalizeViteManifest } from 'vue-bundle-renderer';
8
- import { resolve } from 'mlly';
9
- import { d as distDir } from './index.mjs';
10
- import { c as createIsExternal, i as isCSS } from './external.mjs';
11
- import 'hookable';
12
- import 'url';
13
- import 'unimport';
14
- import 'unplugin';
15
- import 'ufo';
16
- import 'fs';
17
- import 'escape-string-regexp';
18
- import 'scule';
19
- import 'knitwork';
20
- import 'consola';
21
- import 'vite';
22
- import 'perfect-debounce';
23
- import 'node:fs';
24
- import 'nitropack';
25
- import 'defu';
26
- import 'node:module';
27
- import 'chokidar';
28
- import 'untyped';
29
- import '@rollup/plugin-replace';
30
- import 'pkg-types';
31
- import 'ohash';
32
- import 'externality';
33
-
34
- function viteNodePlugin(ctx) {
35
- const invalidates = /* @__PURE__ */ new Set();
36
- return {
37
- name: "nuxt:vite-node-server",
38
- enforce: "post",
39
- configureServer(server) {
40
- server.middlewares.use("/__nuxt_vite_node__", createViteNodeMiddleware(ctx, invalidates));
41
- },
42
- handleHotUpdate({ file, server }) {
43
- function markInvalidate(mod) {
44
- if (invalidates.has(mod.id))
45
- return;
46
- invalidates.add(mod.id);
47
- for (const importer of mod.importers)
48
- markInvalidate(importer);
49
- }
50
- const mods = server.moduleGraph.getModulesByFile(file) || [];
51
- for (const mod of mods)
52
- markInvalidate(mod);
53
- }
54
- };
55
- }
56
- function registerViteNodeMiddleware(ctx) {
57
- addServerMiddleware({
58
- route: "/__nuxt_vite_node__/",
59
- handler: createViteNodeMiddleware(ctx)
60
- });
61
- }
62
- function getManifest(ctx) {
63
- const css = Array.from(ctx.ssrServer.moduleGraph.urlToModuleMap.keys()).filter((i) => isCSS(i));
64
- const manifest = normalizeViteManifest({
65
- "@vite/client": {
66
- file: "@vite/client",
67
- css,
68
- module: true,
69
- isEntry: true
70
- },
71
- [ctx.entry]: {
72
- file: ctx.entry,
73
- isEntry: true,
74
- module: true,
75
- resourceType: "script"
76
- }
77
- });
78
- return manifest;
79
- }
80
- function createViteNodeMiddleware(ctx, invalidates = /* @__PURE__ */ new Set()) {
81
- const app = createApp();
82
- app.use("/manifest", defineEventHandler(() => {
83
- const manifest = getManifest(ctx);
84
- return manifest;
85
- }));
86
- app.use("/invalidates", defineEventHandler(() => {
87
- if (invalidates.size) {
88
- for (const key of ctx.ssrServer.moduleGraph.fileToModulesMap.keys()) {
89
- if (key.startsWith(`${ctx.nuxt.options.appDir}/entry`))
90
- invalidates.add(key);
91
- }
92
- }
93
- const ids = Array.from(invalidates);
94
- invalidates.clear();
95
- return ids;
96
- }));
97
- app.use("/module", defineLazyEventHandler(() => {
98
- const viteServer = ctx.ssrServer;
99
- const node = new ViteNodeServer(viteServer, {
100
- deps: {
101
- inline: [
102
- /\/(nuxt|nuxt3)\//,
103
- /^#/,
104
- ...ctx.nuxt.options.build.transpile
105
- ]
106
- },
107
- transformMode: {
108
- ssr: [/.*/],
109
- web: []
110
- }
111
- });
112
- const isExternal = createIsExternal(viteServer, ctx.nuxt.options.rootDir);
113
- node.shouldExternalize = async (id) => {
114
- const result = await isExternal(id);
115
- if (result?.external)
116
- return resolve(result.id, { url: ctx.nuxt.options.rootDir });
117
- return false;
118
- };
119
- return async (event) => {
120
- const moduleId = decodeURI(event.req.url).substring(1);
121
- if (moduleId === "/")
122
- throw createError({ statusCode: 400 });
123
- const module = await node.fetchModule(moduleId);
124
- return module;
125
- };
126
- }));
127
- return app.nodeHandler;
128
- }
129
- async function initViteNodeServer(ctx) {
130
- let entryPath = resolve$1(ctx.nuxt.options.appDir, "entry.async.mjs");
131
- if (!fse.existsSync(entryPath))
132
- entryPath = resolve$1(ctx.nuxt.options.appDir, "entry.async.ts");
133
- const host = ctx.nuxt.options.server.host || "localhost";
134
- const port = ctx.nuxt.options.server.port || "3000";
135
- const protocol = ctx.nuxt.options.server.https ? "https" : "http";
136
- const viteNodeServerOptions = {
137
- baseURL: `${protocol}://${host}:${port}/__nuxt_vite_node__`,
138
- root: ctx.nuxt.options.srcDir,
139
- entryPath,
140
- base: ctx.ssrServer.config.base || "/_nuxt/"
141
- };
142
- process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions);
143
- const serverResolvedPath = resolve$1(distDir, "core/runtime/vite-node.mjs");
144
- const manifestResolvedPath = resolve$1(distDir, "core/runtime/client.manifest.mjs");
145
- await fse.writeFile(
146
- resolve$1(ctx.nuxt.options.buildDir, "dist/server/server.mjs"),
147
- `export { default } from ${JSON.stringify(pathToFileURL(serverResolvedPath).href)}`
148
- );
149
- await fse.writeFile(
150
- resolve$1(ctx.nuxt.options.buildDir, "dist/server/client.manifest.mjs"),
151
- `export { default } from ${JSON.stringify(pathToFileURL(manifestResolvedPath).href)}`
152
- );
153
- }
154
-
155
- export { initViteNodeServer, registerViteNodeMiddleware, viteNodePlugin };
@@ -1,2 +0,0 @@
1
- declare function _default(): Promise<any>;
2
- export default _default;
@@ -1,6 +0,0 @@
1
- import { $fetch } from 'ohmyfetch';
2
- import { getViteNodeOptions } from './vite-node-shared.mjs';
3
-
4
- const viteNodeOptions = getViteNodeOptions();
5
-
6
- export default () => $fetch('/manifest', { baseURL: viteNodeOptions.baseURL });
@@ -1 +0,0 @@
1
- export function getViteNodeOptions(): any;
@@ -1,8 +0,0 @@
1
- export interface ViteNodeRuntimeOptions {
2
- baseURL: string
3
- rootDir: string
4
- entryPath: string
5
- base: string
6
- }
7
-
8
- export function getViteNodeOptions (): ViteNodeRuntimeOptions;
@@ -1,3 +0,0 @@
1
- export function getViteNodeOptions() {
2
- return JSON.parse(process.env.NUXT_VITE_NODE_OPTIONS || '{}');
3
- }
@@ -1,2 +0,0 @@
1
- declare function _default(ssrContext: any): Promise<any>;
2
- export default _default;
@@ -1,42 +0,0 @@
1
- import { performance } from 'node:perf_hooks';
2
- import { ViteNodeRunner } from 'vite-node/client';
3
- import { $fetch } from 'ohmyfetch';
4
- import consola from 'consola';
5
- import { getViteNodeOptions } from './vite-node-shared.mjs';
6
-
7
- const viteNodeOptions = getViteNodeOptions();
8
- console.log(viteNodeOptions);
9
- const runner = new ViteNodeRunner({
10
- root: viteNodeOptions.root, // Equals to Nuxt `srcDir`
11
- base: viteNodeOptions.base,
12
- async fetchModule(id) {
13
- return await $fetch(`/module/${encodeURI(id)}`, {
14
- baseURL: viteNodeOptions.baseURL,
15
- });
16
- },
17
- });
18
-
19
- let render;
20
-
21
- export default async(ssrContext) => {
22
- // Workaround for stub mode
23
- // https://github.com/nuxt/framework/pull/3983
24
- process.server = true;
25
-
26
- // Invalidate cache for files changed since last rendering
27
- const invalidates = await $fetch('/invalidates', {
28
- baseURL: viteNodeOptions.baseURL,
29
- });
30
- const updates = runner.moduleCache.invalidateDepTree(invalidates);
31
-
32
- // Execute SSR bundle on demand
33
- const start = performance.now();
34
- render = render || (await runner.executeFile(viteNodeOptions.entryPath)).default;
35
- if (updates.size) {
36
- const time = Math.round((performance.now() - start) * 1000) / 1000;
37
- consola.success(`Vite server hmr ${updates.size} files`, time ? `in ${time}ms` : '');
38
- }
39
-
40
- const result = await render(ssrContext);
41
- return result;
42
- };