@mono-lit/utility 0.0.0-stage → 0.0.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 (54) hide show
  1. package/LICENSE.md +54 -0
  2. package/README.md +156 -2
  3. package/dist/app-roots-BJsIxzjk.d.ts +91 -0
  4. package/dist/app-roots-CvJnmXcs.js +128 -0
  5. package/dist/config-node-UzJrXg0Z.js +76 -0
  6. package/dist/config-node.d.ts +977 -0
  7. package/dist/config-node.js +7 -0
  8. package/dist/config.d.ts +2 -0
  9. package/dist/config.js +3 -0
  10. package/dist/create-config-D3m6xTaQ.d.ts +733 -0
  11. package/dist/create-config-DdL3Fh6T.js +357 -0
  12. package/dist/fetching.d.ts +239 -0
  13. package/dist/fetching.js +867 -0
  14. package/dist/generate-CJ7MtcDd.js +291 -0
  15. package/dist/index-C2hZeNkq.d.ts +365 -0
  16. package/dist/index-ClrZbU7n.d.ts +518 -0
  17. package/dist/index.d.ts +29 -0
  18. package/dist/index.js +939 -0
  19. package/dist/merge-file-C5nzi_MY.d.ts +122 -0
  20. package/dist/merge-file-CtyKTu5L.js +133 -0
  21. package/dist/mock-db-5mJTObSC.js +1282 -0
  22. package/dist/mock-db.d.ts +2 -0
  23. package/dist/mock-db.js +4 -0
  24. package/dist/mono-alias-DNDm-jB_.js +508 -0
  25. package/dist/mono-clone.mjs +958 -0
  26. package/dist/mono-db.d.ts +1 -0
  27. package/dist/mono-db.js +151 -0
  28. package/dist/mono-env.mjs +231 -0
  29. package/dist/mono-git.mjs +798 -0
  30. package/dist/mono-link-YlOQ2PVS.js +488 -0
  31. package/dist/mono-prepare.d.ts +1 -0
  32. package/dist/mono-prepare.js +27 -0
  33. package/dist/mono-skills.d.ts +1 -0
  34. package/dist/mono-skills.js +830 -0
  35. package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
  36. package/dist/mono.mjs +34 -0
  37. package/dist/nuxt-layers-DP1m7f1-.js +176 -0
  38. package/dist/nuxt-layers.d.ts +34 -0
  39. package/dist/nuxt-layers.js +3 -0
  40. package/dist/nuxt-runtime.d.ts +18 -0
  41. package/dist/nuxt-runtime.js +102 -0
  42. package/dist/nuxt.d.ts +386 -0
  43. package/dist/nuxt.js +590 -0
  44. package/dist/runtime-C_IWNrAG.js +5817 -0
  45. package/dist/runtime.d.ts +2583 -0
  46. package/dist/runtime.js +4 -0
  47. package/dist/session-Bk985AIM.js +1721 -0
  48. package/dist/types-B6FdB7LJ.d.ts +57 -0
  49. package/dist/universal-B2eD9xho.d.ts +97 -0
  50. package/dist/universal-BNTo_83u.js +599 -0
  51. package/dist/virtual-mono-apps.d.ts +16 -0
  52. package/dist/vite.d.ts +940 -0
  53. package/dist/vite.js +1132 -0
  54. package/package.json +141 -3
