dinou 9.3.0 → 10.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 (166) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/README.md +157 -132
  3. package/dinou/adapters/bun.js +34 -5
  4. package/dinou/adapters/cloudflare.js +110 -17
  5. package/dinou/adapters/deno.js +46 -8
  6. package/dinou/adapters/netlify.js +86 -50
  7. package/dinou/adapters/node.js +8 -0
  8. package/dinou/assets.d.ts +32 -5
  9. package/dinou/bun/build.js +190 -106
  10. package/dinou/cli.js +992 -532
  11. package/dinou/cloudflare/build.js +187 -106
  12. package/dinou/compiled/autoprefixer/index.js +509 -517
  13. package/dinou/compiled/babel-core/index.js +738 -716
  14. package/dinou/compiled/babel-generator/index.js +341 -299
  15. package/dinou/compiled/babel-loader/index.js +766 -744
  16. package/dinou/compiled/babel-parser/index.js +2 -2
  17. package/dinou/compiled/babel-plugin-react-compiler/index.js +178 -178
  18. package/dinou/compiled/babel-plugin-syntax-import-meta/index.js +4 -4
  19. package/dinou/compiled/babel-preset-react/index.js +752 -730
  20. package/dinou/compiled/babel-preset-typescript/index.js +738 -716
  21. package/dinou/compiled/babel-traverse/index.js +463 -433
  22. package/dinou/compiled/babel-types/index.js +176 -176
  23. package/dinou/compiled/chokidar/index.js +4 -4
  24. package/dinou/compiled/commander/index.js +15 -15
  25. package/dinou/compiled/copy-webpack-plugin/index.js +433 -425
  26. package/dinou/compiled/css-loader/index.js +289 -289
  27. package/dinou/compiled/css-loader/runtime/api.js +85 -0
  28. package/dinou/compiled/css-loader/runtime/getUrl.js +26 -0
  29. package/dinou/compiled/css-loader/runtime/noSourceMaps.js +5 -0
  30. package/dinou/compiled/css-loader/runtime/package.json +3 -0
  31. package/dinou/compiled/css-loader/runtime/sourceMaps.js +16 -0
  32. package/dinou/compiled/fast-glob/index.js +5810 -0
  33. package/dinou/compiled/generic-names/index.js +16 -16
  34. package/dinou/compiled/mini-css-extract-plugin/{chunk-YYEJWYXE.js → chunk-R6DP5ZYM.js} +36 -36
  35. package/dinou/compiled/mini-css-extract-plugin/hmr/hotModuleReplacement.js +253 -0
  36. package/dinou/compiled/mini-css-extract-plugin/hmr/normalize-url.js +39 -0
  37. package/dinou/compiled/mini-css-extract-plugin/hmr/package.json +3 -0
  38. package/dinou/compiled/mini-css-extract-plugin/index.js +1 -1
  39. package/dinou/compiled/mini-css-extract-plugin/loader.js +5 -5
  40. package/dinou/compiled/postcss/index.js +83 -83
  41. package/dinou/compiled/postcss-import/index.js +147 -117
  42. package/dinou/compiled/postcss-modules/index.js +216 -216
  43. package/dinou/compiled/resolve/index.js +1224 -0
  44. package/dinou/compiled/rollup-plugin-babel/index.js +753 -731
  45. package/dinou/compiled/rollup-plugin-commonjs/index.js +43 -38
  46. package/dinou/compiled/rollup-plugin-delete/index.js +615 -253
  47. package/dinou/compiled/rollup-plugin-json/index.js +22 -18
  48. package/dinou/compiled/rollup-plugin-node-resolve/index.js +130 -100
  49. package/dinou/compiled/rollup-plugin-postcss/index.js +3299 -3277
  50. package/dinou/compiled/rollup-plugin-replace/index.js +34 -29
  51. package/dinou/compiled/tailwindcss-postcss/index.js +214 -211
  52. package/dinou/compiled/vendors-manifest.json +59 -83
  53. package/dinou/core/asset-extensions.js +482 -33
  54. package/dinou/core/bailout-proxy.js +21 -2
  55. package/dinou/core/build-static-pages.js +523 -371
  56. package/dinou/core/builtin-asset-extensions.js +63 -0
  57. package/dinou/core/cache-revalidate.js +449 -256
  58. package/dinou/core/cache-slot.js +289 -79
  59. package/dinou/core/client-webpack.jsx +470 -39
  60. package/dinou/core/client.jsx +402 -39
  61. package/dinou/core/config.js +3 -0
  62. package/dinou/core/copy-static-dirs.js +98 -0
  63. package/dinou/core/createScopedName.js +22 -4
  64. package/dinou/core/dinou-paths.js +1 -1
  65. package/dinou/core/discover-layouts.js +200 -0
  66. package/dinou/core/edge-ssr.js +1 -1
  67. package/dinou/core/ensure-vendor-mode.js +78 -19
  68. package/dinou/core/env.js +544 -0
  69. package/dinou/core/export-static.js +41 -9
  70. package/dinou/core/generate-route-types.js +989 -95
  71. package/dinou/core/generate-static-rsc.js +5 -6
  72. package/dinou/core/generate-static.js +45 -6
  73. package/dinou/core/get-abs-path-with-ext.js +217 -75
  74. package/dinou/core/get-asset-from-manifest.js +19 -8
  75. package/dinou/core/get-error-jsx.js +4 -5
  76. package/dinou/core/get-file-path-and-dynamic-params.js +561 -338
  77. package/dinou/core/get-jsx.js +220 -53
  78. package/dinou/core/handler.js +1647 -466
  79. package/dinou/core/import-module.js +7 -0
  80. package/dinou/core/layout-functions.js +72 -13
  81. package/dinou/core/link.jsx +34 -6
  82. package/dinou/core/load-dinou-config.js +520 -89
  83. package/dinou/core/manifest-provider.js +4 -14
  84. package/dinou/core/navigation-utils.js +141 -3
  85. package/dinou/core/navigation.js +134 -50
  86. package/dinou/core/node-middleware-runner.js +165 -0
  87. package/dinou/core/postcss-pipeline.js +236 -0
  88. package/dinou/core/ppr-context.js +114 -22
  89. package/dinou/core/ppr-runtime.js +391 -127
  90. package/dinou/core/redirect.jsx +1 -1
  91. package/dinou/core/render-jsx-to-client-jsx.js +216 -48
  92. package/dinou/core/request-context.js +59 -3
  93. package/dinou/core/resolve-contextual-dinou.js +523 -0
  94. package/dinou/core/resolve-setup-files.js +85 -27
  95. package/dinou/core/revalidating.js +10 -2
  96. package/dinou/core/route-generator.js +6 -2
  97. package/dinou/core/rsc-renderer.js +4 -1
  98. package/dinou/core/run-ssg.js +6 -0
  99. package/dinou/core/runtime-env.js +265 -0
  100. package/dinou/core/server-css-modules-plugin.js +155 -0
  101. package/dinou/core/server-function-proxy-webpack.js +27 -2
  102. package/dinou/core/server-function-proxy.js +27 -2
  103. package/dinou/core/slot.js +47 -2
  104. package/dinou/core/static-assets.js +503 -0
  105. package/dinou/core/storage-adapter.js +452 -24
  106. package/dinou/core/transform-server-functions.js +272 -24
  107. package/dinou/core/tsconfig-aliases.js +964 -0
  108. package/dinou/core/uneject.js +640 -0
  109. package/dinou/core/url-resolver.js +1 -1
  110. package/dinou/core/vfs.js +11 -2
  111. package/dinou/css.d.ts +4 -1
  112. package/dinou/deno/build.js +205 -153
  113. package/dinou/deno/seed-kv.js +4 -0
  114. package/dinou/env.d.ts +22 -2
  115. package/dinou/esbuild/build.js +40 -50
  116. package/dinou/esbuild/dev.js +33 -7
  117. package/dinou/esbuild/helpers-esbuild/get-config-esbuild-prod.js +41 -16
  118. package/dinou/esbuild/helpers-esbuild/get-config-esbuild.js +51 -49
  119. package/dinou/esbuild/helpers-esbuild/get-esbuild-entries.js +73 -60
  120. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +35 -16
  121. package/dinou/esbuild/helpers-esbuild/write.js +13 -3
  122. package/dinou/esbuild/plugins-esbuild/assets-plugin.js +100 -238
  123. package/dinou/esbuild/plugins-esbuild/babel-react-compiler-plugin.js +73 -29
  124. package/dinou/esbuild/plugins-esbuild/css-processor-plugin.js +283 -91
  125. package/dinou/esbuild/plugins-esbuild/manifest-generator-plugin.js +3 -5
  126. package/dinou/esbuild/plugins-esbuild/react-client-manifest-plugin.js +9 -3
  127. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +4 -3
  128. package/dinou/esbuild/plugins-esbuild/stable-chunk-names-and-maps-plugin.js +10 -1
  129. package/dinou/esbuild/plugins-postcss/postcss-extract-plugin.js +84 -21
  130. package/dinou/esbuild/react-refresh/esm-hmr/client.js +31 -10
  131. package/dinou/esbuild/react-refresh/esm-hmr-plugin.js +48 -18
  132. package/dinou/esbuild/react-refresh/is-react-refresh-boundary.js +9 -1
  133. package/dinou/esbuild/react-refresh/react-refresh-runtime.js +13 -7
  134. package/dinou/index.d.ts +1028 -88
  135. package/dinou/node/build.js +138 -74
  136. package/dinou/node/bundle-dual-engine.js +393 -131
  137. package/dinou/node/dev.js +1005 -275
  138. package/dinou/package.json +11 -34
  139. package/dinou/rollup/postcss.config.js +3 -4
  140. package/dinou/rollup/react-refresh/esm-hmr/client.js +31 -10
  141. package/dinou/rollup/react-refresh/react-refresh-wrap-modules.js +16 -13
  142. package/dinou/rollup/react-refresh/rollup-plugin-esm-hmr.js +53 -7
  143. package/dinou/rollup/rollup-plugins/dinou-asset-plugin.js +58 -20
  144. package/dinou/rollup/rollup-plugins/manifest-generator-plugin.js +16 -7
  145. package/dinou/rollup/rollup-plugins/rollup-plugin-react-client-manifest.js +118 -42
  146. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +48 -36
  147. package/dinou/rollup/rollup.config.js +174 -101
  148. package/dinou/scripts/build-vendors.js +123 -33
  149. package/dinou/server.d.ts +126 -15
  150. package/dinou/webpack/helpers/get-webpack-entries.js +87 -41
  151. package/dinou/webpack/helpers/patch-webpack-internals.js +93 -1
  152. package/dinou/webpack/loaders/server-functions-loader.js +1 -1
  153. package/dinou/webpack/plugins/manifest-generator-plugin.js +27 -7
  154. package/dinou/webpack/plugins/server-functions-plugin.js +39 -12
  155. package/dinou/webpack/plugins/webpack-memory-plugin.js +25 -12
  156. package/dinou/webpack/postcss.config.js +3 -4
  157. package/dinou/webpack/webpack.config.js +408 -132
  158. package/eject.js +6 -224
  159. package/package.json +7 -9
  160. package/dinou/compiled/cross-env/index.js +0 -661
  161. package/dinou/compiled/dotenv/index.js +0 -375
  162. package/dinou/compiled/esbuild-copy-static-files/index.js +0 -63
  163. package/dinou/compiled/esbuild-tsconfig-paths/index.js +0 -1314
  164. package/dinou/compiled/rollup-plugin-copy/index.js +0 -12066
  165. package/dinou/compiled/rollup-plugin-tsconfig-paths/index.js +0 -569
  166. package/dinou/compiled/tsconfig-paths-webpack-plugin/index.js +0 -3956
