@monkeyplus/flow 4.0.0-beta.9 → 5.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/app.d.ts +1 -0
  2. package/bin/flow.mjs +2 -0
  3. package/build.config.ts +25 -0
  4. package/dist/app/composables/index.d.ts +4 -0
  5. package/dist/app/composables/index.mjs +12 -0
  6. package/dist/app/entry.d.ts +3 -0
  7. package/dist/app/entry.mjs +23 -0
  8. package/dist/app/flow.d.ts +73 -0
  9. package/dist/app/flow.mjs +85 -0
  10. package/dist/app/index.d.ts +3 -0
  11. package/dist/app/index.mjs +3 -0
  12. package/dist/core/runtime/nitro/flow.d.ts +3 -0
  13. package/dist/core/runtime/nitro/flow.mjs +32 -0
  14. package/dist/core/runtime/nitro/paths.d.ts +4 -0
  15. package/dist/core/runtime/nitro/paths.mjs +15 -0
  16. package/dist/core/runtime/nitro/renderer.d.ts +2 -0
  17. package/dist/core/runtime/nitro/renderer.mjs +59 -0
  18. package/dist/head/runtime/composables.d.ts +9 -0
  19. package/dist/head/runtime/composables.mjs +2 -0
  20. package/dist/head/runtime/index.d.ts +1 -0
  21. package/dist/head/runtime/index.mjs +1 -0
  22. package/dist/head/runtime/plugin.d.ts +2 -0
  23. package/dist/head/runtime/plugin.mjs +6 -0
  24. package/dist/index.d.ts +8 -61
  25. package/dist/index.mjs +1275 -954
  26. package/dist/pages/runtime/helpers/chunks.d.ts +0 -0
  27. package/dist/pages/runtime/helpers/chunks.mjs +0 -0
  28. package/dist/pages/runtime/helpers/index.d.ts +5 -0
  29. package/dist/pages/runtime/helpers/index.mjs +28 -0
  30. package/dist/pages/runtime/plugin.d.ts +2 -0
  31. package/dist/pages/runtime/plugin.mjs +51 -0
  32. package/dist/vite-client/runtime/injectManifest.d.ts +26 -0
  33. package/dist/vite-client/runtime/injectManifest.mjs +104 -0
  34. package/dist/vite-client/runtime/plugin.d.ts +2 -0
  35. package/dist/vite-client/runtime/plugin.mjs +27 -0
  36. package/package.json +55 -36
  37. package/src/app/composables/index.ts +20 -0
  38. package/src/app/entry.ts +36 -0
  39. package/src/app/flow.ts +157 -0
  40. package/src/app/index.ts +5 -0
  41. package/src/auto-imports/module.ts +143 -0
  42. package/src/auto-imports/presets.ts +49 -0
  43. package/src/auto-imports/transform.ts +48 -0
  44. package/src/core/app.ts +90 -0
  45. package/src/core/builder.ts +59 -0
  46. package/src/core/flow.ts +93 -0
  47. package/src/core/modules.ts +32 -0
  48. package/src/core/nitro.ts +206 -0
  49. package/src/core/plugins/import-protection.ts +49 -0
  50. package/src/core/plugins/unctx.ts +31 -0
  51. package/src/core/runtime/nitro/flow.ts +43 -0
  52. package/src/core/runtime/nitro/paths.ts +20 -0
  53. package/src/core/runtime/nitro/renderer.ts +72 -0
  54. package/src/core/templates.ts +119 -0
  55. package/src/core/vite/builder/css.ts +28 -0
  56. package/src/core/vite/builder/dev-bundler.ts +247 -0
  57. package/src/core/vite/builder/index.ts +92 -0
  58. package/src/core/vite/builder/manifest.ts +33 -0
  59. package/src/core/vite/builder/plugins/analyze.ts +32 -0
  60. package/src/core/vite/builder/plugins/cache-dir.ts +13 -0
  61. package/src/core/vite/builder/plugins/dynamic-base.ts +64 -0
  62. package/src/core/vite/builder/plugins/virtual.ts +45 -0
  63. package/src/core/vite/builder/server.ts +163 -0
  64. package/src/core/vite/builder/types/index.ts +13 -0
  65. package/src/core/vite/builder/utils/index.ts +53 -0
  66. package/src/core/vite/builder/utils/warmup.ts +27 -0
  67. package/src/core/vite/builder/utils/wpfs.ts +7 -0
  68. package/src/core/vite/builder/vite-node.ts +110 -0
  69. package/src/core/vite/client/index.ts +48 -0
  70. package/src/dirs.ts +8 -0
  71. package/src/head/module.ts +37 -0
  72. package/src/head/runtime/composables.ts +16 -0
  73. package/src/head/runtime/index.ts +1 -0
  74. package/src/head/runtime/plugin.ts +12 -0
  75. package/src/index.ts +2 -0
  76. package/src/pages/module.ts +55 -0
  77. package/src/pages/runtime/helpers/chunks.ts +0 -0
  78. package/src/pages/runtime/helpers/index.ts +33 -0
  79. package/src/pages/runtime/plugin.ts +58 -0
  80. package/src/pages/templates.ts +20 -0
  81. package/src/pages/utils.ts +49 -0
  82. package/src/vite-client/module.ts +70 -0
  83. package/src/vite-client/runtime/injectManifest.ts +188 -0
  84. package/src/vite-client/runtime/plugin.ts +33 -0
  85. package/types.d.ts +2 -0
  86. package/dist/index.cjs +0 -1061
  87. package/types/core.d.ts +0 -143
  88. package/types/flow.d.ts +0 -239
  89. package/types/index.d.ts +0 -38
  90. package/types/interfaces.d.ts +0 -61
package/dist/index.mjs CHANGED
@@ -1,1034 +1,1355 @@
1
- import path, { join } from 'path';
2
- import { applyToDefaults } from '@hapi/hoek';
3
- import consola from 'consola';
4
- import * as R from 'ramda';
5
- import { flatten, dissoc, groupBy, mapObjIndexed } from 'ramda';
6
- import { notFound } from '@hapi/boom';
7
- import os from 'os';
8
- import chalk from 'chalk';
9
- import fs from 'fs-extra';
10
- import fs$1 from 'fs';
11
1
  import { createHooks } from 'hookable';
2
+ import { dirname, resolve, normalize, join, isAbsolute, relative, extname } from 'pathe';
3
+ import { defineFlowModule, addPlugin, defineNuxtModule, logger, addTemplate, addPluginTemplate, addVitePlugin, useNuxt, resolveAlias, resolveFiles, addDevServerHandler, nuxtCtx, installModule, loadFlowConfig, templateUtils, normalizeTemplate, compileTemplate, normalizePlugin, resolveFilesFlow, isIgnoredFlow } from '@monkeyplus/flow-kit';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { defineUnimportPreset, createUnimport, toImports, scanDirExports } from 'unimport';
6
+ import { createUnplugin } from 'unplugin';
7
+ import { parseURL, parseQuery, joinURL, withoutTrailingSlash } from 'ufo';
8
+ import escapeRE from 'escape-string-regexp';
9
+ import { camelCase, pascalCase } from 'scule';
10
+ import { genImport, genDynamicImport, genArrayFromRaw, genString, genObjectFromRawEntries } from 'knitwork';
11
+ import fse from 'fs-extra';
12
+ import logger$1 from 'consola';
13
+ import * as vite from 'vite';
14
+ import { createServer, build as build$1 } from 'vite';
15
+ import { debounce } from 'perfect-debounce';
16
+ import { existsSync, promises, readdirSync, statSync } from 'node:fs';
17
+ import { createNitro, scanHandlers, writeTypes, build as build$2, prepare, copyPublicAssets, prerender, createDevServer } from 'nitropack';
18
+ import defu from 'defu';
19
+ import { dynamicEventHandler, toEventHandler } from 'h3';
20
+ import { createRequire, builtinModules } from 'node:module';
12
21
  import chokidar from 'chokidar';
22
+ import { generateTypes, resolveSchema } from 'untyped';
23
+ import { getPort } from 'get-port-please';
24
+ import { sanitizeFilePath } from 'mlly';
25
+ import replace from '@rollup/plugin-replace';
26
+ import { isExternal as isExternal$1, ExternalsDefaults } from 'externality';
27
+ import { createHash } from 'node:crypto';
28
+ import MagicString from 'magic-string';
13
29
 
14
- const name = "@monkeyplus/flow";
15
- const version = "4.0.0-beta.9";
16
- const description = "Utils hapi";
17
- const author = "Andres Navarrete";
18
- const license = "MIT";
19
- const main = "./dist/index.cjs";
20
- const module = "./dist/index.mjs";
21
- const types = "./dist/index.d.ts";
22
- const files = [
23
- "dist/",
24
- "types/"
25
- ];
26
- const exports = {
27
- ".": {
28
- "import": "./dist/index.mjs",
29
- require: "./dist/index.cjs"
30
- }
31
- };
32
- const scripts = {
33
- build: "unbuild",
34
- dev: "pnpm stub && pnpm types",
35
- stub: "unbuild --stub",
36
- types: "tsup ./src/index.ts --dts-only --external types && esno ../../scripts/replace",
37
- lint: "eslint --ext .js,.ts .",
38
- fix: "eslint --fix --ext .ts .",
39
- prepublishOnly: "pnpm run build",
40
- start: "esno src/index.ts",
41
- test: "vitest"
42
- };
43
- const dependencies$1 = {
44
- "@hapi/boom": "9.x.x",
45
- "@hapi/hoek": "9.x.x",
46
- consola: "^2.15.3",
47
- chalk: "^4.1.2",
48
- chokidar: "^3.5.3",
49
- hookable: "^5.1.1",
50
- "fs-extra": "^10.0.0",
51
- ramda: "^0.28.0"
52
- };
53
- const devDependencies = {
54
- "@types/fs-extra": "^9.0.13",
55
- "@types/hapi__hapi": "^20.0.10",
56
- "@types/hapi__nes": "^11.0.5",
57
- "@types/hapi__vision": "^5.5.3",
58
- "@types/ramda": "^0.27.64"
59
- };
60
- const peerDependencies = {
61
- "@hapi/hapi": "^20.x"
62
- };
63
- const gitHead = "1d5387b9c77909019f36d360a0ac53ddaa40e4af";
64
- const pkg = {
65
- name: name,
66
- version: version,
67
- description: description,
68
- author: author,
69
- license: license,
70
- main: main,
71
- module: module,
72
- types: types,
73
- files: files,
74
- exports: exports,
75
- scripts: scripts,
76
- dependencies: dependencies$1,
77
- devDependencies: devDependencies,
78
- peerDependencies: peerDependencies,
79
- gitHead: gitHead
80
- };
30
+ const version = "5.0.0-beta.1";
81
31
 
82
- const logger$1 = consola.withScope(pkg.name);
83
- const dependencies = {
84
- "@hapi/vision": "6.x.x",
85
- "@hapi/inert": "6.x.x",
86
- "@hapi/h2o2": "9.x.x",
87
- "@hapi/nes": "12.x.x"
88
- };
89
- const isProduction = process.env.NODE_ENV === "production";
90
- const isGenerate = process.env.GENERATE;
32
+ let _distDir = dirname(fileURLToPath(import.meta.url));
33
+ if (_distDir.endsWith("chunks"))
34
+ _distDir = dirname(_distDir);
35
+ const distDir = _distDir;
36
+ const pkgDir = resolve(distDir, "..");
37
+ resolve(distDir, "runtime");
91
38
 