package/dist/nuxt.js ADDED
@@ -0,0 +1,590 @@
1
+ import { o as pathAppRoots, t as appRootDirs } from "./app-roots-CvJnmXcs.js";
2
+ import { c as resolveMonoConfig, l as srcDirForType, o as resolveExtendsAppNames, s as resolveExtendsEcosystems } from "./create-config-DdL3Fh6T.js";
3
+ import { n as mergeEcosystem, r as monoEcosystem, t as ecosystemSubAllowed } from "./merge-file-CtyKTu5L.js";
4
+ import { t as getMonoConfig } from "./config-node-UzJrXg0Z.js";
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
+ import { a as defaultMonoExpose, i as monoRouterLinkToNuxtLink, l as remoteGate, o as sanitizeForExpose, s as parsePageMeta } from "./mono-link-YlOQ2PVS.js";
7
+ import { r as registerMonoNuxtLayers, t as monoLayerCandidates } from "./nuxt-layers-DP1m7f1-.js";
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
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";
11
+
12
+ //#region src/nuxt/nuxt-ecosystem.ts
13
+ /**
14
+ * The built-in ecosystem map, given THIS app's `template`.
15
+ *
16
+ * `pages`/`imports`/`components` are role-independent — a host absorbs its
17
+ * remotes' features, a remote absorbs its host's, and both want the same four
18
+ * folders. The shell is where the roles disagree:
19
+ *
20
+ * - `layouts` follows `mono.vite()` exactly (`monoLayoutsOptions`): a `host`
21
+ * owns the shared shell and must not adopt a remote's `default.vue`, while a
22
+ * `remote` — and an ABSENT `template`, which has always read as `remote` —
23
+ * consumes the host's.
24
+ * - `middleware` / `plugins` have no `mono.vite()` analogue, so there is no
25
+ * prior behaviour to preserve. They are enabled for an EXPLICIT `remote`
26
+ * only: quietly running a remote's global middleware or its Sentry plugin
27
+ * inside an existing Nuxt host would be a regression, not a fix. A host that
28
+ * wants them opts in by restating the entry in `mono.utils.ecosystem`.
29
+ */
30
+ function nuxtEcosystemDefaults(template) {
31
+ return {
32
+ pages: {
33
+ type: "pages",
34
+ relDir: "pages"
35
+ },
36
+ composables: {
37
+ type: "imports",
38
+ relDir: "composables"
39
+ },
40
+ stores: {
41
+ type: "imports",
42
+ relDir: "stores"
43
+ },
44
+ components: {
45
+ type: "components",
46
+ relDir: "components"
47
+ },
48
+ layouts: {
49
+ type: "layouts",
50
+ relDir: "layouts",
51
+ enabled: template !== "host"
52
+ },
53
+ middleware: {
54
+ type: "middleware",
55
+ relDir: "middleware",
56
+ enabled: template === "remote"
57
+ },
58
+ plugins: {
59
+ type: "plugins",
60
+ relDir: "plugins",
61
+ enabled: template === "remote"
62
+ }
63
+ };
64
+ }
65
+ /**
66
+ * Default page-exclude globs for the federated `pages` dirs.
67
+ *
68
+ * Only the root `index.vue` is ever in question, and the answer is visible on
69
+ * disk: an app that ships its own `pages/index.vue` owns `/`, so a federated
70
+ * root index would clobber it. An app that does NOT — every remote, which takes
71
+ * the host's login page as `/` — must let it through. Same derivation as
72
+ * `monoPagesOptions` (`src/vite/mono-vite.ts`), which reads `ownsRoot` off the
73
+ * filesystem rather than asking the config.
74
+ *
75
+ * Deeper `<folder>/index.vue` pages are never excluded by this.
76
+ */
77
+ function remotePageExcludes(ownPagesDir) {
78
+ return existsSync(join(ownPagesDir, "index.vue")) ? ["index.vue"] : [];
79
+ }
80
+ /**
81
+ * The identity two files fight over when one is federated and one is the app's
82
+ * own: the basename, minus its extension and minus a trailing Nuxt mode/scope
83
+ * suffix (`.client` / `.server` / `.global`).
84
+ *
85
+ * Dropping the suffix is deliberate — an app's own `plugins/mono.ts` should win
86
+ * over a host's `plugins/mono.client.ts`, since they are two versions of one
87
+ * plugin rather than two plugins.
88
+ */
89
+ function ecosystemFileKey(file) {
90
+ return (file.replaceAll("\\", "/").split("/").pop() ?? file).replace(/\.(vue|[cm]?[jt]sx?)$/, "").replace(/\.(client|server|global)$/, "");
91
+ }
92
+ /**
93
+ * The `ecosystemFileKey`s this app ships in its OWN `<srcDir>/<sub>` folder.
94
+ *
95
+ * Used to skip a federated layout/middleware/plugin the app has replaced. Nuxt
96
+ * already refuses to clobber for layouts (`app.layouts`) and middleware
97
+ * (`addRouteMiddleware` matches on name), but `addPlugin` dedupes on absolute
98
+ * `src` — which never matches across two checkouts — so the rule is applied
99
+ * here for all three rather than relying on three different behaviours.
100
+ */
101
+ function ownEcosystemKeys(ownDir) {
102
+ const keys = /* @__PURE__ */ new Set();
103
+ if (!existsSync(ownDir)) return keys;
104
+ for (const entry of readdirSync(ownDir, { withFileTypes: true })) {
105
+ if (entry.isDirectory()) continue;
106
+ keys.add(ecosystemFileKey(entry.name));
107
+ }
108
+ return keys;
109
+ }
110
+ /** Recursively collect files under `dir` whose extension is in `exts`. */
111
+ function walkFiles(dir, exts) {
112
+ const out = [];
113
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return out;
114
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
115
+ const full = join(dir, entry.name);
116
+ if (entry.isDirectory()) out.push(...walkFiles(full, exts));
117
+ else if (exts.some((ext) => entry.name.endsWith(ext))) out.push(full);
118
+ }
119
+ return out;
120
+ }
121
+ /** Top-level files only (no recursion) whose extension is in `exts`. */
122
+ function topLevelFiles(dir, exts) {
123
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return [];
124
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => !e.isDirectory() && exts.some((ext) => e.name.endsWith(ext))).map((e) => join(dir, e.name));
125
+ }
126
+ /**
127
+ * `layouts/home.vue` -> `home`, `layouts/admin/users.vue` -> `admin-users` —
128
+ * the same path-to-name flattening Nuxt applies to its own `layouts/` dir.
129
+ */
130
+ function layoutNameFor(layoutsDir, file) {
131
+ return relative(layoutsDir, file).replace(/\.vue$/, "").split(sep).join("-");
132
+ }
133
+ /** `route-guard.global.ts` -> `{ name: 'route-guard', global: true }`. */
134
+ function middlewareNameFor(file) {
135
+ const base = (file.replaceAll("\\", "/").split("/").pop() ?? file).replace(/\.[cm]?[jt]sx?$/, "");
136
+ const global = base.endsWith(".global");
137
+ return {
138
+ name: global ? base.slice(0, -7) : base,
139
+ global
140
+ };
141
+ }
142
+ /** Source extensions Nuxt accepts for middleware / plugins. */
143
+ const SCRIPT_EXTENSIONS = [
144
+ ".ts",
145
+ ".mts",
146
+ ".cts",
147
+ ".js",
148
+ ".mjs",
149
+ ".cjs",
150
+ ".tsx",
151
+ ".jsx"
152
+ ];
153
+
154
+ //#endregion
155
+ //#region src/nuxt/host-nuxt.ts
156
+ /**
157
+ * Mono Nuxt module — the Nuxt equivalent of the Vite side's `mono.vite()`
158
+ * ecosystem block, and like it, ONE module serving both roles. A Nuxt HOST
159
+ * absorbs its remotes' features; a Nuxt REMOTE (`template: 'remote'`) absorbs
160
+ * its host's shell. `mono.config.ts`'s `template` is what says which, exactly as
161
+ * it does for `mono.vite()` — the file is still named `host-nuxt.ts` only
162
+ * because the export path `@mono-lit/utility/nuxt` is public.
163
+ *
164
+ * At BUILD time it:
165
+ *
166
+ * - builds the `monoAlias` map (`@<own>`, `@<remote>`, `@mono-apps`, …) and
167
+ * applies it to Nuxt + jiti, plus any `mono.alias` overrides
168
+ * - resolves `mono.config.ts` (incl. its `extends` chain) via c12/jiti and
169
+ * exposes a trimmed, serialisable subset to the client as the compile-time
170
+ * global `__MONO_CONFIG_EXPOSE__`
171
+ * - discovers folders across every federated app under `.mono/apps/<name>` (via
172
+ * `mergeEcosystem`) per the `ecosystem` map and wires each into Nuxt:
173
+ * - type 'pages' -> routes via `extendPages` (layout/title from `definePage`)
174
+ * - type 'imports' -> `addImportsDir` (composables/stores auto-import)
175
+ * - type 'components' -> `addComponentsDir`
176
+ * - type 'layouts' -> `app.layouts` via the `app:templates` hook
177
+ * - type 'middleware' -> `addRouteMiddleware` (`.global` honoured)
178
+ * - type 'plugins' -> `addPlugin` (`.client`/`.server` honoured)
179
+ * Defaults cover pages/composables/stores/components for every role, plus
180
+ * layouts/middleware/plugins for a remote — see `nuxtEcosystemDefaults`. A
181
+ * file this app ships itself always wins over the federated one of the same
182
+ * name.
183
+ * - rewrites the unplugin-vue-router macro `definePage({ meta: X })` to Nuxt's
184
+ * `definePageMeta(X)` for the out-of-tree remote `.vue` files
185
+ * - rewrites `<RouterLink>` -> `<NuxtLink>` in remote templates, so remote links
186
+ * prefetch and handle external URLs like the host's own
187
+ * - opens Vite's dev-server `fs.allow` to `.apps/` and excludes the
188
+ * web-components lib from dep pre-bundling (single `customElements.define`).
189
+ *
190
+ * Configure via the `mono` key in `nuxt.config.ts`; register with
191
+ * `modules: ['@mono-lit/utility/nuxt']`.
192
+ */
193
+ /**
194
+ * Turn an `ecosystems` policy into a plain allow/deny for one custom
195
+ * `dir`/`sub` ecosystem entry.
196
+ *
197
+ * `mergeEcosystem` matches the policy against each resolved directory, but a
198
+ * custom entry's `dir` is arbitrary (`dir: 'shared/widgets'`) and carries no
199
+ * sub name to match on. So decide per app up front, using the entry's own
200
+ * identity as the sub, and hand `mergeEcosystem` a verdict instead: `[]` blocks
201
+ * that app, an absent key leaves it untouched.
202
+ *
203
+ * Returns `undefined` when no app is blocked, so the common path stays free of
204
+ * an empty filter object.
205
+ */
206
+ function gateCustomEntry(ecosystems, sub) {
207
+ const blocked = {};
208
+ for (const [app, allow] of Object.entries(ecosystems)) if (!ecosystemSubAllowed(sub, allow)) blocked[app] = [];
209
+ return Object.keys(blocked).length ? blocked : void 0;
210
+ }
211
+ const monoNuxtModule = defineNuxtModule({
212
+ meta: {
213
+ name: "mono-nuxt",
214
+ configKey: "mono"
215
+ },
216
+ defaults: {},
217
+ async setup(options, nuxt) {
218
+ const rootDir = nuxt.options.rootDir;
219
+ const u = options.utils ?? options;
220
+ const optimizeExclude = u.optimizeExclude ?? ["@mono-lit/helper"];
221
+ assertAppSources(extractConfig(rootDir).apps, rootDir);
222
+ const appRoots = resolveFederatedRoots({ dirname: rootDir });
223
+ const alias = monoAlias({ dirname: rootDir });
224
+ for (const [key, value] of Object.entries(u.alias ?? {})) {
225
+ const dir = value?.dir;
226
+ if (!dir) continue;
227
+ alias[key] = isAbsolute(dir) ? dir : resolve(rootDir, dir);
228
+ }
229
+ nuxt.options.alias = {
230
+ ...alias,
231
+ ...nuxt.options.alias
232
+ };
233
+ const { alias: stubAlias, missing } = u.stubMissing === false ? {
234
+ alias: {},
235
+ missing: []
236
+ } : monoStubAliases({ dirname: rootDir });
237
+ if (missing.length && u.warnMissing !== false) console.warn(formatMissingApps(missing));
238
+ const rawConfig = await getMonoConfig({
239
+ cwd: rootDir,
240
+ jitiOptions: { alias: {
241
+ ...alias,
242
+ ...stubAlias
243
+ } }
244
+ });
245
+ const hasExtends = rawConfig.extends != null;
246
+ const activeNames = resolveExtendsAppNames(rawConfig);
247
+ const activeApps = hasExtends ? (rawConfig.apps ?? []).filter((a) => activeNames.includes(a.name)) : rawConfig.apps ?? [];
248
+ const extendsEcosystems = resolveExtendsEcosystems(rawConfig);
249
+ const monoConfig = {
250
+ ...resolveMonoConfig(rawConfig),
251
+ apps: rawConfig.apps,
252
+ ...rawConfig.extends != null ? { extends: rawConfig.extends } : {}
253
+ };
254
+ const ownSrcDir = join(rootDir, srcDirForType(rawConfig.type ?? "nuxt"));
255
+ const ecosystem = {
256
+ ...nuxtEcosystemDefaults(rawConfig.template),
257
+ ...u.ecosystem ?? {}
258
+ };
259
+ const layerCandidates = monoLayerCandidates({
260
+ apps: activeApps,
261
+ appRoots,
262
+ template: rawConfig.template
263
+ });
264
+ const layered = registerMonoNuxtLayers({
265
+ nuxt,
266
+ candidates: layerCandidates
267
+ });
268
+ dedupeLayerPlugins(nuxt, layerCandidates, ownSrcDir);
269
+ const mergeApps = activeApps.filter((app) => !layered.has(app.name));
270
+ const mergeNames = activeNames.filter((name) => !layered.has(name));
271
+ if (layered.size) console.log(`[mono-nuxt] merged via native Nuxt layers: ${[...layered].join(", ")}`);
272
+ for (const [name, entry] of Object.entries(ecosystem)) {
273
+ if (!entry || entry.enabled === false) continue;
274
+ if (hasExtends && activeApps.length === 0) break;
275
+ const entryApps = entry.type === "imports" ? activeApps : mergeApps;
276
+ const entryNames = entry.type === "imports" ? activeNames : mergeNames;
277
+ if (!entryApps.length && hasExtends) continue;
278
+ const dirs = entry.relDir != null ? monoEcosystem({
279
+ dirname: rootDir,
280
+ apps: entryApps,
281
+ subs: entry.relDir,
282
+ appDir: entry.appDir,
283
+ includes: entry.includes,
284
+ excludes: entry.excludes,
285
+ ecosystems: extendsEcosystems,
286
+ dirIncludes: entry.dirIncludes,
287
+ dirExcludes: entry.dirExcludes
288
+ }) : mergeEcosystem({
289
+ dirname: rootDir,
290
+ dir: entry.dir,
291
+ sub: entry.sub,
292
+ appDir: entry.appDir,
293
+ appDirs: entry.appDirs,
294
+ includes: entry.includes ?? (hasExtends ? entryNames : void 0),
295
+ excludes: entry.excludes,
296
+ ecosystems: gateCustomEntry(extendsEcosystems, entry.sub ?? name),
297
+ dirIncludes: entry.dirIncludes,
298
+ dirExcludes: entry.dirExcludes
299
+ });
300
+ switch (entry.type) {
301
+ case "imports":
302
+ for (const dir of dirs) if (existsSync(dir)) addImportsDir([dir, join(dir, "**")]);
303
+ break;
304
+ case "components": {
305
+ const pathPrefix = entry.pathPrefix !== false;
306
+ for (const dir of dirs) if (existsSync(dir) && statSync(dir).isDirectory()) addComponentsDir({
307
+ path: dir,
308
+ pathPrefix
309
+ });
310
+ break;
311
+ }
312
+ case "pages":
313
+ registerRemotePages(dirs, entry.exclude ?? remotePageExcludes(join(ownSrcDir, "pages")), name);
314
+ break;
315
+ case "layouts":
316
+ registerRemoteLayouts(nuxt, dirs, entry.exclude ?? [], ownSrcDir, name);
317
+ break;
318
+ case "middleware":
319
+ registerRemoteMiddleware(dirs, entry.exclude ?? [], ownSrcDir, name);
320
+ break;
321
+ case "plugins":
322
+ registerRemotePlugins(dirs, entry.exclude ?? [], ownSrcDir, name);
323
+ break;
324
+ }
325
+ }
326
+ extendViteConfig((config) => {
327
+ config.define = {
328
+ ...config.define,
329
+ __MONO_CONFIG_EXPOSE__: JSON.stringify(sanitizeForExpose((u.expose ?? defaultMonoExpose)(monoConfig)) ?? {})
330
+ };
331
+ if (Object.keys(stubAlias).length) {
332
+ config.resolve ??= {};
333
+ const existing = config.resolve.alias;
334
+ config.resolve.alias = Array.isArray(existing) ? [...Object.entries(stubAlias).map(([find, replacement]) => ({
335
+ find,
336
+ replacement
337
+ })), ...existing] : {
338
+ ...stubAlias,
339
+ ...existing
340
+ };
341
+ }
342
+ config.server ??= {};
343
+ config.server.fs ??= {};
344
+ config.server.fs.allow = [
345
+ ...config.server.fs.allow ?? [],
346
+ rootDir,
347
+ join(rootDir, ".mono", "apps"),
348
+ ...appRootDirs(pathAppRoots(appRoots))
349
+ ];
350
+ config.optimizeDeps ??= {};
351
+ config.optimizeDeps.exclude = [...config.optimizeDeps.exclude ?? [], ...optimizeExclude];
352
+ config.ssr ??= {};
353
+ config.ssr.noExternal = [
354
+ ...Array.isArray(config.ssr.noExternal) ? config.ssr.noExternal : [],
355
+ "@mono-lit/utility",
356
+ "notivue",
357
+ "devextreme",
358
+ "exceljs",
359
+ "file-saver-es",
360
+ "@odata2ts/http-client-fetch",
361
+ "uuid",
362
+ "tslib"
363
+ ];
364
+ });
365
+ if (u.nuxtLink !== false) addVitePlugin(monoRouterLinkToNuxtLink({ appsRoots: appRootDirs(appRoots) }));
366
+ const isRemoteFile = remoteGate({ appsRoots: appRootDirs(appRoots) });
367
+ addVitePlugin({
368
+ name: "mono-define-page-to-pagemeta",
369
+ enforce: "pre",
370
+ transform(code, id) {
371
+ const file = id?.split("?")[0]?.replace(/\\/g, "/");
372
+ if (!file || !file.endsWith(".vue") || !isRemoteFile(file)) return;
373
+ if (!code.includes("definePage")) return;
374
+ const out = code.replace(/\bdefinePage\s*\(\s*\{\s*meta\s*:\s*(\{[\s\S]*?\})\s*,?\s*\}\s*\)/g, "definePageMeta($1)");
375
+ return out === code ? void 0 : {
376
+ code: out,
377
+ map: null
378
+ };
379
+ }
380
+ });
381
+ addPluginTemplate({
382
+ filename: "mono-state-init.mjs",
383
+ getContents: () => [
384
+ "import { initMono } from \"@mono-lit/utility/runtime\"",
385
+ "export default defineNuxtPlugin(() => {",
386
+ " initMono(__MONO_CONFIG_EXPOSE__)",
387
+ "})"
388
+ ].join("\n")
389
+ });
390
+ }
391
+ });
392
+ /**
393
+ * Register every `.vue` under the given remote `dirs` as a Nuxt route, skipping
394
+ * files matching any `exclude` glob and never clobbering an existing host route.
395
+ */
396
+ function registerRemotePages(dirs, exclude, label) {
397
+ extendPages((pages) => {
398
+ const existing = new Set(pages.map((p) => p.path));
399
+ const added = [];
400
+ for (const dir of dirs) {
401
+ if (!existsSync(dir)) continue;
402
+ for (const file of walkVue(dir)) {
403
+ const rel = relative(dir, file).split(sep).join("/");
404
+ if (exclude.some((pattern) => globMatch(pattern, rel))) continue;
405
+ const routePath = toRoutePath(rel);
406
+ if (existing.has(routePath)) continue;
407
+ existing.add(routePath);
408
+ pages.push({
409
+ name: "remote-" + rel.replace(/\.vue$/, "").replace(/[^a-zA-Z0-9]+/g, "-"),
410
+ path: routePath,
411
+ file,
412
+ meta: parsePageMeta(safeRead(file))
413
+ });
414
+ added.push(routePath);
415
+ }
416
+ }
417
+ if (added.length) console.log(`[mono-nuxt] merged remote route(s) [${label}]:`, added.join(", "));
418
+ });
419
+ }
420
+ /**
421
+ * Give this app's own plugins priority over a Nuxt LAYER's, by name.
422
+ *
423
+ * Nuxt gives layouts and middleware that rule for free but not plugins, which it
424
+ * dedupes on absolute `src` — so a remote's `plugins/mono.ts` and its host's
425
+ * both survive, and both call `createMono()` with a different config. Dropping
426
+ * the layer's copy is the whole fix.
427
+ *
428
+ * Runs on `app:resolve`, the one point where `app.plugins` exists and is still
429
+ * mutable. A no-op when this app ships no plugins of its own.
430
+ */
431
+ function dedupeLayerPlugins(nuxt, candidates, ownSrcDir) {
432
+ if (!candidates.length) return;
433
+ const ownKeys = ownEcosystemKeys(join(ownSrcDir, "plugins"));
434
+ if (!ownKeys.size) return;
435
+ const roots = candidates.map((c) => normalize(c.root).toLowerCase());
436
+ const inLayer = (src) => {
437
+ const file = normalize(src).toLowerCase();
438
+ return roots.some((root) => file.startsWith(root + sep));
439
+ };
440
+ nuxt.hook("app:resolve", (app) => {
441
+ const dropped = [];
442
+ app.plugins = app.plugins.filter((plugin) => {
443
+ const src = plugin?.src;
444
+ if (!src || !inLayer(src)) return true;
445
+ if (!ownKeys.has(ecosystemFileKey(src))) return true;
446
+ dropped.push(relative(rootOf(candidates, src), src).split(sep).join("/"));
447
+ return false;
448
+ });
449
+ if (dropped.length) console.log(`[mono-nuxt] shadowed federated plugin(s) with this app's own:`, dropped.join(", "));
450
+ });
451
+ }
452
+ /** The layer root a file sits in, for a readable log line. */
453
+ function rootOf(candidates, file) {
454
+ const lower = normalize(file).toLowerCase();
455
+ return candidates.find((c) => lower.startsWith(normalize(c.root).toLowerCase() + sep))?.root ?? "";
456
+ }
457
+ /**
458
+ * Register every `.vue` under the given federated `layouts` dirs as a Nuxt
459
+ * layout, so a remote renders inside its host's shell.
460
+ *
461
+ * Done through the `app:templates` hook rather than kit's `addLayout` on
462
+ * purpose: `addLayout` routes the file through `addTemplate`, which COPIES it
463
+ * into `.nuxt/` — a snapshot that breaks HMR on the host's shell and any
464
+ * path-relative import inside it. Writing `app.layouts` directly is what Nuxt
465
+ * itself does for `<srcDir>/layouts`, and it points at the real file.
466
+ *
467
+ * The hook runs after Nuxt has resolved this app's own layouts, so the
468
+ * `layoutName in app.layouts` guard already gives own-file-wins; the
469
+ * `ownEcosystemKeys` check in front of it makes the same rule explicit and
470
+ * consistent with middleware/plugins.
471
+ */
472
+ function registerRemoteLayouts(nuxt, dirs, exclude, ownSrcDir, label) {
473
+ const own = ownEcosystemKeys(join(ownSrcDir, "layouts"));
474
+ const found = [];
475
+ for (const dir of dirs) for (const file of walkFiles(dir, [".vue"])) {
476
+ const rel = relative(dir, file).split(sep).join("/");
477
+ if (exclude.some((pattern) => globMatch(pattern, rel))) continue;
478
+ if (own.has(ecosystemFileKey(file))) continue;
479
+ found.push({
480
+ name: layoutNameFor(dir, file),
481
+ file
482
+ });
483
+ }
484
+ if (!found.length) return;
485
+ nuxt.hook("app:templates", (app) => {
486
+ const added = [];
487
+ for (const { name, file } of found) {
488
+ if (name in app.layouts) continue;
489
+ app.layouts[name] = {
490
+ name,
491
+ file
492
+ };
493
+ added.push(name);
494
+ }
495
+ if (added.length) console.log(`[mono-nuxt] merged federated layout(s) [${label}]:`, added.join(", "));
496
+ });
497
+ }
498
+ /**
499
+ * Register the top-level files of the given federated `middleware` dirs as Nuxt
500
+ * route middleware, honouring the `.global` suffix.
501
+ *
502
+ * TOP LEVEL ONLY, deliberately: Nuxt treats every file in `middleware/` as a
503
+ * middleware, but a federated app nests plain helper modules underneath —
504
+ * mono-nuxt-host keeps its guard dispatcher in `middleware/run-guards.ts` and
505
+ * the guards themselves in `middleware/guards/`, imported BY the global
506
+ * middleware rather than registered alongside it. Recursing would register four
507
+ * guards as four independent middlewares.
508
+ *
509
+ * `addRouteMiddleware` matches on `name`, so a name this app already defines is
510
+ * left alone (it warns rather than overwrites); the `ownEcosystemKeys` check
511
+ * skips it before that happens.
512
+ */
513
+ function registerRemoteMiddleware(dirs, exclude, ownSrcDir, label) {
514
+ const own = ownEcosystemKeys(join(ownSrcDir, "middleware"));
515
+ const added = [];
516
+ for (const dir of dirs) for (const file of topLevelFiles(dir, SCRIPT_EXTENSIONS)) {
517
+ const rel = relative(dir, file).split(sep).join("/");
518
+ if (exclude.some((pattern) => globMatch(pattern, rel))) continue;
519
+ if (own.has(ecosystemFileKey(file))) continue;
520
+ const { name, global } = middlewareNameFor(file);
521
+ addRouteMiddleware({
522
+ name,
523
+ path: file,
524
+ global
525
+ });
526
+ added.push(global ? `${name} (global)` : name);
527
+ }
528
+ if (added.length) console.log(`[mono-nuxt] merged federated middleware [${label}]:`, added.join(", "));
529
+ }
530
+ /**
531
+ * Register the top-level files of the given federated `plugins` dirs as Nuxt
532
+ * plugins. `normalizePlugin` reads the `.client` / `.server` suffix off the
533
+ * path itself, so no `mode` is passed.
534
+ *
535
+ * `append: true` keeps discovery order — `addPlugin` unshifts by default, which
536
+ * would reverse a whole directory.
537
+ *
538
+ * This is the one destination where own-file-wins is load-bearing rather than
539
+ * belt-and-braces: `addPlugin` dedupes on the absolute `src`, which never
540
+ * matches across two checkouts. A remote shipping its own `plugins/mono.ts`
541
+ * (pointing `createMono` at ITS config instead of the host's) relies on this.
542
+ */
543
+ function registerRemotePlugins(dirs, exclude, ownSrcDir, label) {
544
+ const own = ownEcosystemKeys(join(ownSrcDir, "plugins"));
545
+ const added = [];
546
+ for (const dir of dirs) for (const file of topLevelFiles(dir, SCRIPT_EXTENSIONS)) {
547
+ const rel = relative(dir, file).split(sep).join("/");
548
+ if (exclude.some((pattern) => globMatch(pattern, rel))) continue;
549
+ if (own.has(ecosystemFileKey(file))) continue;
550
+ addPlugin({ src: file }, { append: true });
551
+ added.push(rel);
552
+ }
553
+ if (added.length) console.log(`[mono-nuxt] merged federated plugin(s) [${label}]:`, added.join(", "));
554
+ }
555
+ /** Recursively collect `.vue` files under a directory. */
556
+ function walkVue(dir) {
557
+ const out = [];
558
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
559
+ const full = join(dir, entry.name);
560
+ if (entry.isDirectory()) out.push(...walkVue(full));
561
+ else if (entry.name.endsWith(".vue")) out.push(full);
562
+ }
563
+ return out;
564
+ }
565
+ /** `budget/alokasi/index.vue` -> `/budget/alokasi`, `budget/[id].vue` -> `/budget/:id`. */
566
+ function toRoutePath(rel) {
567
+ let p = rel.replace(/\.vue$/, "").replace(/\/index$/, "").replace(/\[([^\]]+)\]/g, ":$1");
568
+ p = "/" + p;
569
+ if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
570
+ return p;
571
+ }
572
+ function safeRead(file) {
573
+ try {
574
+ return readFileSync(file, "utf-8");
575
+ } catch {
576
+ return "";
577
+ }
578
+ }
579
+ /**
580
+ * Minimal glob matcher for a `/`-joined relative path. Supports `**` (any path
581
+ * segments), `*` (any chars within a segment) and `?` (single char). No
582
+ * dependency — enough for page-exclude patterns like `index.vue` (root only).
583
+ */
584
+ function globMatch(pattern, input) {
585
+ const re = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(//g, ".*").replace(/\?/g, "[^/]");
586
+ return new RegExp(`^${re}$`).test(input);
587
+ }
588
+
589
+ //#endregion
590
+ export { monoNuxtModule as default };