@monkeyplus/flow 5.0.0-rc.28 → 5.0.0-rc.3

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.
@@ -1,6 +1,6 @@
1
1
  import type { RadixRouter } from 'radix3';
2
2
  import type { Hookable } from 'hookable';
3
- import type { FlowAppUtils, FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
3
+ import type { FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
4
4
  declare type HookResult = Promise<void> | void;
5
5
  export interface FlowAppHooks {
6
6
  'flow:pages': (page: FlowPage[]) => HookResult;
@@ -27,7 +27,7 @@ export interface FlowApp {
27
27
  callHook: FlowApp['hooks']['callHook'];
28
28
  eta: any;
29
29
  app: {
30
- utils: FlowAppUtils;
30
+ utils: Record<string, any>;
31
31
  plugins: Record<string, any>;
32
32
  globals: Record<string, any>;
33
33
  };
@@ -1,6 +1,6 @@
1
- import "node-fetch-native/polyfill";
2
1
  import { defineEventHandler } from "h3";
3
- import { defineCachedFunction, useRuntimeConfig } from "#internal/nitro";
2
+ import "node-fetch-native/polyfill";
3
+ import { useRuntimeConfig } from "#internal/nitro";
4
4
  const getServerApp = cachedImport(() => import("#server"));
5
5
  const getFlowRenderer = cachedResult(async () => {
6
6
  const createFlowApp = await getServerApp();
@@ -12,7 +12,6 @@ export default defineEventHandler(async ({ context }) => {
12
12
  const flow = await getFlowRenderer();
13
13
  context.flow = flow;
14
14
  context.render = flow.render;
15
- context.defineCachedFunction = defineCachedFunction;
16
15
  });
17
16
  function _interopDefault(e) {
18
17
  return e && typeof e === "object" && "default" in e ? e.default : e;
@@ -16,32 +16,27 @@ export default eventHandler(async (event) => {
16
16
  if (view.bundle)
17
17
  await flow.callHook("page:chunks", view.bundle, chunks);
18
18
  const templateContext = {};
19
- const dynamic = params?._;
20
- const contextPage = {
21
- chunks,
22
- locale
23
- };
24
- const contextInject = {};
25
- const utils = Object.assign({ getLocale: () => locale, injectContext: (key, value) => contextInject[key] = value, defineCachedFunction: event.context.defineCachedFunction }, flow.app.utils);
19
+ const dynamyc = params?._;
20
+ const contextPage = {};
21
+ const utils = Object.assign({ getLocale: () => locale }, flow.app.utils);
26
22
  templateContext.url = url;
27
23
  templateContext.locale = locale;
28
24
  templateContext.view = view;
29
- if (dynamic && page.dynamic) {
25
+ if (dynamyc && page.dynamic) {
30
26
  const pages = await page.dynamic.method({ locale, utils });
31
- const dynamicPage = pages.find((_page) => _page.url === dynamic);
27
+ const dynamicPage = pages.find((_page) => _page.url === dynamyc);
32
28
  if (!dynamicPage)
33
29
  return;
34
30
  if (page.dynamic.assign)
35
31
  templateContext[page.dynamic.assign] = dynamicPage.context;
36
- contextPage.dynamic = dynamicPage;
32
+ contextPage.dynamyc = dynamicPage;
37
33
  }
38
34
  templateContext.seo = {};
39
35
  templateContext.context = {};
40
- const sharedContext = await utils.getSharedContext(utils);
41
- templateContext.sharedContext = sharedContext || {};
36
+ templateContext.sharedContext = {};
42
37
  templateContext.utils = utils;
43
- templateContext.seo = await page.seo?.({ ...contextPage, utils, sharedContext }) || {};
44
- templateContext.context = await page.context?.({ ...contextPage, utils, sharedContext }) || {};
38
+ templateContext.seo = await page.seo?.({ ...contextPage, utils }) || {};
39
+ templateContext.context = await page.context?.({ ...contextPage, utils }) || {};
45
40
  templateContext.getHeadScripts = () => {
46
41
  return scripts.head.join("\n");
47
42
  };
@@ -51,20 +46,11 @@ export default eventHandler(async (event) => {
51
46
  templateContext.getBodyChunks = () => {
52
47
  return chunks.body.join("\n");
53
48
  };
54
- templateContext.getInjectContext = () => {
55
- return `<script id="__FLOW_DATA__" type="application/json">${JSON.stringify(contextInject)}<\/script>`;
56
- };
57
49
  const query = useQuery(event);
58
50
  if (query?.context)
59
51
  return { ...templateContext, utils: Object.keys(utils) };
60
- let html;
61
- if (view.render)
62
- html = await view.render(templateContext, event);
63
- else
64
- html = await flow.render(view, templateContext);
65
- event.res.setHeader("Content-Type", view.contentType || "text/html;charset=UTF-8");
66
- if (view.postRender)
67
- html = await view.postRender(html, event);
52
+ const html = await flow.render(view, templateContext);
53
+ event.res.setHeader("Content-Type", "text/html;charset=UTF-8");
68
54
  if (flow.generate) {
69
55
  await flow.callHook("page:generate", generate);
70
56
  globalThis.generate = generate;
package/dist/index.mjs CHANGED
@@ -1,12 +1,10 @@
1
1
  import { createHooks } from 'hookable';
2
2
  import { dirname, resolve, normalize, join, isAbsolute, relative, extname } from 'pathe';
3
3
  import { defineFlowModule, addPlugin, defineNuxtModule, logger, addTemplate, addPluginTemplate, addVitePlugin, useNuxt, resolveAlias, resolveFilesFlow, nuxtCtx, installModule, loadFlowConfig, templateUtils, normalizeTemplate, compileTemplate, normalizePlugin, isIgnoredFlow } from '@monkeyplus/flow-kit';
4
- import { fileURLToPath } from 'url';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
5
  import { defineUnimportPreset, createUnimport, toImports, scanDirExports } from 'unimport';
6
- import { pathToFileURL } from 'node:url';
7
6
  import { createUnplugin } from 'unplugin';
8
7
  import { parseURL, parseQuery, joinURL, withoutTrailingSlash } from 'ufo';
9
- import fs from 'fs';
10
8
  import escapeRE from 'escape-string-regexp';
11
9
  import { camelCase, pascalCase } from 'scule';
12
10
  import { genImport, genDynamicImport, genArrayFromRaw, genString, genObjectFromRawEntries } from 'knitwork';
@@ -29,7 +27,7 @@ import { isExternal as isExternal$1, ExternalsDefaults } from 'externality';
29
27
  import { createHash } from 'node:crypto';
30
28
  import MagicString from 'magic-string';
31
29
 
32
- const version = "5.0.0-rc.28";
30
+ const version = "5.0.0-rc.3";
33
31
 
34
32
  let _distDir = dirname(fileURLToPath(import.meta.url));
35
33
  if (_distDir.endsWith("chunks"))
@@ -89,14 +87,6 @@ const commonPresets = [
89
87
  imports: [
90
88
  "useHead"
91
89
  ]
92
- }),
93
- defineUnimportPreset({
94
- from: "#_pages",
95
- imports: [
96
- "definePage",
97
- "defineDinamycPage",
98
- "defineSharedContext"
99
- ]
100
90
  })
101
91
  ];
102
92
  const appPreset = defineUnimportPreset({
@@ -231,20 +221,14 @@ ${ctx.generateTypeDecarations({ resolvePath: r })}`
231
221
  });
232
222
  }
233
223
 
234
- async function resolveFiles(dir) {
224
+ async function resolvePagesRoutes() {
235
225
  const nuxt = useNuxt();
236
- const dirs = [resolve(nuxt.options.srcDir, dir)];
237
- const allRoutes = (await Promise.all(dirs.map(async (dir2) => {
238
- const files = await resolveFilesFlow(dir2, `**/*{${nuxt.options.extensions.join(",")}}`);
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 resolveFilesFlow(dir, `**/*{${nuxt.options.extensions.join(",")}}`);
239
229
  files.sort();
240
- return files.filter((file) => {
241
- if (file.includes(" copy"))
242
- return false;
243
- if (!fs.readFileSync(file, "utf8").includes("export"))
244
- return false;
245
- return true;
246
- }).map((file) => {
247
- const segments = relative(dir2, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
230
+ return files.map((file) => {
231
+ const segments = relative(dir, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
248
232
  return {
249
233
  file,
250
234
  name: camelCase(segments)
@@ -253,31 +237,21 @@ async function resolveFiles(dir) {
253
237
  }))).flat();
254
238
  return allRoutes;
255
239
  }
256
- function normalizeExports(files) {
257
- const imports = files.map((page) => genImport(page.file, page.name)).join("\n");
258
- const exports = files.reduce((acc, curr) => {
259
- const name = curr.name;
260
- return `${name}:typeof ${name}==='function'?${name}():${name},${acc}`;
261
- }, "");
240
+ function normalizePages(pages) {
241
+ const imports = pages.map((page) => genImport(page.file, [{ name: "pages", as: page.name }])).join("\n");
262
242
  return {
263
243
  imports,
264
- exports
244
+ exports: pages.reduce((acc, curr) => `${curr.name || ""},${acc}`, "")
265
245
  };
266
246
  }
267
247
 
268
248
  const pagesTypeTemplate = {
269
- filename: "types/pages.d.ts",
249
+ filename: "pages.d.ts",
270
250
  getContents: ({ options }) => `// Generated by pages discovery
271
251
  export {}
272
252
  declare global {
273
- type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
274
- ? ElementType
275
- : never;
276
253
 
277
- ${options.pages.map((c) => {
278
- const _type = `ArrElement<typeof ${genDynamicImport(isAbsolute(c.file) ? relative(join(options.buildDir, "types"), c.file) : c.file, { wrapper: false })}['default']>`;
279
- return `export type ${pascalCase(c.name)}Context=Awaited<ReturnType<${_type}['locales']['es-ec']['context']>>`;
280
- }).join("\n")}
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")}
281
255
  }
282
256
  export const pagesNames: string[]
283
257
  `.replaceAll(".ts", "")
@@ -289,54 +263,38 @@ const pagesModule = defineNuxtModule({
289
263
  },
290
264
  async setup(_options, flow) {
291
265
  const runtimeDir = resolve(distDir, "pages/runtime");
292
- flow.options.alias["#_pages"] = runtimeDir;
293
266
  const pages = [];
294
- const contexts = [];
295
- const options = { pages, buildDir: flow.options.buildDir, contexts };
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 };
296
278
  addTemplate({
297
279
  ...pagesTypeTemplate,
298
280
  options
299
281
  });
300
- const pagesDirs = [{ path: resolve(flow.options.srcDir, flow.options.dir.pages) }];
301
282
  flow.options.alias["#pages"] = resolve(flow.options.buildDir, "pages.mjs");
302
- flow.options.alias["#pagesContexts"] = resolve(flow.options.buildDir, "pages.contexts.mjs");
303
283
  addTemplate({
304
284
  filename: "pages.mjs",
305
285
  async getContents({ options: options2 }) {
306
- const { exports, imports } = normalizeExports(options2.pages);
307
- const module = [imports, `export default {${exports}}`].join("\n");
308
- return module;
286
+ const { exports, imports } = normalizePages(options2.pages);
287
+ return [imports, `export default {${exports}}`].join("\n");
309
288
  },
310
289
  options
311
290
  });
312
- addTemplate({
313
- filename: "pages.contexts.mjs",
314
- async getContents({ options: options2 }) {
315
- const { exports, imports } = normalizeExports(options2.contexts);
316
- const module = [imports, `export default {${exports}}`].join("\n");
317
- return module;
318
- },
319
- options
320
- });
321
- flow.hook("app:templates", async () => {
322
- options.pages = await resolveFiles(flow.options.dir?.pages || "pages");
323
- });
324
291
  flow.hook("app:templates", async () => {
325
- options.contexts = await resolveFiles("shared/contexts");
292
+ options.pages = await resolvePagesRoutes();
326
293
  });
327
294
  flow.hook("prepare:types", ({ references }) => {
328
- references.push({ path: resolve(flow.options.buildDir, "types/pages.d.ts") });
295
+ references.push({ path: resolve(flow.options.buildDir, "pages.d.ts") });
329
296
  });
330
- flow.hook("builder:watch", async (event, path) => {
331
- if (!["add", "unlink", "change"].includes(event))
332
- return;
333
- if (path.includes(" copy"))
334
- return;
335
- const fPath = resolve(flow.options.rootDir, path);
336
- if (pagesDirs.find((dir) => fPath.startsWith(dir.path)))
337
- await flow.callHook("builder:generateApp");
338
- });
339
- addPlugin(resolve(runtimeDir, "pages"));
297
+ addPlugin({ src: resolve(runtimeDir, "plugin") });
340
298
  }
341
299
  });
342
300
 
@@ -364,7 +322,7 @@ const createClient = async (flow) => {
364
322
  if (vite)
365
323
  vite?.ws?.send({ type: "full-reload" });
366
324
  };
367
- const doReload = debounce(_doReload, 75);
325
+ const doReload = debounce(_doReload, 60);
368
326
  flow.hook("bundler:change", () => {
369
327
  doReload();
370
328
  });
@@ -420,24 +378,23 @@ const viteModule = defineFlowModule({
420
378
  }
421
379
  });
422
380
  } else {
423
- const file = resolve(flow.options.rootDir, ".vite/manifest.json");
424
- addTemplate({
425
- filename: "viteManifest.mjs",
426
- async getContents() {
427
- return [
428
- "import fs from 'fs';",
429
- `export default ()=>{
430
- const manifest =JSON.parse(fs.readFileSync("${file}", 'utf8');
431
- return {manifest,base:'${_options.dir}'}
432
- })`
433
- ].join("\n");
434
- }
435
- });
436
- flow.hook("build:before", async () => {
381
+ flow.hook("modules:done", async () => {
437
382
  const start = Date.now();
438
383
  logger$1.info("Building client...");
439
384
  await builClient(flow);
385
+ const file = resolve(flow.options.rootDir, ".vite/manifest.json");
386
+ const manifest = await fse.readFile(file, "utf8");
440
387
  logger$1.success(`Client build in ${Date.now() - start}ms`);
388
+ addTemplate({
389
+ filename: "viteManifest.mjs",
390
+ async getContents() {
391
+ return [
392
+ "export default ()=>(",
393
+ manifest,
394
+ ")"
395
+ ].join("\n");
396
+ }
397
+ });
441
398
  });
442
399
  flow.hook("generate:before", async () => {
443
400
  const files = resolve(flow.options.rootDir, ".vite/scripts");
@@ -521,8 +478,7 @@ async function initNitro(flow) {
521
478
  externals: {
522
479
  inline: [
523
480
  ...flow.options.dev ? [] : ["eta", "@monkeyplus/", "@vue/", "@nuxt/", flow.options.buildDir],
524
- "@monkeyplus/flow/dist",
525
- "C:/Users/gnu/Documents/GitHub/flow/packages/flow/dist/app"
481
+ "@monkeyplus/flow/dist"
526
482
  ]
527
483
  },
528
484
  alias: {
@@ -533,8 +489,7 @@ async function initNitro(flow) {
533
489
  ...flow.options.alias
534
490
  },
535
491
  rollupConfig: {
536
- plugins: [],
537
- external: [""]
492
+ plugins: []
538
493
  }
539
494
  });
540
495
  await flow.callHook("nitro:config", nitroConfig);
@@ -1126,8 +1081,6 @@ const buildServer = async (ctx) => {
1126
1081
  "/__vue-jsx",
1127
1082
  "#app",
1128
1083
  /(nuxt|nuxt3)\/(dist|src|app)/,
1129
- /flow\/(dist|src|app)/,
1130
- /flow\/modules\/(content|icons|images|netlify|netlify-cms|seo|sitemap|vue)/,
1131
1084
  /@monkeyplus\/flow\/(dist|src|app)/,
1132
1085
  /@nuxt\/nitro\/(dist|src)/
1133
1086
  ]
@@ -1205,11 +1158,9 @@ const buildServer = async (ctx) => {
1205
1158
  await onBuild();
1206
1159
  ctx.flow.callHook("bundler:change", {});
1207
1160
  };
1208
- const doBuild = debounce(_doBuild, 50);
1161
+ const doBuild = debounce(_doBuild);
1209
1162
  await _doBuild();
1210
1163
  viteServer.watcher.on("all", (_event, file) => {
1211
- if (file.includes("/pages/"))
1212
- return;
1213
1164
  file = normalize(file);
1214
1165
  if (file.indexOf(ctx.flow.options.buildDir) === 0)
1215
1166
  return;
@@ -1329,7 +1280,6 @@ async function bundleVite(flow) {
1329
1280
  include: []
1330
1281
  },
1331
1282
  build: {
1332
- ssr: true,
1333
1283
  rollupOptions: {
1334
1284
  output: { sanitizeFileName: sanitizeFilePath },
1335
1285
  input: resolve(flow.options.appDir, "entry")
@@ -1366,8 +1316,6 @@ async function bundleVite(flow) {
1366
1316
  flow.hook("vite:serverCreated", (server) => {
1367
1317
  ctx.nuxt.hook("app:templatesGenerated", () => {
1368
1318
  for (const [id, mod] of server.moduleGraph.idToModuleMap) {
1369
- if (id.includes("pages.mjs"))
1370
- server.moduleGraph.invalidateModule(mod);
1371
1319
  if (id.startsWith("\0virtual:"))
1372
1320
  server.moduleGraph.invalidateModule(mod);
1373
1321
  }
@@ -1409,7 +1357,8 @@ function watch(flow) {
1409
1357
  "node_modules"
1410
1358
  ]
1411
1359
  });
1412
- watcher.on("all", (event, path) => flow.callHook("builder:watch", event, normalize(path)));
1360
+ const watchHook = debounce((event, path) => flow.callHook("builder:watch", event, normalize(path)));
1361
+ watcher.on("all", watchHook);
1413
1362
  flow.hook("close", () => watcher.close());
1414
1363
  return watcher;
1415
1364
  }
@@ -1,9 +1,3 @@
1
- import type { DynamicPage, PageCtx, SimplePage } from '@monkeyplus/flow-schema';
2
- export declare function definePage<T>(...pages: SimplePage<T>[]): SimplePage<T>[];
3
- export declare function defineDinamycPage<T>(...pages: DynamicPage<T>[]): DynamicPage<T>[];
4
- interface SharedContext {
5
- assign?: 'global' | 'local';
6
- setup: (cxt: PageCtx) => any;
7
- }
8
- export declare function defineSharedContext(shared: SharedContext): SharedContext;
9
- export {};
1
+ import type { DynamicPage, SimplePage } from '@monkeyplus/flow-schema';
2
+ export declare function definePage(page: SimplePage): SimplePage;
3
+ export declare function defineDinamycPage(page: DynamicPage): DynamicPage;
@@ -1,13 +1,6 @@
1
- export function definePage(...pages) {
2
- return pages;
1
+ export function definePage(page) {
2
+ return page;
3
3
  }
4
- export function defineDinamycPage(...pages) {
5
- return pages.map((page) => {
6
- if (!page.name.endsWith("/**"))
7
- page.name = `${page.name}/**`;
8
- return page;
9
- });
10
- }
11
- export function defineSharedContext(shared) {
12
- return shared;
4
+ export function defineDinamycPage(page) {
5
+ return page;
13
6
  }
@@ -0,0 +1,53 @@
1
+ import { joinURL } from "ufo";
2
+ import { definePage } from "./helpers/index.mjs";
3
+ import { defineFlowPlugin, useRuntimeConfig } from "#app";
4
+ import pages from "#pages";
5
+ export default defineFlowPlugin(async (flow) => {
6
+ const { app } = useRuntimeConfig();
7
+ const allPages = [];
8
+ Object.entries(pages).forEach(([name, page]) => {
9
+ const { getPages } = definePage({
10
+ name,
11
+ ...page
12
+ });
13
+ const _pages = getPages(app.locale.location, app.locale.language);
14
+ _pages.forEach((page2) => {
15
+ flow.router.byUrl.insert(page2.url, page2.context);
16
+ flow.router.byName.insert(page2.name, page2.context);
17
+ allPages.push(page2.context);
18
+ });
19
+ });
20
+ function getUrl(namePage, localeCode) {
21
+ const code = localeCode || this?.getLocale()?.code;
22
+ const [lang, loc] = code.split("-");
23
+ const name = joinURL("/", loc, lang, namePage);
24
+ const { path } = flow.router.byName.lookup(name) || {};
25
+ return path || "/404";
26
+ }
27
+ async function getUrls(withLocale = false) {
28
+ const urls = [];
29
+ for (const page of allPages) {
30
+ if (!page.path.includes("/**")) {
31
+ urls.push(withLocale ? { url: page.path, locale: page.locale.code, name: page.name } : page.path);
32
+ } else {
33
+ const dPages = await page.page.dynamic.method({
34
+ locale: page.locale,
35
+ utils: Object.assign({ getLocale: () => page.locale }, flow.app.utils)
36
+ });
37
+ dPages.forEach((dPage) => {
38
+ const _path = joinURL(page.path.replace("/**", ""), dPage.url);
39
+ urls.push(withLocale ? { url: _path, locale: page.locale.code, name: joinURL(page.name, dPage.name) } : _path);
40
+ });
41
+ }
42
+ }
43
+ return urls.sort();
44
+ }
45
+ flow.setUtil("getUrl", getUrl);
46
+ flow.setUtil("getUrls", getUrls);
47
+ flow.setUtil("getPages", () => allPages);
48
+ return {
49
+ provide: {
50
+ pages: { allPages }
51
+ }
52
+ };
53
+ });
@@ -1,14 +1,13 @@
1
1
  import logger from "consola";
2
- import { joinURL } from "ufo";
3
2
  import { generateBundle } from "./injectManifest.mjs";
4
3
  import { defineFlowPlugin } from "#app";
5
4
  import manifest from "#viteManifest";
6
5
  export default defineFlowPlugin((flow) => {
7
6
  if (typeof manifest === "function") {
7
+ const _manifest = manifest();
8
8
  flow.hook("page:chunks", (bundle, chunks) => {
9
9
  try {
10
- const data = manifest();
11
- const chunk = generateBundle(flow.$config.app || {}, data.manifest, joinURL("/", data.base, `${bundle}.ts`).replace("/", ""));
10
+ const chunk = generateBundle(flow.$config.app || {}, _manifest, `client/pages/${bundle}.ts`);
12
11
  if (chunk) {
13
12
  chunks.head.push(chunk.head);
14
13
  chunks.body.push(chunk.body);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monkeyplus/flow",
3
- "version": "5.0.0-rc.28",
3
+ "version": "5.0.0-rc.3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -25,9 +25,9 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@monkeyplus/flow-cli": "5.0.0-rc.28",
29
- "@monkeyplus/flow-kit": "5.0.0-rc.28",
30
- "@monkeyplus/flow-schema": "5.0.0-rc.28",
28
+ "@monkeyplus/flow-cli": "5.0.0-rc.3",
29
+ "@monkeyplus/flow-kit": "5.0.0-rc.3",
30
+ "@monkeyplus/flow-schema": "5.0.0-rc.3",
31
31
  "@rollup/plugin-replace": "^4.0.0",
32
32
  "@vueuse/head": "^0.7.6",
33
33
  "c12": "^0.2.7",
@@ -50,7 +50,7 @@
50
50
  "magic-string": "^0.26.2",
51
51
  "mlly": "^0.5.2",
52
52
  "mri": "^1.2.0",
53
- "nitropack": "^0.4.8",
53
+ "nitropack": "^0.4.4",
54
54
  "pathe": "^0.2.0",
55
55
  "perfect-debounce": "^0.1.3",
56
56
  "radix3": "^0.1.2",
@@ -1,90 +0,0 @@
1
- import { joinURL } from "ufo";
2
- import consola from "consola";
3
- import { definePage } from "./helpers/index.mjs";
4
- import { defineFlowPlugin, useRuntimeConfig } from "#app";
5
- import pages from "#build/pages";
6
- import contexts from "#build/pages.contexts";
7
- export default defineFlowPlugin(async (flow) => {
8
- const { app } = useRuntimeConfig();
9
- const allPages = [];
10
- const basePages = Object.entries(pages);
11
- consola.success("Parsed %i pages files", basePages.length);
12
- basePages.forEach(([name, _pages]) => {
13
- const __pages = Array.isArray(_pages) ? _pages : [_pages];
14
- __pages.forEach((page) => {
15
- const { getPages } = definePage({
16
- name,
17
- ...page
18
- });
19
- const _pages2 = getPages(app.locale.location, app.locale.language);
20
- _pages2.forEach((page2) => {
21
- flow.router.byUrl.insert(page2.url, page2.context);
22
- flow.router.byName.insert(page2.name, page2.context);
23
- allPages.push(page2.context);
24
- });
25
- });
26
- });
27
- const cache = {};
28
- async function getUrl(namePage, localeCode) {
29
- const code = localeCode || this?.getLocale()?.code;
30
- const [lang, loc] = code.split("-");
31
- const name = joinURL("/", loc, lang, namePage);
32
- const { path, params, page } = flow.router.byName.lookup(name) || {};
33
- if (params?._ && page.dynamic) {
34
- if (!cache[path]) {
35
- cache[path] = this.defineCachedFunction(async (_ctx) => {
36
- return await page.dynamic.method(_ctx);
37
- }, { maxAge: 8, getKey: () => path, swr: false });
38
- }
39
- const fn = cache[path];
40
- const list = await fn({ utils: this, locale: this.getLocale() });
41
- const dPage = list.find((el) => el.name === params._);
42
- return dPage ? path.replace("**", dPage.url) : "/404";
43
- }
44
- return path || "/404";
45
- }
46
- async function getUrls(withLocale = false) {
47
- const urls = [];
48
- for (const page of allPages) {
49
- if (page.path.includes("/**") && page.page.dynamic) {
50
- const dPages = await page.page.dynamic.method({
51
- locale: page.locale,
52
- utils: Object.assign({ getLocale: () => page.locale }, flow.app.utils),
53
- chunks: {}
54
- });
55
- dPages.forEach((dPage) => {
56
- const _path = joinURL(page.path.replace("/**", ""), dPage.url);
57
- urls.push(withLocale ? { url: _path, locale: page.locale.code, name: joinURL(page.name, dPage.name) } : _path);
58
- });
59
- } else {
60
- const url = page.path.replaceAll("*", "");
61
- urls.push(withLocale ? { url, locale: page.locale.code, name: page.name } : url);
62
- }
63
- }
64
- return urls.sort();
65
- }
66
- async function getSharedContext(utils) {
67
- const entries = Object.entries(contexts);
68
- if (!entries.length)
69
- return {};
70
- const _contexts = await Promise.all(entries.map(async ([key, method]) => {
71
- const data = await method.setup(utils);
72
- return { [key]: data };
73
- }));
74
- return _contexts.reduce((acc, curr) => {
75
- return {
76
- ...acc,
77
- ...curr
78
- };
79
- }, {});
80
- }
81
- flow.setUtil("getUrl", getUrl);
82
- flow.setUtil("getUrls", getUrls);
83
- flow.setUtil("getPages", () => allPages);
84
- flow.setUtil("getSharedContext", getSharedContext);
85
- return {
86
- provide: {
87
- pages: { allPages }
88
- }
89
- };
90
- });
File without changes