@mono-lit/utility 0.0.1 → 0.0.2

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 (36) hide show
  1. package/LICENSE.md +54 -54
  2. package/README.md +156 -156
  3. package/dist/{app-roots-BJsIxzjk.d.ts → app-roots-DK41xMWj.d.ts} +1 -2
  4. package/dist/config-node.d.ts +134 -188
  5. package/dist/config-node.js +1 -1
  6. package/dist/config.d.ts +1 -1
  7. package/dist/{create-config-D3m6xTaQ.d.ts → create-config-B8IhX4ht.d.ts} +5 -3
  8. package/dist/fetching.d.ts +51 -46
  9. package/dist/fetching.js +163 -15
  10. package/dist/{index-C2hZeNkq.d.ts → index-BAy6tbOG.d.ts} +12 -6
  11. package/dist/{index-ClrZbU7n.d.ts → index-DYlzhHq7.d.ts} +83 -87
  12. package/dist/index.d.ts +3 -7
  13. package/dist/index.js +5 -3
  14. package/dist/{merge-file-C5nzi_MY.d.ts → merge-file-CLc3wxY4.d.ts} +5 -28
  15. package/dist/{mock-db-5mJTObSC.js → mock-db-4tTWrF-P.js} +12 -12
  16. package/dist/mock-db.d.ts +1 -1
  17. package/dist/mock-db.js +1 -1
  18. package/dist/mono-db.d.ts +1 -1
  19. package/dist/mono-db.js +115 -108
  20. package/dist/mono-prepare.d.ts +1 -1
  21. package/dist/mono-prepare.js +3 -2
  22. package/dist/mono-skills.d.ts +1 -1
  23. package/dist/mono-skills.js +39 -32
  24. package/dist/nuxt-layers.d.ts +4 -2
  25. package/dist/nuxt-runtime.d.ts +4 -5
  26. package/dist/nuxt-runtime.js +1 -1
  27. package/dist/nuxt.d.ts +40 -36
  28. package/dist/nuxt.js +153 -6
  29. package/dist/{runtime-C_IWNrAG.js → runtime-vs7U9Ed4.js} +394 -157
  30. package/dist/runtime.d.ts +68 -133
  31. package/dist/runtime.js +2 -2
  32. package/dist/{session-Bk985AIM.js → session-Bcig-rPi.js} +4 -4
  33. package/dist/{universal-B2eD9xho.d.ts → universal-BR0O7Qwk.d.ts} +8 -46
  34. package/dist/{universal-BNTo_83u.js → universal-DIVEzCvN.js} +3 -2
  35. package/dist/vite.d.ts +44 -41
  36. package/package.json +11 -11
package/dist/nuxt.js CHANGED
@@ -5,9 +5,9 @@ import { t as getMonoConfig } from "./config-node-UzJrXg0Z.js";
5
5
  import { d as resolveFederatedRoots, n as extractConfig, o as formatMissingApps, s as monoAlias, t as assertAppSources, u as monoStubAliases } from "./mono-alias-DNDm-jB_.js";
6
6
  import { a as defaultMonoExpose, i as monoRouterLinkToNuxtLink, l as remoteGate, o as sanitizeForExpose, s as parsePageMeta } from "./mono-link-YlOQ2PVS.js";
7
7
  import { r as registerMonoNuxtLayers, t as monoLayerCandidates } from "./nuxt-layers-DP1m7f1-.js";