@@ -1,93 +1,466 @@
1
1
  // dinou/core/generate-route-types.js
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { readCustomAssetExtensionsSync } from "./asset-extensions.js";
5
+ import { collectDeclaredEnvKeys } from "./env.js";
4
6
 
5
- const PAGE_EXTENSIONS = [".tsx", ".jsx", ".ts", ".js"];
7
+ const PAGE_EXTENSIONS = [".tsx", ".jsx", ".ts", ".js", ".mjs"];
8
+ const LAYOUT_FUNCTIONS_NAMES = ["layout_functions", "layout.functions"];
9
+ const VALID_IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
10
+
11
+ function safeReaddir(dir) {
12
+ try {
13
+ return fs.readdirSync(dir, { withFileTypes: true });
14
+ } catch (e) {
15
+ return [];
16
+ }
17
+ }
18
+
19
+ function hasEntryFile(entries, baseNames) {
20
+ const names = Array.isArray(baseNames) ? baseNames : [baseNames];
21
+ return entries.some(
22
+ (e) =>
23
+ !e.isDirectory() &&
24
+ names.some((base) => PAGE_EXTENSIONS.some((ext) => e.name === `${base}${ext}`))
25
+ );
26
+ }
27
+
28
+ function hasDinouShadowInDir(dir, entries) {
29
+ if (hasEntryFile(entries, "dinou")) {
30
+ return true;
31
+ }
32
+ const dinouSubdir = entries.find((e) => e.isDirectory() && e.name === "dinou");
33
+ if (dinouSubdir) {
34
+ const subEntries = safeReaddir(path.join(dir, "dinou"));
35
+ if (hasEntryFile(subEntries, "index")) {
36
+ return true;
37
+ }
38
+ }
39
+ return false;
40
+ }
41
+
42
+ function normKey(p) {
43
+ const resolved = path.resolve(p).replace(/\\/g, "/");
44
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
45
+ }
46
+
47
+ function formatTsKey(key) {
48
+ return VALID_IDENTIFIER_RE.test(key) ? key : JSON.stringify(key);
49
+ }
50
+
51
+ function extractParamsFromSegments(segments, { forNavigation = false } = {}) {
52
+ const params = {};
53
+ for (const seg of segments) {
54
+ if (seg.startsWith("[[...") && seg.endsWith("]]")) {
55
+ const paramName = seg.slice(5, -2);
56
+ params[paramName] = forNavigation ? "string[] | undefined" : "string[]";
57
+ } else if (seg.startsWith("[[") && seg.endsWith("]]")) {
58
+ const paramName = seg.slice(2, -2);
59
+ params[paramName] = "string | undefined";
60
+ } else if (seg.startsWith("[...") && seg.endsWith("]")) {
61
+ const paramName = seg.slice(4, -1);
62
+ params[paramName] = "string[]";
63
+ } else if (seg.startsWith("[") && seg.endsWith("]")) {
64
+ const paramName = seg.slice(1, -1);
65
+ params[paramName] = "string";
66
+ }
67
+ }
68
+ return params;
69
+ }
70
+
71
+ function formatParamsMapEntries(paramsMap) {
72
+ const sortedPaths = Object.keys(paramsMap).sort();
73
+ return sortedPaths
74
+ .map((rPath) => {
75
+ const pObj = paramsMap[rPath];
76
+ const keys = Object.keys(pObj);
77
+ if (keys.length === 0) {
78
+ return ` ${JSON.stringify(rPath)}: Record<string, never>;`;
79
+ }
80
+ const props = keys
81
+ .map((k) => {
82
+ const isOptional = pObj[k].includes("undefined");
83
+ const cleanType = pObj[k].replace(" | undefined", "");
84
+ return `${formatTsKey(k)}${isOptional ? "?" : ""}: ${cleanType}`;
85
+ })
86
+ .join("; ");
87
+ return ` ${JSON.stringify(rPath)}: { ${props} };`;
88
+ })
89
+ .join("\n");
90
+ }
91
+
92
+ function formatLayoutSlotsEntries(layoutPaths, slotNamesBySegment) {
93
+ const mergedPaths = new Set([...layoutPaths, ...slotNamesBySegment.keys()]);
94
+ const sortedPaths = [...mergedPaths].sort();
95
+ return sortedPaths
96
+ .map((lPath) => {
97
+ const slotSet = slotNamesBySegment.get(lPath);
98
+ if (!slotSet || slotSet.size === 0) {
99
+ return ` ${JSON.stringify(lPath)}: {};`;
100
+ }
101
+ const slotProps = Array.from(slotSet)
102
+ .sort()
103
+ .map((sName) => `${formatTsKey(sName)}?: ReactNode`)
104
+ .join("; ");
105
+ return ` ${JSON.stringify(lPath)}: { ${slotProps} };`;
106
+ })
107
+ .join("\n");
108
+ }
6
109
 