92
- const LifeCircle = {
93
- register: (server) => {
94
- server.ext("onPreStart", async () => {
95
- await server.methods.flow.pages();
96
- });
97
- server.ext("onRequest", async (req, h) => {
98
- await server.methods.flow.pages();
99
- const stateRequest = {
100
- global: {},
101
- local: {},
102
- context: {},
103
- utils: {},
104
- extensions: {}
39
+ const metaModule = defineFlowModule({
40
+ meta: {
41
+ name: "meta"
42
+ },
43
+ defaults: {
44
+ charset: "utf-8",
45
+ viewport: "width=device-width, initial-scale=1"
46
+ },
47
+ setup(options, flow) {
48
+ const runtimeDir = flow.options.alias["#head"] || resolve(distDir, "head/runtime");
49
+ flow.options.alias["#head"] = runtimeDir;
50
+ addPlugin({ src: resolve(runtimeDir, "plugin") });
51
+ }
52
+ });
53
+
54
+ const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }) => {
55
+ return {
56
+ name: "flow:auto-imports-transform",
57
+ enforce: "post",
58
+ transformInclude(id) {
59
+ const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
60
+ const { type, macro } = parseQuery(search);
61
+ const exclude = options.transform?.exclude || [/[\\/]node_modules[\\/]/];
62
+ const include = options.transform?.include || [];
63
+ if (exclude.some((pattern) => id.match(pattern)))
64
+ return false;
65
+ if (include.some((pattern) => id.match(pattern)))
66
+ return true;
67
+ if (pathname.endsWith(".vue") && (type === "template" || type === "script" || macro || !search))
68
+ return true;
69
+ if (pathname.match(/\.((c|m)?j|t)sx?$/g))
70
+ return true;
71
+ },
72
+ async transform(_code, id) {
73
+ const { code, s } = await ctx.injectImports(_code);
74
+ if (code === _code)
75
+ return;
76
+ return {
77
+ code,
78
+ map: sourcemap && s.generateMap({ source: id, includeContent: true })
105
79
  };
106
- req.plugins.flow = stateRequest;
107
- const { flow: state } = server.app;
108
- const pathRedirect = state.pages.redirects[req.path];
109
- if (state.truncates[req.path])
110
- return h.redirect("/").takeover();
111
- if (pathRedirect)
112
- return h.redirect(pathRedirect).takeover();
113
- return h.continue;
80
+ }
81
+ };
82
+ });
83
+
84
+ const commonPresets = [
85
+ defineUnimportPreset({
86
+ from: "#head",
87
+ imports: [
88
+ "useHead"
89
+ ]
90
+ })
91
+ ];
92
+ const appPreset = defineUnimportPreset({
93
+ from: "#app",
94
+ imports: [
95
+ "useRuntimeConfig",
96
+ "defineFlowPlugin",
97
+ "defineNuxtPlugin",
98
+ "useCookie",
99
+ "refreshNuxtData",
100
+ "useAsyncData",
101
+ "useRoute"
102
+ ]
103
+ });
104
+ const vuePreset = defineUnimportPreset({
105
+ from: "vue",
106
+ imports: [
107
+ "defineComponent",
108
+ "getCurrentInstance",
109
+ "useSlots",
110
+ "h",
111
+ "computed"
112
+ ]
113
+ });
114
+ const defaultPresets = [
115
+ ...commonPresets,
116
+ appPreset,
117
+ vuePreset
118
+ ];
119
+
120
+ const autoImportsModule = defineNuxtModule({
121
+ meta: {
122
+ name: "auto-imports",
123
+ configKey: "autoImports"
124
+ },
125
+ defaults: {
126
+ presets: defaultPresets,
127
+ global: false,
128
+ imports: [],
129
+ dirs: [],
130
+ transform: {
131
+ exclude: void 0
132
+ }
133
+ },
134
+ async setup(options, flow) {
135
+ await flow.callHook("autoImports:sources", options.presets);
136
+ options.presets.forEach((i) => {
137
+ if (typeof i !== "string" && i.names && !i.imports) {
138
+ i.imports = i.names;
139
+ logger.warn("auto-imports: presets.names is deprecated, use presets.imports instead");
140
+ }
114
141
  });
115
- server.ext("onPreHandler", async (req, h) => {
116
- const { dynamic } = req.route.settings.plugins?.flow || {};
117
- const flow = req.route.settings.app?.flow;
118
- if (!dynamic)
119
- return h.continue;
120
- const pages = await dynamic.pages({
121
- server,
122
- route: req.route,
123
- locale: flow?.locale
124
- });
125
- if (!pages || !pages.length)
126
- return h.continue;
127
- const page = pages.find((_page) => _page.url === req.params.url);
128
- if (!page)
129
- return notFound();
130
- Object.assign(req.plugins.flow.local, {
131
- [dynamic.assign || "dynamic"]: page.context ?? { a: "" }
132
- });
133
- req.app.dynamic = R.omit(["context"], page);
134
- return h.continue;
142
+ const ctx = createUnimport({
143
+ presets: options.presets,
144
+ imports: options.imports
135
145
  });
136
- }
137
- };
146
+ let composablesDirs = [];
147
+ for (const layer of flow.options._layers) {
148
+ composablesDirs.push(resolve(layer.config.srcDir, "composables"));
149
+ for (const dir of layer.config.autoImports?.dirs ?? [])
150
+ composablesDirs.push(resolve(layer.config.srcDir, dir));
151
+ }
152
+ await flow.callHook("autoImports:dirs", composablesDirs);
153
+ composablesDirs = composablesDirs.map((dir) => normalize(dir));
154
+ addTemplate({
155
+ filename: "imports.mjs",
156
+ getContents: () => ctx.toExports()
157
+ });
158
+ flow.options.alias["#imports"] = join(flow.options.buildDir, "imports");
159
+ if (flow.options.dev && options.global) {
160
+ addPluginTemplate({
161
+ filename: "auto-imports.mjs",
162
+ getContents: () => {
163
+ const imports = ctx.getImports();
164
+ const importStatement = toImports(imports);
165
+ const globalThisSet = imports.map((i) => `globalThis.${i.as} = ${i.as};`).join("\n");
166
+ return `${importStatement}
138
167
 
139
- const ServerInfo = {
140
- register: (server) => {
141
- const serverInfo = () => {
142
- const interfaces = os.networkInterfaces();
143
- const hostname = "localhost";
144
- const protocol = "http";
145
- console.log("");
146
- logger$1.success(chalk.green(`Flow v${pkg.version} dev server running at:`));
147
- console.log("");
148
- Object.keys(interfaces).forEach((key) => (interfaces[key] || []).filter((details) => details.family === "IPv4").map((detail) => {
149
- return {
150
- type: detail.address.includes("127.0.0.1") ? "Local: " : "Network: ",
151
- host: detail.address.replace("127.0.0.1", hostname)
152
- };
153
- }).forEach(({ type, host }) => {
154
- const url = `${protocol}://${host}:${chalk.bold(server.info.port)}`;
155
- console.log(` > ${type} ${chalk.cyan(url)}`);
156
- }));
168
+ ${globalThisSet}
169
+
170
+ export default () => {};`;
171
+ }
172
+ });
173
+ } else {
174
+ addVitePlugin(TransformPlugin.vite({ ctx, options, sourcemap: flow.options.sourcemap }));
175
+ }
176
+ const regenerateAutoImports = async () => {
177
+ ctx.clearDynamicImports();
178
+ await ctx.modifyDynamicImports(async (imports) => {
179
+ imports.push(...await scanDirExports(composablesDirs));
180
+ await flow.callHook("autoImports:extend", imports);
181
+ });
157
182
  };
158
- return { serverInfo };
183
+ await regenerateAutoImports();
184
+ addDeclarationTemplates(ctx);
185
+ flow.hook("prepare:types", ({ references }) => {
186
+ references.push({ path: resolve(flow.options.buildDir, "types/auto-imports.d.ts") });
187
+ references.push({ path: resolve(flow.options.buildDir, "imports.d.ts") });
188
+ });
189
+ flow.hook("builder:watch", async (_, path) => {
190
+ const _resolved = resolve(flow.options.srcDir, path);
191
+ if (composablesDirs.find((dir) => _resolved.startsWith(dir)))
192
+ await flow.callHook("builder:generateApp");
193
+ });
194
+ flow.hook("builder:generateApp", async () => {
195
+ await regenerateAutoImports();
196
+ });
159
197
  }
160
- };
161
-
162
- function getLocalDefaults(loc, opts) {
163
- const bundle = R.path(["locales", loc, "view", "bundle"], opts);
164
- const view = R.path(["locales", loc, "view"], opts);
165
- const runContext = R.path(["locales", loc, "context"], opts);
166
- const seo = R.path(["locales", loc, "seo"], opts);
167
- const blogInfo = R.path(["locales", loc, "blogInfo"], opts);
168
- return {
169
- bundle,
170
- view,
171
- runContext,
172
- seo: seo || {},
173
- blogInfo
198
+ });
199
+ function addDeclarationTemplates(ctx) {
200
+ const nuxt = useNuxt();
201
+ const stripExtension = (path) => path.replace(/\.[a-z]+$/, "");
202
+ const resolved = {};
203
+ const r = ({ from }) => {
204
+ if (resolved[from])
205
+ return resolved[from];
206
+ let path = resolveAlias(from);
207
+ if (isAbsolute(path))
208
+ path = relative(join(nuxt.options.buildDir, "types"), path);
209
+ path = stripExtension(path);
210
+ resolved[from] = path;
211
+ return path;
174
212
  };
213
+ addTemplate({
214
+ filename: "imports.d.ts",
215
+ getContents: () => ctx.toExports()
216
+ });
217
+ addTemplate({
218
+ filename: "types/auto-imports.d.ts",
219
+ getContents: () => `// Generated by auto imports
220
+ ${ctx.generateTypeDecarations({ resolvePath: r })}`
221
+ });
175
222
  }
176
- function getLevel(locale, defLevel) {
177
- const level = typeof defLevel === "string" ? defLevel : typeof defLevel === "object" ? defLevel.locales[locale] || defLevel.default : "";
178
- return level;
223
+
224
+ async function resolvePagesRoutes() {
225
+ const nuxt = useNuxt();
226
+ const pagesDirs = [...new Set(nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.pages || "pages")))];
227
+ const allRoutes = (await Promise.all(pagesDirs.map(async (dir) => {
228
+ const files = await resolveFiles(dir, `**/*{${nuxt.options.extensions.join(",")}}`);
229
+ files.sort();
230
+ return files.map((file) => {
231
+ const segments = relative(dir, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
232
+ return {
233
+ file,
234
+ name: camelCase(segments)
235
+ };
236
+ });
237
+ }))).flat();
238
+ return allRoutes;
179
239
  }
180
- const definePages = (options) => (defaultLocale) => (levelOptions = {}) => {
181
- const prefixName = levelOptions.prefixName || "";
182
- const pages = (locales) => locales.map(({ locale, url, seo }) => {
183
- const page = getLocalDefaults(locale, options);
184
- const levelBase = getLevel(locale, levelOptions.level);
185
- const level = getLevel(locale, options.level);
186
- const [language, ubication] = locale.split("-");
187
- const prefixLang = language === defaultLocale.language ? "" : language;
188
- const prefixUbication = ubication === defaultLocale.ubication ? "" : ubication;
189
- const prefixLevel = path.posix.join("/", prefixLang, prefixUbication, levelBase, level);
190
- const publicPath = defaultLocale.publicPath || "/";
191
- const fullPath = path.posix.join("/", publicPath, prefixLevel, url);
192
- const redirect = R.last(fullPath) === "/" ? path.posix.join(fullPath, "index.html") : void 0;
193
- const app = {
194
- localeName: path.posix.join(prefixName, locale, options.name),
195
- name: options.name,
196
- locale,
197
- language,
198
- level,
199
- redirect,
200
- seo: R.mergeDeepLeft(seo || {}, page.seo),
201
- blogInfo: page.blogInfo,
202
- urlObject: {
203
- publicPath,
204
- level: prefixLevel,
205
- url,
206
- path: fullPath,
207
- static: R.last(fullPath) === "/" ? `${fullPath}index.html` : `${fullPath}.html`
208
- },
209
- view: { ...options.view, ...page.view },
210
- runSharedContext: options.context,
211
- runLocalContext: page.runContext
212
- };
213
- return app;
214
- });
240
+ function normalizePages(pages) {
241
+ const imports = pages.map((page) => genImport(page.file, [{ name: "pages", as: page.name }])).join("\n");
215
242
  return {
216
- name: options.name,
217
- pages
243
+ imports,
244
+ exports: pages.reduce((acc, curr) => `${curr.name || ""},${acc}`, "")
218
245
  };
246
+ }
247
+
248
+ const pagesTypeTemplate = {
249
+ filename: "pages.d.ts",
250
+ getContents: ({ options }) => `// Generated by pages discovery
251
+ export {}
252
+ declare global {
253
+
254
+ ${options.pages.map((c) => `export type ${pascalCase(c.name)}Context=Awaited<ReturnType<typeof ${genDynamicImport(isAbsolute(c.file) ? relative(options.buildDir, c.file) : c.file, { wrapper: false })}['pages']['locales']['es-ec']['context']>>`).join("\n")}
255
+ }
256
+ export const pagesNames: string[]
257
+ `.replaceAll(".ts", "")
219
258
  };
220
259
 
221
- const handlerPage = async (req, h) => {
222
- const { configs } = req.server.plugins.flow;
223
- const { flow } = req.route.settings.app;
224
- const { dynamic } = req.app;
225
- const local = {};
226
- const global = {};
227
- const page = R.clone({
228
- ...R.pick(["publicPath", "path"], flow.urlObject),
229
- ...R.pick([
230
- "name",
231
- "localeName",
232
- "locale",
233
- "level",
234
- "template",
235
- "bundle",
236
- "language"
237
- ], flow)
238
- });
239
- if (dynamic) {
240
- Object.assign(page, {
241
- path: dynamic.url,
242
- ...R.omit(["url"], dynamic)
260
+ const pagesModule = defineNuxtModule({
261
+ meta: {
262
+ name: "pages"
263
+ },
264
+ async setup(_options, flow) {
265
+ const runtimeDir = resolve(distDir, "pages/runtime");
266
+ const pages = [];
267
+ flow.hook("builder:watch", async (event, path) => {
268
+ const dirs = [
269
+ flow.options.dir.pages,
270
+ flow.options.dir.layouts,
271
+ flow.options.dir.middleware
272
+ ].filter(Boolean);
273
+ const pathPattern = new RegExp(`^(${dirs.map(escapeRE).join("|")})/`);
274
+ if (event !== "change" && path.match(pathPattern))
275
+ await flow.callHook("builder:generateApp");
276
+ });
277
+ const options = { pages, buildDir: flow.options.buildDir };
278
+ addTemplate({
279
+ ...pagesTypeTemplate,
280
+ options
281
+ });
282
+ flow.options.alias["#pages"] = resolve(flow.options.buildDir, "pages.mjs");
283
+ addTemplate({
284
+ filename: "pages.mjs",
285
+ async getContents({ options: options2 }) {
286
+ const { exports, imports } = normalizePages(options2.pages);
287
+ return [imports, `export default {${exports}}`].join("\n");
288
+ },
289
+ options
290
+ });
291
+ flow.hook("app:templates", async () => {
292
+ options.pages = await resolvePagesRoutes();
293
+ });
294
+ flow.hook("prepare:types", ({ references }) => {
295
+ references.push({ path: resolve(flow.options.buildDir, "pages.d.ts") });
243
296
  });
297
+ addPlugin({ src: resolve(runtimeDir, "plugin") });
244
298
  }
245
- const utils = {
246
- ...req.plugins.flow.utils,
247
- getLocalUrl: (name) => {
248
- return h.getUrl(flow.locale, name);
299
+ });
300
+
301
+ const createClient = async (flow) => {
302
+ const vite = await createServer({
303
+ root: resolve(flow.options.rootDir),
304
+ base: "/_vite/",
305
+ build: {
306
+ manifest: true
249
307
  },
250
- getUrl: h.getUrl
251
- };
252
- const seo = {
253
- ...flow.seo,
254
- ...req.pre.seo,
255
- url: configs.url,
256
- pageUrl: `${configs.url}${req.url.pathname}`
257
- };
258
- const contextMethod = {
259
- seo,
260
- req,
261
- h,
262
- page,
263
- extensions: req.plugins.flow.extensions,
264
- global: req.plugins.flow.global,
265
- utils
308
+ server: {
309
+ middlewareMode: "ssr"
310
+ }
311
+ });
312
+ const _doReload = () => {
313
+ vite.ws.send({ type: "full-reload" });
266
314
  };
267
- const extraContexts = req.plugins.flow.context;
268
- for (const key in extraContexts) {
269
- if (extraContexts[key]?.method) {
270
- const assign = extraContexts[key].assign;
271
- const data = await extraContexts[key].method(contextMethod);
272
- const _context = { [key]: data };
273
- if (assign === "global")
274
- Object.assign(global, _context);
275
- else if (assign === "local")
276
- Object.assign(local, _context);
277
- else
278
- Object.assign(seo, _context);
315
+ const doReload = debounce(_doReload, 50);
316
+ flow.hook("bundler:change", () => {
317
+ doReload();
318
+ });
319
+ flow.hook("close", async () => {
320
+ await vite.close();
321
+ });
322
+ return vite;
323
+ };
324
+ const builClient = async (flow) => {
325
+ return await build$1({
326
+ root: flow.options.rootDir,
327
+ mode: "production",
328
+ build: {
329
+ assetsDir: "scripts",
330
+ target: "es2017",
331
+ outDir: ".vite",
332
+ manifest: true
279
333
  }
334
+ });
335
+ };
336
+
337
+ const viteModule = defineFlowModule({
338
+ meta: {
339
+ name: "viteClient"
340
+ },
341
+ defaults: {
342
+ route: "/_vite/"
343
+ },
344
+ async setup(_options, flow) {
345
+ const runtimeDir = resolve(distDir, "vite-client/runtime");
346
+ flow.options.alias["#viteManifest"] = resolve(flow.options.buildDir, "viteManifest.mjs");
347
+ if (flow.options.dev) {
348
+ const _vite = await createClient(flow);
349
+ addDevServerHandler({
350
+ handler: _vite.middlewares,
351
+ route: _options.route
352
+ });
353
+ addTemplate({
354
+ filename: "viteManifest.mjs",
355
+ async getContents() {
356
+ return [
357
+ "export default {",
358
+ 'head:()=>`<script type="module" src="/_vite/@vite/client"><\/script>`',
359
+ ",",
360
+ 'body: (bundle)=>`<script type="module" src="/_vite/client/pages/${bundle}.ts"><\/script>`',
361
+ "}"
362
+ ].join("\n");
363
+ }
364
+ });
365
+ } else {
366
+ flow.hook("modules:done", async () => {
367
+ const start = Date.now();
368
+ logger$1.info("Building client...");
369
+ await builClient(flow);
370
+ const file = resolve(flow.options.rootDir, ".vite/manifest.json");
371
+ const manifest = await fse.readFile(file, "utf8");
372
+ logger$1.success(`Client build in ${Date.now() - start}ms`);
373
+ addTemplate({
374
+ filename: "viteManifest.mjs",
375
+ async getContents() {
376
+ return [
377
+ "export default ()=>(",
378
+ manifest,
379
+ ")"
380
+ ].join("\n");
381
+ }
382
+ });
383
+ });
384
+ flow.hook("generate:before", async () => {
385
+ const files = resolve(flow.options.rootDir, ".vite/scripts");
386
+ await fse.copy(files, resolve(flow.options.generate.dir, "assets"));
387
+ });
388
+ }
389
+ addPlugin({ src: resolve(runtimeDir, "plugin") });
280
390
  }
281
- if (flow.runSharedContext) {
282
- const _context = await flow.runSharedContext(contextMethod);
283
- Object.assign(local, _context);
284
- }
285
- if (flow.runLocalContext) {
286
- const _context = await flow.runLocalContext(contextMethod);
287
- Object.assign(local, _context);
391
+ });
392
+
393
+ const _require = createRequire(import.meta.url);
394
+ const ImportProtectionPlugin = createUnplugin((options) => {
395
+ const cache = {};
396
+ return {
397
+ name: "flow:import-protection",
398
+ enforce: "pre",
399
+ resolveId(id, importer) {
400
+ const invalidImports = options.patterns.filter(([pattern]) => pattern instanceof RegExp ? pattern.test(id) : pattern === id);
401
+ let matched;
402
+ for (const match of invalidImports) {
403
+ cache[id] = cache[id] || /* @__PURE__ */ new Map();
404
+ const [pattern, warning] = match;
405
+ if (cache[id].has(pattern))
406
+ continue;
407
+ const relativeImporter = isAbsolute(importer) ? relative(options.rootDir, importer) : importer;
408
+ logger.error(warning || "Invalid import", `[importing \`${id}\` from \`${relativeImporter}\`]`);
409
+ cache[id].set(pattern, true);
410
+ matched = true;
411
+ }
412
+ if (matched)
413
+ return _require.resolve("unenv/runtime/mock/proxy");
414
+ return null;
415
+ }
416
+ };
417
+ });
418
+
419
+ async function initNitro(flow) {
420
+ const { handlers, devHandlers } = await resolveHandlers(flow);
421
+ const _nitroConfig = flow.options.nitro || {};
422
+ globalThis.generate = {};
423
+ const nitroConfig = defu(_nitroConfig, {
424
+ rootDir: flow.options.rootDir,
425
+ srcDir: join(flow.options.srcDir, "server"),
426
+ dev: flow.options.dev,
427
+ preset: flow.options.dev ? "nitro-dev" : void 0,
428
+ buildDir: flow.options.buildDir,
429
+ scanDirs: flow.options._layers.map((layer) => join(layer.config.srcDir, "server")),
430
+ renderer: resolve(distDir, "core/runtime/nitro/renderer"),
431
+ nodeModulesDirs: flow.options.modulesDir,
432
+ handlers,
433
+ devHandlers: [],
434
+ baseURL: flow.options.app.baseURL,
435
+ runtimeConfig: {
436
+ ...flow.options.runtimeConfig,
437
+ app: {
438
+ ...flow.options.runtimeConfig.app,
439
+ rootDir: flow.options.rootDir,
440
+ locale: flow.options.locale
441
+ },
442
+ nitro: {
443
+ envPrefix: "FLOW_",
444
+ ...flow.options.runtimeConfig.nitro
445
+ },
446
+ generate: flow.options._generate
447
+ },
448
+ typescript: {
449
+ generateTsConfig: false
450
+ },
451
+ publicAssets: [
452
+ {
453
+ baseURL: flow.options.app.buildAssetsDir,
454
+ dir: resolve(flow.options.buildDir, "dist/client")
455
+ },
456
+ ...flow.options._layers.map((layer) => join(layer.config.srcDir, layer.config.dir?.public || "public")).filter((dir) => existsSync(dir)).map((dir) => ({ dir }))
457
+ ],
458
+ prerender: {
459
+ crawlLinks: flow.options._generate ? flow.options.generate.crawler : false,
460
+ routes: [].concat(flow.options._generate ? ["/_urls", ...flow.options.generate.routes] : [])
461
+ },
462
+ sourcemap: flow.options.sourcemap,
463
+ externals: {
464
+ inline: [
465
+ ...flow.options.dev ? [] : ["eta", "@monkeyplus/", "@vue/", "@nuxt/", flow.options.buildDir],
466
+ "@monkeyplus/flow/dist"
467
+ ]
468
+ },
469
+ alias: {
470
+ "estree-walker": "unenv/runtime/mock/proxy",
471
+ "@babel/parser": "unenv/runtime/mock/proxy",
472
+ "#paths": resolve(distDir, "core/runtime/nitro/paths"),
473
+ "#server": "#build/dist/server/server.mjs",
474
+ "#app": flow.options.appDir,
475
+ ...flow.options.alias
476
+ },
477
+ rollupConfig: {
478
+ plugins: []
479
+ }
480
+ });
481
+ await flow.callHook("nitro:config", nitroConfig);
482
+ nitroConfig.handlers.unshift({
483
+ middleware: true,
484
+ handler: resolve(distDir, "core/runtime/nitro/flow")
485
+ });
486
+ const nitro = await createNitro(nitroConfig);
487
+ await flow.callHook("nitro:init", nitro);
488
+ nitro.vfs = flow.vfs = nitro.vfs || flow.vfs || {};
489
+ flow.hook("close", () => nitro.hooks.callHook("close"));
490
+ nitro.hooks.hook("rollup:before", (nitro2) => {
491
+ const plugin = ImportProtectionPlugin.rollup({
492
+ rootDir: flow.options.rootDir,
493
+ patterns: [
494
+ ...["#app", /^#build(\/|$)/].map((p) => [p, "Flow app aliases are not allowed in server routes."])
495
+ ]
496
+ });
497
+ nitro2.options.rollupConfig.plugins.push(plugin);
498
+ });
499
+ const devMidlewareHandler = dynamicEventHandler();
500
+ nitro.options.devHandlers.unshift({ handler: devMidlewareHandler });
501
+ nitro.options.devHandlers.push(...devHandlers);
502
+ nitro.options.handlers.unshift({
503
+ route: "/__flow_error",
504
+ lazy: true,
505
+ handler: resolve(distDir, "core/runtime/nitro/renderer")
506
+ });
507
+ flow.hook("prepare:types", async (opts) => {
508
+ if (flow.options._prepare) {
509
+ await scanHandlers(nitro);
510
+ await writeTypes(nitro);
511
+ }
512
+ opts.references.push({ path: resolve(flow.options.buildDir, "types/nitro.d.ts") });
513
+ });
514
+ flow.hook("build:done", async () => {
515
+ await flow.callHook("nitro:build:before", nitro);
516
+ if (flow.options.dev) {
517
+ await build$2(nitro);
518
+ } else {
519
+ await prepare(nitro);
520
+ await copyPublicAssets(nitro);
521
+ await prerender(nitro);
522
+ if (!flow.options._generate) {
523
+ await build$2(nitro);
524
+ } else {
525
+ const nitroDev = await createNitro({
526
+ ...nitro.options._config,
527
+ rootDir: nitro.options.rootDir,
528
+ logLevel: 0,
529
+ preset: "nitro-prerender"
530
+ });
531
+ flow.server = nitroDev;
532
+ const distDir2 = resolve(flow.options.rootDir, "dist");
533
+ if (!existsSync(distDir2))
534
+ await promises.symlink(nitro.options.output.publicDir, distDir2, "junction").catch(() => {
535
+ });
536
+ }
537
+ }
538
+ });
539
+ if (flow.options.dev) {
540
+ flow.hook("build:compile", ({ compiler }) => {
541
+ compiler.outputFileSystem = { ...fse, join };
542
+ });
543
+ flow.hook("server:devMiddleware", (m) => {
544
+ devMidlewareHandler.set(toEventHandler(m));
545
+ });
546
+ flow.server = createDevServer(nitro);
547
+ flow.hook("build:resources", () => {
548
+ flow.server.reload();
549
+ });
550
+ const waitUntilCompile = new Promise((resolve2) => nitro.hooks.hook("compiled", () => resolve2()));
551
+ flow.hook("build:done", () => waitUntilCompile);
288
552
  }
289
- const context = {
290
- view: flow.view,
291
- context: Object.freeze({ ...local, ...req.plugins.flow.local }),
292
- seo,
293
- page,
294
- utils: {},
295
- hapi: { req, h },
296
- global: Object.freeze({ ...global, ...req.plugins.flow.global })
553
+ }
554
+ async function resolveHandlers(flow) {
555
+ const handlers = [...flow.options.serverHandlers];
556
+ const devHandlers = [...flow.options.devServerHandlers];
557
+ return {
558
+ handlers,
559
+ devHandlers
297
560
  };
298
- if (req.query.context) {
299
- context.utils = Object.keys(utils);
300
- context.hapi = ["req", "h"];
301
- return context;
561
+ }
562
+
563
+ const addModuleTranspiles = (opts = {}) => {
564
+ const flow = useNuxt();
565
+ const modules = [
566
+ ...opts.additionalModules || [],
567
+ ...flow.options.modules,
568
+ ...flow.options._modules
569
+ ].map((m) => typeof m === "string" ? m : Array.isArray(m) ? m[0] : m.src).filter((m) => typeof m === "string").map((m) => m.split("node_modules/").pop());
570
+ flow.options.build.transpile = flow.options.build.transpile.map((m) => typeof m === "string" ? m.split("node_modules/").pop() : m);
571
+ function isTranspilePresent(mod) {
572
+ return flow.options.build.transpile.some((t) => !(t instanceof Function) && (t instanceof RegExp ? t.test(mod) : new RegExp(t).test(mod)));
573
+ }
574
+ for (const module of modules) {
575
+ if (!isTranspilePresent(module))
576
+ flow.options.build.transpile.push(module);
302
577
  }
303
- context.utils = utils;
304
- return h.view(`${configs.dirTemplates}${flow.view.layout || "default"}`, context);
305
578
  };
306
579
 
307
- const logger = consola.withScope("@monkeyplus/flow");
308
- const defaults = {
309
- locales: ["es-ec"],
310
- defaultUbication: "ec",
311
- defaultLanguage: "es",
312
- staticDir: "static",
313
- hmr: {
314
- dirs: ["views"]
315
- },
316
- publicPath: "/",
317
- locale: "es-ec",
318
- relativeTo: "",
319
- dirTemplates: "",
320
- outputDir: "build",
321
- url: process.env.CUSTOM_URL || process.env.URL,
322
- engines: ["eta"],
323
- plugins: {}
324
- };
325
- function getConfigs(server, options) {
326
- const relativeTo = path.resolve(options.relativeTo);
327
- const getObject = (object) => {
328
- const config = applyToDefaults(defaults, { ...object, ...options });
329
- return {
330
- ...config,
331
- relativeTo,
332
- locale: `${config.defaultLanguage}-${config.defaultUbication}`
333
- };
580
+ function createFlow(options) {
581
+ const hooks = createHooks();
582
+ const flow = {
583
+ _version: "3.0.0-rc.3",
584
+ version,
585
+ options,
586
+ hooks,
587
+ callHook: hooks.callHook,
588
+ addHooks: hooks.addHooks,
589
+ hook: hooks.hook,
590
+ ready: () => initFlow(flow),
591
+ close: () => Promise.resolve(hooks.callHook("close", flow)),
592
+ vfs: {}
334
593
  };
335
- try {
336
- const pathWeb = path.resolve(options.relativeTo, "flow.config");
337
- logger.info("Flow apply settings from file: flow.config");
338
- const configBase = require(pathWeb);
339
- const config = getObject(configBase);
340
- return config;
341
- } catch (error) {
342
- logger.info("Flow no config file apply default settings");
343
- return getObject({});
594
+ return flow;
595
+ }
596
+ async function initFlow(flow) {
597
+ nuxtCtx.set(flow);
598
+ flow.hook("close", () => nuxtCtx.unset());
599
+ await flow.callHook("modules:before", { nuxt: flow });
600
+ const modulesToInstall = [
601
+ ...flow.options.modules,
602
+ ...flow.options._modules
603
+ ];
604
+ for (const m of modulesToInstall) {
605
+ if (Array.isArray(m))
606
+ await installModule(m[0], m[1]);
607
+ else
608
+ await installModule(m, {});
344
609
  }
610
+ await flow.callHook("modules:done", { nuxt: flow });
611
+ await addModuleTranspiles();
612
+ await initNitro(flow);
613
+ await flow.callHook("ready", flow);
614
+ }
615
+ async function loadFlow(opts) {
616
+ const options = await loadFlowConfig(opts);
617
+ options.appDir = resolve(distDir, "app");
618
+ options._majorVersion = 3;
619
+ options._modules.push(pagesModule, metaModule, autoImportsModule, viteModule);
620
+ options.modulesDir.push(resolve(pkgDir, "node_modules"));
621
+ const flow = createFlow(options);
622
+ if (opts.ready !== false)
623
+ await flow.ready();
624
+ return flow;
625
+ }
626
+ function defineFlowConfig(config) {
627
+ return config;
345
628
  }
346
- const isDinamyc = (url) => /\{url?(.+)\}/.test(url);
347
629
 
348
- const Decorators = {
349
- register: (server) => {
350
- const { flow: state } = server.app;
351
- const { configs, helpers } = server.plugins.flow;
352
- const flowDecorate = (route, options) => {
353
- const { plugins, app } = route.settings;
354
- Object.assign(plugins, { generate: ".html" });
355
- const flow = app.flow;
356
- const runCommons = (pageInfo) => {
357
- helpers.addStaticPage(pageInfo.localeName, {
358
- url: route.path,
359
- locale: pageInfo.locale,
360
- localeName: pageInfo.localeName,
361
- name: pageInfo.name
362
- });
363
- if (pageInfo.redirect)
364
- helpers.addRedirect(pageInfo.redirect, route.path);
365
- };
366
- if (flow) {
367
- runCommons(flow);
368
- } else {
369
- const routes = definePages({
370
- name: options.name,
371
- view: options.view,
372
- locales: {
373
- [options.locale || configs.locale]: {}
374
- },
375
- context: options.context
376
- })({
377
- language: configs.defaultLanguage,
378
- ubication: configs.defaultUbication,
379
- publicPath: configs.publicPath
380
- })().pages([
381
- { locale: options.locale || configs.locale, url: route.path }
382
- ]);
383
- const pageInfo = routes[0];
384
- runCommons(pageInfo);
385
- Object.assign(app, { flow: pageInfo, content: options.content });
386
- }
387
- const extensions = plugins?.flow?.extensions || {};
388
- if (isDinamyc(route.path)) {
389
- if (!route.settings.plugins?.flow?.dynamic)
390
- throw new Error("Dynamic pages require a method");
391
- helpers.addDynamicPages(flow.localeName, ((options2) => async () => {
392
- const _pages = await route.settings.plugins?.flow?.dynamic?.pages(options2);
393
- const obj = {};
394
- for (const sPage of _pages || []) {
395
- const localeName = `${app?.flow.localeName}/${sPage.name}`;
396
- obj[localeName] = {
397
- locale: app?.flow.locale,
398
- localeName,
399
- name: localeName.replace(`${app?.flow.locale}/`, ""),
400
- url: route.path.replace("{url*}", sPage.url),
401
- context: sPage.context,
402
- dynamicSlug: sPage.dynamicSlug
403
- };
404
- }
405
- return obj;
406
- })({
407
- server,
408
- route,
409
- locale: app?.flow.locale
410
- }));
411
- }
412
- for (const extension in extensions) {
413
- const optionExtension = plugins?.flow?.extensions[extension];
414
- const routeMethod = state.extensions[extension]?.routeMethod;
415
- if (routeMethod)
416
- routeMethod({ pageInfo: app.flow, route }, optionExtension);
417
- }
418
- return handlerPage;
419
- };
420
- const getUrl = (_locale, _name) => {
421
- try {
422
- const pageName = path.posix.join(_locale, _name);
423
- const page = state.pages.all[pageName];
424
- if (page) {
425
- return page.url;
426
- } else {
427
- logger$1.warn("Not found link with name: %s", pageName);
428
- return "/404";
429
- }
430
- } catch (error) {
431
- logger$1.error(error);
432
- return "/";
433
- }
434
- };
435
- server.method("flow.getUrl", getUrl, {});
436
- server.decorate("handler", "flow", flowDecorate);
437
- server.decorate("toolkit", "getUrl", server.methods.flow.getUrl);
630
+ const serverPluginTemplate = {
631
+ filename: "plugins/server.mjs",
632
+ getContents(ctx) {
633
+ const serverPlugins = ctx.app.plugins;
634
+ return [
635
+ templateUtils.importSources(serverPlugins.map((p) => p.src)),
636
+ `export default ${genArrayFromRaw([
637
+ ...serverPlugins.map((p) => templateUtils.importName(p.src))
638
+ ])}`
639
+ ].join("\n");
438
640
  }
439
641
  };
642
+ const pluginsDeclaration = {
643
+ filename: "types/plugins.d.ts",
644
+ getContents: (ctx) => {
645
+ const EXTENSION_RE = new RegExp(`(?<=\\w)(${ctx.nuxt.options.extensions.map((e) => escapeRE(e)).join("|")})$`, "g");
646
+ const tsImports = ctx.app.plugins.map((p) => (isAbsolute(p.src) ? relative(join(ctx.nuxt.options.buildDir, "types"), p.src) : p.src).replace(EXTENSION_RE, ""));
647
+ return `// Generated by Flow'
648
+ import type { Plugin } from '#app'
440
649
 
441
- const useGenerator = {
442
- register: (server) => {
443
- const { configs, helpers } = server.plugins.flow;
444
- const getFlowPages = async () => {
445
- const files = {};
446
- const allPages = await server.methods.flow.pages();
447
- const pages = Object.values(allPages);
448
- logger.success("Read %i static pages", pages.length);
449
- for (const page of pages)
450
- files[page.url] = ".html";
451
- const routes = server.table();
452
- for (const route of routes) {
453
- const isDynamic = /\{url?(.+)\}/.test(route.path);
454
- const generate = route.settings.plugins?.generate;
455
- if (!isDynamic && generate) {
456
- if (!files[route.path])
457
- files[route.path] = generate;
458
- }
459
- }
460
- return files;
461
- };
462
- const writeFile = async (file, payload) => {
463
- await fs.ensureFile(file);
464
- await fs.writeFile(file, payload, "utf8");
465
- };
466
- const useCreateFile = (isVirtual = false) => async (dir, url, ext) => {
467
- if (typeof ext === "object") {
468
- if (!isVirtual) {
469
- const dirFile = path.dirname(url);
470
- await fs.ensureDir(path.join(dir, dirFile));
471
- const file = await fs.readFile(ext.file);
472
- await fs.writeFile(path.join(dir, url), file);
473
- }
474
- return { type: ext.type || "assets", url };
475
- } else {
476
- const r = await server.inject({
477
- url,
478
- method: "get"
479
- });
480
- let file = "";
481
- if (typeof ext === "boolean") {
482
- if (!isVirtual) {
483
- file = path.join(dir, url);
484
- await writeFile(file, r.payload);
485
- }
486
- return { type: "assets", url };
487
- } else if (typeof ext === "string") {
488
- if (ext === ".html") {
489
- if (!isVirtual) {
490
- const isIndex = R.last(url) === "/";
491
- const nameFile = isIndex ? `${url}index.html` : `${url}.html`;
492
- file = path.join(dir, nameFile);
493
- await writeFile(file, r.payload);
494
- }
495
- return { type: "page", url };
496
- }
497
- }
498
- return { type: "asset", url };
499
- }
500
- };
501
- const injectAssets = (assets) => {
502
- for (const asset of assets) {
503
- const dirs = asset.dirs;
504
- for (const dir of dirs) {
505
- const dirFiles = fs.readdirSync(path.join(asset.relativeTo, dir));
506
- for (const file of dirFiles) {
507
- const pathFile = path.join(asset.relativeTo, dir, file);
508
- const ext = path.extname(pathFile);
509
- if (!!ext) {
510
- const pathRoute = path.posix.join("/", asset.prefix, dir, file);
511
- const pathRouteOverride = asset.override?.[pathRoute];
512
- server.route({
513
- path: pathRouteOverride || pathRoute,
514
- method: "get",
515
- options: {
516
- plugins: {
517
- generate: {
518
- isAsset: true,
519
- file: pathFile,
520
- type: asset.type,
521
- isRemane: !!pathRouteOverride
522
- }
523
- }
524
- },
525
- handler: {
526
- file: {
527
- path: pathFile,
528
- confine: false
529
- }
530
- }
531
- });
532
- } else {
533
- injectAssets([
534
- {
535
- dirs: [path.posix.join(dir, file)],
536
- prefix: asset.prefix,
537
- relativeTo: asset.relativeTo,
538
- override: asset.override,
539
- type: asset.type || file
540
- }
541
- ]);
542
- }
543
- }
544
- }
545
- }
546
- };
547
- const runGenerate = async ({
548
- assets = [],
549
- ommitAssets = [],
550
- virtualGenerate = false
551
- }) => {
552
- await server.methods.flow.pages();
553
- const _assetsApp = [...Object.values(server.app.flow.generate.folders)];
554
- const _assets = [...assets, ..._assetsApp];
555
- if (!virtualGenerate)
556
- injectAssets(_assets);
557
- const dirOutut = helpers.getPath(configs.outputDir ?? "build");
558
- const staticDirs = Object.keys(server.app.flow.generate.staticFolders).map((dir) => helpers.getPath(dir));
559
- const files = await getFlowPages();
560
- const pairFiles = R.toPairs(files);
561
- const ommit = ommitAssets;
562
- try {
563
- await fs.remove(dirOutut);
564
- for (const dirStatic of staticDirs)
565
- await fs.copy(dirStatic, dirOutut);
566
- for (const omitFile of ommit)
567
- await fs.remove(path.join(dirOutut, omitFile));
568
- const createFile = useCreateFile(virtualGenerate);
569
- const files2 = await Promise.all(pairFiles.map(async (v) => {
570
- return await createFile(dirOutut, ...v);
571
- }));
572
- const groups = R.groupBy((file) => {
573
- if (file.url.includes("images/"))
574
- return "image";
575
- else
576
- return (path.extname(file.url) || file.type).toLowerCase();
577
- }, files2);
578
- const _groups = {
579
- pages: 0,
580
- js: 0,
581
- css: 0,
582
- images: 0,
583
- fonts: 0,
584
- others: 0
585
- };
586
- for (const type in groups) {
587
- const cp = (ext) => ext === type;
588
- const qty = groups[type].length;
589
- if (type === "page")
590
- _groups.pages += qty;
591
- else if (type === ".js")
592
- _groups.js += qty;
593
- else if (type === ".css")
594
- _groups.css += qty;
595
- else if ([".gif", ".png", ".jpg", ".jpeg", "image"].find(cp))
596
- _groups.images += qty;
597
- else if ([".woff", ".eot", ".ttf"].find(cp))
598
- _groups.fonts += qty;
599
- else
600
- _groups.others += qty;
601
- }
602
- for (const type in _groups)
603
- logger.success("%i %s generated", _groups[type], type);
604
- const bf = server.app.flow.generate.postGenerate;
605
- if (Object.keys(bf).length) {
606
- logger.info("Post generate");
607
- }
608
- for (const key in bf)
609
- await bf[key]();
610
- } catch (error) {
611
- logger.error(error);
612
- await fs.remove(dirOutut);
613
- throw new Error(error);
614
- }
615
- };
616
- return { runGenerate };
650
+ type Decorate<T extends Record<string, any>> = { [K in keyof T as K extends string ? \`$\${K}\` : never]: T[K] }
651
+
652
+ type InjectionType<A extends Plugin> = A extends Plugin<infer T> ? Decorate<T> : unknown
653
+
654
+ type FlowAppInjections =
655
+ ${tsImports.map((p) => `InjectionType<typeof ${genDynamicImport(p, { wrapper: false })}.default>`).join(" &\n ")}
656
+
657
+ declare module '#app' {
658
+ interface FlowApp extends FlowAppInjections { }
659
+ }
660
+ // TODO: Insert extend types
661
+
662
+
663
+ export { }
664
+ `;
617
665
  }
618
666
  };
619
-
620
- const definePage = (pageOptions) => (levelOptions) => (configs) => {
621
- const pages = [];
622
- for (const locale in pageOptions.locales) {
623
- if (configs.locales.find((_locale) => _locale === locale)) {
624
- const singlePage = pageOptions.locales[locale];
625
- pages.push({ url: singlePage.url, locale });
626
- }
667
+ const adHocModules = ["auto-imports", "meta", "pages", "vite-client"];
668
+ const schemaTemplate = {
669
+ filename: "types/schema.d.ts",
670
+ getContents: ({ nuxt }) => {
671
+ const moduleInfo = nuxt.options._installedModules.map((m) => ({
672
+ ...m.meta || {},
673
+ importName: m.entryPath || m.meta?.name
674
+ })).filter((m) => m.configKey && m.name && !adHocModules.includes(m.name));
675
+ return [
676
+ "import { FlowModule } from '@monkeyplus/flow-schema'",
677
+ "declare module '@monkeyplus/flow-schema' {",
678
+ " interface FlowConfig {",
679
+ ...moduleInfo.filter(Boolean).map((meta) => ` [${genString(meta.configKey)}]?: typeof ${genDynamicImport(meta.importName, { wrapper: false })}.default extends FlowModule<infer O> ? Partial<O> : Record<string, any>`),
680
+ " }",
681
+ generateTypes(resolveSchema(Object.fromEntries(Object.entries(nuxt.options.runtimeConfig).filter(([key]) => key !== "public"))), {
682
+ interfaceName: "RuntimeConfig",
683
+ addExport: false,
684
+ addDefaults: false,
685
+ allowExtraKeys: false,
686
+ indentation: 2
687
+ }),
688
+ generateTypes(resolveSchema(nuxt.options.runtimeConfig.public), {
689
+ interfaceName: "PublicRuntimeConfig",
690
+ addExport: false,
691
+ addDefaults: false,
692
+ allowExtraKeys: false,
693
+ indentation: 2
694
+ }),
695
+ "}"
696
+ ].join("\n");
697
+ }
698
+ };
699
+ const publicPathTemplate = {
700
+ filename: "paths.mjs",
701
+ getContents({ nuxt }) {
702
+ return [
703
+ "import { joinURL } from 'ufo'",
704
+ !nuxt.options.dev && "import { useRuntimeConfig } from '#internal/nitro'",
705
+ nuxt.options.dev ? `const appConfig = ${JSON.stringify(nuxt.options.app)}` : "const appConfig = useRuntimeConfig().app",
706
+ "export const baseURL = () => appConfig.baseURL",
707
+ "export const buildAssetsDir = () => appConfig.buildAssetsDir",
708
+ "export const buildAssetsURL = (...path) => joinURL(publicAssetsURL(), buildAssetsDir(), ...path)",
709
+ "export const publicAssetsURL = (...path) => {",
710
+ " const publicBase = appConfig.cdnURL || appConfig.baseURL",
711
+ " return path.length ? joinURL(publicBase, ...path) : publicBase",
712
+ "}"
713
+ ].filter(Boolean).join("\n");
627
714
  }
628
- const infoPages = definePages({
629
- name: pageOptions.name,
630
- view: pageOptions.view,
631
- context: pageOptions.context,
632
- level: pageOptions.level,
633
- locales: pageOptions.locales
634
- })({
635
- language: configs.defaultLanguage,
636
- ubication: configs.defaultUbication,
637
- publicPath: configs.publicPath
638
- })(levelOptions).pages(pages);
639
- const {
640
- options: sharedOptions,
641
- rules: sharedRules,
642
- vhost: sharedVHost
643
- } = pageOptions;
644
- const sharedPre = sharedOptions?.pre || [];
645
- const routes = infoPages.map((page) => {
646
- const localPage = pageOptions.locales[page.locale];
647
- const route = {
648
- path: page.urlObject.path,
649
- method: "get",
650
- options: {
651
- app: {
652
- flow: page
653
- },
654
- plugins: {
655
- flow: {
656
- extensions: pageOptions.extensions || {},
657
- dynamic: localPage.dynamic
658
- }
659
- }
660
- },
661
- handler: {
662
- flow: {
663
- name: page.localeName,
664
- locale: page.locale,
665
- view: page.view
666
- }
667
- }
668
- };
669
- if (sharedRules || localPage.rules)
670
- route.rules = localPage.rules || sharedRules;
671
- if (sharedVHost || localPage.vhost)
672
- route.vhost = localPage.vhost || sharedVHost;
673
- if (sharedOptions || localPage.options) {
674
- const localOptions = localPage?.options || {};
675
- const localPre = localPage?.options?.pre || [];
676
- const pre = [...sharedPre, ...localPre];
677
- const options = R.mergeDeepRight(sharedOptions || {}, localOptions);
678
- route.options = R.mergeDeepRight(options, route.options);
679
- if (route.options && pre.length)
680
- route.options.pre = pre;
681
- }
682
- return route;
683
- });
684
- return routes;
685
715
  };
686
716
 
687
- const readPagesDir = (pathDir, folder) => {
688
- const p = fs$1.readdirSync(pathDir);
689
- return flatten(p.filter((f) => !f.includes(".js.map") && !f.includes(" copy.js.map") && !f.includes(" copy.js") && !f.includes(".model")).map((e) => {
690
- if (e.includes(".js") || e.includes(".ts")) {
691
- return {
692
- path: path.join(pathDir, e),
693
- prefix: folder
694
- };
695
- } else {
696
- return readPagesDir(path.join(pathDir, e), e);
717
+ const defaultTemplates = {
718
+ __proto__: null,
719
+ serverPluginTemplate: serverPluginTemplate,
720
+ pluginsDeclaration: pluginsDeclaration,
721
+ schemaTemplate: schemaTemplate,
722
+ publicPathTemplate: publicPathTemplate
723
+ };
724
+
725
+ function createApp(flow, options = {}) {
726
+ return defu(options, {
727
+ dir: flow.options.srcDir,
728
+ extensions: flow.options.extensions,
729
+ plugins: [],
730
+ templates: []
731
+ });
732
+ }
733
+ async function generateApp(flow, app) {
734
+ await resolveApp(flow, app);
735
+ app.templates = Object.values(defaultTemplates).concat(flow.options.build.templates);
736
+ await flow.callHook("app:templates", app);
737
+ app.templates = app.templates.map((tmpl) => normalizeTemplate(tmpl));
738
+ const templateContext = { utils: templateUtils, nuxt: flow, app };
739
+ await Promise.all(app.templates.map(async (template) => {
740
+ const contents = await compileTemplate(template, templateContext);
741
+ const fullPath = template.dst || resolve(flow.options.buildDir, template.filename);
742
+ flow.vfs[fullPath] = contents;
743
+ const aliasPath = `#build/${template.filename.replace(/\.\w+$/, "")}`;
744
+ flow.vfs[aliasPath] = contents;
745
+ if (process.platform === "win32")
746
+ flow.vfs[fullPath.replace(/\//g, "\\")] = contents;
747
+ if (template.write) {
748
+ await promises.mkdir(dirname(fullPath), { recursive: true });
749
+ await promises.writeFile(fullPath, contents, "utf8");
697
750
  }
698
751
  }));
699
- };
700
- const registerPages = async (server, dir) => {
701
- const dirPages = path.resolve(dir || "./pages");
702
- const listFiles = readPagesDir(dirPages);
703
- const listPrePages = [];
704
- for (const item of listFiles) {
752
+ await flow.callHook("app:templatesGenerated", app);
753
+ }
754
+ async function resolveApp(flow, app) {
755
+ app.plugins = [...flow.options.plugins.map(normalizePlugin)];
756
+ for (const config of flow.options._layers.map((layer) => layer.config)) {
757
+ app.plugins.push(...[
758
+ ...config.plugins || [],
759
+ ...await resolveFilesFlow(config.srcDir, [
760
+ "plugins/*.{ts,js,mjs,cjs,mts,cts}",
761
+ "plugins/*/index.*{ts,js,mjs,cjs,mts,cts}"
762
+ ])
763
+ ].map((plugin) => normalizePlugin(plugin)));
764
+ }
765
+ app.plugins = uniqueBy(app.plugins, "src");
766
+ await flow.callHook("app:resolve", app);
767
+ }
768
+ function uniqueBy(arr, key) {
769
+ const res = [];
770
+ const seen = /* @__PURE__ */ new Set();
771
+ for (const item of arr) {
772
+ if (seen.has(item[key]))
773
+ continue;
774
+ seen.add(item[key]);
775
+ res.push(item);
776
+ }
777
+ return res;
778
+ }
779
+
780
+ async function warmupViteServer(server, entries) {
781
+ const warmedUrls = /* @__PURE__ */ new Set();
782
+ const warmup = async (url) => {
783
+ if (warmedUrls.has(url))
784
+ return;
785
+ warmedUrls.add(url);
705
786
  try {
706
- const module = require(item.path)?.default;
707
- if (typeof module === "function") {
708
- listPrePages.push(module());
709
- } else if (typeof module === "object") {
710
- if (Array.isArray(module)) {
711
- module.forEach((el) => listPrePages.push(el()));
712
- } else {
713
- const _pages = await module.pages({ server });
714
- if (Array.isArray(_pages))
715
- _pages.forEach((page) => listPrePages.push(definePage(page)()));
716
- else
717
- listPrePages.push(definePage(_pages)());
718
- }
719
- }
720
- } catch (details) {
721
- logger$1.error(details);
787
+ await server.transformRequest(url);
788
+ } catch (e) {
789
+ logger.debug("Warmup for %s failed with: %s", url, e);
722
790
  }
723
- }
724
- for (const page of listPrePages)
725
- await server.flow.addPage(page);
791
+ const mod = await server.moduleGraph.getModuleByUrl(url);
792
+ const deps = Array.from(mod?.importedModules || []);
793
+ await Promise.all(deps.map((m) => warmup(m.url.replace("/@id/__x00__", "\0"))));
794
+ };
795
+ await Promise.all(entries.map((entry) => warmup(entry)));
796
+ }
797
+
798
+ function cacheDirPlugin(rootDir, name) {
799
+ const optimizeCacheDir = resolve(rootDir, "node_modules/.cache/vite", name);
800
+ return {
801
+ name: "flow:cache-dir",
802
+ configResolved(resolvedConfig) {
803
+ resolvedConfig.optimizeCacheDir = optimizeCacheDir;
804
+ }
805
+ };
806
+ }
807
+
808
+ const wpfs = {
809
+ ...fse,
810
+ join
726
811
  };
727
812
 
728
- const RunMethods = {
729
- register: (server) => {
730
- const { flow: state } = server.app;
731
- const { configs: config } = server.plugins.flow;
732
- const registerRoute = (route) => {
733
- const _routes = server.table();
734
- const _route = _routes.find((v) => v.path === route.path);
735
- if (_route)
736
- logger$1.warn(`Duplicate route, the route ${route.path} already exists`);
737
- else
738
- server.route(route);
813
+ function uniq(arr) {
814
+ return Array.from(new Set(arr));
815
+ }
816
+ const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
817
+ function isCSS(file) {
818
+ return IS_CSS_RE.test(file);
819
+ }
820
+ function hashId(id) {
821
+ return `$id_${hash(id)}`;
822
+ }
823
+ function hash(input, length = 8) {
824
+ return createHash("sha256").update(input).digest("hex").slice(0, length);
825
+ }
826
+ function readDirRecursively(dir) {
827
+ return readdirSync(dir).reduce((files, file) => {
828
+ const name = join(dir, file);
829
+ const isDirectory2 = statSync(name).isDirectory();
830
+ return isDirectory2 ? [...files, ...readDirRecursively(name)] : [...files, name];
831
+ }, []);
832
+ }
833
+ async function isDirectory(path) {
834
+ try {
835
+ return (await promises.stat(path)).isDirectory();
836
+ } catch (_err) {
837
+ return false;
838
+ }
839
+ }
840
+
841
+ function isExternal(opts, id) {
842
+ const ssrConfig = opts.viteServer.config.ssr;
843
+ const externalOpts = {
844
+ inline: [
845
+ /virtual:/,
846
+ /\.ts$/,
847
+ ...ExternalsDefaults.inline,
848
+ ...ssrConfig.noExternal
849
+ ],
850
+ external: [
851
+ ...ssrConfig.external,
852
+ /node_modules/
853
+ ],
854
+ resolve: {
855
+ type: "module",
856
+ extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
857
+ }
858
+ };
859
+ return isExternal$1(id, opts.viteServer.config.root, externalOpts);
860
+ }
861
+ async function transformRequest(opts, id) {
862
+ if (id && id.startsWith("/@id/__x00__"))
863
+ id = `\0${id.slice("/@id/__x00__".length)}`;
864
+ if (id && id.startsWith("/@id/"))
865
+ id = id.slice("/@id/".length);
866
+ if (id && id.startsWith("/@fs/")) {
867
+ id = id.slice("/@fs".length);
868
+ if (id.match(/^\/\w:/))
869
+ id = id.slice(1);
870
+ } else if (!id.includes("entry") && id.startsWith("/")) {
871
+ const resolvedPath = resolve(opts.viteServer.config.root, `.${id}`);
872
+ if (existsSync(resolvedPath))
873
+ id = resolvedPath;
874
+ }
875
+ const withoutVersionQuery = id.replace(/\?v=\w+$/, "");
876
+ if (await isExternal(opts, withoutVersionQuery)) {
877
+ const path = builtinModules.includes(withoutVersionQuery.split("node:").pop()) ? withoutVersionQuery : pathToFileURL(withoutVersionQuery).href;
878
+ return {
879
+ code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
880
+ ${genDynamicImport(path, { wrapper: false })}
881
+ .then(r => {
882
+ if (r.default && r.default.__esModule)
883
+ r = r.default
884
+ exports.default = r.default
885
+ ssrExportAll(r)
886
+ })
887
+ .catch(e => {
888
+ console.error(e)
889
+ throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
890
+ })`,
891
+ deps: [],
892
+ dynamicDeps: []
739
893
  };
740
- const addPage = (_page, extra) => {
741
- const registerPages2 = (_pages2) => {
742
- for (const _route of _pages2) {
743
- if (state.routes[_route.path])
744
- logger$1.warn("The route %s alredy exist", _route.path);
745
- else
746
- state.routes[_route.path] = _route;
747
- }
748
- };
749
- let _pages;
750
- if (typeof _page === "function") {
751
- _pages = _page(config);
752
- registerPages2(_pages);
753
- } else {
754
- _pages = definePage(_page)()(config);
755
- registerPages2(_pages);
894
+ }
895
+ const res = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
896
+ console.warn(`[SSR] Error transforming ${id}:`, err);
897
+ }) || { code: "", map: {}, deps: [], dynamicDeps: [] };
898
+ const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
899
+ ${res.code || "/* empty */"};
900
+ }`;
901
+ return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
902
+ }
903
+ async function transformRequestRecursive(opts, id, parent = "<entry>", chunks = {}) {
904
+ if (chunks[id]) {
905
+ chunks[id].parents.push(parent);
906
+ return;
907
+ }
908
+ const res = await transformRequest(opts, id);
909
+ const deps = uniq([...res.deps, ...res.dynamicDeps]);
910
+ chunks[id] = {
911
+ id,
912
+ code: res.code,
913
+ deps,
914
+ parents: [parent]
915
+ };
916
+ for (const dep of deps)
917
+ await transformRequestRecursive(opts, dep, id, chunks);
918
+ return Object.values(chunks);
919
+ }
920
+ async function bundleRequest(opts, entryURL) {
921
+ const chunks = await transformRequestRecursive(opts, entryURL);
922
+ const listIds = (ids) => ids.map((id) => `// - ${id} (${hashId(id)})`).join("\n");
923
+ const chunksCode = chunks.map((chunk) => `
924
+ // --------------------
925
+ // Request: ${chunk.id}
926
+ // Parents:
927
+ ${listIds(chunk.parents)}
928
+ // Dependencies:
929
+ ${listIds(chunk.deps)}
930
+ // --------------------
931
+ const ${hashId(chunk.id)} = ${chunk.code}
932
+ `).join("\n");
933
+ const manifestCode = `const __modules__ = ${genObjectFromRawEntries(chunks.map((chunk) => [chunk.id, hashId(chunk.id)]))}`;
934
+ const ssrModuleLoader = `
935
+ const __pendingModules__ = new Map()
936
+ const __pendingImports__ = new Map()
937
+ const __ssrContext__ = { global: globalThis }
938
+
939
+ function __ssrLoadModule__(url, urlStack = []) {
940
+ const pendingModule = __pendingModules__.get(url)
941
+ if (pendingModule) { return pendingModule }
942
+ const modulePromise = __instantiateModule__(url, urlStack)
943
+ __pendingModules__.set(url, modulePromise)
944
+ modulePromise.catch(() => { __pendingModules__.delete(url) })
945
+ .finally(() => { __pendingModules__.delete(url) })
946
+ return modulePromise
947
+ }
948
+
949
+ async function __instantiateModule__(url, urlStack) {
950
+ const mod = __modules__[url]
951
+ if (mod.stubModule) { return mod.stubModule }
952
+ const stubModule = { [Symbol.toStringTag]: 'Module' }
953
+ Object.defineProperty(stubModule, '__esModule', { value: true })
954
+ mod.stubModule = stubModule
955
+ // https://vitejs.dev/guide/api-hmr.html
956
+ const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
957
+ urlStack = urlStack.concat(url)
958
+ const isCircular = url => urlStack.includes(url)
959
+ const pendingDeps = []
960
+ const ssrImport = async (dep) => {
961
+ // TODO: Handle externals if dep[0] !== '.' | '/'
962
+ if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
963
+ pendingDeps.push(dep)
964
+ if (pendingDeps.length === 1) {
965
+ __pendingImports__.set(url, pendingDeps)
756
966
  }
757
- };
758
- const init = async () => {
759
- await registerPages(server);
760
- const pages = server.app.flow.routes;
761
- for (const key in pages) {
762
- const page = pages[key];
763
- registerRoute(page);
967
+ await __ssrLoadModule__(dep, urlStack)
968
+ if (pendingDeps.length === 1) {
969
+ __pendingImports__.delete(url)
970
+ } else {
971
+ pendingDeps.splice(pendingDeps.indexOf(dep), 1)
764
972
  }
765
- for (const key in state.extensions) {
766
- const ext = state.extensions[key];
767
- if (ext.initMethod)
768
- await ext.initMethod();
973
+ }
974
+ return __modules__[dep].stubModule
975
+ }
976
+ function ssrDynamicImport (dep) {
977
+ // TODO: Handle dynamic import starting with . relative to url
978
+ return ssrImport(dep)
979
+ }
980
+
981
+ function ssrExportAll(sourceModule) {
982
+ for (const key in sourceModule) {
983
+ if (key !== 'default') {
984
+ try {
985
+ Object.defineProperty(stubModule, key, {
986
+ enumerable: true,
987
+ configurable: true,
988
+ get() { return sourceModule[key] }
989
+ })
990
+ } catch (_err) { }
769
991
  }
770
- logger$1.debug("Register %s pages", `${Object.values(pages).length}`);
771
- };
772
- return { init, addPage };
992
+ }
773
993
  }
774
- };
775
994
 
776
- const createHmr = (options) => {
777
- const state = {
778
- dir: options.relativeTo || "",
779
- dirs: options.dirs || [],
780
- extensions: options.extensions || ["eta"]
995
+ const cjsModule = {
996
+ get exports () {
997
+ return stubModule.default
998
+ },
999
+ set exports (v) {
1000
+ stubModule.default = v
1001
+ },
1002
+ }
1003
+
1004
+ await mod(
1005
+ __ssrContext__.global,
1006
+ cjsModule,
1007
+ stubModule.default,
1008
+ stubModule,
1009
+ importMeta,
1010
+ ssrImport,
1011
+ ssrDynamicImport,
1012
+ ssrExportAll
1013
+ )
1014
+
1015
+ return stubModule
1016
+ }
1017
+ `;
1018
+ const code = [
1019
+ chunksCode,
1020
+ manifestCode,
1021
+ ssrModuleLoader,
1022
+ `export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
1023
+ ].join("\n\n");
1024
+ return {
1025
+ code,
1026
+ ids: chunks.map((i) => i.id)
781
1027
  };
782
- let watcher;
783
- const hooks = createHooks();
784
- const watch = () => {
785
- watcher = chokidar.watch(state.dirs.map((d) => path.join(d, `**/*.(${state.extensions.join("|")})`)), {
786
- cwd: state.dir,
787
- ignoreInitial: true,
788
- ignored: "node_modules/**/*"
789
- }).on("change", (path2) => {
790
- logger$1.info("Changed file", path2);
791
- hooks.callHook("page:refresh");
792
- });
1028
+ }
1029
+
1030
+ async function writeManifest(ctx, extraEntries = []) {
1031
+ const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
1032
+ const serverDist = resolve(ctx.flow.options.buildDir, "dist/server");
1033
+ const entries = [
1034
+ "@vite/client",
1035
+ "entry.mjs",
1036
+ ...extraEntries
1037
+ ];
1038
+ const devClientManifest = {
1039
+ publicPath: joinURL(ctx.flow.options.app.baseURL, ctx.flow.options.app.buildAssetsDir),
1040
+ all: entries,
1041
+ initial: entries,
1042
+ async: [],
1043
+ modules: {}
793
1044
  };
794
- watch();
795
- return { watcher, hooks };
796
- };
1045
+ const clientManifest = ctx.flow.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
1046
+ await fse.mkdirp(serverDist);
1047
+ await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(clientManifest, null, 2), "utf8");
1048
+ await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), `export default ${JSON.stringify(clientManifest, null, 2)}`, "utf8");
1049
+ }
797
1050
 
798
- const RegisterCommon = async (server, configs) => {
799
- server.route({
800
- method: "GET",
801
- path: "/{param*}",
802
- options: {
803
- ext: {
804
- onPreResponse: {
805
- method: (req, h) => {
806
- return h.continue;
807
- }
1051
+ const buildServer = async (ctx) => {
1052
+ const serverConfig = vite.mergeConfig(ctx.config, {
1053
+ configFile: false,
1054
+ define: {
1055
+ "process.server": true,
1056
+ "typeof window": '"undefined"',
1057
+ "typeof document": '"undefined"',
1058
+ "typeof navigator": '"undefined"',
1059
+ "typeof location": '"undefined"',
1060
+ "typeof XMLHttpRequest": '"undefined"'
1061
+ },
1062
+ ssr: {
1063
+ noExternal: [
1064
+ ...ctx.flow.options.build.transpile,
1065
+ /\/esm\/.*\.js$/,
1066
+ /\.(es|esm|esm-browser|esm-bundler).js$/,
1067
+ "/__vue-jsx",
1068
+ "#app",
1069
+ /(nuxt|nuxt3)\/(dist|src|app)/,
1070
+ /@nuxt\/nitro\/(dist|src)/
1071
+ ]
1072
+ },
1073
+ build: {
1074
+ outDir: resolve(ctx.flow.options.buildDir, "dist/server"),
1075
+ manifest: true,
1076
+ rollupOptions: {
1077
+ external: ["#internal/nitro"],
1078
+ output: {
1079
+ entryFileNames: "server.mjs",
1080
+ preferConst: true,
1081
+ format: "module"
1082
+ },
1083
+ onwarn(warning, rollupWarn) {
1084
+ if (!["UNUSED_EXTERNAL_IMPORT"].includes(warning.code))
1085
+ rollupWarn(warning);
808
1086
  }
809
1087
  }
810
1088
  },
811
- handler: {
812
- directory: {
813
- path: configs.staticDir,
814
- listing: true
1089
+ server: {
1090
+ preTransformRequests: false,
1091
+ cors: true
1092
+ },
1093
+ plugins: [
1094
+ cacheDirPlugin(ctx.flow.options.rootDir, "server")
1095
+ ]
1096
+ });
1097
+ await ctx.flow.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
1098
+ ctx.flow.hook("nitro:build:before", async () => {
1099
+ if (ctx.flow.options.dev)
1100
+ return;
1101
+ const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
1102
+ const publicDir = join(ctx.flow.options.srcDir, ctx.flow.options.dir.public);
1103
+ let publicFiles = [];
1104
+ if (await isDirectory(publicDir)) {
1105
+ publicFiles = readDirRecursively(publicDir).map((r) => r.replace(publicDir, ""));
1106
+ for (const file of publicFiles) {
1107
+ try {
1108
+ fse.rmSync(join(clientDist, file));
1109
+ } catch {
1110
+ }
1111
+ }
1112
+ }
1113
+ if (await isDirectory(clientDist)) {
1114
+ const nestedAssetsPath = withoutTrailingSlash(join(clientDist, ctx.flow.options.app.buildAssetsDir));
1115
+ if (await isDirectory(nestedAssetsPath)) {
1116
+ await fse.copy(nestedAssetsPath, clientDist, { recursive: true });
1117
+ await fse.remove(nestedAssetsPath);
815
1118
  }
816
1119
  }
817
1120
  });
818
- if (!isGenerate) {
819
- const hmr = createHmr({
820
- dirs: configs.hmr.dirs,
821
- relativeTo: configs.relativeTo
822
- });
823
- hmr.hooks.hook("page:refresh", () => {
824
- setTimeout(() => {
825
- logger$1.info("Refresh page");
826
- server.publish("/_flow/hmr", { reload: true });
827
- }, 40);
828
- });
829
- server.subscription("/_flow/hmr");
830
- server.route({
831
- path: "/_flow/hmr/client.js",
832
- method: "get",
833
- handler: {
834
- file: {
835
- path: join(__dirname, "../resources/client"),
836
- confine: false
837
- }
1121
+ const onBuild = () => ctx.flow.callHook("build:resources", wpfs);
1122
+ if (!ctx.flow.options.dev) {
1123
+ const start = Date.now();
1124
+ logger.info("Building server...");
1125
+ await vite.build(serverConfig);
1126
+ await onBuild();
1127
+ logger.success(`Server built in ${Date.now() - start}ms`);
1128
+ return;
1129
+ }
1130
+ const viteServer = await vite.createServer(serverConfig);
1131
+ ctx.ssrServer = viteServer;
1132
+ await ctx.flow.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
1133
+ ctx.flow.hook("close", () => viteServer.close());
1134
+ await viteServer.pluginContainer.buildStart({});
1135
+ const _doBuild = async () => {
1136
+ const start = Date.now();
1137
+ const { code, ids } = await bundleRequest({ viteServer }, resolve(ctx.flow.options.appDir, "entry"));
1138
+ await fse.ensureFile(resolve(ctx.flow.options.buildDir, "dist/server/server.mjs"));
1139
+ await fse.writeFile(resolve(ctx.flow.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
1140
+ await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
1141
+ const time = Date.now() - start;
1142
+ logger.success(`Vite server built in ${time}ms`);
1143
+ await onBuild();
1144
+ ctx.flow.callHook("bundler:change", {});
1145
+ };
1146
+ const doBuild = debounce(_doBuild);
1147
+ await _doBuild();
1148
+ viteServer.watcher.on("all", (_event, file) => {
1149
+ file = normalize(file);
1150
+ if (file.indexOf(ctx.flow.options.buildDir) === 0)
1151
+ return;
1152
+ doBuild();
1153
+ });
1154
+ ctx.flow.hook("app:templatesGenerated", () => doBuild());
1155
+ };
1156
+
1157
+ const PREFIX = "virtual:";
1158
+ function virtual(vfs) {
1159
+ const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
1160
+ const resolveWithExt = (id) => {
1161
+ for (const ext of extensions) {
1162
+ const rId = id + ext;
1163
+ if (rId in vfs)
1164
+ return rId;
1165
+ }
1166
+ return null;
1167
+ };
1168
+ return {
1169
+ name: "virtual",
1170
+ resolveId(id, importer) {
1171
+ if (process.platform === "win32" && isAbsolute(id)) {
1172
+ id = resolve(id);
838
1173
  }
839
- });
840
- server.route({
841
- path: "/_flow/hmr/connect.js",
842
- method: "get",
843
- handler: {
844
- file: {
845
- path: join(__dirname, "../resources/ws.js"),
846
- confine: false
847
- }
1174
+ const resolvedId = resolveWithExt(id);
1175
+ if (resolvedId)
1176
+ return PREFIX + resolvedId;
1177
+ if (importer && !isAbsolute(id)) {
1178
+ const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
1179
+ const importedDir = dirname(importerNoPrefix);
1180
+ const resolved = resolveWithExt(join(importedDir, id));
1181
+ if (resolved)
1182
+ return PREFIX + resolved;
848
1183
  }
849
- });
850
- logger$1.debug("Enable development routes");
851
- server.route({
852
- path: "/_flow/sitemap",
853
- method: "get",
854
- handler: async () => {
855
- const { pages: getPages } = server.methods.flow;
856
- const urls = await getPages();
857
- const pages = Object.values(urls).map((p) => dissoc("context", p));
858
- return {
859
- total: pages.length,
860
- pages
861
- };
1184
+ return null;
1185
+ },
1186
+ load(id) {
1187
+ if (!id.startsWith(PREFIX))
1188
+ return null;
1189
+ const idNoPrefix = id.slice(PREFIX.length);
1190
+ return {
1191
+ code: vfs[idNoPrefix],
1192
+ map: null
1193
+ };
1194
+ }
1195
+ };
1196
+ }
1197
+
1198
+ const VITE_ASSET_RE = /^export default ["'](__VITE_ASSET.*)["']$/;
1199
+ const DynamicBasePlugin = createUnplugin((options = {}) => {
1200
+ return {
1201
+ name: "nuxt:dynamic-base-path",
1202
+ resolveId(id) {
1203
+ if (id.startsWith("/__NUXT_BASE__"))
1204
+ return id.replace("/__NUXT_BASE__", "");
1205
+ if (id === "#internal/nitro")
1206
+ return "#internal/nitro";
1207
+ return null;
1208
+ },
1209
+ enforce: "post",
1210
+ transform(code, id) {
1211
+ const s = new MagicString(code);
1212
+ if (options.globalPublicPath && id.includes("paths.mjs") && code.includes("const appConfig = "))
1213
+ s.append(`${options.globalPublicPath} = buildAssetsURL();
1214
+ `);
1215
+ const assetId = code.match(VITE_ASSET_RE);
1216
+ if (assetId) {
1217
+ s.overwrite(0, code.length, [
1218
+ "import { buildAssetsURL } from '#build/paths.mjs';",
1219
+ `export default buildAssetsURL("${assetId[1]}".replace("/__NUXT_BASE__", ""));`
1220
+ ].join("\n"));
862
1221
  }
863
- });
864
- server.route({
865
- path: "/_flow/locales",
866
- method: "get",
867
- handler: async (req) => {
868
- const { pages: getPages } = server.methods.flow;
869
- const urls = await getPages();
870
- const pages = Object.values(urls).map((p) => dissoc("context", p));
871
- const locales = groupBy((page) => page.locale, pages);
1222
+ if (!id.includes("paths.mjs") && code.includes("NUXT_BASE") && !code.includes("import { publicAssetsURL as __publicAssetsURL }"))
1223
+ s.prepend("import { publicAssetsURL as __publicAssetsURL } from '#build/paths.mjs';\n");
1224
+ if (id === "vite/preload-helper") {
1225
+ s.prepend("import { buildAssetsDir } from '#build/paths.mjs';\n");
1226
+ s.replace(/const base = ['"]\/__NUXT_BASE__\/['"]/, "const base = buildAssetsDir()");
1227
+ }
1228
+ s.replace(/from *['"]\/__NUXT_BASE__(\/[^'"]*)['"]/g, 'from "$1"');
1229
+ const delimiterRE = /(?<!(const base = |from *))(`([^`]*)\/__NUXT_BASE__\/([^`]*)`|'([^']*)\/__NUXT_BASE__\/([^']*)'|"([^"]*)\/__NUXT_BASE__\/([^"]*)")/g;
1230
+ s.replace(delimiterRE, (r) => `\`${r.replace(/\/__NUXT_BASE__\//g, "${__publicAssetsURL()}").slice(1, -1)}\``);
1231
+ if (s.hasChanged()) {
872
1232
  return {
873
- locales: req.server.plugins.flow.configs.locales,
874
- all: mapObjIndexed((l) => {
875
- return {
876
- total: l.length,
877
- pages: l
878
- };
879
- }, locales)
1233
+ code: s.toString(),
1234
+ map: options.sourcemap && s.generateMap({ source: id, includeContent: true })
880
1235
  };
881
1236
  }
882
- });
883
- server.route({
884
- path: "/_flow/configs",
885
- method: "get",
886
- handler: (req) => {
887
- return req.server.plugins.flow.configs;
888
- }
889
- });
890
- }
891
- const HMR = {
892
- head: ' <script src="/_flow/hmr/client.js"><\/script>',
893
- body: ' <script src="/_flow/hmr/connect.js"><\/script>'
894
- };
895
- server.ext("onPreHandler", async (req, h) => {
896
- if (req.route.settings.plugins?.generate === ".html") {
897
- const { global } = req.plugins.flow;
898
- Object.assign(global, {
899
- hmr: isProduction || isGenerate ? { head: "", body: "" } : HMR
900
- });
901
1237
  }
902
- return h.continue;
903
- });
904
- };
1238
+ };
1239
+ });
905
1240
 
906
- const plugin = {
907
- pkg,
908
- dependencies,
909
- register: async (server, _options) => {
910
- const config = getConfigs(server, _options);
911
- server.expose("configs", config);
912
- const state = {
913
- pages: { statics: {}, redirects: {}, dynamics: {}, all: {} },
914
- truncates: {},
915
- extensions: {},
916
- generate: {
917
- folders: {},
918
- staticFolders: {},
919
- postGenerate: {},
920
- beforePackage: {}
1241
+ async function bundleVite(flow) {
1242
+ const hmrPortDefault = 24678;
1243
+ const hmrPort = await getPort({
1244
+ port: hmrPortDefault,
1245
+ ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i)
1246
+ });
1247
+ const ctx = {
1248
+ nuxt: flow,
1249
+ flow,
1250
+ config: vite.mergeConfig({
1251
+ resolve: {
1252
+ alias: {
1253
+ ...flow.options.alias,
1254
+ "#app": flow.options.appDir,
1255
+ "#build/plugins": resolve(flow.options.buildDir, "plugins/server"),
1256
+ "#build": flow.options.buildDir,
1257
+ "/entry.mjs": resolve(flow.options.appDir, "entry")
1258
+ }
921
1259
  },
922
- engines: {},
923
- routes: {},
924
- plugins: {}
925
- };
926
- server.app.flow = state;
927
- const { serverInfo } = ServerInfo.register(server);
928
- const serverDecorate = {
929
- serverInfo
930
- };
931
- const helpers = {
932
- getPath: (...paths) => path.join(config.relativeTo, ...paths),
933
- addRedirect: (key, urlPath) => {
934
- state.pages.redirects[key] = urlPath;
1260
+ optimizeDeps: {
1261
+ entries: [
1262
+ resolve(flow.options.appDir, "entry.ts")
1263
+ ],
1264
+ include: []
935
1265
  },
936
- addStaticPage: (key, url) => {
937
- if (isDinamyc(url.url))
938
- return void 0;
939
- if (state.pages.statics[key]) {
940
- logger$1.warn("The namePage %s already exist", state.pages.statics[key]);
941
- } else {
942
- state.pages.statics[key] = url;
1266
+ build: {
1267
+ rollupOptions: {
1268
+ output: { sanitizeFileName: sanitizeFilePath },
1269
+ input: resolve(flow.options.appDir, "entry")
943
1270
  }
944
1271
  },
945
- addDynamicPages: (key, method) => {
946
- if (state.pages.dynamics[key])
947
- logger$1.warn("The dynamdcPages %s already exist", key);
948
- else
949
- state.pages.dynamics[key] = method;
950
- }
951
- };
952
- server.expose("helpers", helpers);
953
- server.method("flow.pages", async () => {
954
- const pages = {
955
- ...state.pages.statics
956
- };
957
- for (const key in state.pages.dynamics) {
958
- if (Object.prototype.hasOwnProperty.call(state.pages.dynamics, key)) {
959
- const element = state.pages.dynamics[key];
960
- const dynamicPages = await element();
961
- for (const keyPage in dynamicPages) {
962
- if (Object.prototype.hasOwnProperty.call(dynamicPages, keyPage)) {
963
- const page = dynamicPages[keyPage];
964
- if (!pages[keyPage])
965
- pages[keyPage] = page;
966
- else
967
- logger$1.warn("Duplicate page %s", keyPage);
968
- }
969
- }
1272
+ plugins: [
1273
+ replace({
1274
+ ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
1275
+ preventAssignment: true
1276
+ }),
1277
+ virtual(flow.vfs),
1278
+ DynamicBasePlugin.vite({ sourcemap: flow.options.sourcemap })
1279
+ ],
1280
+ server: {
1281
+ watch: {
1282
+ ignored: isIgnoredFlow
1283
+ },
1284
+ hmr: {
1285
+ protocol: "ws",
1286
+ clientPort: hmrPort,
1287
+ port: hmrPort
1288
+ },
1289
+ fs: {
1290
+ allow: [
1291
+ flow.options.appDir
1292
+ ]
970
1293
  }
971
1294
  }
972
- state.pages.all = pages;
973
- return pages;
974
- }, {
975
- cache: { expiresIn: 3e3, generateTimeout: 8e3 }
1295
+ }, flow.options.vite)
1296
+ };
1297
+ await flow.callHook("vite:extend", ctx);
1298
+ flow.hook("vite:serverCreated", (server) => {
1299
+ ctx.nuxt.hook("app:templatesGenerated", () => {
1300
+ for (const [id, mod] of server.moduleGraph.idToModuleMap) {
1301
+ if (id.startsWith("\0virtual:"))
1302
+ server.moduleGraph.invalidateModule(mod);
1303
+ }
976
1304
  });
977
- server.expose("pages", () => {
978
- return state.pages.all;
1305
+ const start = Date.now();
1306
+ warmupViteServer(server, ["/entry.mjs"]).then(() => logger.info(`Vite server warmed up in ${Date.now() - start}ms`)).catch(logger.error);
1307
+ });
1308
+ await buildServer(ctx);
1309
+ }
1310
+
1311
+ async function build(flow) {
1312
+ const app = createApp(flow);
1313
+ const generateApp$1 = debounce(() => generateApp(flow, app), void 0, { leading: true });
1314
+ await generateApp$1();
1315
+ if (flow.options.dev) {
1316
+ watch(flow);
1317
+ flow.hook("builder:watch", async (event, path) => {
1318
+ if (event !== "change" && /app|error|plugins/i.test(path))
1319
+ await generateApp$1();
979
1320
  });
980
- server.decorate("server", "flow", serverDecorate);
981
- Decorators.register(server);
982
- LifeCircle.register(server);
983
- const { runGenerate } = useGenerator.register(server);
984
- serverDecorate.runGenerate = runGenerate;
985
- const { addPage, init } = RunMethods.register(server);
986
- serverDecorate.addPage = addPage;
987
- serverDecorate.init = init;
988
- serverDecorate.prepagePackage = async () => {
989
- for (const key in state.generate.beforePackage)
990
- await state.generate.beforePackage[key]();
991
- };
992
- serverDecorate.assignPluginOptions = (realm, options = {}, d = {}, _context) => {
993
- const key = realm.plugin.replace("@monkeyplus/", "").replace("flow-", "");
994
- const baseOptions = applyToDefaults(d, options);
995
- const { plugins } = config;
996
- if (plugins[key] && Object.values(plugins[key])) {
997
- if (typeof plugins[key] === "boolean") {
998
- try {
999
- const module = require(path.resolve("./extensions", key))?.default;
1000
- if (typeof module === "function") {
1001
- const promise = module({ server, ..._context });
1002
- const isPromise = !!promise && typeof promise.then === "function";
1003
- if (isPromise) {
1004
- return promise.then((opts2) => {
1005
- const _opts = applyToDefaults(baseOptions, opts2 || {});
1006
- Object.assign(plugins, { [key]: _opts });
1007
- return _opts;
1008
- });
1009
- }
1010
- Object.assign(plugins, { [key]: promise });
1011
- return promise;
1012
- }
1013
- const opts = applyToDefaults(baseOptions, module || {});
1014
- Object.assign(plugins, { [key]: opts });
1015
- return opts;
1016
- } catch (error) {
1017
- logger$1.error("Error in load extension: %s", key);
1018
- return baseOptions;
1019
- }
1020
- } else {
1021
- const opts = applyToDefaults(baseOptions, plugins[key]);
1022
- Object.assign(plugins, { [key]: opts });
1023
- return opts;
1024
- }
1025
- } else {
1026
- Object.assign(plugins, { [key]: baseOptions });
1027
- return baseOptions;
1028
- }
1029
- };
1030
- await RegisterCommon(server, config);
1321
+ flow.hook("builder:generateApp", generateApp$1);
1031
1322
  }
1032
- };
1323
+ await flow.callHook("build:before", { flow }, flow.options.build);
1324
+ if (!flow.options._prepare) {
1325
+ await bundle(flow);
1326
+ await flow.callHook("build:done", { flow });
1327
+ }
1328
+ if (!flow.options.dev)
1329
+ await flow.callHook("close", flow);
1330
+ }
1331
+ function watch(flow) {
1332
+ const watcher = chokidar.watch(flow.options.srcDir, {
1333
+ ...flow.options.watchers.chokidar,
1334
+ cwd: flow.options.srcDir,
1335
+ ignoreInitial: true,
1336
+ ignored: [
1337
+ ".flow",
1338
+ "node_modules"
1339
+ ]
1340
+ });
1341
+ const watchHook = debounce((event, path) => flow.callHook("builder:watch", event, normalize(path)));
1342
+ watcher.on("all", watchHook);
1343
+ flow.hook("close", () => watcher.close());
1344
+ return watcher;
1345
+ }
1346
+ async function bundle(nuxt) {
1347
+ try {
1348
+ return bundleVite(nuxt);
1349
+ } catch (error) {
1350
+ await nuxt.callHook("build:error", error);
1351
+ throw error;
1352
+ }
1353
+ }
1033
1354
 
1034
- export { definePage, plugin };
1355
+ export { build, createFlow, defineFlowConfig, loadFlow };