@vaadin/hilla-file-router 25.2.6 → 25.2.8

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaadin/hilla-file-router",
3
- "version": "25.2.6",
3
+ "version": "25.2.8",
4
4
  "description": "Hilla file-based router",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
@@ -62,9 +62,9 @@
62
62
  },
63
63
  "dependencies": {
64
64
  "@ungap/with-resolvers": "0.1.0",
65
- "@vaadin/hilla-generator-utils": "25.2.6",
66
- "@vaadin/hilla-react-auth": "25.2.6",
67
- "@vaadin/hilla-react-signals": "25.2.6",
65
+ "@vaadin/hilla-generator-utils": "25.2.8",
66
+ "@vaadin/hilla-react-auth": "25.2.8",
67
+ "@vaadin/hilla-react-signals": "25.2.8",
68
68
  "typescript": "6.0.3"
69
69
  }
70
70
  }
@@ -19,7 +19,7 @@ export function createMenuItems() {
19
19
  vaadinObj.registrations ??= [];
20
20
  vaadinObj.registrations.push({
21
21
  is: feature ? `@vaadin/hilla-file-router/${feature}` : "@vaadin/hilla-file-router",
22
- version: "25.2.6"
22
+ version: "25.2.8"
23
23
  });
24
24
  })("createMenuItems", window.Vaadin);
25
25
  const collator = new Intl.Collator("en-US");