8
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
8
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
9
9
  import { isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
10
- import { addComponentsDir, addImportsDir, addPlugin, addPluginTemplate, addRouteMiddleware, addVitePlugin, defineNuxtModule, extendPages, extendViteConfig } from "@nuxt/kit";
10
+ import { addComponentsDir, addImportsDir, addPlugin, addPluginTemplate, addRouteMiddleware, addTemplate, addVitePlugin, defineNuxtModule, extendPages, extendViteConfig } from "@nuxt/kit";
11
11
 
12
12
  //#region src/nuxt/nuxt-ecosystem.ts
13
13
  /**
@@ -245,6 +245,7 @@ const monoNuxtModule = defineNuxtModule({
245
245
  const hasExtends = rawConfig.extends != null;
246
246
  const activeNames = resolveExtendsAppNames(rawConfig);
247
247
  const activeApps = hasExtends ? (rawConfig.apps ?? []).filter((a) => activeNames.includes(a.name)) : rawConfig.apps ?? [];
248
+ const activeRoots = appRoots.filter((r) => activeApps.some((a) => a.name === r.name));
248
249
  const extendsEcosystems = resolveExtendsEcosystems(rawConfig);
249
250
  const monoConfig = {
250
251
  ...resolveMonoConfig(rawConfig),
@@ -318,9 +319,7 @@ const monoNuxtModule = defineNuxtModule({
318
319
  case "middleware":
319
320
  registerRemoteMiddleware(dirs, entry.exclude ?? [], ownSrcDir, name);
320
321
  break;
321
- case "plugins":
322
- registerRemotePlugins(dirs, entry.exclude ?? [], ownSrcDir, name);
323
- break;
322
+ case "plugins": registerRemotePlugins(dirs, entry.exclude ?? [], ownSrcDir, name);
324
323
  }
325
324
  }
326
325
  extendViteConfig((config) => {
@@ -387,8 +386,156 @@ const monoNuxtModule = defineNuxtModule({
387
386
  "})"
388
387
  ].join("\n")
389
388
  });
389
+ if (usesPreFetchModule(nuxt)) {
390
+ defaultPreFetchLearning(nuxt);
391
+ registerPreFetchLearning(nuxt, monoConfig);
392
+ registerPreFetchDirs(nuxt, activeRoots);
393
+ registerPreFetchServer(nuxt, sanitizeForExpose((u.expose ?? defaultMonoExpose)(monoConfig)) ?? {});
394
+ addPluginTemplate({
395
+ filename: "mono-prefetch-bridge.client.mjs",
396
+ mode: "client",
397
+ getContents: () => [
398
+ "import { monoSetPrefetchBridge } from \"@mono-lit/utility/fetching\"",
399
+ "// Runs after @mono-lit/nuxt-pre-fetch's `pre` plugin, which provides $nuxtPreFetch.",
400
+ "export default defineNuxtPlugin({",
401
+ " name: \"mono:prefetch-bridge\",",
402
+ " setup(nuxtApp) {",
403
+ " const api = nuxtApp.$nuxtPreFetch",
404
+ " if (api && api.serving) monoSetPrefetchBridge(api)",
405
+ " },",
406
+ "})"
407
+ ].join("\n")
408
+ });
409
+ }
390
410
  }
391
411
  });
412
+ function usesPreFetchModule(nuxt) {
413
+ return (nuxt.options.modules ?? []).map((entry) => Array.isArray(entry) ? entry[0] : entry).some((name) => typeof name === "string" && name.includes("nuxt-pre-fetch")) || nuxt.options.nuxtPreFetch !== void 0;
414
+ }
415
+ /**
416
+ * Learning follows the data layer the app installs, unless the app sets `nuxtPreFetch.learn.enabled`
417
+ * itself: `@mono-lit/data` describes a page's OData calls on the server (`definePrefetch`), so the
418
+ * first visit is prefetched and nothing needs learning; plain DevExtreme stores can't, so their calls
419
+ * marked `prefetch: true` are learned and prefetched from the next visit. (This module runs before
420
+ * nuxt-pre-fetch, which reads the option with the default in place.)
421
+ */
422
+ function defaultPreFetchLearning(nuxt) {
423
+ const options = nuxt.options.nuxtPreFetch ??= {};
424
+ options.learn ??= {};
425
+ if (typeof options.learn.enabled === "boolean") return;
426
+ options.learn.enabled = !dataLayerDescribesRequests(nuxt);
427
+ }
428
+ /**
429
+ * Whether `@mono-lit/devextreme` — as this app resolves it: an alias, a pnpm override, or the package
430
+ * itself — is `@mono-lit/data`, the data layer that describes its requests on the server.
431
+ */
432
+ function dataLayerDescribesRequests(nuxt) {
433
+ const DATA_LAYER = "@mono-lit/devextreme";
434
+ try {
435
+ const aliased = nuxt.options.alias[DATA_LAYER];
436
+ let dir = aliased && isAbsolute(aliased) ? aliased : realpathSync(resolve(nuxt.options.rootDir, "node_modules", DATA_LAYER));
437
+ for (let i = 0; i < 6; i++) {
438
+ const manifest = join(dir, "package.json");
439
+ if (existsSync(manifest)) return JSON.parse(readFileSync(manifest, "utf8")).name === "@mono-lit/data";
440
+ dir = resolve(dir, "..");
441
+ }
442
+ } catch {}
443
+ return false;
444
+ }
445
+ /**
446
+ * The pages of every merged app are compiled into this one, so their `definePrefetch` files are
447
+ * too: each active app's `app/prefetch` (or `src/prefetch`) is appended to nuxt-pre-fetch's
448
+ * `prefetchDir` (this module runs before it, so the option is read with them).
449
+ */
450
+ function registerPreFetchDirs(nuxt, roots) {
451
+ const dirs = roots.flatMap(({ root }) => ["app/prefetch", "src/prefetch"].map((dir) => resolve(root, dir))).filter((dir) => existsSync(dir));
452
+ if (!dirs.length) return;
453
+ const options = nuxt.options.nuxtPreFetch ??= {};
454
+ const own = options.prefetchDir ?? "prefetch";
455
+ options.prefetchDir = [.../* @__PURE__ */ new Set([...Array.isArray(own) ? own : [own], ...dirs])];
456
+ }
457
+ /** Hosts of every `fetching.api` entry and the auth cookie names, for learned requests. */
458
+ function registerPreFetchLearning(nuxt, monoConfig) {
459
+ const fetching = monoConfig.fetching;
460
+ const hosts = /* @__PURE__ */ new Set();
461
+ for (const entry of Object.values(fetching?.api ?? {})) {
462
+ if (typeof entry?.url !== "string") continue;
463
+ try {
464
+ hosts.add(new URL(entry.url).host.toLowerCase());
465
+ } catch {}
466
+ }
467
+ const auth = fetching?.auth ?? {};
468
+ const use = auth.use && typeof auth.use === "object" ? auth.use : {};
469
+ const cookies = [
470
+ auth.token,
471
+ auth.tokenRefresh,
472
+ use.apiRequest,
473
+ use.refreshTokenRequest
474
+ ].filter((name) => typeof name === "string" && !!name);
475
+ const headers = Object.keys(fetching?.headers ?? {}).map((name) => name.toLowerCase());
476
+ const runtimeConfig = nuxt.options.runtimeConfig;
477
+ runtimeConfig.nuxtPreFetch ??= {};
478
+ const dynamic = runtimeConfig.nuxtPreFetch.dynamic ??= {};
479
+ const merge = (current, add) => [.../* @__PURE__ */ new Set([...Array.isArray(current) ? current : [], ...add])];
480
+ dynamic.allowedHosts = merge(dynamic.allowedHosts, [...hosts]);
481
+ dynamic.authCookies = merge(dynamic.authCookies, cookies);
482
+ if (headers.length) dynamic.forwardHeaders = merge(dynamic.forwardHeaders ?? ["accept"], headers);
483
+ }
484
+ /**
485
+ * `definePrefetch` files call `monoFetch.prefetch` / `monoFetchOdata.prefetch` on the SERVER:
486
+ * Nitro needs the same (exposed) mono config the browser gets, and has to bundle the packages
487
+ * whose folder-style deep imports (`devextreme/core/utils/deferred`) plain Node can't load.
488
+ */
489
+ function registerPreFetchServer(nuxt, exposed) {
490
+ const plugin = addTemplate({
491
+ filename: "mono/prefetch-init.mjs",
492
+ write: true,
493
+ getContents: () => [
494
+ "import { initMono } from \"@mono-lit/utility/runtime\"",
495
+ "import config from \"#mono/config\"",
496
+ "export default function monoPrefetchInit() { initMono(config) }"
497
+ ].join("\n")
498
+ });
499
+ nuxt.hook("nitro:config", (nitroConfig) => {
500
+ nitroConfig.virtual ??= {};
501
+ nitroConfig.virtual["#mono/config"] = () => `export default ${JSON.stringify(exposed)}`;
502
+ nitroConfig.plugins ??= [];
503
+ nitroConfig.plugins.push(plugin.dst);
504
+ nitroConfig.alias = {
505
+ ...appPackageAliases(nuxt.options.rootDir, "@mono-lit/utility"),
506
+ ...nitroConfig.alias
507
+ };
508
+ nitroConfig.externals ??= {};
509
+ nitroConfig.externals.inline = [
510
+ ...nitroConfig.externals.inline ?? [],
511
+ "@mono-lit/utility",
512
+ "@mono-lit/devextreme",
513
+ "@mono-lit/data",
514
+ "devextreme",
515
+ plugin.dst
516
+ ];
517
+ });
518
+ }
519
+ /**
520
+ * `<pkg>` and each of its `exports` subpaths, resolved to the copy THIS app links (its
521
+ * `node_modules/<pkg>`, symlinks followed): exact-path aliases that pin one instance. Empty when
522
+ * the app doesn't link it.
523
+ */
524
+ function appPackageAliases(rootDir, pkg) {
525
+ try {
526
+ const dir = realpathSync(resolve(rootDir, "node_modules", pkg));
527
+ const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
528
+ const aliases = {};
529
+ for (const [subpath, target] of Object.entries(manifest.exports ?? {})) {
530
+ const entry = typeof target === "string" ? target : target?.import ?? target?.default;
531
+ if (typeof entry !== "string" || subpath.includes("*")) continue;
532
+ aliases[subpath === "." ? pkg : `${pkg}${subpath.slice(1)}`] = resolve(dir, entry);
533
+ }
534
+ return aliases;
535
+ } catch {
536
+ return {};
537
+ }
538
+ }
392
539
  /**
393
540
  * Register every `.vue` under the given remote `dirs` as a Nuxt route, skipping
394
541
  * files matching any `exclude` glob and never clobbering an existing host route.
@@ -409,7 +556,7 @@ function registerRemotePages(dirs, exclude, label) {
409
556
  name: "remote-" + rel.replace(/\.vue$/, "").replace(/[^a-zA-Z0-9]+/g, "-"),
410
557
  path: routePath,
411
558
  file,
412
- meta: parsePageMeta(safeRead(file))
559
+ meta: { ...parsePageMeta(safeRead(file)) }
413
560
  });
414
561
  added.push(routePath);
415
562
  }