7
110
  /**
8
- * Recursively scans directory to collect all page routes according to Dinou conventions.
9
- * - Ignores folders starting with '_' (private folders)
10
- * - Ignores folders starting with '@' (parallel route slots)
11
- * - Transparently handles route groups '(group)' by stripping them from URL paths
12
- * - Tracks dynamic parameters: [id], [...slug], [[slug]], [[...slug]]
111
+ * Inspects a parallel `@slot` folder (supporting nested route groups `(group)`
112
+ * and optional trailing segments `[[opt]]` / `[[...opt]]`) for `page.*` and `error.*`,
113
+ * and records contextual `./dinou` directories for slot segments.
13
114
  */
14
- function collectRoutes(dir, segments = [], routes = []) {
15
- if (!fs.existsSync(dir)) return routes;
115
+ function inspectSlotDirectory(
116
+ slotDir,
117
+ extraSegments = [],
118
+ state = {
119
+ hasPage: false,
120
+ hasError: false,
121
+ extraSegments: [],
122
+ contextualDirs: [],
123
+ },
124
+ context = null
125
+ ) {
126
+ if (!fs.existsSync(slotDir)) return state;
16
127
 
17
128
  let entries;
18
129
  try {
19
- entries = fs.readdirSync(dir, { withFileTypes: true });
130
+ entries = fs.readdirSync(slotDir, { withFileTypes: true });
20
131
  } catch (e) {
21
- return routes;
132
+ return state;
22
133
  }
23
134
 
24
- // Check if this folder has a page file
25
- const hasPage = entries.some(
26
- (e) => !e.isDirectory() && PAGE_EXTENSIONS.some((ext) => e.name === `page${ext}`)
27
- );
135
+ const foundPage = hasEntryFile(entries, "page");
136
+ const foundError = hasEntryFile(entries, "error");
137
+ let hasChildSlotRoute = false;
28
138
 
29
- if (hasPage) {
30
- const routePath = segments.length === 0 ? "/" : "/" + segments.join("/");
31
- routes.push({
32
- path: routePath,
33
- segments: [...segments],
34
- });
139
+ if (foundPage) {
140
+ state.hasPage = true;
141
+ for (const seg of extraSegments) {
142
+ if (!state.extraSegments.includes(seg)) {
143
+ state.extraSegments.push(seg);
144
+ }
145
+ }
146
+ }
147
+ if (foundError) {
148
+ state.hasError = true;
35
149
  }
36
150
 
37
151
  for (const entry of entries) {
38
152
  if (!entry.isDirectory()) continue;
39
-
40
153
  const name = entry.name;
41
- // Ignore private folders (_*) and parallel route slots (@*)
42
154
  if (name.startsWith("_") || name.startsWith("@")) continue;
43
155
 
44
- // Route groups: (group) - do not add to URL path
45
156
  if (name.startsWith("(") && name.endsWith(")")) {
46
- collectRoutes(path.join(dir, name), segments, routes);
47
- continue;
157
+ const prevCount = state.contextualDirs.length;
158
+ inspectSlotDirectory(path.join(slotDir, name), extraSegments, state, context);
159
+ if (state.contextualDirs.length > prevCount) {
160
+ hasChildSlotRoute = true;
161
+ }
162
+ } else if (name.startsWith("[[") && name.endsWith("]]")) {
163
+ const prevCount = state.contextualDirs.length;
164
+ inspectSlotDirectory(
165
+ path.join(slotDir, name),
166
+ [...extraSegments, name],
167
+ state,
168
+ context
169
+ );
170
+ if (state.contextualDirs.length > prevCount) {
171
+ hasChildSlotRoute = true;
172
+ }
48
173
  }
174
+ }
49
175
 
50
- collectRoutes(path.join(dir, name), [...segments, name], routes);
176
+ if (context && (foundPage || foundError || hasChildSlotRoute)) {
177
+ const relDir = path.relative(context.srcRoot, slotDir).replace(/\\/g, "/");
178
+ const lookupPath =
179
+ extraSegments.length > 0
180
+ ? `${context.baseSlotPath}/${extraSegments.join("/")}`
181
+ : context.baseSlotPath;
182
+ const hasShadowDinou = hasDinouShadowInDir(slotDir, entries);
183
+ state.contextualDirs.push({
184
+ relDir,
185
+ fromPath: context.parentSegmentPath,
186
+ lookupPath,
187
+ isSlot: true,
188
+ isEscaped: Boolean(context.isEscaped),
189
+ hasShadowDinou,
190
+ });
51
191
  }
52
192
 
193
+ return state;
194
+ }
195
+
196
+ /**
197
+ * Recursively scans directory to collect all navigable `page.*` routes according to Dinou conventions.
198
+ * - Ignores folders starting with '_' for route registration
199
+ * - Ignores folders starting with '@' (parallel route slots)
200
+ * - Transparently handles route groups '(group)' by stripping them from URL paths
201
+ * - Tracks dynamic parameters: [id], [...slug], [[slug]], [[...slug]]
202
+ */
203
+ function collectRoutes(dir, segments = [], routes = []) {
204
+ const topology = collectRouteTopology(dir, segments);
205
+ routes.push(...topology.routes);
53
206
  return routes;
54
207
  }
55
208
 
56
209
  /**
57
- * Generates TypeScript type definitions for all discovered routes.
210
+ * Single-pass horizontal & hierarchical topology scanner across `src/`:
211
+ * - `routes`: navigable URLs (`page.*`) for Level 1 (`<Link>`, `router.push`)
212
+ * - `pageSegments`: `page.*`, `page_functions.*`, and `not_found.*` segments for `PageProps` / `PageFunctions`
213
+ * - `layouts`: `layout.*` and `layout_functions.*` segments (including intermediate layouts without a sibling `page.*`)
214
+ * - `slots`: parallel `@slot` segments (`@slot/page.*`) and parent layout slot injection map
215
+ * - `errorSegments`: all segments capable of hosting an `error.*` boundary (including `@slot/error.*` and intermediate folders)
216
+ * - `contextualDirs`: physical directories inside `src/` that belong to the route tree (for `.dinou/routes/<relDir>/dinou.{d.ts,js}`),
217
+ * including fallback contextual shims for `_`-escaped route folders so TypeScript/IDEs never break on `"./dinou"`.
58
218
  */
59
- function generateRouteDefinitions(routes) {
219
+ function collectRouteTopology(
220
+ dir,
221
+ segments = [],
222
+ topology = {
223
+ routes: [],
224
+ pageSegments: [],
225
+ layouts: [],
226
+ slots: [],
227
+ errorSegments: [],
228
+ slotNamesBySegment: new Map(),
229
+ contextualDirs: [],
230
+ }
231
+ ) {
232
+ if (!topology.contextualDirs) {
233
+ topology.contextualDirs = [];
234
+ }
235
+ const srcRoot = path.resolve(dir);
236
+
237
+ function scanDir(currentDir, currentSegments, isEscaped = false) {
238
+ if (!fs.existsSync(currentDir)) return false;
239
+
240
+ let entries;
241
+ try {
242
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
243
+ } catch (e) {
244
+ return false;
245
+ }
246
+
247
+ const segmentPath =
248
+ currentSegments.length === 0 ? "/" : "/" + currentSegments.join("/");
249
+
250
+ const hasPage = hasEntryFile(entries, "page");
251
+ const hasPageFunctions = hasEntryFile(entries, "page_functions");
252
+ const hasNotFound = hasEntryFile(entries, "not_found");
253
+ const hasLayout = hasEntryFile(entries, "layout");
254
+ const hasLayoutFunctions = hasEntryFile(entries, LAYOUT_FUNCTIONS_NAMES);
255
+ const hasError = hasEntryFile(entries, "error");
256
+
257
+ const hasOwnRouteFile =
258
+ hasPage ||
259
+ hasPageFunctions ||
260
+ hasNotFound ||
261
+ hasLayout ||
262
+ hasLayoutFunctions ||
263
+ hasError;
264
+
265
+ if (!isEscaped) {
266
+ if (hasPage) {
267
+ topology.routes.push({
268
+ path: segmentPath,
269
+ segments: [...currentSegments],
270
+ });
271
+ }
272
+
273
+ if (hasPage || hasPageFunctions || hasNotFound) {
274
+ topology.pageSegments.push({
275
+ path: segmentPath,
276
+ segments: [...currentSegments],
277
+ });
278
+ }
279
+
280
+ if (hasLayout || hasLayoutFunctions) {
281
+ topology.layouts.push({
282
+ path: segmentPath,
283
+ segments: [...currentSegments],
284
+ });
285
+ }
286
+
287
+ if (hasError || hasPage || hasNotFound || hasLayout || hasLayoutFunctions) {
288
+ topology.errorSegments.push({
289
+ path: segmentPath,
290
+ segments: [...currentSegments],
291
+ });
292
+ }
293
+ }
294
+
295
+ let hasChildRoute = false;
296
+ const localSlotNames = new Set();
297
+
298
+ for (const entry of entries) {
299
+ if (!entry.isDirectory()) continue;
300
+
301
+ const name = entry.name;
302
+ // Escaped/parked folders (_*): excluded from global route maps,
303
+ // but still emit fallback contextual "./dinou" shims if they contain route files.
304
+ if (name.startsWith("_")) {
305
+ const escapedHasRoute = scanDir(
306
+ path.join(currentDir, name),
307
+ [...currentSegments, name],
308
+ true
309
+ );
310
+ if (isEscaped && escapedHasRoute) {
311
+ hasChildRoute = true;
312
+ }
313
+ continue;
314
+ }
315
+
316
+ // Parallel route slots: @slot
317
+ if (name.startsWith("@")) {
318
+ const slotName = name.slice(1);
319
+ if (!slotName) continue;
320
+
321
+ const baseSlotPath =
322
+ (currentSegments.length === 0 ? "" : "/" + currentSegments.join("/")) +
323
+ "/@" +
324
+ slotName;
325
+ const slotState = inspectSlotDirectory(
326
+ path.join(currentDir, name),
327
+ [],
328
+ undefined,
329
+ {
330
+ srcRoot,
331
+ parentSegmentPath: segmentPath,
332
+ baseSlotPath,
333
+ isEscaped,
334
+ }
335
+ );
336
+ const slotDetailedPath =
337
+ slotState.extraSegments.length > 0
338
+ ? `${baseSlotPath}/${slotState.extraSegments.join("/")}`
339
+ : null;
340
+ const slotCombinedSegments = [
341
+ ...currentSegments,
342
+ ...slotState.extraSegments,
343
+ ];
344
+
345
+ if (slotState.hasPage) {
346
+ hasChildRoute = true;
347
+ localSlotNames.add(slotName);
348
+ if (!isEscaped) {
349
+ if (!topology.slotNamesBySegment.has(segmentPath)) {
350
+ topology.slotNamesBySegment.set(segmentPath, new Set());
351
+ }
352
+ topology.slotNamesBySegment.get(segmentPath).add(slotName);
353
+
354
+ topology.slots.push({
355
+ path: baseSlotPath,
356
+ parentPath: segmentPath,
357
+ slotName,
358
+ segments: slotCombinedSegments,
359
+ });
360
+ if (slotDetailedPath) {
361
+ topology.slots.push({
362
+ path: slotDetailedPath,
363
+ parentPath: segmentPath,
364
+ slotName,
365
+ segments: slotCombinedSegments,
366
+ });
367
+ }
368
+ }
369
+ }
370
+
371
+ if (slotState.hasPage || slotState.hasError) {
372
+ hasChildRoute = true;
373
+ if (!isEscaped) {
374
+ topology.errorSegments.push({
375
+ path: baseSlotPath,
376
+ segments: slotCombinedSegments,
377
+ });
378
+ if (slotDetailedPath) {
379
+ topology.errorSegments.push({
380
+ path: slotDetailedPath,
381
+ segments: slotCombinedSegments,
382
+ });
383
+ }
384
+ }
385
+ }
386
+
387
+ if (slotState.contextualDirs.length > 0) {
388
+ hasChildRoute = true;
389
+ topology.contextualDirs.push(...slotState.contextualDirs);
390
+ }
391
+ continue;
392
+ }
393
+
394
+ // Route groups: (group) - do not add to URL path
395
+ if (name.startsWith("(") && name.endsWith(")")) {
396
+ if (scanDir(path.join(currentDir, name), currentSegments, isEscaped)) {
397
+ hasChildRoute = true;
398
+ }
399
+ continue;
400
+ }
401
+
402
+ if (scanDir(path.join(currentDir, name), [...currentSegments, name], isEscaped)) {
403
+ hasChildRoute = true;
404
+ }
405
+ }
406
+
407
+ const hasAnyRouteInSubtree = hasOwnRouteFile || hasChildRoute;
408
+ if (hasAnyRouteInSubtree) {
409
+ const relDir = path.relative(srcRoot, currentDir).replace(/\\/g, "/");
410
+ const hasShadowDinou = hasDinouShadowInDir(currentDir, entries);
411
+ topology.contextualDirs.push({
412
+ relDir,
413
+ fromPath: segmentPath,
414
+ lookupPath: segmentPath,
415
+ isSlot: false,
416
+ isEscaped,
417
+ escapedSlotNames: isEscaped ? Array.from(localSlotNames).sort() : undefined,
418
+ hasShadowDinou,
419
+ });
420
+ }
421
+
422
+ return hasAnyRouteInSubtree;
423
+ }
424
+
425
+ scanDir(srcRoot, segments, false);
426
+ return topology;
427
+ }
428
+
429
+ /**
430
+ * Generates TypeScript type definitions for all discovered routes, layouts, parallel slots, and error boundaries.
431
+ * Accepts either a full `topology` object from `collectRouteTopology` or a legacy `routes` array.
432
+ */
433
+ function generateRouteDefinitions(routesOrTopology) {
434
+ const isLegacyArray = Array.isArray(routesOrTopology);
435
+ const routes = isLegacyArray ? routesOrTopology : routesOrTopology?.routes || [];
436
+ const pageSegments = isLegacyArray ? routes : routesOrTopology?.pageSegments || routes;
437
+ const layouts = isLegacyArray ? [] : routesOrTopology?.layouts || [];
438
+ const slots = isLegacyArray ? [] : routesOrTopology?.slots || [];
439
+ const errorSegments = isLegacyArray ? routes : routesOrTopology?.errorSegments || [];
440
+ const slotNamesBySegment = isLegacyArray
441
+ ? new Map()
442
+ : routesOrTopology?.slotNamesBySegment || new Map();
443
+
60
444
  const staticRoutes = new Set();
61
445
  const dynamicTemplateRoutes = new Set();
446
+ const navigableParamsMap = {};
62
447
  const routeParamsMap = {};
448
+ const layoutParamsMap = {};
449
+ const slotParamsMap = {};
450
+ const errorParamsMap = {};
63
451
 
452
+ // 1. Level 1 navigable URLs & navigable pattern params (strictly from `page.*` routes)
64
453
  for (const route of routes) {
65
454
  const segments = route.segments;
455
+ navigableParamsMap[route.path] = {
456
+ ...(navigableParamsMap[route.path] || {}),
457
+ ...extractParamsFromSegments(segments, { forNavigation: true }),
458
+ };
66
459
  const isDynamic = segments.some((s) => s.startsWith("[") && s.endsWith("]"));
67
460
 
68
- // Calculate parameter types for Level 2
69
- const params = {};
70
- for (const seg of segments) {
71
- if (seg.startsWith("[[...") && seg.endsWith("]]")) {
72
- const paramName = seg.slice(5, -2);
73
- params[paramName] = "string[] | undefined";
74
- } else if (seg.startsWith("[[") && seg.endsWith("]]")) {
75
- const paramName = seg.slice(2, -2);
76
- params[paramName] = "string | undefined";
77
- } else if (seg.startsWith("[...") && seg.endsWith("]")) {
78
- const paramName = seg.slice(4, -1);
79
- params[paramName] = "string[]";
80
- } else if (seg.startsWith("[") && seg.endsWith("]")) {
81
- const paramName = seg.slice(1, -1);
82
- params[paramName] = "string";
83
- }
84
- }
85
- routeParamsMap[route.path] = params;
86
-
87
461
  if (!isDynamic) {
88
462
  staticRoutes.add(route.path);
89
463
  } else {
90
- // Build template literal type for Level 1 autocomplete & validation
91
464
  const transformedSegments = segments.map((seg) => {
92
465
  if (seg.startsWith("[[...") && seg.endsWith("]]")) {
93
466
  return "${string}";
@@ -103,10 +476,13 @@ function generateRouteDefinitions(routes) {
103
476
 
104
477
  dynamicTemplateRoutes.add("`/" + transformedSegments.join("/") + "`");
105
478
 
106
- // For optional segments ([[foo]] or [[...foo]]), progressively peel off trailing optional
107
- // segments to register all valid intermediate route variants (including the base static route).
479
+ // Progressively peel off trailing optional segments to register valid intermediate variants
108
480
  let cur = [...segments];
109
- while (cur.length > 0 && cur[cur.length - 1].startsWith("[[") && cur[cur.length - 1].endsWith("]]")) {
481
+ while (
482
+ cur.length > 0 &&
483
+ cur[cur.length - 1].startsWith("[[") &&
484
+ cur[cur.length - 1].endsWith("]]")
485
+ ) {
110
486
  cur.pop();
111
487
  if (cur.length === 0) {
112
488
  staticRoutes.add("/");
@@ -126,50 +502,539 @@ function generateRouteDefinitions(routes) {
126
502
  }
127
503
  }
128
504
 
505
+ // 2. Level 2 Page & NotFound parameters (`DinouRouteParamsMap`)
506
+ for (const segEntry of pageSegments) {
507
+ routeParamsMap[segEntry.path] = {
508
+ ...(routeParamsMap[segEntry.path] || {}),
509
+ ...extractParamsFromSegments(segEntry.segments),
510
+ };
511
+ }
512
+
513
+ // 3. Level 2 Layout segment parameters (`DinouLayoutParamsMap`)
514
+ for (const layoutEntry of layouts) {
515
+ layoutParamsMap[layoutEntry.path] = {
516
+ ...(layoutParamsMap[layoutEntry.path] || {}),
517
+ ...extractParamsFromSegments(layoutEntry.segments),
518
+ };
519
+ }
520
+
521
+ // 4. Level 2 Parallel `@slot` parameters (`DinouSlotParamsMap`)
522
+ for (const slotEntry of slots) {
523
+ slotParamsMap[slotEntry.path] = {
524
+ ...(slotParamsMap[slotEntry.path] || {}),
525
+ ...extractParamsFromSegments(slotEntry.segments),
526
+ };
527
+ }
528
+
529
+ // 5. Level 2 Error boundary parameters (`DinouErrorParamsMap`)
530
+ for (const errEntry of errorSegments) {
531
+ errorParamsMap[errEntry.path] = {
532
+ ...(errorParamsMap[errEntry.path] || {}),
533
+ ...extractParamsFromSegments(errEntry.segments),
534
+ };
535
+ }
536
+
129
537
  return {
130
538
  staticRoutes: Array.from(staticRoutes).sort(),
131
539
  dynamicRoutes: Array.from(dynamicTemplateRoutes).sort(),
540
+ navigableParamsMap,
132
541
  routeParamsMap,
542
+ layoutParamsMap,
543
+ slotParamsMap,
544
+ errorParamsMap,
545
+ slotNamesBySegment,
133
546
  };
134
547
  }
135
548
 
549
+ function buildContextualDinouJs(fromPath) {
550
+ const routeLiteral = JSON.stringify(fromPath);
551
+ return `// This file is auto-generated by Dinou. Do not edit directly.
552
+ import React, { createElement } from "react";
553
+ import {
554
+ Link as BaseLink,
555
+ useRouter as useBaseRouter,
556
+ defineConfig,
557
+ getContext,
558
+ noDynamic,
559
+ usePathname,
560
+ useSearchParams,
561
+ refreshSlot,
562
+ useNavigationLoading,
563
+ redirect,
564
+ ClientRedirect,
565
+ } from "dinou";
566
+
567
+ const useMemo = React.useMemo || ((fn) => fn());
568
+
569
+ export const ROUTE = ${routeLiteral};
570
+
571
+ export function Link(props) {
572
+ return createElement(BaseLink, {
573
+ ...props,
574
+ from: props?.from ?? ROUTE,
575
+ });
576
+ }
577
+
578
+ export function useRouter() {
579
+ const router = useBaseRouter();
580
+ return useMemo(
581
+ () => ({
582
+ ...router,
583
+ push: (href, options) =>
584
+ router.push(href, { ...options, from: options?.from ?? ROUTE }),
585
+ replace: (href, options) =>
586
+ router.replace(href, { ...options, from: options?.from ?? ROUTE }),
587
+ }),
588
+ [router]
589
+ );
590
+ }
591
+
592
+ export {
593
+ defineConfig,
594
+ getContext,
595
+ noDynamic,
596
+ usePathname,
597
+ useSearchParams,
598
+ refreshSlot,
599
+ useNavigationLoading,
600
+ redirect,
601
+ ClientRedirect,
602
+ };
603
+
604
+ const dinou = {
605
+ ROUTE,
606
+ defineConfig,
607
+ getContext,
608
+ noDynamic,
609
+ usePathname,
610
+ useSearchParams,
611
+ useRouter,
612
+ refreshSlot,
613
+ useNavigationLoading,
614
+ redirect,
615
+ ClientRedirect,
616
+ Link,
617
+ };
618
+
619
+ export default dinou;
620
+ `;
621
+ }
622
+
623
+ function buildContextualDinouDts({
624
+ fromPath,
625
+ lookupPath,
626
+ isSlot,
627
+ isEscaped = false,
628
+ escapedSlotNames = [],
629
+ }) {
630
+ const routeLiteral = JSON.stringify(fromPath);
631
+ const lookupLiteral = JSON.stringify(lookupPath);
632
+ const slotPropsDecl = isSlot
633
+ ? `export interface SlotProps {\n params: RouteParams;\n}`
634
+ : `export type SlotProps<T extends Dinou.DinouSlotPattern = Dinou.DinouSlotPattern> = Dinou.SlotProps<T>;`;
635
+
636
+ const routeConstDecl = isEscaped
637
+ ? `export declare const ROUTE: string;`
638
+ : `export declare const ROUTE = ${routeLiteral};`;
639
+
640
+ const layoutParamsLookup = isEscaped ? routeLiteral : "typeof ROUTE";
641
+
642
+ const layoutSlotsExpr = isEscaped
643
+ ? escapedSlotNames && escapedSlotNames.length > 0
644
+ ? `{ ${escapedSlotNames.map((sName) => `${formatTsKey(sName)}?: ReactNode`).join("; ")} }`
645
+ : `{}`
646
+ : `Dinou.LayoutSlots<typeof ROUTE>`;
647
+
648
+ return `// This file is auto-generated by Dinou. Do not edit directly.
649
+ import type { ReactNode } from "react";
650
+ import type * as Dinou from "dinou";
651
+ import {
652
+ defineConfig,
653
+ getContext,
654
+ noDynamic,
655
+ usePathname,
656
+ useSearchParams,
657
+ refreshSlot,
658
+ useNavigationLoading,
659
+ redirect,
660
+ ClientRedirect,
661
+ } from "dinou";
662
+
663
+ /**
664
+ * URL route pattern associated with this directory (${routeLiteral}).
665
+ */
666
+ ${routeConstDecl}
667
+
668
+ /**
669
+ * Resolved dynamic route parameters for this directory (${lookupLiteral}),
670
+ * or for an explicit segment pattern \`T\` if provided.
671
+ */
672
+ export type RouteParams<
673
+ T extends Dinou.DinouSegmentPattern | undefined = undefined
674
+ > = [T] extends [undefined]
675
+ ? Dinou.LookupSingleSegmentParams<${lookupLiteral}>
676
+ : Dinou.RouteParams<Extract<T, Dinou.DinouSegmentPattern>>;
677
+
678
+ /**
679
+ * Zero-boilerplate Page component props pre-bound to this directory (${lookupLiteral}).
680
+ * Optionally accepts \`TProps\` for custom props returned by \`page_functions.ts\` (\`getProps\`).
681
+ */
682
+ export type PageProps<TProps extends object = {}> = Dinou.SimplifyParams<
683
+ {
684
+ params: RouteParams;
685
+ } & TProps
686
+ >;
687
+
688
+ /**
689
+ * Zero-boilerplate Layout component props pre-bound to this directory (${routeLiteral}),
690
+ * including auto-inferred sibling \`@slot\` ReactNode props and optional \`TProps\` from \`layout_functions.ts\`.
691
+ */
692
+ export type LayoutProps<TProps extends object = {}> = Dinou.SimplifyParams<
693
+ {
694
+ children: ReactNode;
695
+ params: Dinou.LookupSingleSegmentParams<${layoutParamsLookup}>;
696
+ } & ${layoutSlotsExpr} &
697
+ TProps
698
+ >;
699
+
700
+ ${slotPropsDecl}
701
+
702
+ /**
703
+ * Zero-boilerplate Error boundary props (\`error.tsx\`) pre-bound to this directory (${lookupLiteral}).
704
+ */
705
+ export interface ErrorProps {
706
+ error: Error;
707
+ params: RouteParams;
708
+ }
709
+
710
+ /**
711
+ * Zero-boilerplate Not-Found boundary props (\`not_found.tsx\`) pre-bound to this directory (${lookupLiteral}).
712
+ */
713
+ export type NotFoundProps<TProps extends object = {}> = Dinou.SimplifyParams<
714
+ {
715
+ params: RouteParams;
716
+ } & TProps
717
+ >;
718
+
719
+ /**
720
+ * Zero-boilerplate \`page_functions.ts\` contract pre-bound to this directory's \`RouteParams\`.
721
+ */
722
+ export type PageFunctions<TProps = any> = Dinou.RouteSegmentConfig<
723
+ RouteParams,
724
+ TProps,
725
+ Dinou.StaticPathParams<${isEscaped ? "string" : lookupLiteral}>
726
+ >;
727
+
728
+ /**
729
+ * Zero-boilerplate \`layout_functions.ts\` contract pre-bound to this directory's layout \`params\`.
730
+ */
731
+ export type LayoutFunctions<TProps = any> = Dinou.RouteSegmentConfig<
732
+ Dinou.LookupSingleSegmentParams<${layoutParamsLookup}>,
733
+ TProps,
734
+ Dinou.StaticPathParams<${isEscaped ? "string" : layoutParamsLookup}>
735
+ >;
736
+
737
+ /**
738
+ * Props for the route-contextual \`<Link>\` component pre-bound to \`from=${routeLiteral}\`.
739
+ */
740
+ export type LinkProps<
741
+ TFrom extends Dinou.DinouFromRoute | undefined = undefined,
742
+ THref extends Dinou.ScopedLinkTargetForFrom<
743
+ typeof ROUTE,
744
+ TFrom
745
+ > = Dinou.ScopedLinkTargetForFrom<typeof ROUTE, TFrom>
746
+ > = Dinou.ScopedLinkProps<typeof ROUTE, TFrom, THref>;
747
+
748
+ /**
749
+ * Route-contextual \`<Link>\` pre-bound to \`from=${routeLiteral}\`.
750
+ * Autocompletes and validates relative targets (\`"sub"\`, \`"./sub"\`, \`"../other"\`),
751
+ * absolute routes, and dynamic \`[param]\` routes without requiring a \`from\` prop.
752
+ */
753
+ export declare const Link: Dinou.ScopedLinkComponent<typeof ROUTE>;
754
+
755
+ /**
756
+ * Route-contextual \`useRouter()\` hook pre-bound to \`from=${routeLiteral}\`.
757
+ * Autocompletes and validates relative targets (\`router.push("sub")\`) and absolute/dynamic
758
+ * routes without requiring \`{ from }\`.
759
+ */
760
+ export declare const useRouter: Dinou.ScopedUseRouterHook<typeof ROUTE>;
761
+
762
+ export {
763
+ defineConfig,
764
+ getContext,
765
+ noDynamic,
766
+ usePathname,
767
+ useSearchParams,
768
+ refreshSlot,
769
+ useNavigationLoading,
770
+ redirect,
771
+ ClientRedirect,
772
+ };
773
+
774
+ export type {
775
+ Query,
776
+ Cookies,
777
+ Headers,
778
+ CookieOptions,
779
+ ResponseProxy,
780
+ DinouEnv,
781
+ RequestContextStore,
782
+ NodeMiddleware,
783
+ ServerHookContext,
784
+ DinouPlugin,
785
+ DinouConfig,
786
+ PPRConfig,
787
+ AllowUndefinedStaticPath,
788
+ ToStaticPathParamValue,
789
+ ToStaticPathParams,
790
+ StaticPathParams,
791
+ StaticPathItem,
792
+ StaticPathsResult,
793
+ RouteSegmentConfig,
794
+ ClientRedirectProps,
795
+ NavigationOptions,
796
+ DinouRouter,
797
+ DinouRoute,
798
+ DinouRoutePattern,
799
+ DinouRegisteredSlotPattern,
800
+ DinouSlotPattern,
801
+ DinouLayoutPattern,
802
+ DinouErrorPattern,
803
+ DinouNotFoundPattern,
804
+ DinouSegmentPattern,
805
+ LayoutParams,
806
+ LayoutSlots,
807
+ SlotParams,
808
+ ErrorParams,
809
+ DinouNavigableRoutePatternMap,
810
+ DinouNavigableRouteKey,
811
+ DinouDynamicRoutePattern,
812
+ DinouDynamicRouteWithSuffix,
813
+ DinouEffectiveRoutePattern,
814
+ DinouLinkTarget,
815
+ DinouFromRoute,
816
+ DinouRelativeLinkTarget,
817
+ DinouLinkTargetForFrom,
818
+ DinouScopedLinkTarget,
819
+ ScopedLinkTargetForFrom,
820
+ ScopedLinkProps,
821
+ ScopedLinkComponent,
822
+ ScopedUseRouterHook,
823
+ } from "dinou";
824
+
825
+ declare const dinou: {
826
+ ROUTE: typeof ROUTE;
827
+ defineConfig: typeof defineConfig;
828
+ getContext: typeof getContext;
829
+ noDynamic: typeof noDynamic;
830
+ usePathname: typeof usePathname;
831
+ useSearchParams: typeof useSearchParams;
832
+ useRouter: typeof useRouter;
833
+ refreshSlot: typeof refreshSlot;
834
+ useNavigationLoading: typeof useNavigationLoading;
835
+ redirect: typeof redirect;
836
+ ClientRedirect: typeof ClientRedirect;
837
+ Link: typeof Link;
838
+ };
839
+
840
+ export default dinou;
841
+ `;
842
+ }
843
+
844
+ const deferredPruneTimers = new Map();
845
+
846
+ function scheduleDeferredRouteTypesPrune(projectRoot, remainingAttempts = 5) {
847
+ if (remainingAttempts <= 0) return;
848
+ const rootKey = normKey(projectRoot);
849
+ if (deferredPruneTimers.has(rootKey)) return;
850
+
851
+ const timer = setTimeout(() => {
852
+ deferredPruneTimers.delete(rootKey);
853
+ try {
854
+ generateRouteTypes(projectRoot, { _retryAttempts: remainingAttempts - 1 });
855
+ } catch (e) {}
856
+ }, 150);
857
+ if (typeof timer.unref === "function") {
858
+ timer.unref();
859
+ }
860
+ deferredPruneTimers.set(rootKey, timer);
861
+ }
862
+
863
+ function writeFileIfChanged(targetPath, content) {
864
+ const current = fs.existsSync(targetPath)
865
+ ? fs.readFileSync(targetPath, "utf8")
866
+ : null;
867
+ if (current !== content) {
868
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
869
+ fs.writeFileSync(targetPath, content, "utf8");
870
+ }
871
+ }
872
+
873
+ function pruneContextualRoutesDir(routesOutRoot, expectedFiles) {
874
+ if (!fs.existsSync(routesOutRoot)) return false;
875
+ let hadLockedArtifacts = false;
876
+
877
+ function cleanDirRecursive(dir, isRoot = false) {
878
+ let entries;
879
+ try {
880
+ entries = fs.readdirSync(dir, { withFileTypes: true });
881
+ } catch (e) {
882
+ return;
883
+ }
884
+
885
+ for (const entry of entries) {
886
+ const fullPath = path.join(dir, entry.name);
887
+ if (entry.isDirectory()) {
888
+ cleanDirRecursive(fullPath, false);
889
+ } else if (entry.name === "dinou.js" || entry.name === "dinou.d.ts") {
890
+ if (!expectedFiles.has(normKey(fullPath))) {
891
+ try {
892
+ fs.rmSync(fullPath, { force: true, maxRetries: 5, retryDelay: 25 });
893
+ } catch (e) {}
894
+ if (fs.existsSync(fullPath)) {
895
+ hadLockedArtifacts = true;
896
+ }
897
+ }
898
+ }
899
+ }
900
+
901
+ if (!isRoot) {
902
+ try {
903
+ const remaining = fs.readdirSync(dir);
904
+ if (remaining.length === 0) {
905
+ fs.rmSync(dir, {
906
+ recursive: true,
907
+ force: true,
908
+ maxRetries: 3,
909
+ retryDelay: 20,
910
+ });
911
+ if (fs.existsSync(dir)) {
912
+ hadLockedArtifacts = true;
913
+ }
914
+ }
915
+ } catch (e) {
916
+ if (fs.existsSync(dir)) {
917
+ try {
918
+ if (fs.readdirSync(dir).length === 0) {
919
+ hadLockedArtifacts = true;
920
+ }
921
+ } catch (err) {}
922
+ }
923
+ }
924
+ }
925
+ }
926
+
927
+ cleanDirRecursive(routesOutRoot, true);
928
+ return hadLockedArtifacts;
929
+ }
930
+
931
+ function syncContextualRouteModules(
932
+ projectRoot,
933
+ contextualDirs,
934
+ retryAttempts = 5
935
+ ) {
936
+ const routesOutRoot = path.resolve(projectRoot, ".dinou/routes");
937
+ const expectedFiles = new Set();
938
+ let hadWriteLockError = false;
939
+
940
+ for (const ctxEntry of contextualDirs) {
941
+ if (ctxEntry.hasShadowDinou && !ctxEntry.isEscaped) {
942
+ const shadowRel = ctxEntry.relDir ? `src/${ctxEntry.relDir}/dinou` : "src/dinou";
943
+ console.warn(
944
+ `[Dinou] Warning: "${shadowRel}" shadows the generated route-contextual "./dinou" module for segment "${ctxEntry.lookupPath}".`
945
+ );
946
+ }
947
+
948
+ const outDir = ctxEntry.relDir
949
+ ? path.resolve(routesOutRoot, ctxEntry.relDir)
950
+ : routesOutRoot;
951
+ const jsPath = path.join(outDir, "dinou.js");
952
+ const dtsPath = path.join(outDir, "dinou.d.ts");
953
+
954
+ expectedFiles.add(normKey(jsPath));
955
+ expectedFiles.add(normKey(dtsPath));
956
+
957
+ try {
958
+ writeFileIfChanged(jsPath, buildContextualDinouJs(ctxEntry.fromPath));
959
+ writeFileIfChanged(dtsPath, buildContextualDinouDts(ctxEntry));
960
+ } catch (e) {
961
+ hadWriteLockError = true;
962
+ }
963
+ }
964
+
965
+ const hadLockedArtifacts = pruneContextualRoutesDir(routesOutRoot, expectedFiles);
966
+ if (hadLockedArtifacts || hadWriteLockError) {
967
+ scheduleDeferredRouteTypesPrune(projectRoot, retryAttempts);
968
+ }
969
+ }
970
+
136
971
  /**
137
- * Generates the .dinou/types/routes.d.ts ambient definitions file.
972
+ * Generates `.dinou/types/routes.d.ts` ambient definitions and `.dinou/routes/<relDir>/dinou.{js,d.ts}`
973
+ * route-contextual modules.
138
974
  * @param {string} projectRoot Root directory of the project (default process.cwd())
975
+ * @param {{ _retryAttempts?: number }} [options]
139
976
  */
140
- function generateRouteTypes(projectRoot = process.cwd()) {
977
+ function generateRouteTypes(projectRoot = process.cwd(), options = {}) {
978
+ const retryAttempts =
979
+ typeof options?._retryAttempts === "number" ? options._retryAttempts : 5;
141
980
  const srcDir = path.resolve(projectRoot, "src");
142
981
  if (!fs.existsSync(srcDir)) return;
143
982
 
144
- const routes = collectRoutes(srcDir);
145
- const { staticRoutes, dynamicRoutes, routeParamsMap } = generateRouteDefinitions(routes);
983
+ const topology = collectRouteTopology(srcDir);
984
+ const {
985
+ staticRoutes,
986
+ dynamicRoutes,
987
+ navigableParamsMap,
988
+ routeParamsMap,
989
+ layoutParamsMap,
990
+ slotParamsMap,
991
+ errorParamsMap,
992
+ slotNamesBySegment,
993
+ } = generateRouteDefinitions(topology);
146
994
 
147
- const staticUnion = staticRoutes.length > 0
148
- ? staticRoutes.map((r) => ` | ${JSON.stringify(r)}`).join("\n")
149
- : " | string";
995
+ const staticUnion =
996
+ staticRoutes.length > 0
997
+ ? staticRoutes.map((r) => ` | ${JSON.stringify(r)}`).join("\n")
998
+ : " | string";
150
999
 
151
- const dynamicUnion = dynamicRoutes.length > 0
152
- ? dynamicRoutes.map((r) => ` | ${r}`).join("\n")
153
- : " | never";
1000
+ const dynamicUnion =
1001
+ dynamicRoutes.length > 0
1002
+ ? dynamicRoutes.map((r) => ` | ${r}`).join("\n")
1003
+ : " | never";
154
1004
 
155
- const paramsEntries = Object.entries(routeParamsMap)
156
- .map(([rPath, pObj]) => {
157
- const keys = Object.keys(pObj);
158
- if (keys.length === 0) {
159
- return ` ${JSON.stringify(rPath)}: Record<string, never>;`;
160
- }
161
- const props = keys
162
- .map((k) => {
163
- const isOptional = pObj[k].includes("undefined");
164
- const cleanType = pObj[k].replace(" | undefined", "");
165
- return `${k}${isOptional ? "?" : ""}: ${cleanType}`;
166
- })
167
- .join("; ");
168
- return ` ${JSON.stringify(rPath)}: { ${props} };`;
169
- })
170
- .join("\n");
1005
+ const navigableParamsEntries = formatParamsMapEntries(navigableParamsMap);
1006
+ const paramsEntries = formatParamsMapEntries(routeParamsMap);
1007
+ const layoutParamsEntries = formatParamsMapEntries(layoutParamsMap);
1008
+ const layoutSlotsEntries = formatLayoutSlotsEntries(
1009
+ Object.keys(layoutParamsMap),
1010
+ slotNamesBySegment
1011
+ );
1012
+ const slotParamsEntries = formatParamsMapEntries(slotParamsMap);
1013
+ const errorParamsEntries = formatParamsMapEntries(errorParamsMap);
1014
+
1015
+ const formatInterfaceBody = (body) => (body ? `\n${body}\n ` : "");
1016
+ const customAssetExts = readCustomAssetExtensionsSync(projectRoot);
1017
+ const customAssetDeclarations =
1018
+ customAssetExts.length > 0
1019
+ ? "\n" +
1020
+ customAssetExts
1021
+ .map(
1022
+ (ext) =>
1023
+ `declare module "*.${ext}" {\n const value: string;\n export default value;\n}\n`
1024
+ )
1025
+ .join("\n")
1026
+ : "";
1027
+
1028
+ const declaredEnvKeys = collectDeclaredEnvKeys(projectRoot);
1029
+ const customEnvDeclarations =
1030
+ declaredEnvKeys.length > 0
1031
+ ? `\ndeclare global {\n namespace NodeJS {\n interface ProcessEnv {\n${declaredEnvKeys
1032
+ .map((k) => ` ${k}?: string;`)
1033
+ .join("\n")}\n }\n }\n}\n`
1034
+ : "";
171
1035
 
172
1036
  const content = `// This file is auto-generated by Dinou. Do not edit directly.
1037
+ import type { ReactNode } from "react";
173
1038
  import "dinou";
174
1039
 
175
1040
  declare module "dinou" {
@@ -186,59 +1051,88 @@ ${dynamicUnion};
186
1051
  | \`https://\${string}\`
187
1052
  | \`mailto:\${string}\`
188
1053
  | \`tel:\${string}\`
189
- | \`./\${string}\`
190
- | \`../\${string}\`
191
1054
  | \`#\${string}\`
192
1055
  | \`?\${string}\`;
193
1056
 
194
1057
  export type DinouGeneratedRoute =
195
- | DinouInternalRoute
196
- | \`\${DinouInternalRoute}?\${string}\`
197
- | \`\${DinouInternalRoute}#\${string}\`
198
- | DinouRelativeOrExternalRoute;
1058
+ | DinouStaticRoutes
1059
+ | ((
1060
+ | DinouDynamicRoutes
1061
+ | \`\${DinouInternalRoute}?\${string}\`
1062
+ | \`\${DinouInternalRoute}#\${string}\`
1063
+ | DinouRelativeOrExternalRoute
1064
+ ) & Record<never, never>);
199
1065
 
200
- export interface DinouRouteParamsMap {
201
- ${paramsEntries}
202
- }
1066
+ export interface DinouNavigableParamsMap {${formatInterfaceBody(navigableParamsEntries)}}
1067
+
1068
+ export interface DinouRouteParamsMap {${formatInterfaceBody(paramsEntries)}}
1069
+
1070
+ export interface DinouLayoutParamsMap {${formatInterfaceBody(layoutParamsEntries)}}
1071
+
1072
+ export interface DinouLayoutSlotsMap {${formatInterfaceBody(layoutSlotsEntries)}}
1073
+
1074
+ export interface DinouSlotParamsMap {${formatInterfaceBody(slotParamsEntries)}}
1075
+
1076
+ export interface DinouErrorParamsMap {${formatInterfaceBody(errorParamsEntries)}}
203
1077
 
204
1078
  namespace DinouRouter {
205
1079
  interface Register {
206
1080
  route: DinouGeneratedRoute;
1081
+ navigableParams: DinouNavigableParamsMap;
207
1082
  params: DinouRouteParamsMap;
1083
+ layoutParams: DinouLayoutParamsMap;
1084
+ layoutSlots: DinouLayoutSlotsMap;
1085
+ slotParams: DinouSlotParamsMap;
1086
+ errorParams: DinouErrorParamsMap;
208
1087
  }
209
1088
  }
210
1089
  }
211
- `;
1090
+ ${customAssetDeclarations}${customEnvDeclarations}`;
212
1091
 
213
- // Write .dinou/types/routes.d.ts
1092
+ // 1. Write .dinou/types/routes.d.ts
214
1093
  const typesDir = path.resolve(projectRoot, ".dinou/types");
215
1094
  try {
216
- fs.mkdirSync(typesDir, { recursive: true });
217
- const targetFile = path.join(typesDir, "routes.d.ts");
218
- const currentContent = fs.existsSync(targetFile) ? fs.readFileSync(targetFile, "utf8") : "";
219
- if (currentContent !== content) {
220
- fs.writeFileSync(targetFile, content, "utf8");
221
- }
1095
+ writeFileIfChanged(path.join(typesDir, "routes.d.ts"), content);
222
1096
  } catch (e) {
1097
+ scheduleDeferredRouteTypesPrune(projectRoot, retryAttempts);
223
1098
  if (process.env.DINOU_DEBUG) {
224
1099
  console.warn("[Dinou] Could not write .dinou/types/routes.d.ts:", e.message);
225
1100
  }
226
1101
  }
227
1102
 
1103
+ // 2. Write & prune .dinou/routes/<relDir>/dinou.{js,d.ts}
1104
+ try {
1105
+ syncContextualRouteModules(
1106
+ projectRoot,
1107
+ topology.contextualDirs || [],
1108
+ retryAttempts
1109
+ );
1110
+ } catch (e) {
1111
+ scheduleDeferredRouteTypesPrune(projectRoot, retryAttempts);
1112
+ if (process.env.DINOU_DEBUG) {
1113
+ console.warn("[Dinou] Could not sync .dinou/routes modules:", e.message);
1114
+ }
1115
+ }
1116
+
228
1117
  return {
229
1118
  staticCount: staticRoutes.length,
230
1119
  dynamicCount: dynamicRoutes.length,
231
- totalRoutes: routes.length,
1120
+ totalRoutes: topology.routes.length,
1121
+ layoutCount: Object.keys(layoutParamsMap).length,
1122
+ slotCount: Object.keys(slotParamsMap).length,
1123
+ contextualDirCount: (topology.contextualDirs || []).length,
232
1124
  };
233
1125
  }
234
1126
 
235
1127
  export {
236
1128
  collectRoutes,
1129
+ collectRouteTopology,
237
1130
  generateRouteDefinitions,
238
1131
  generateRouteTypes,
239
1132
  };
240
1133
  export default {
241
1134
  collectRoutes,
1135
+ collectRouteTopology,
242
1136
  generateRouteDefinitions,
243
1137
  generateRouteTypes,
244
1138
  };