@monkeyplus/flow 5.0.0-rc.85 → 5.0.0-rc.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import type { RuntimeConfig } from '@monkeyplus/flow-schema';
2
+ declare const _default: (ctx?: RuntimeConfig) => Promise<any>;
3
+ export default _default;
@@ -0,0 +1 @@
1
+ export default (ctx) => import("#app/entry").then((m) => m.default(ctx));
@@ -0,0 +1,245 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { existsSync } from 'node:fs';
3
+ import { builtinModules } from 'node:module';
4
+ import { resolve, normalize, isAbsolute } from 'pathe';
5
+ import { genObjectFromRawEntries, genDynamicImport } from 'knitwork';
6
+ import fse from 'fs-extra';
7
+ import { debounce } from 'perfect-debounce';
8
+ import { isIgnored, 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';
15
+
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"
32
+ }
33
+ };
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
+ }
45
+ 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");
50
+ }
51
+
52
+ async function transformRequest(opts, id) {
53
+ if (id && id.startsWith("/@id/__x00__"))
54
+ id = `\0${id.slice("/@id/__x00__".length)}`;
55
+ if (id && id.startsWith("/@id/"))
56
+ id = id.slice("/@id/".length);
57
+ if (id && !id.startsWith("/@fs/") && id.startsWith("/")) {
58
+ const resolvedPath = resolve(opts.viteServer.config.root, `.${id}`);
59
+ if (existsSync(resolvedPath))
60
+ id = resolvedPath;
61
+ }
62
+ id = id.replace(/^\/?(?=\w:)/, "/@fs/");
63
+ const externalId = id.replace(/\?v=\w+$|^\/@fs/, "");
64
+ if (await opts.isExternal(externalId)) {
65
+ const path = builtinModules.includes(externalId.split("node:").pop()) ? externalId : isAbsolute(externalId) ? pathToFileURL(externalId).href : externalId;
66
+ return {
67
+ code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
68
+ ${genDynamicImport(path, { wrapper: false })}
69
+ .then(r => {
70
+ if (r.default && r.default.__esModule)
71
+ r = r.default
72
+ exports.default = r.default
73
+ ssrExportAll(r)
74
+ })
75
+ .catch(e => {
76
+ console.error(e)
77
+ throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
78
+ })`,
79
+ deps: [],
80
+ dynamicDeps: []
81
+ };
82
+ }
83
+ const res = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
84
+ console.warn(`[SSR] Error transforming ${id}:`, err);
85
+ }) || { code: "", map: {}, deps: [], dynamicDeps: [] };
86
+ const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
87
+ ${res.code || "/* empty */"};
88
+ }`;
89
+ return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
90
+ }
91
+ async function transformRequestRecursive(opts, id, parent = "<entry>", chunks = {}) {
92
+ if (chunks[id]) {
93
+ chunks[id].parents.push(parent);
94
+ return;
95
+ }
96
+ const res = await transformRequest(opts, id);
97
+ const deps = uniq([...res.deps, ...res.dynamicDeps]);
98
+ chunks[id] = {
99
+ id,
100
+ code: res.code,
101
+ deps,
102
+ parents: [parent]
103
+ };
104
+ for (const dep of deps)
105
+ await transformRequestRecursive(opts, dep, id, chunks);
106
+ return Object.values(chunks);
107
+ }
108
+ async function bundleRequest(opts, entryURL) {
109
+ const chunks = await transformRequestRecursive(opts, entryURL);
110
+ const listIds = (ids) => ids.map((id) => `// - ${id} (${hashId(id)})`).join("\n");
111
+ const chunksCode = chunks.map((chunk) => `
112
+ // --------------------
113
+ // Request: ${chunk.id}
114
+ // Parents:
115
+ ${listIds(chunk.parents)}
116
+ // Dependencies:
117
+ ${listIds(chunk.deps)}
118
+ // --------------------
119
+ const ${hashId(`${chunk.id}-${chunk.code}`)} = ${chunk.code}
120
+ `).join("\n");
121
+ const manifestCode = `const __modules__ = ${genObjectFromRawEntries(chunks.map((chunk) => [chunk.id, hashId(`${chunk.id}-${chunk.code}`)]))}`;
122
+ const ssrModuleLoader = `
123
+ const __pendingModules__ = new Map()
124
+ const __pendingImports__ = new Map()
125
+ const __ssrContext__ = { global: globalThis }
126
+
127
+ function __ssrLoadModule__(url, urlStack = []) {
128
+ const pendingModule = __pendingModules__.get(url)
129
+ if (pendingModule) { return pendingModule }
130
+ const modulePromise = __instantiateModule__(url, urlStack)
131
+ __pendingModules__.set(url, modulePromise)
132
+ modulePromise.catch(() => { __pendingModules__.delete(url) })
133
+ .finally(() => { __pendingModules__.delete(url) })
134
+ return modulePromise
135
+ }
136
+
137
+ async function __instantiateModule__(url, urlStack) {
138
+ const mod = __modules__[url]
139
+ if (mod.stubModule) { return mod.stubModule }
140
+ const stubModule = { [Symbol.toStringTag]: 'Module' }
141
+ Object.defineProperty(stubModule, '__esModule', { value: true })
142
+ mod.stubModule = stubModule
143
+ // https://vitejs.dev/guide/api-hmr.html
144
+ const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
145
+ urlStack = urlStack.concat(url)
146
+ const isCircular = url => urlStack.includes(url)
147
+ const pendingDeps = []
148
+ const ssrImport = async (dep) => {
149
+ // TODO: Handle externals if dep[0] !== '.' | '/'
150
+ if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
151
+ pendingDeps.push(dep)
152
+ if (pendingDeps.length === 1) {
153
+ __pendingImports__.set(url, pendingDeps)
154
+ }
155
+ await __ssrLoadModule__(dep, urlStack)
156
+ if (pendingDeps.length === 1) {
157
+ __pendingImports__.delete(url)
158
+ } else {
159
+ pendingDeps.splice(pendingDeps.indexOf(dep), 1)
160
+ }
161
+ }
162
+ return __modules__[dep].stubModule
163
+ }
164
+ function ssrDynamicImport (dep) {
165
+ // TODO: Handle dynamic import starting with . relative to url
166
+ return ssrImport(dep)
167
+ }
168
+
169
+ function ssrExportAll(sourceModule) {
170
+ for (const key in sourceModule) {
171
+ if (key !== 'default') {
172
+ try {
173
+ Object.defineProperty(stubModule, key, {
174
+ enumerable: true,
175
+ configurable: true,
176
+ get() { return sourceModule[key] }
177
+ })
178
+ } catch (_err) { }
179
+ }
180
+ }
181
+ }
182
+
183
+ const cjsModule = {
184
+ get exports () {
185
+ return stubModule.default
186
+ },
187
+ set exports (v) {
188
+ stubModule.default = v
189
+ },
190
+ }
191
+
192
+ await mod(
193
+ __ssrContext__.global,
194
+ cjsModule,
195
+ stubModule.default,
196
+ stubModule,
197
+ importMeta,
198
+ ssrImport,
199
+ ssrDynamicImport,
200
+ ssrExportAll
201
+ )
202
+
203
+ return stubModule
204
+ }
205
+ `;
206
+ const code = [
207
+ chunksCode,
208
+ manifestCode,
209
+ ssrModuleLoader,
210
+ `export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
211
+ ].join("\n\n");
212
+ return {
213
+ code,
214
+ ids: chunks.map((i) => i.id)
215
+ };
216
+ }
217
+ async function initViteDevBundler(ctx, onBuild) {
218
+ const viteServer = ctx.ssrServer;
219
+ const options = {
220
+ viteServer,
221
+ isExternal: createIsExternal(viteServer, ctx.nuxt.options.rootDir)
222
+ };
223
+ const _doBuild = async () => {
224
+ const start = Date.now();
225
+ const { code, ids } = await bundleRequest(options, ctx.entry);
226
+ await fse.ensureFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"));
227
+ await fse.writeFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
228
+ await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
229
+ const time = Date.now() - start;
230
+ logger.success(`Vite server built in ${time}ms`);
231
+ await onBuild();
232
+ ctx.nuxt.callHook("bundler:change", {});
233
+ };
234
+ const doBuild = debounce(_doBuild);
235
+ await _doBuild();
236
+ viteServer.watcher.on("all", (_event, file) => {
237
+ file = normalize(file);
238
+ if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnored(file))
239
+ return;
240
+ doBuild();
241
+ });
242
+ ctx.nuxt.hook("app:templatesGenerated", () => doBuild());
243
+ }
244
+
245
+ export { bundleRequest, initViteDevBundler };
@@ -0,0 +1,37 @@
1
+ import 'node:fs';
2
+ import { hash } from 'ohash';
3
+ import 'pathe';
4
+ import { isExternal, ExternalsDefaults } 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 };