@@ -1 +1 @@
1
- {"mappings":"AACA,SAAsB,2CAA4C;AAIlE,OAAO,MAAMA,cAAkF,OAC5F,OAAwB,QAAQ,MAClC;AAED,SAAS,WAAWC,OAA4B;AAC9C,UAAS,MAAM,MAAM;AACtB;AAED,SAAS,uBAAuBC,MAAuB;AACrD,QAAO,KAAK,MAAM,IAAI,CAAC,KAAK,CAAC,YAAY,QAAQ,WAAW,IAAI,CAAC;AAClE;;;;;;;;;AAUD,OAAO,SAAS,kBAA2D;AAGzE,EAAC,CAAC,SAAS,YAAa,WAAW,WAAW,CAAE,MAAM;AACtD,YAAU,kBAAkB,CAAE;AAC9B,YAAU,cAAc,KAAK;GAC3B,IAAI,WAAW,4BAA4B,QAAQ,IAAI;GACvD,SAAS;EACV,EAAC;CACH,GAAE,mBAAoB,OAAwB,OAAO;CACpD,MAAM,WAAW,IAAI,KAAK,SAAS;AACnC,MAAK,YAAY,OAAO;AACtB,SAAO,CAAE;CACV;CAED,MAAM,QAAQ,OAAO,QAAQ,YAAY,MAAM;AAE/C,QACE,MAEG,OAAO,CAAC,CAAC,MAAM,MAAM,MAAM,WAAW,MAAM,KAAK,uBAAuB,KAAK,CAAC,CAE9E,IAAI,CAAC,CAAC,MAAM,OAAO,MAAM;EACxB,IAAI;EACJ,MAAM,OAAO,MAAM;EACnB,OAAO,OAAO,MAAM,SAAS,OAAO;EACpC,OAAO,OAAO,MAAM;EACpB,QAAQ,OAAO;CAChB,GAAE,CAEF,KAAK,CAAC,OAAO,UAAU;EACtB,MAAM,cAAc,MAAM,SAAS,OAAO,cAAc,MAAM,SAAS,OAAO;AAC9E,SAAO,eAAe,IAAI,aAAa,SAAS,QAAQ,MAAM,IAAI,MAAM,GAAG;CAC5E,EAAC;AAEP;AAED,IAAI,OAAO,KAAK,KAAK;AACnB,QAAO,KAAK,IAAI,GAAG,mBAAmB,MAAM;AAC1C,QAAM,iBAAiB,CACpB,KAAK,OAAO,SAAS,KAAK,MAAM,CAAC,CACjC,KAAK,CAAC,SAAS;AACd,eAAY,QAAQ;EACrB,EAAC,CACD,MAAM,CAACC,MAAe;AACrB,WAAQ,MAAM,8BAA8B,EAAE;EAC/C,EAAC;CACL,EAAC;AACH","names":["viewsSignal: Signal<Readonly<Record<string, Readonly<ViewConfig>>> | undefined>","value: ViewConfig","path: string","e: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/file-router/src/runtime/createMenuItems.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport { type Signal, signal } from '@vaadin/hilla-react-signals';\nimport type { VaadinWindow } from '../shared/internal.js';\nimport type { MenuItem, ViewConfig } from '../types.js';\n\nexport const viewsSignal: Signal<Readonly<Record<string, Readonly<ViewConfig>>> | undefined> = signal(\n (window as VaadinWindow).Vaadin?.views,\n);\n\nfunction isExcluded(value: ViewConfig): boolean {\n return !!value.menu?.exclude;\n}\n\nfunction hasVariablePathSegment(path: string): boolean {\n return path.split('/').some((segment) => segment.startsWith(':'));\n}\n\n/**\n * Creates menu items from the views provided by the server. The views are sorted according to the\n * {@link ViewConfig.menu.order}, filtered out if they are explicitly excluded via {@link ViewConfig.menu.exclude}.\n * Note that views with no order are put below views with an order. Ties are resolved based on the path string\n * comparison.\n *\n * @returns A list of menu items.\n */\nexport function createMenuItems<T = unknown>(): ReadonlyArray<MenuItem<T>> {\n // @ts-expect-error: esbuild injection\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n ((feature, vaadinObj = (globalThis.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-file-router/${feature}` : '@vaadin/hilla-file-router',\n version: '25.2.6',\n });\n})('createMenuItems', (window as VaadinWindow).Vaadin);\n const collator = new Intl.Collator('en-US');\n if (!viewsSignal.value) {\n return [];\n }\n\n const views = Object.entries(viewsSignal.value);\n\n return (\n views\n // Filter out the views that are explicitly excluded from the menu.\n .filter(([path, value]) => !isExcluded(value) && !hasVariablePathSegment(path))\n // Map the views to menu items.\n .map(([path, config]) => ({\n to: path,\n icon: config.menu?.icon,\n title: config.menu?.title ?? config.title,\n order: config.menu?.order,\n detail: config.detail as T | undefined,\n }))\n // Sort views according to the order specified in the view configuration.\n .sort((menuA, menuB) => {\n const ordersDiff = (menuA.order ?? Number.MAX_VALUE) - (menuB.order ?? Number.MAX_VALUE);\n return ordersDiff !== 0 ? ordersDiff : collator.compare(menuA.to, menuB.to);\n })\n );\n}\n\nif (import.meta.hot) {\n import.meta.hot.on('fs-route-update', () => {\n fetch('?v-r=routeinfo')\n .then(async (resp) => resp.json())\n .then((json) => {\n viewsSignal.value = json;\n })\n .catch((e: unknown) => {\n console.error('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,CAAC,CACjC,KAAK,CAAC,SAAS;AACd,eAAY,QAAQ;EACrB,EAAC,CACD,MAAM,CAACC,MAAe;AACrB,WAAQ,MAAM,8BAA8B,EAAE;EAC/C,EAAC;CACL,EAAC;AACH","names":["viewsSignal: Signal<Readonly<Record<string, Readonly<ViewConfig>>> | undefined>","value: ViewConfig","path: string","e: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/file-router/src/runtime/createMenuItems.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport { type Signal, signal } from '@vaadin/hilla-react-signals';\nimport type { VaadinWindow } from '../shared/internal.js';\nimport type { MenuItem, ViewConfig } from '../types.js';\n\nexport const viewsSignal: Signal<Readonly<Record<string, Readonly<ViewConfig>>> | undefined> = signal(\n (window as VaadinWindow).Vaadin?.views,\n);\n\nfunction isExcluded(value: ViewConfig): boolean {\n return !!value.menu?.exclude;\n}\n\nfunction hasVariablePathSegment(path: string): boolean {\n return path.split('/').some((segment) => segment.startsWith(':'));\n}\n\n/**\n * Creates menu items from the views provided by the server. The views are sorted according to the\n * {@link ViewConfig.menu.order}, filtered out if they are explicitly excluded via {@link ViewConfig.menu.exclude}.\n * Note that views with no order are put below views with an order. Ties are resolved based on the path string\n * comparison.\n *\n * @returns A list of menu items.\n */\nexport function createMenuItems<T = unknown>(): ReadonlyArray<MenuItem<T>> {\n // @ts-expect-error: esbuild injection\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n ((feature, vaadinObj = (globalThis.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-file-router/${feature}` : '@vaadin/hilla-file-router',\n version: '25.2.8',\n });\n})('createMenuItems', (window as VaadinWindow).Vaadin);\n const collator = new Intl.Collator('en-US');\n if (!viewsSignal.value) {\n return [];\n }\n\n const views = Object.entries(viewsSignal.value);\n\n return (\n views\n // Filter out the views that are explicitly excluded from the menu.\n .filter(([path, value]) => !isExcluded(value) && !hasVariablePathSegment(path))\n // Map the views to menu items.\n .map(([path, config]) => ({\n to: path,\n icon: config.menu?.icon,\n title: config.menu?.title ?? config.title,\n order: config.menu?.order,\n detail: config.detail as T | undefined,\n }))\n // Sort views according to the order specified in the view configuration.\n .sort((menuA, menuB) => {\n const ordersDiff = (menuA.order ?? Number.MAX_VALUE) - (menuB.order ?? Number.MAX_VALUE);\n return ordersDiff !== 0 ? ordersDiff : collator.compare(menuA.to, menuB.to);\n })\n );\n}\n\nif (import.meta.hot) {\n import.meta.hot.on('fs-route-update', () => {\n fetch('?v-r=routeinfo')\n .then(async (resp) => resp.json())\n .then((json) => {\n viewsSignal.value = json;\n })\n .catch((e: unknown) => {\n console.error('Failed to fetch route info', e);\n });\n });\n}\n"],"version":3}
package/vite-plugin.js CHANGED
@@ -1,7 +1,48 @@
1
1
  import { basename } from "node:path";
2
2
  import { fileURLToPath, pathToFileURL } from "node:url";
3
3
  import { generateRuntimeFiles } from "./vite-plugin/generateRuntimeFiles.js";
4
- const INJECTION = "if (Object.keys(nextExports).length === 2 && 'default' in nextExports && 'config' in nextExports) {nextExports = { ...nextExports, config: currentExports.config };}";
4
+ const REFRESH_IGNORE_VIRTUAL_ID = "virtual:hilla-file-router-refresh-ignore";
5
+ const RESOLVED_REFRESH_IGNORE_VIRTUAL_ID = `\0${REFRESH_IGNORE_VIRTUAL_ID}`;
6
+ /**
7
+ * Installs the `__getReactRefreshIgnoredExports` hook of the React Refresh
8
+ * runtime.
9
+ *
10
+ * React Fast Refresh (the HMR mechanism of `@vitejs/plugin-react`) requires
11
+ * all exports of a module to be React components; otherwise, an update
12
+ * invalidates the module and causes a full page reload. Route files, however,
13
+ * are allowed to export a static `config` object in addition to the React
14
+ * component. To keep Fast Refresh working for them, each route file is
15
+ * registered in `window.__HILLA_FILE_ROUTER_VIEWS__`, and the hook excludes
16
+ * the `config` export of registered modules from the refresh boundary
17
+ * validation. Updates to the `config` contents are propagated separately
18
+ * through the regenerated `file-routes.ts` module.
19
+ *
20
+ * The hook is delivered as a virtual module imported by every route file, so
21
+ * Vite evaluates it once per application boot.
22
+ */
23
+ const REFRESH_IGNORE_INSTALLER = `if (typeof window !== 'undefined') {
24
+ const previousHook = window.__getReactRefreshIgnoredExports;
25
+ window.__getReactRefreshIgnoredExports = ({ id }) => {
26
+ const ignoredExports = previousHook?.({ id }) ?? [];
27
+ return window.__HILLA_FILE_ROUTER_VIEWS__?.has(id) ? [...ignoredExports, 'config'] : ignoredExports;
28
+ };
29
+ }
30
+ `;
31
+ /**
32
+ * Creates a code snippet that registers a route file for the exclusion of its
33
+ * `config` export from the React Fast Refresh boundary validation.
34
+ *
35
+ * @param id - The module id of the route file, as seen by the Vite transform
36
+ * pipeline. The React Refresh runtime receives the same id at runtime.
37
+ */
38
+ function createReactRefreshConfigExclusion(id) {
39
+ return `
40
+ ;import ${JSON.stringify(REFRESH_IGNORE_VIRTUAL_ID)};
41
+ if (typeof window !== 'undefined') {
42
+ (window.__HILLA_FILE_ROUTER_VIEWS__ ??= new Set()).add(${JSON.stringify(id)});
43
+ }
44
+ `;
45
+ }
5
46
  /**
6
47
  * A Vite plugin that generates a router from the files in the specific directory.
7
48
  *
@@ -47,6 +88,12 @@ export default function vitePluginFileSystemRouter({ viewsDir = "frontend/views/
47
88
  async buildStart() {
48
89
  await _generateRuntimeFiles();
49
90
  },
91
+ resolveId(source) {
92
+ return source === REFRESH_IGNORE_VIRTUAL_ID ? RESOLVED_REFRESH_IGNORE_VIRTUAL_ID : undefined;
93
+ },
94
+ load(id) {
95
+ return id === RESOLVED_REFRESH_IGNORE_VIRTUAL_ID ? REFRESH_IGNORE_INSTALLER : undefined;
96
+ },
50
97
  async hotUpdate({ file, modules }) {
51
98
  const fileUrlString = String(pathToFileURL(file));
52
99
  if (fileUrlString === String(runtimeUrls.json)) {
@@ -83,15 +130,17 @@ export default function vitePluginFileSystemRouter({ viewsDir = "frontend/views/
83
130
  let modifiedCode = code;
84
131
  if (id.startsWith(_viewsDirPosix) && !basename(id).startsWith("_")) {
85
132
  if (isDevMode) {
86
- const injectionPattern = /import\.meta\.hot\.accept[\s\S]+if\s\(!nextExports\)\s+return;/gu;
87
- if (injectionPattern.test(modifiedCode)) {
88
- modifiedCode = `${modifiedCode.substring(0, injectionPattern.lastIndex)}${INJECTION}${modifiedCode.substring(injectionPattern.lastIndex)}`;
133
+ const [path] = id.split("?");
134
+ if (extensions.some((ext) => path.endsWith(ext))) {
135
+ modifiedCode += createReactRefreshConfigExclusion(id);
89
136
  }
90
137
  } else {
91
- const functionNames = /export\s+default\s+(?:function\s+)?(\w+)/u.exec(modifiedCode);
138
+ const functionNames = /export\s+default\s+(?:(?:function|class)\s+)?(\w+)/u.exec(modifiedCode);
92
139
  if (functionNames?.length) {
93
140
  const [, functionName] = functionNames;
94
- modifiedCode += `Object.defineProperty(${functionName}, 'name', { value: '${functionName}' });\n`;
141
+ if (functionName !== "function" && functionName !== "class") {
142
+ modifiedCode += `Object.defineProperty(${functionName}, 'name', { value: '${functionName}' });\n`;
143
+ }
95
144
  }
96
145
  }
97
146
  return { code: modifiedCode };
@@ -1 +1 @@
1
- {"mappings":"AAAA,SAAS,2BAA4B;AACrC,SAAS,eAAe,+BAAgC;AAGxD,SAAS,mEAA0F;AAEnG,MAAM,YACJ;;;;;;;AA8CF,eAAe,SAAS,2BAA2B,EACjD,WAAW,mBACX,eAAe,uBACf,aAAa,CAAC,QAAQ,MAAO,GAC7B,YAAY,OACZ,QAAQ,OACM,GAAG,CAAE,GAAU;CAC7B,IAAIA;CACJ,IAAIC;CACJ,IAAIC;CACJ,IAAIC;CACJ,IAAIC;CACJ,IAAIC;AAEJ,QAAO;EACL,MAAM;EACN,SAAS;EACT,eAAe,EAAE,QAAQ,MAAM,OAAO,EAAE,QAAQ,EAAE,EAAE;GAClD,MAAM,QAAQ,cAAc,KAAK;GACjC,MAAM,gBAAgB,IAAI,IAAI,cAAc;AAE5C,eAAY,IAAI,IAAI,UAAU;AAC9B,oBAAiB,cAAc,UAAU,CAAC,WAA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,YAAY,gBAAgB,IAAK,WAAW,EAAE,QAAQ,MAAO,EAAC;IACtF,EAAC,CACH;IAED,MAAM,gBAAgB,QAAQ,MAAM,CAAC,WAAW,OAAO,UAAU,SAAS,EAAE;AAC5E,QAAI,eAAe;AAQjB,YAAO,CAAC,GAAG,iBAAkB;IAC9B;AAID,WAAO,CAAC,GAAG,mBAAmB,GAAG,OAAQ;GAC1C;AAED,UAAO;EACR;EACD,UAAU,MAAM,IAAgD;GAC9D,IAAI,eAAe;AACnB,OAAI,GAAG,WAAW,eAAe,KAAK,SAAS,GAAG,CAAC,WAAW,IAAI,EAAE;AAClE,QAAI,WAAW;KAYb,MAAM,mBAAmB;AACzB,SAAI,iBAAiB,KAAK,aAAa,EAAE;AACvC,sBAAgB,EAAE,aAAa,UAAU,GAAG,iBAAiB,UAAU,CAAC,EAAE,UAAU,EAAE,aAAa,UACjG,iBAAiB,UAClB,CAAC;KACH;IACF,OAAM;KAEL,MAAM,gBAAgB,4CAA4C,KAAK,aAAa;AAEpF,SAAI,eAAe,QAAQ;MACzB,MAAM,GAAG,aAAa,GAAG;AACzB,uBAAiB,wBAAwB,aAAa,sBAAsB,aAAa;KAC1F;IACF;AAED,WAAO,EACL,MAAM,aACP;GACF;AAED,UAAO;EACR;CACF;AACF","names":["_viewsDir: URL","_outDir: URL","_logger: Logger","runtimeUrls: RuntimeFileUrls","_generateRuntimeFiles: () => Promise<boolean>","_viewsDirPosix: string","e: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/file-router/src/vite-plugin.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { TransformResult } from 'rollup';\nimport type { EnvironmentModuleNode, HotUpdateOptions, Logger, Plugin } from 'vite';\nimport { generateRuntimeFiles, type RuntimeFileUrls } from './vite-plugin/generateRuntimeFiles.js';\n\nconst INJECTION =\n \"if (Object.keys(nextExports).length === 2 && 'default' in nextExports && 'config' in nextExports) {nextExports = { ...nextExports, config: currentExports.config };}\";\n\n/**\n * The options for the Vite file-based router plugin.\n */\nexport type PluginOptions = Readonly<{\n /**\n * The base directory for the router. The folders and files in this directory\n * will be used as route paths.\n *\n * @defaultValue `frontend/views`\n */\n viewsDir?: URL | string;\n /**\n * The directory where the generated view file will be stored.\n *\n * @defaultValue `frontend/generated`\n */\n generatedDir?: URL | string;\n /**\n * The list of extensions that will be collected as routes of the file-based\n * router.\n *\n * @defaultValue `['.tsx', '.jsx']`\n */\n extensions?: readonly string[];\n /**\n * The flag to indicate whether the plugin is running in development mode.\n *\n * @defaultValue `false`\n */\n isDevMode?: boolean;\n /**\n * The flag to indicate whether to output debug information\n *\n * @defaultValue `false`\n */\n debug?: boolean;\n}>;\n\n/**\n * A Vite plugin that generates a router from the files in the specific directory.\n *\n * @param options - The plugin options.\n * @returns A Vite plugin.\n */\nexport default function vitePluginFileSystemRouter({\n viewsDir = 'frontend/views/',\n generatedDir = 'frontend/generated/',\n extensions = ['.tsx', '.jsx'],\n isDevMode = false,\n debug = false,\n}: PluginOptions = {}): Plugin {\n let _viewsDir: URL;\n let _outDir: URL;\n let _logger: Logger;\n let runtimeUrls: RuntimeFileUrls;\n let _generateRuntimeFiles: () => Promise<boolean>;\n let _viewsDirPosix: string;\n\n return {\n name: 'vite-plugin-file-router',\n enforce: 'pre',\n configResolved({ logger, root, build: { outDir } }) {\n const _root = pathToFileURL(root);\n const _generatedDir = new URL(generatedDir, _root);\n\n _viewsDir = new URL(viewsDir, _root);\n _viewsDirPosix = fileURLToPath(_viewsDir).replaceAll('\\\\', '/');\n _outDir = pathToFileURL(outDir);\n _logger = logger;\n\n if (debug) {\n _logger.info(`The directory of route files: ${String(_viewsDir)}`);\n _logger.info(`The directory of generated files: ${String(_generatedDir)}`);\n _logger.info(`The output directory: ${String(_outDir)}`);\n }\n runtimeUrls = {\n json: new URL('file-routes.json', isDevMode ? _generatedDir : _outDir),\n code: new URL('file-routes.ts', _generatedDir),\n layouts: new URL('layouts.json', _generatedDir),\n };\n _generateRuntimeFiles = async (): Promise<boolean> => {\n try {\n return await generateRuntimeFiles(_viewsDir, runtimeUrls, extensions, _logger, debug);\n } catch (e: unknown) {\n _logger.error(String(e));\n return true;\n }\n };\n },\n async buildStart() {\n await _generateRuntimeFiles();\n },\n async hotUpdate({ file, modules }: HotUpdateOptions): Promise<void | EnvironmentModuleNode[]> {\n const fileUrlString = String(pathToFileURL(file));\n\n if (fileUrlString === String(runtimeUrls.json)) {\n // Reload file routes JSON with a custom HMR event.\n this.environment.hot.send({ type: 'custom', event: 'fs-route-update' });\n return [];\n }\n\n if (fileUrlString === String(runtimeUrls.code)) {\n // Skip HMR for file routes from Vite builtin file change listener,\n // as we have our own HMR handling below.\n return [];\n }\n\n if (!file.startsWith(_viewsDirPosix)) {\n // Outside views folder, only changes to layouts file should trigger\n // files generation.\n if (fileUrlString !== String(runtimeUrls.layouts)) {\n return;\n }\n }\n\n // Check and update file routes if needed.\n if (await _generateRuntimeFiles()) {\n // The \"file-routes.ts\" file was changed at this point, so it should\n // be considered within the HMR update that caused the routes update.\n\n const mg = this.environment.moduleGraph;\n const fileRoutesModules = mg.getModulesByFile(fileURLToPath(runtimeUrls.code).replaceAll('\\\\', '/'))!;\n\n // Make eager update for file routes in Vite module graph\n // for consistency with the generated file contents.\n await Promise.all(\n Array.from(fileRoutesModules, async (fileRouteModule) => {\n mg.invalidateModule(fileRouteModule);\n await this.environment.fetchModule(fileRouteModule.id!, undefined, { cached: false });\n }),\n );\n\n const neverImported = modules.every((module) => module.importers.size === 0);\n if (neverImported) {\n // The current file is a not imported anywhere, however it caused\n // \"file-routes.ts\" update: possibly a route for this file\n // was removed, or we're processing \"layouts.json\".\n\n // Default Vite HMR behavior for not imported modules is a full page\n // reload. However, in this case, we could avoid it and only do HMR\n // for the file routes instead.\n return [...fileRoutesModules];\n }\n\n // Add \"file-routes.ts\" to current HMR module update list to reload\n // both at the same time.\n return [...fileRoutesModules, ...modules];\n }\n\n return undefined;\n },\n transform(code, id): Promise<TransformResult> | TransformResult {\n let modifiedCode = code;\n if (id.startsWith(_viewsDirPosix) && !basename(id).startsWith('_')) {\n if (isDevMode) {\n // To enable HMR for route files with exported configurations, we need\n // to address a limitation in `react-refresh`. This library requires\n // strict equality (`===`) for non-component exports. However, the\n // dynamic nature of HMR makes maintaining this equality between object\n // literals challenging.\n //\n // To work around this, we implement a strategy that preserves the\n // reference to the original configuration object (`currentExports.config`),\n // replacing any newly created configuration objects (`nextExports.config`)\n // with it. This ensures that the HMR mechanism perceives the\n // configuration as unchanged.\n const injectionPattern = /import\\.meta\\.hot\\.accept[\\s\\S]+if\\s\\(!nextExports\\)\\s+return;/gu;\n if (injectionPattern.test(modifiedCode)) {\n modifiedCode = `${modifiedCode.substring(0, injectionPattern.lastIndex)}${INJECTION}${modifiedCode.substring(\n injectionPattern.lastIndex,\n )}`;\n }\n } else {\n // In production mode, the function name is assigned as name to the function itself to avoid minification\n const functionNames = /export\\s+default\\s+(?:function\\s+)?(\\w+)/u.exec(modifiedCode);\n\n if (functionNames?.length) {\n const [, functionName] = functionNames;\n modifiedCode += `Object.defineProperty(${functionName}, 'name', { value: '${functionName}' });\\n`;\n }\n }\n\n return {\n code: modifiedCode,\n };\n }\n\n return undefined;\n },\n };\n}\n"],"version":3}
1
+ {"mappings":"AAAA,SAAS,2BAA4B;AACrC,SAAS,eAAe,+BAAgC;AAGxD,SAAS,mEAA0F;AAEnG,MAAM,4BAA4B;AAClC,MAAM,sCAAsC,IAAI,0BAA0B;;;;;;;;;;;;;;;;;;AAmB1E,MAAM,4BAA4B;;;;;;;;;;;;;;;AAgBlC,SAAS,kCAAkCA,IAAoB;AAC7D,SAAQ;UACA,KAAK,UAAU,0BAA0B,CAAC;;2DAEO,KAAK,UAAU,GAAG,CAAC;;;AAG7E;;;;;;;AA8CD,eAAe,SAAS,2BAA2B,EACjD,WAAW,mBACX,eAAe,uBACf,aAAa,CAAC,QAAQ,MAAO,GAC7B,YAAY,OACZ,QAAQ,OACM,GAAG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;GACF;AAED,UAAO;EACR;CACF;AACF","names":["id: string","_viewsDir: URL","_outDir: URL","_logger: Logger","runtimeUrls: RuntimeFileUrls","_generateRuntimeFiles: () => Promise<boolean>","_viewsDirPosix: string","e: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/file-router/src/vite-plugin.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { TransformResult } from 'rollup';\nimport type { EnvironmentModuleNode, HotUpdateOptions, Logger, Plugin } from 'vite';\nimport { generateRuntimeFiles, type RuntimeFileUrls } from './vite-plugin/generateRuntimeFiles.js';\n\nconst REFRESH_IGNORE_VIRTUAL_ID = 'virtual:hilla-file-router-refresh-ignore';\nconst RESOLVED_REFRESH_IGNORE_VIRTUAL_ID = `\\0${REFRESH_IGNORE_VIRTUAL_ID}`;\n\n/**\n * Installs the `__getReactRefreshIgnoredExports` hook of the React Refresh\n * runtime.\n *\n * React Fast Refresh (the HMR mechanism of `@vitejs/plugin-react`) requires\n * all exports of a module to be React components; otherwise, an update\n * invalidates the module and causes a full page reload. Route files, however,\n * are allowed to export a static `config` object in addition to the React\n * component. To keep Fast Refresh working for them, each route file is\n * registered in `window.__HILLA_FILE_ROUTER_VIEWS__`, and the hook excludes\n * the `config` export of registered modules from the refresh boundary\n * validation. Updates to the `config` contents are propagated separately\n * through the regenerated `file-routes.ts` module.\n *\n * The hook is delivered as a virtual module imported by every route file, so\n * Vite evaluates it once per application boot.\n */\nconst REFRESH_IGNORE_INSTALLER = `if (typeof window !== 'undefined') {\n const previousHook = window.__getReactRefreshIgnoredExports;\n window.__getReactRefreshIgnoredExports = ({ id }) => {\n const ignoredExports = previousHook?.({ id }) ?? [];\n return window.__HILLA_FILE_ROUTER_VIEWS__?.has(id) ? [...ignoredExports, 'config'] : ignoredExports;\n };\n}\n`;\n\n/**\n * Creates a code snippet that registers a route file for the exclusion of its\n * `config` export from the React Fast Refresh boundary validation.\n *\n * @param id - The module id of the route file, as seen by the Vite transform\n * pipeline. The React Refresh runtime receives the same id at runtime.\n */\nfunction createReactRefreshConfigExclusion(id: string): string {\n return `\n;import ${JSON.stringify(REFRESH_IGNORE_VIRTUAL_ID)};\nif (typeof window !== 'undefined') {\n (window.__HILLA_FILE_ROUTER_VIEWS__ ??= new Set()).add(${JSON.stringify(id)});\n}\n`;\n}\n\n/**\n * The options for the Vite file-based router plugin.\n */\nexport type PluginOptions = Readonly<{\n /**\n * The base directory for the router. The folders and files in this directory\n * will be used as route paths.\n *\n * @defaultValue `frontend/views`\n */\n viewsDir?: URL | string;\n /**\n * The directory where the generated view file will be stored.\n *\n * @defaultValue `frontend/generated`\n */\n generatedDir?: URL | string;\n /**\n * The list of extensions that will be collected as routes of the file-based\n * router.\n *\n * @defaultValue `['.tsx', '.jsx']`\n */\n extensions?: readonly string[];\n /**\n * The flag to indicate whether the plugin is running in development mode.\n *\n * @defaultValue `false`\n */\n isDevMode?: boolean;\n /**\n * The flag to indicate whether to output debug information\n *\n * @defaultValue `false`\n */\n debug?: boolean;\n}>;\n\n/**\n * A Vite plugin that generates a router from the files in the specific directory.\n *\n * @param options - The plugin options.\n * @returns A Vite plugin.\n */\nexport default function vitePluginFileSystemRouter({\n viewsDir = 'frontend/views/',\n generatedDir = 'frontend/generated/',\n extensions = ['.tsx', '.jsx'],\n isDevMode = false,\n debug = false,\n}: PluginOptions = {}): Plugin {\n let _viewsDir: URL;\n let _outDir: URL;\n let _logger: Logger;\n let runtimeUrls: RuntimeFileUrls;\n let _generateRuntimeFiles: () => Promise<boolean>;\n let _viewsDirPosix: string;\n\n return {\n name: 'vite-plugin-file-router',\n enforce: 'pre',\n configResolved({ logger, root, build: { outDir } }) {\n const _root = pathToFileURL(root);\n const _generatedDir = new URL(generatedDir, _root);\n\n _viewsDir = new URL(viewsDir, _root);\n _viewsDirPosix = fileURLToPath(_viewsDir).replaceAll('\\\\', '/');\n _outDir = pathToFileURL(outDir);\n _logger = logger;\n\n if (debug) {\n _logger.info(`The directory of route files: ${String(_viewsDir)}`);\n _logger.info(`The directory of generated files: ${String(_generatedDir)}`);\n _logger.info(`The output directory: ${String(_outDir)}`);\n }\n runtimeUrls = {\n json: new URL('file-routes.json', isDevMode ? _generatedDir : _outDir),\n code: new URL('file-routes.ts', _generatedDir),\n layouts: new URL('layouts.json', _generatedDir),\n };\n _generateRuntimeFiles = async (): Promise<boolean> => {\n try {\n return await generateRuntimeFiles(_viewsDir, runtimeUrls, extensions, _logger, debug);\n } catch (e: unknown) {\n _logger.error(String(e));\n return true;\n }\n };\n },\n async buildStart() {\n await _generateRuntimeFiles();\n },\n resolveId(source) {\n return source === REFRESH_IGNORE_VIRTUAL_ID ? RESOLVED_REFRESH_IGNORE_VIRTUAL_ID : undefined;\n },\n load(id) {\n return id === RESOLVED_REFRESH_IGNORE_VIRTUAL_ID ? REFRESH_IGNORE_INSTALLER : undefined;\n },\n async hotUpdate({ file, modules }: HotUpdateOptions): Promise<void | EnvironmentModuleNode[]> {\n const fileUrlString = String(pathToFileURL(file));\n\n if (fileUrlString === String(runtimeUrls.json)) {\n // Reload file routes JSON with a custom HMR event.\n this.environment.hot.send({ type: 'custom', event: 'fs-route-update' });\n return [];\n }\n\n if (fileUrlString === String(runtimeUrls.code)) {\n // Skip HMR for file routes from Vite builtin file change listener,\n // as we have our own HMR handling below.\n return [];\n }\n\n if (!file.startsWith(_viewsDirPosix)) {\n // Outside views folder, only changes to layouts file should trigger\n // files generation.\n if (fileUrlString !== String(runtimeUrls.layouts)) {\n return;\n }\n }\n\n // Check and update file routes if needed.\n if (await _generateRuntimeFiles()) {\n // The \"file-routes.ts\" file was changed at this point, so it should\n // be considered within the HMR update that caused the routes update.\n\n const mg = this.environment.moduleGraph;\n const fileRoutesModules = mg.getModulesByFile(fileURLToPath(runtimeUrls.code).replaceAll('\\\\', '/'))!;\n\n // Make eager update for file routes in Vite module graph\n // for consistency with the generated file contents.\n await Promise.all(\n Array.from(fileRoutesModules, async (fileRouteModule) => {\n mg.invalidateModule(fileRouteModule);\n await this.environment.fetchModule(fileRouteModule.id!, undefined, { cached: false });\n }),\n );\n\n const neverImported = modules.every((module) => module.importers.size === 0);\n if (neverImported) {\n // The current file is a not imported anywhere, however it caused\n // \"file-routes.ts\" update: possibly a route for this file\n // was removed, or we're processing \"layouts.json\".\n\n // Default Vite HMR behavior for not imported modules is a full page\n // reload. However, in this case, we could avoid it and only do HMR\n // for the file routes instead.\n return [...fileRoutesModules];\n }\n\n // Add \"file-routes.ts\" to current HMR module update list to reload\n // both at the same time.\n return [...fileRoutesModules, ...modules];\n }\n\n return undefined;\n },\n transform(code, id): Promise<TransformResult> | TransformResult {\n let modifiedCode = code;\n if (id.startsWith(_viewsDirPosix) && !basename(id).startsWith('_')) {\n if (isDevMode) {\n const [path] = id.split('?');\n if (extensions.some((ext) => path!.endsWith(ext))) {\n modifiedCode += createReactRefreshConfigExclusion(id);\n }\n } else {\n // In production mode, the function name is assigned as name to the function itself to avoid minification\n const functionNames = /export\\s+default\\s+(?:(?:function|class)\\s+)?(\\w+)/u.exec(modifiedCode);\n\n if (functionNames?.length) {\n const [, functionName] = functionNames;\n // For anonymous default exports, the keyword itself is captured\n // instead of a name, so there is nothing to preserve.\n if (functionName !== 'function' && functionName !== 'class') {\n modifiedCode += `Object.defineProperty(${functionName}, 'name', { value: '${functionName}' });\\n`;\n }\n }\n }\n\n return {\n code: modifiedCode,\n };\n }\n\n return undefined;\n },\n };\n}\n"],"version":3}