@teyik0/furin 0.5.0-alpha.2 → 0.7.0-alpha.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 (230) hide show
  1. package/dist/adapter/runtime-build.d.ts +3 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +5 -0
  4. package/dist/build/entry-template.ts +9 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +9589 -6685
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/request-keys.d.ts +4 -0
  9. package/dist/build/types.d.ts +6 -0
  10. package/dist/cli/index.js +9539 -6644
  11. package/dist/client/browser-events-runtime.d.ts +2 -1
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -1
  14. package/dist/client/dev-error-overlay.ts +1 -0
  15. package/dist/client/document.d.ts +3 -0
  16. package/dist/client/hmr.d.ts +1 -1
  17. package/dist/client/internal/runtime-types.d.ts +2 -0
  18. package/dist/client/link.js +1011 -157
  19. package/dist/client/mutation.d.ts +38 -0
  20. package/dist/client/query-store.d.ts +85 -0
  21. package/dist/client/query.d.ts +14 -0
  22. package/dist/client/route-api.d.ts +11 -0
  23. package/dist/client/router/context.d.ts +3 -2
  24. package/dist/client/router/index.d.ts +1 -1
  25. package/dist/client/router/link-utils.d.ts +8 -1
  26. package/dist/client/router/navigation.d.ts +2 -9
  27. package/dist/client/router/optimistic.d.ts +41 -0
  28. package/dist/client/router/search/index.d.ts +3 -3
  29. package/dist/client/router/search-store.d.ts +1 -0
  30. package/dist/client/router/sync-catch-up.d.ts +3 -0
  31. package/dist/client/router/types.d.ts +49 -7
  32. package/dist/client/sync.d.ts +39 -22
  33. package/dist/client.d.ts +11 -33
  34. package/dist/client.js +1222 -57
  35. package/dist/config.d.ts +7 -0
  36. package/dist/config.js +1 -0
  37. package/dist/define-route.d.ts +231 -123
  38. package/dist/env.d.ts +2 -2
  39. package/dist/furin.d.ts +4 -2
  40. package/dist/furin.js +9717 -6796
  41. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  42. package/dist/plugin/index.js +811 -145
  43. package/dist/plugin/transform-client-module.d.ts +16 -0
  44. package/dist/plugin/transform-client.d.ts +2 -0
  45. package/dist/plugin/transform-dev-page.d.ts +7 -0
  46. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  47. package/dist/routes.d.ts +6 -0
  48. package/dist/rsc-client.js +87 -16
  49. package/dist/rsc.js +87 -16
  50. package/dist/server/auto-invalidate/registry.d.ts +5 -2
  51. package/dist/server/auto-invalidate/types.d.ts +2 -0
  52. package/dist/server/browser-events/plugin.d.ts +3 -0
  53. package/dist/server/cache/isr.d.ts +2 -4
  54. package/dist/server/cache/route-cache.d.ts +5 -0
  55. package/dist/server/dev/graph.d.ts +1 -0
  56. package/dist/server/dev/runtime.production.d.ts +1 -0
  57. package/dist/server/dev-page-plugin.d.ts +6 -19
  58. package/dist/server/internal.d.ts +5 -0
  59. package/dist/server/internal.js +105 -57
  60. package/dist/server/production-server.js +104 -56
  61. package/dist/server/render/assemble.d.ts +6 -6
  62. package/dist/server/render/document.d.ts +1 -1
  63. package/dist/server/render/element.d.ts +1 -1
  64. package/dist/server/render/loaders.d.ts +15 -5
  65. package/dist/server/render/mixed-cache.d.ts +6 -0
  66. package/dist/server/render/react-stream.d.ts +3 -0
  67. package/dist/server/render/ssr.d.ts +5 -4
  68. package/dist/server/render/template.d.ts +4 -0
  69. package/dist/server/router/defined-route.d.ts +2 -0
  70. package/dist/server/router/discovery.d.ts +1 -0
  71. package/dist/server/router/hmr.d.ts +1 -1
  72. package/dist/server/router/patterns.d.ts +3 -0
  73. package/dist/server/router/plugin.d.ts +3 -0
  74. package/dist/server/router/types.d.ts +4 -0
  75. package/dist/server/security/csp.d.ts +12 -0
  76. package/dist/server/sync/adapter.d.ts +25 -4
  77. package/dist/server/sync/atomic.d.ts +25 -0
  78. package/dist/server/sync/drizzle/index.d.ts +45 -0
  79. package/dist/server/sync/drizzle/index.js +540 -0
  80. package/dist/server/sync/execution-error.d.ts +2 -0
  81. package/dist/server/sync/index.d.ts +2 -1
  82. package/dist/server/sync/index.js +580 -124
  83. package/dist/server/sync/mutation-handler.d.ts +4 -0
  84. package/dist/server/sync/plugin.d.ts +34 -11
  85. package/dist/server/sync/postgres/execute.d.ts +3 -0
  86. package/dist/server/sync/postgres/index.d.ts +12 -1
  87. package/dist/server/sync/postgres/index.js +42 -13
  88. package/dist/server/sync/postgres/sql.d.ts +8 -0
  89. package/dist/server/sync/prisma/index.d.ts +24 -0
  90. package/dist/server/sync/prisma/index.js +340 -0
  91. package/dist/server/sync/queries.d.ts +21 -0
  92. package/dist/server/sync/query-context.d.ts +5 -0
  93. package/dist/server/sync/redis/index.js +3 -3
  94. package/dist/server/sync/redis/scripts.d.ts +1 -1
  95. package/dist/server/sync/response.d.ts +1 -0
  96. package/dist/server/sync/sqlite/index.d.ts +3 -0
  97. package/dist/server/sync/sqlite/index.js +10 -4
  98. package/dist/server/sync/stream.d.ts +2 -5
  99. package/dist/server/sync/validation.d.ts +4 -0
  100. package/dist/shared/defer.d.ts +31 -0
  101. package/dist/shared/error.d.ts +2 -2
  102. package/dist/shared/page-key.d.ts +7 -0
  103. package/dist/shared/query-bindings.d.ts +12 -0
  104. package/dist/shared/route-frame.d.ts +1 -0
  105. package/dist/shared/sync-query.d.ts +40 -0
  106. package/package.json +40 -16
  107. package/src/adapter/README.md +3 -0
  108. package/src/adapter/bun.ts +3 -0
  109. package/src/adapter/package.ts +16 -2
  110. package/src/adapter/runtime-build.ts +99 -14
  111. package/src/adapter/static.ts +17 -6
  112. package/src/adapter/vercel.ts +33 -23
  113. package/src/build/client.ts +23 -5
  114. package/src/build/entry-template.ts +9 -0
  115. package/src/build/hydrate.ts +18 -3
  116. package/src/build/preload-manifest.ts +100 -0
  117. package/src/build/production-instrumentation.ts +6 -3
  118. package/src/build/request-keys.ts +93 -0
  119. package/src/build/ssg-cache.ts +9 -4
  120. package/src/build/types.ts +4 -0
  121. package/src/cli/index.ts +1 -0
  122. package/src/client/boundaries.tsx +1 -1
  123. package/src/client/browser-events-runtime.ts +73 -16
  124. package/src/client/client-module.ts +57 -0
  125. package/src/client/define-route.ts +11 -2
  126. package/src/client/dev-error-overlay.ts +1 -0
  127. package/src/client/document.tsx +47 -20
  128. package/src/client/hmr.ts +4 -2
  129. package/src/client/internal/runtime-types.ts +2 -0
  130. package/src/client/link.tsx +8 -8
  131. package/src/client/mutation.ts +136 -0
  132. package/src/client/query-store.ts +418 -0
  133. package/src/client/query.tsx +67 -0
  134. package/src/client/route-api.tsx +75 -0
  135. package/src/client/router/boundary-tree.tsx +10 -6
  136. package/src/client/router/context.ts +57 -4
  137. package/src/client/router/index.ts +3 -0
  138. package/src/client/router/link-utils.ts +29 -1
  139. package/src/client/router/navigation.ts +3 -50
  140. package/src/client/router/optimistic.ts +233 -0
  141. package/src/client/router/provider.tsx +404 -96
  142. package/src/client/router/search/index.ts +37 -17
  143. package/src/client/router/search-store.ts +4 -0
  144. package/src/client/router/sync-catch-up.ts +7 -0
  145. package/src/client/router/types.ts +71 -9
  146. package/src/client/sync.ts +438 -65
  147. package/src/client.ts +20 -60
  148. package/src/config.ts +5 -0
  149. package/src/define-route.ts +442 -155
  150. package/src/env.d.ts +2 -2
  151. package/src/furin.ts +213 -38
  152. package/src/plugin/hmr-dependencies.ts +58 -0
  153. package/src/plugin/index.ts +38 -2
  154. package/src/plugin/route-config-autofix.ts +2 -2
  155. package/src/plugin/routes.ts +19 -8
  156. package/src/plugin/transform-client-module.ts +123 -0
  157. package/src/plugin/transform-client.ts +293 -13
  158. package/src/plugin/transform-dev-page.ts +231 -0
  159. package/src/plugin/transform-isomorphic.ts +11 -5
  160. package/src/routes.ts +8 -0
  161. package/src/rsc/shared.tsx +104 -18
  162. package/src/rsc/version.ts +5 -0
  163. package/src/server/auto-invalidate/registry.ts +56 -24
  164. package/src/server/auto-invalidate/runtime.ts +17 -0
  165. package/src/server/auto-invalidate/types.ts +6 -0
  166. package/src/server/browser-events/plugin.ts +112 -1
  167. package/src/server/cache/dev-loader.ts +1 -1
  168. package/src/server/cache/invalidation.ts +2 -0
  169. package/src/server/cache/isr-ssg.ts +1 -1
  170. package/src/server/cache/isr.ts +6 -34
  171. package/src/server/cache/route-cache.ts +40 -4
  172. package/src/server/cache/ssg.ts +1 -1
  173. package/src/server/dev/diagnostics.ts +4 -2
  174. package/src/server/dev/error.ts +2 -1
  175. package/src/server/dev/graph.ts +70 -7
  176. package/src/server/dev/runtime.production.ts +4 -0
  177. package/src/server/dev/symbolicate.ts +2 -0
  178. package/src/server/dev-page-plugin.ts +160 -63
  179. package/src/server/evlog.ts +1 -1
  180. package/src/server/internal.ts +5 -0
  181. package/src/server/render/assemble.ts +15 -11
  182. package/src/server/render/document.tsx +13 -2
  183. package/src/server/render/element.tsx +11 -6
  184. package/src/server/render/isr.ts +71 -33
  185. package/src/server/render/loaders.ts +328 -70
  186. package/src/server/render/mixed-cache.ts +327 -0
  187. package/src/server/render/not-found.ts +14 -11
  188. package/src/server/render/ppr-document.ts +47 -11
  189. package/src/server/render/ppr-route.ts +54 -20
  190. package/src/server/render/react-stream.ts +17 -0
  191. package/src/server/render/route-frame-transport.ts +3 -0
  192. package/src/server/render/ssg.ts +53 -19
  193. package/src/server/render/ssr.ts +105 -36
  194. package/src/server/render/static-params.ts +1 -1
  195. package/src/server/render/template.ts +23 -0
  196. package/src/server/router/defined-route.ts +3 -0
  197. package/src/server/router/discovery.ts +14 -0
  198. package/src/server/router/hmr.ts +109 -18
  199. package/src/server/router/patterns.ts +27 -0
  200. package/src/server/router/plugin.ts +94 -19
  201. package/src/server/router/source-version.ts +20 -2
  202. package/src/server/router/types.ts +4 -0
  203. package/src/server/security/csp.ts +44 -0
  204. package/src/server/sync/adapter.ts +41 -4
  205. package/src/server/sync/atomic.ts +303 -0
  206. package/src/server/sync/drizzle/index.ts +145 -0
  207. package/src/server/sync/execution-error.ts +1 -0
  208. package/src/server/sync/fingerprint.ts +2 -6
  209. package/src/server/sync/index.ts +6 -0
  210. package/src/server/sync/mutation-handler.ts +69 -0
  211. package/src/server/sync/plugin.ts +177 -60
  212. package/src/server/sync/postgres/execute.ts +20 -0
  213. package/src/server/sync/postgres/index.ts +60 -16
  214. package/src/server/sync/postgres/sql.ts +20 -0
  215. package/src/server/sync/prisma/index.ts +70 -0
  216. package/src/server/sync/queries.ts +75 -0
  217. package/src/server/sync/query-context.ts +85 -0
  218. package/src/server/sync/redis/index.ts +7 -3
  219. package/src/server/sync/redis/scripts.ts +1 -1
  220. package/src/server/sync/response.ts +21 -0
  221. package/src/server/sync/sqlite/index.ts +19 -8
  222. package/src/server/sync/stream.ts +14 -22
  223. package/src/server/sync/validation.ts +34 -0
  224. package/src/shared/defer.ts +48 -0
  225. package/src/shared/error.ts +2 -2
  226. package/src/shared/page-key.ts +36 -0
  227. package/src/shared/query-bindings.ts +138 -0
  228. package/src/shared/route-frame.ts +13 -1
  229. package/src/shared/route-map.ts +12 -2
  230. package/src/shared/sync-query.ts +138 -0
@@ -1,4 +1,31 @@
1
1
  // @bun
2
+ // src/plugin/index.ts
3
+ import { dirname as dirname3, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
4
+
5
+ // src/rsc/build/environment.ts
6
+ import { fileURLToPath } from "url";
7
+ var SERVER_ONLY_RE = /^(?:@teyik0\/)?furin\/server-only$/;
8
+ var CLIENT_ONLY_RE = /^(?:@teyik0\/)?furin\/client-only$/;
9
+ function environmentGuardPlugin(graph) {
10
+ return {
11
+ name: `furin-environment-${graph}`,
12
+ setup(build) {
13
+ build.onResolve({ filter: SERVER_ONLY_RE }, (args) => {
14
+ if (graph === "client") {
15
+ throw new Error(`[furin] ${args.importer} imports furin/server-only from the client graph.`);
16
+ }
17
+ return { path: fileURLToPath(import.meta.resolve("../../server-only.ts")) };
18
+ });
19
+ build.onResolve({ filter: CLIENT_ONLY_RE }, (args) => {
20
+ if (graph !== "client") {
21
+ throw new Error(`[furin] ${args.importer} imports furin/client-only from the ${graph} graph.`);
22
+ }
23
+ return { path: fileURLToPath(import.meta.resolve("../../client-only.ts")) };
24
+ });
25
+ }
26
+ };
27
+ }
28
+
2
29
  // src/server/lang-detect.ts
3
30
  function detectLangFromPath(filePath) {
4
31
  if (filePath.endsWith(".d.ts")) {
@@ -35,7 +62,7 @@ function unwrapTSExpression(node) {
35
62
  return current;
36
63
  }
37
64
 
38
- // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
65
+ // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
39
66
  var comma = 44;
40
67
  var semicolon = 59;
41
68
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -46,17 +73,17 @@ for (let i = 0;i < chars.length; i++) {
46
73
  intToChar[i] = c;
47
74
  charToInt[c] = i;
48
75
  }
49
- function encodeInteger(builder, num, relative) {
50
- let delta = num - relative;
51
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
76
+ function encodeInteger(builder, num) {
52
77
  do {
53
- let clamped = delta & 31;
54
- delta >>>= 5;
55
- if (delta > 0)
78
+ let clamped = num & 31;
79
+ num >>>= 5;
80
+ if (num > 0)
56
81
  clamped |= 32;
57
82
  builder.write(intToChar[clamped]);
58
- } while (delta > 0);
59
- return num;
83
+ } while (num > 0);
84
+ }
85
+ function encodeSign(num) {
86
+ return num < 0 ? -num << 1 | 1 : num << 1;
60
87
  }
61
88
  var bufLength = 1024 * 16;
62
89
  var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder : typeof Buffer !== "undefined" ? {
@@ -92,6 +119,23 @@ var StringWriter = class {
92
119
  return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
93
120
  }
94
121
  };
122
+ function encodeRangeMappings(decoded) {
123
+ if (decoded.length === 0)
124
+ return "";
125
+ const writer = new StringWriter;
126
+ for (let i = 0;i < decoded.length; i++) {
127
+ const indices = decoded[i];
128
+ if (i > 0)
129
+ writer.write(semicolon);
130
+ let index = 0;
131
+ for (let j = 0;j < indices.length; j++) {
132
+ const offset = indices[j];
133
+ encodeInteger(writer, offset - index);
134
+ index = offset;
135
+ }
136
+ }
137
+ return writer.flush();
138
+ }
95
139
  function encode(decoded) {
96
140
  const writer = new StringWriter;
97
141
  let sourcesIndex = 0;
@@ -109,21 +153,26 @@ function encode(decoded) {
109
153
  const segment = line[j];
110
154
  if (j > 0)
111
155
  writer.write(comma);
112
- genColumn = encodeInteger(writer, segment[0], genColumn);
156
+ encodeInteger(writer, encodeSign(segment[0] - genColumn));
157
+ genColumn = segment[0];
113
158
  if (segment.length === 1)
114
159
  continue;
115
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
116
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
117
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
160
+ encodeInteger(writer, encodeSign(segment[1] - sourcesIndex));
161
+ encodeInteger(writer, encodeSign(segment[2] - sourceLine));
162
+ encodeInteger(writer, encodeSign(segment[3] - sourceColumn));
163
+ sourcesIndex = segment[1];
164
+ sourceLine = segment[2];
165
+ sourceColumn = segment[3];
118
166
  if (segment.length === 4)
119
167
  continue;
120
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
168
+ encodeInteger(writer, encodeSign(segment[4] - namesIndex));
169
+ namesIndex = segment[4];
121
170
  }
122
171
  }
123
172
  return writer.flush();
124
173
  }
125
174
 
126
- // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
175
+ // ../../node_modules/.bun/magic-string@1.4.2/node_modules/magic-string/dist/index.mjs
127
176
  var BitSet = class BitSet {
128
177
  constructor(arg) {
129
178
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -217,7 +266,7 @@ var Chunk = class Chunk {
217
266
  this.outro = "";
218
267
  this.end = index;
219
268
  if (this.edited) {
220
- newChunk.edit("", false);
269
+ newChunk.edit("", false, true);
221
270
  this.content = "";
222
271
  } else
223
272
  this.content = originalBefore;
@@ -237,11 +286,12 @@ var Chunk = class Chunk {
237
286
  return true;
238
287
  const trimmed = this.content.replace(rx, "");
239
288
  if (trimmed.length) {
240
- if (trimmed !== this.content)
289
+ if (trimmed !== this.content) {
241
290
  if (this.edited)
242
291
  this.edit(trimmed, this.storeName, true);
243
292
  else
244
293
  this.split(this.start + trimmed.length).edit("", undefined, true);
294
+ }
245
295
  return true;
246
296
  } else {
247
297
  this.edit("", undefined, true);
@@ -256,13 +306,14 @@ var Chunk = class Chunk {
256
306
  return true;
257
307
  const trimmed = this.content.replace(rx, "");
258
308
  if (trimmed.length) {
259
- if (trimmed !== this.content)
309
+ if (trimmed !== this.content) {
260
310
  if (this.edited)
261
311
  this.edit(trimmed, this.storeName, true);
262
312
  else {
263
313
  this.split(this.end - trimmed.length);
264
314
  this.edit("", undefined, true);
265
315
  }
316
+ }
266
317
  return true;
267
318
  } else {
268
319
  this.edit("", undefined, true);
@@ -296,11 +347,21 @@ var SourceMap = class {
296
347
  this.sources = properties.sources;
297
348
  this.sourcesContent = properties.sourcesContent;
298
349
  this.names = properties.names;
299
- this.mappings = encode(properties.mappings);
350
+ this.mappings = typeof properties.mappings === "string" ? properties.mappings : encode(properties.mappings);
300
351
  if (typeof properties.x_google_ignoreList !== "undefined")
301
352
  this.x_google_ignoreList = properties.x_google_ignoreList;
302
353
  if (typeof properties.debugId !== "undefined")
303
354
  this.debugId = properties.debugId;
355
+ if (typeof properties.rangeMappings !== "undefined") {
356
+ let shouldOutputRangeMapping = false;
357
+ for (const line of properties.rangeMappings)
358
+ if (line.length !== 0) {
359
+ shouldOutputRangeMapping = true;
360
+ break;
361
+ }
362
+ if (shouldOutputRangeMapping)
363
+ this.rangeMappings = encodeRangeMappings(properties.rangeMappings);
364
+ }
304
365
  }
305
366
  toString() {
306
367
  return JSON.stringify(this);
@@ -310,13 +371,11 @@ var SourceMap = class {
310
371
  }
311
372
  };
312
373
  function getLocator(source) {
313
- const originalLines = source.split(`
314
- `);
315
- const lineOffsets = [];
316
- for (let i = 0, pos = 0;i < originalLines.length; i++) {
317
- lineOffsets.push(pos);
318
- pos += originalLines[i].length + 1;
319
- }
374
+ const lineOffsets = [0];
375
+ for (let i = source.indexOf(`
376
+ `);i !== -1; i = source.indexOf(`
377
+ `, i + 1))
378
+ lineOffsets.push(i + 1);
320
379
  return function locate(index) {
321
380
  let i = 0;
322
381
  let j = lineOffsets.length;
@@ -368,15 +427,127 @@ var toString = Object.prototype.toString;
368
427
  function isObject(thing) {
369
428
  return toString.call(thing) === "[object Object]";
370
429
  }
371
- var wordRegex = /\w/;
430
+ var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
431
+ var intToChar2 = /* @__PURE__ */ (() => {
432
+ const chars = /* @__PURE__ */ new Uint8Array(64);
433
+ for (let i = 0;i < 64; i++)
434
+ chars[i] = BASE64_CHARS.charCodeAt(i);
435
+ return chars;
436
+ })();
437
+ var COMMA = 44;
438
+ var SEMICOLON = 59;
439
+ var BUFFER_SIZE = 16384;
440
+ var FLUSH_THRESHOLD = 16348;
441
+ var scratch = /* @__PURE__ */ new Uint8Array(BUFFER_SIZE);
442
+ function writeVlq(pos, num) {
443
+ num = num < 0 ? -num << 1 | 1 : num << 1;
444
+ do {
445
+ let clamped = num & 31;
446
+ num >>>= 5;
447
+ if (num > 0)
448
+ clamped |= 32;
449
+ scratch[pos++] = intToChar2[clamped];
450
+ } while (num > 0);
451
+ return pos;
452
+ }
453
+ var decoder = /* @__PURE__ */ new TextDecoder;
454
+ var MappingsEncoder = class {
455
+ constructor() {
456
+ this.out = "";
457
+ this.pos = 0;
458
+ this.lines = [];
459
+ this.buffered = 0;
460
+ this.needsComma = false;
461
+ this.prevGenColumn = 0;
462
+ this.prevSourceIndex = 0;
463
+ this.prevSourceLine = 0;
464
+ this.prevSourceColumn = 0;
465
+ this.prevNameIndex = 0;
466
+ }
467
+ endLine(segments) {
468
+ this.lines.push(segments);
469
+ this.buffered += segments.length + 1;
470
+ if (this.buffered >= 4096)
471
+ this.drain(null);
472
+ }
473
+ segments(segments) {
474
+ this.drain(segments);
475
+ }
476
+ finish(segments) {
477
+ this.drain(segments);
478
+ this.flush();
479
+ return this.out;
480
+ }
481
+ drain(trailing) {
482
+ const lines = this.lines;
483
+ const lineCount = lines.length;
484
+ for (let l = 0;l <= lineCount; l++) {
485
+ const line = l < lineCount ? lines[l] : trailing;
486
+ if (line === null)
487
+ break;
488
+ for (let i = 0;i < line.length; i++) {
489
+ if (this.pos > FLUSH_THRESHOLD)
490
+ this.flush();
491
+ const segment = line[i];
492
+ if (this.needsComma)
493
+ scratch[this.pos++] = COMMA;
494
+ this.needsComma = true;
495
+ this.pos = writeVlq(this.pos, segment[0] - this.prevGenColumn);
496
+ this.prevGenColumn = segment[0];
497
+ this.pos = writeVlq(this.pos, segment[1] - this.prevSourceIndex);
498
+ this.prevSourceIndex = segment[1];
499
+ this.pos = writeVlq(this.pos, segment[2] - this.prevSourceLine);
500
+ this.prevSourceLine = segment[2];
501
+ this.pos = writeVlq(this.pos, segment[3] - this.prevSourceColumn);
502
+ this.prevSourceColumn = segment[3];
503
+ if (segment.length === 5) {
504
+ this.pos = writeVlq(this.pos, segment[4] - this.prevNameIndex);
505
+ this.prevNameIndex = segment[4];
506
+ }
507
+ }
508
+ if (l < lineCount) {
509
+ if (this.pos > FLUSH_THRESHOLD)
510
+ this.flush();
511
+ scratch[this.pos++] = SEMICOLON;
512
+ this.needsComma = false;
513
+ this.prevGenColumn = 0;
514
+ }
515
+ }
516
+ lines.length = 0;
517
+ this.buffered = 0;
518
+ this.flush();
519
+ }
520
+ flush() {
521
+ this.out += decoder.decode(scratch.subarray(0, this.pos));
522
+ this.pos = 0;
523
+ }
524
+ };
525
+ var NEWLINE_CHAR$1 = 10;
526
+ function isWordCode(code) {
527
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
528
+ }
372
529
  var Mappings = class {
373
- constructor(hires) {
530
+ constructor(hires, encoder = null) {
374
531
  this.hires = hires;
375
532
  this.generatedCodeLine = 0;
376
533
  this.generatedCodeColumn = 0;
377
534
  this.raw = [];
378
535
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
379
- this.pending = null;
536
+ this.rawRangeMappings = [];
537
+ this.rawRangeMappingsIndices = this.rawRangeMappings[this.generatedCodeLine] = [];
538
+ this.encoder = encoder;
539
+ }
540
+ nextLine() {
541
+ if (this.encoder === null) {
542
+ this.generatedCodeLine += 1;
543
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
544
+ } else {
545
+ this.encoder.endLine(this.rawSegments);
546
+ this.rawSegments = [];
547
+ this.generatedCodeLine += 1;
548
+ }
549
+ this.generatedCodeColumn = 0;
550
+ this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
380
551
  }
381
552
  addEdit(sourceIndex, content, loc, nameIndex) {
382
553
  if (content.length) {
@@ -394,9 +565,7 @@ var Mappings = class {
394
565
  if (nameIndex >= 0)
395
566
  segment.push(nameIndex);
396
567
  this.rawSegments.push(segment);
397
- this.generatedCodeLine += 1;
398
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
399
- this.generatedCodeColumn = 0;
568
+ this.nextLine();
400
569
  previousContentLineEnd = contentLineEnd;
401
570
  contentLineEnd = content.indexOf(`
402
571
  `, contentLineEnd + 1);
@@ -411,68 +580,133 @@ var Mappings = class {
411
580
  segment.push(nameIndex);
412
581
  this.rawSegments.push(segment);
413
582
  this.advance(content.slice(previousContentLineEnd + 1));
414
- } else if (this.pending) {
415
- this.rawSegments.push(this.pending);
416
- this.advance(content);
417
583
  }
418
- this.pending = null;
419
584
  }
420
585
  addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
421
- let originalCharIndex = chunk.start;
422
- let first = true;
423
- let charInHiresBoundary = false;
424
- while (originalCharIndex < chunk.end) {
425
- if (original[originalCharIndex] === `
426
- `) {
427
- loc.line += 1;
428
- loc.column = 0;
429
- this.generatedCodeLine += 1;
430
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
431
- this.generatedCodeColumn = 0;
432
- first = true;
433
- charInHiresBoundary = false;
434
- } else {
435
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
436
- const segment = [
586
+ const end = chunk.end;
587
+ let i = chunk.start;
588
+ if (this.hires) {
589
+ const boundary = this.hires === "boundary";
590
+ const experimentalRange = this.hires === "experimental-range";
591
+ const encoder = experimentalRange ? null : this.encoder;
592
+ let charInHiresBoundary = false;
593
+ while (i < end) {
594
+ if (encoder !== null && this.rawSegments.length >= 4096) {
595
+ encoder.segments(this.rawSegments);
596
+ this.rawSegments.length = 0;
597
+ }
598
+ if (experimentalRange && i + 1 >= end)
599
+ this.rawSegments.push([
437
600
  this.generatedCodeColumn,
438
601
  sourceIndex,
439
602
  loc.line,
440
603
  loc.column
441
- ];
442
- if (this.hires === "boundary")
443
- if (wordRegex.test(original[originalCharIndex])) {
604
+ ]);
605
+ const code = original.charCodeAt(i);
606
+ if (code === NEWLINE_CHAR$1) {
607
+ loc.line += 1;
608
+ loc.column = 0;
609
+ this.nextLine();
610
+ charInHiresBoundary = false;
611
+ } else {
612
+ if (boundary) {
613
+ if (isWordCode(code)) {
444
614
  if (!charInHiresBoundary) {
445
- this.rawSegments.push(segment);
615
+ this.rawSegments.push([
616
+ this.generatedCodeColumn,
617
+ sourceIndex,
618
+ loc.line,
619
+ loc.column
620
+ ]);
446
621
  charInHiresBoundary = true;
447
622
  }
448
623
  } else {
449
- this.rawSegments.push(segment);
624
+ this.rawSegments.push([
625
+ this.generatedCodeColumn,
626
+ sourceIndex,
627
+ loc.line,
628
+ loc.column
629
+ ]);
450
630
  charInHiresBoundary = false;
451
631
  }
452
- else
453
- this.rawSegments.push(segment);
632
+ } else if (experimentalRange) {
633
+ if (i === chunk.start) {
634
+ this.rawRangeMappingsIndices.push(this.rawSegments.length);
635
+ this.rawSegments.push([
636
+ this.generatedCodeColumn,
637
+ sourceIndex,
638
+ loc.line,
639
+ loc.column
640
+ ]);
641
+ }
642
+ } else
643
+ this.rawSegments.push([
644
+ this.generatedCodeColumn,
645
+ sourceIndex,
646
+ loc.line,
647
+ loc.column
648
+ ]);
649
+ loc.column += 1;
650
+ this.generatedCodeColumn += 1;
651
+ }
652
+ i += 1;
653
+ }
654
+ } else {
655
+ const bits = sourcemapLocations.bits;
656
+ while (i < end) {
657
+ let newline = original.indexOf(`
658
+ `, i);
659
+ if (newline === -1 || newline > end)
660
+ newline = end;
661
+ if (newline > i) {
662
+ this.rawSegments.push([
663
+ this.generatedCodeColumn,
664
+ sourceIndex,
665
+ loc.line,
666
+ loc.column
667
+ ]);
668
+ for (let w = i + 1 >> 5, last = newline - 1 >> 5;w <= last; w++) {
669
+ let word = bits[w];
670
+ if (!word)
671
+ continue;
672
+ const base = w << 5;
673
+ while (word) {
674
+ const lowest = word & -word;
675
+ const index = base + 31 - Math.clz32(lowest);
676
+ if (index > i && index < newline) {
677
+ const offset = index - i;
678
+ this.rawSegments.push([
679
+ this.generatedCodeColumn + offset,
680
+ sourceIndex,
681
+ loc.line,
682
+ loc.column + offset
683
+ ]);
684
+ }
685
+ word ^= lowest;
686
+ }
687
+ }
688
+ loc.column += newline - i;
689
+ this.generatedCodeColumn += newline - i;
454
690
  }
455
- loc.column += 1;
456
- this.generatedCodeColumn += 1;
457
- first = false;
691
+ if (newline === end)
692
+ break;
693
+ loc.line += 1;
694
+ loc.column = 0;
695
+ this.nextLine();
696
+ i = newline + 1;
458
697
  }
459
- originalCharIndex += 1;
460
698
  }
461
- this.pending = null;
462
699
  }
463
700
  advance(str) {
464
701
  if (!str)
465
702
  return;
466
- const lines = str.split(`
703
+ const lastNewline = str.lastIndexOf(`
467
704
  `);
468
- if (lines.length > 1) {
469
- for (let i = 0;i < lines.length - 1; i++) {
470
- this.generatedCodeLine++;
471
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
472
- }
473
- this.generatedCodeColumn = 0;
474
- }
475
- this.generatedCodeColumn += lines[lines.length - 1].length;
705
+ for (let i = str.indexOf(`
706
+ `);i !== -1; i = str.indexOf(`
707
+ `, i + 1))
708
+ this.nextLine();
709
+ this.generatedCodeColumn += str.length - lastNewline - 1;
476
710
  }
477
711
  };
478
712
  var n = `
@@ -484,6 +718,55 @@ var warned = {
484
718
  insertRight: false,
485
719
  storeName: false
486
720
  };
721
+ function expandReplacement(replacement, matched, position, str, captures, namedCaptures) {
722
+ if (!replacement.includes("$"))
723
+ return replacement;
724
+ let result = "";
725
+ let index = 0;
726
+ while (index < replacement.length) {
727
+ const dollar = replacement.indexOf("$", index);
728
+ if (dollar === -1) {
729
+ result += replacement.slice(index);
730
+ break;
731
+ }
732
+ result += replacement.slice(index, dollar);
733
+ const char = replacement[dollar + 1];
734
+ let expansion = "$";
735
+ let consumed = 1;
736
+ if (char === "$")
737
+ consumed = 2;
738
+ else if (char === "&") {
739
+ expansion = matched;
740
+ consumed = 2;
741
+ } else if (char === "`") {
742
+ expansion = str.slice(0, position);
743
+ consumed = 2;
744
+ } else if (char === "'") {
745
+ expansion = str.slice(position + matched.length);
746
+ consumed = 2;
747
+ } else if (char === "<" && namedCaptures !== undefined) {
748
+ const close = replacement.indexOf(">", dollar + 2);
749
+ if (close !== -1) {
750
+ expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? "";
751
+ consumed = close + 1 - dollar;
752
+ }
753
+ } else if (char >= "0" && char <= "9") {
754
+ const second = replacement[dollar + 2];
755
+ const double = second >= "0" && second <= "9" ? Number(char + second) : NaN;
756
+ const single = Number(char);
757
+ if (double >= 1 && double <= captures.length) {
758
+ expansion = captures[double - 1] ?? "";
759
+ consumed = 3;
760
+ } else if (single >= 1 && single <= captures.length) {
761
+ expansion = captures[single - 1] ?? "";
762
+ consumed = 2;
763
+ }
764
+ }
765
+ result += expansion;
766
+ index = dollar + consumed;
767
+ }
768
+ return result;
769
+ }
487
770
  var MagicString = class MagicString {
488
771
  constructor(string, options = {}) {
489
772
  const chunk = new Chunk(0, string.length, string);
@@ -619,9 +902,28 @@ var MagicString = class MagicString {
619
902
  }
620
903
  generateDecodedMap(options) {
621
904
  options = options || {};
905
+ const mappings = new Mappings(options.hires);
906
+ const names = this._generateMappings(mappings);
907
+ return {
908
+ ...this._mapProperties(options, names),
909
+ mappings: mappings.raw,
910
+ rangeMappings: mappings.rawRangeMappings
911
+ };
912
+ }
913
+ generateMap(options) {
914
+ options = options || {};
915
+ const encoder = new MappingsEncoder;
916
+ const mappings = new Mappings(options.hires, encoder);
917
+ const names = this._generateMappings(mappings);
918
+ return new SourceMap({
919
+ ...this._mapProperties(options, names),
920
+ mappings: encoder.finish(mappings.rawSegments),
921
+ rangeMappings: mappings.rawRangeMappings
922
+ });
923
+ }
924
+ _generateMappings(mappings) {
622
925
  const sourceIndex = 0;
623
926
  const names = Object.keys(this.storedNames);
624
- const mappings = new Mappings(options.hires);
625
927
  const locate = getLocator(this.original);
626
928
  if (this.intro)
627
929
  mappings.advance(this.intro);
@@ -638,18 +940,17 @@ var MagicString = class MagicString {
638
940
  });
639
941
  if (this.outro)
640
942
  mappings.advance(this.outro);
943
+ return names;
944
+ }
945
+ _mapProperties(options, names) {
641
946
  return {
642
947
  file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
643
948
  sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
644
949
  sourcesContent: options.includeContent ? [this.original] : undefined,
645
950
  names,
646
- mappings: mappings.raw,
647
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
951
+ x_google_ignoreList: this.ignoreList ? [0] : undefined
648
952
  };
649
953
  }
650
- generateMap(options) {
651
- return new SourceMap(this.generateDecodedMap(options));
652
- }
653
954
  _ensureindentStr() {
654
955
  if (this.indentStr === undefined)
655
956
  this.indentStr = guessIndent(this.original);
@@ -683,19 +984,21 @@ var MagicString = class MagicString {
683
984
  isExcluded[i] = true;
684
985
  });
685
986
  let shouldIndentNextCharacter = options.indentStart !== false;
686
- const replacer = (match) => {
687
- if (shouldIndentNextCharacter)
688
- return `${resolvedIndentStr}${match}`;
689
- shouldIndentNextCharacter = true;
690
- return match;
987
+ const indentPiece = (str) => {
988
+ if (str === "")
989
+ return str;
990
+ const indented = str.replace(pattern, (match, offset) => offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match);
991
+ shouldIndentNextCharacter = str[str.length - 1] === `
992
+ `;
993
+ return indented;
691
994
  };
692
- this.intro = this.intro.replace(pattern, replacer);
995
+ this.intro = indentPiece(this.intro);
693
996
  let charIndex = 0;
694
997
  let chunk = this.firstChunk;
695
998
  const indentAt = (index) => {
696
999
  shouldIndentNextCharacter = false;
697
1000
  if (index === chunk.start)
698
- chunk.prependRight(resolvedIndentStr);
1001
+ chunk.appendRight(resolvedIndentStr);
699
1002
  else {
700
1003
  this._splitChunk(chunk, index);
701
1004
  chunk = chunk.next;
@@ -704,13 +1007,11 @@ var MagicString = class MagicString {
704
1007
  };
705
1008
  while (chunk) {
706
1009
  const end = chunk.end;
1010
+ if (!isExcluded[chunk.start])
1011
+ chunk.intro = indentPiece(chunk.intro);
707
1012
  if (chunk.edited) {
708
- if (!isExcluded[charIndex]) {
709
- chunk.content = chunk.content.replace(pattern, replacer);
710
- if (chunk.content.length)
711
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === `
712
- `;
713
- }
1013
+ if (!isExcluded[charIndex])
1014
+ chunk.content = indentPiece(chunk.content);
714
1015
  } else if (options.exclude) {
715
1016
  charIndex = chunk.start;
716
1017
  while (charIndex < end) {
@@ -743,10 +1044,12 @@ var MagicString = class MagicString {
743
1044
  charIndex += 1;
744
1045
  }
745
1046
  }
1047
+ if (!isExcluded[chunk.end - 1])
1048
+ chunk.outro = indentPiece(chunk.outro);
746
1049
  charIndex = chunk.end;
747
1050
  chunk = chunk.next;
748
1051
  }
749
- this.outro = this.outro.replace(pattern, replacer);
1052
+ this.outro = indentPiece(this.outro);
750
1053
  return this;
751
1054
  }
752
1055
  insert() {
@@ -766,7 +1069,7 @@ var MagicString = class MagicString {
766
1069
  }
767
1070
  return this.prependRight(index, content);
768
1071
  }
769
- move(start, end, index) {
1072
+ move(start, end, index, affinity = "right") {
770
1073
  start = start + this.offset;
771
1074
  end = end + this.offset;
772
1075
  index = index + this.offset;
@@ -789,10 +1092,31 @@ var MagicString = class MagicString {
789
1092
  }
790
1093
  const oldLeft = first.previous;
791
1094
  const oldRight = last.next;
792
- const newRight = this.byStart.get(index);
793
- if (!newRight && last === this.lastChunk)
794
- return this;
795
- const newLeft = newRight ? newRight.previous : this.lastChunk;
1095
+ let newLeft;
1096
+ let newRight;
1097
+ if (affinity === "left") {
1098
+ newLeft = this.byEnd.get(index) ?? null;
1099
+ if (!newLeft) {
1100
+ if (first === this.firstChunk)
1101
+ return this;
1102
+ newRight = this.firstChunk;
1103
+ } else {
1104
+ if (newLeft.next === first)
1105
+ return this;
1106
+ newRight = newLeft.next;
1107
+ }
1108
+ } else {
1109
+ newRight = this.byStart.get(index) ?? null;
1110
+ if (!newRight) {
1111
+ if (last === this.lastChunk)
1112
+ return this;
1113
+ newLeft = this.lastChunk;
1114
+ } else {
1115
+ if (newRight.previous === last)
1116
+ return this;
1117
+ newLeft = newRight.previous;
1118
+ }
1119
+ }
796
1120
  if (oldLeft)
797
1121
  oldLeft.next = oldRight;
798
1122
  if (oldRight)
@@ -929,9 +1253,11 @@ var MagicString = class MagicString {
929
1253
  this._split(end);
930
1254
  let chunk = this.byStart.get(start);
931
1255
  while (chunk) {
932
- chunk.intro = "";
933
- chunk.outro = "";
934
- chunk.edit("");
1256
+ if (chunk.start > start)
1257
+ chunk.intro = "";
1258
+ if (chunk.end < end)
1259
+ chunk.outro = "";
1260
+ chunk.edit("", false, true);
935
1261
  chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
936
1262
  }
937
1263
  return this;
@@ -1021,7 +1347,7 @@ var MagicString = class MagicString {
1021
1347
  let result = "";
1022
1348
  let chunk = this.firstChunk;
1023
1349
  while (chunk && (chunk.start > start || chunk.end <= start)) {
1024
- if (chunk.start < end && chunk.end >= end)
1350
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0)
1025
1351
  return result;
1026
1352
  chunk = chunk.next;
1027
1353
  }
@@ -1029,6 +1355,8 @@ var MagicString = class MagicString {
1029
1355
  throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
1030
1356
  const startChunk = chunk;
1031
1357
  while (chunk) {
1358
+ if (end === 0 && chunk.start === 0)
1359
+ break;
1032
1360
  if (chunk.intro && (startChunk !== chunk || chunk.start === start))
1033
1361
  result += chunk.intro;
1034
1362
  const containsEnd = chunk.start < end && chunk.end >= end;
@@ -1090,12 +1418,16 @@ var MagicString = class MagicString {
1090
1418
  return str + this.outro;
1091
1419
  }
1092
1420
  isEmpty() {
1421
+ if (this.intro.length && this.intro.trim())
1422
+ return false;
1093
1423
  let chunk = this.firstChunk;
1094
1424
  while (chunk) {
1095
1425
  if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
1096
1426
  return false;
1097
1427
  chunk = chunk.next;
1098
1428
  }
1429
+ if (this.outro.length && this.outro.trim())
1430
+ return false;
1099
1431
  return true;
1100
1432
  }
1101
1433
  length() {
@@ -1133,7 +1465,8 @@ var MagicString = class MagicString {
1133
1465
  return true;
1134
1466
  chunk = chunk.previous;
1135
1467
  } while (chunk);
1136
- return false;
1468
+ this.intro = this.intro.replace(rx, "");
1469
+ return this.intro.length > 0;
1137
1470
  }
1138
1471
  trimEnd(charType) {
1139
1472
  this.trimEndAborted(charType);
@@ -1159,7 +1492,8 @@ var MagicString = class MagicString {
1159
1492
  return true;
1160
1493
  chunk = chunk.next;
1161
1494
  } while (chunk);
1162
- return false;
1495
+ this.outro = this.outro.replace(rx, "");
1496
+ return this.outro.length > 0;
1163
1497
  }
1164
1498
  trimStart(charType) {
1165
1499
  this.trimStartAborted(charType);
@@ -1184,31 +1518,43 @@ var MagicString = class MagicString {
1184
1518
  }
1185
1519
  return outputIndex !== this.original.length;
1186
1520
  }
1521
+ _hasRemovedContent(start, end) {
1522
+ let chunk = this.byStart.get(start);
1523
+ if (!chunk) {
1524
+ chunk = this.lastSearchedChunk;
1525
+ const searchForward = start >= chunk.end;
1526
+ while (chunk && !chunk.contains(start))
1527
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1528
+ if (chunk)
1529
+ this.lastSearchedChunk = chunk;
1530
+ }
1531
+ while (chunk && chunk.start < end) {
1532
+ if (chunk.content === "")
1533
+ return true;
1534
+ chunk = this.byStart.get(chunk.end);
1535
+ }
1536
+ return false;
1537
+ }
1187
1538
  _replaceRegexp(searchValue, replacement) {
1188
1539
  function getReplacement(match, str) {
1189
1540
  if (typeof replacement === "string")
1190
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1191
- if (i === "$")
1192
- return "$";
1193
- if (i === "&")
1194
- return match[0];
1195
- if (+i < match.length)
1196
- return match[+i];
1197
- return `$${i}`;
1198
- });
1541
+ return expandReplacement(replacement, match[0], match.index, str, match.slice(1), match.groups);
1199
1542
  else
1200
- return replacement(match[0], ...match.slice(1), match.index, str, match.groups);
1543
+ return match.groups === undefined ? replacement(match[0], ...match.slice(1), match.index, str) : replacement(match[0], ...match.slice(1), match.index, str, match.groups);
1201
1544
  }
1202
1545
  const replaceMatch = (match) => {
1203
1546
  if (match.index == null)
1204
- return;
1547
+ return false;
1548
+ if (this._hasRemovedContent(match.index, match.index + match[0].length))
1549
+ return false;
1205
1550
  const replacement = getReplacement(match, this.original);
1206
1551
  if (replacement === match[0])
1207
- return;
1552
+ return true;
1208
1553
  if (match[0].length === 0)
1209
1554
  this.appendRight(match.index, replacement);
1210
1555
  else
1211
1556
  this.overwrite(match.index, match.index + match[0].length, replacement);
1557
+ return true;
1212
1558
  };
1213
1559
  if (searchValue.global) {
1214
1560
  searchValue.lastIndex = 0;
@@ -1216,22 +1562,34 @@ var MagicString = class MagicString {
1216
1562
  replaceMatch(match);
1217
1563
  } else {
1218
1564
  const match = this.original.match(searchValue);
1219
- if (match)
1220
- replaceMatch(match);
1565
+ if (match && !replaceMatch(match)) {
1566
+ const global = new RegExp(searchValue.source, `${searchValue.flags}g`);
1567
+ for (const next of this.original.matchAll(global))
1568
+ if (replaceMatch(next))
1569
+ break;
1570
+ }
1221
1571
  }
1222
1572
  return this;
1223
1573
  }
1224
1574
  _replaceString(string, replacement) {
1225
1575
  const { original } = this;
1226
- const index = original.indexOf(string);
1227
- if (index !== -1) {
1576
+ let index = original.indexOf(string);
1577
+ while (index !== -1) {
1578
+ if (this._hasRemovedContent(index, index + string.length)) {
1579
+ index = original.indexOf(string, index + string.length);
1580
+ continue;
1581
+ }
1228
1582
  if (typeof replacement === "function")
1229
1583
  replacement = replacement(string, index, original);
1230
- if (string !== replacement)
1584
+ else
1585
+ replacement = expandReplacement(replacement, string, index, original, [], undefined);
1586
+ if (string !== replacement) {
1231
1587
  if (string.length === 0)
1232
1588
  this.appendRight(index, replacement);
1233
1589
  else
1234
1590
  this.overwrite(index, index + string.length, replacement);
1591
+ }
1592
+ break;
1235
1593
  }
1236
1594
  return this;
1237
1595
  }
@@ -1245,15 +1603,19 @@ var MagicString = class MagicString {
1245
1603
  const stringLength = string.length;
1246
1604
  if (stringLength === 0) {
1247
1605
  for (let index = 0;index <= original.length; index += 1) {
1248
- const _replacement = typeof replacement === "function" ? replacement("", index, original) : replacement;
1606
+ if (this._hasRemovedContent(index, index))
1607
+ continue;
1608
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], undefined);
1249
1609
  if (_replacement !== "")
1250
1610
  this.appendRight(index, _replacement);
1251
1611
  }
1252
1612
  return this;
1253
1613
  }
1254
1614
  for (let index = original.indexOf(string);index !== -1; index = original.indexOf(string, index + stringLength)) {
1615
+ if (this._hasRemovedContent(index, index + stringLength))
1616
+ continue;
1255
1617
  const previous = original.slice(index, index + stringLength);
1256
- const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : replacement;
1618
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], undefined);
1257
1619
  if (previous !== _replacement)
1258
1620
  this.overwrite(index, index + stringLength, _replacement);
1259
1621
  }
@@ -1267,7 +1629,7 @@ var MagicString = class MagicString {
1267
1629
  return this._replaceRegexp(searchValue, replacement);
1268
1630
  }
1269
1631
  };
1270
- // ../../node_modules/.bun/yuku-ast@0.9.5/node_modules/yuku-ast/dist/aliases.js
1632
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/aliases.js
1271
1633
  var ALIAS_GROUPS = {
1272
1634
  Expression: [
1273
1635
  "Identifier",
@@ -1423,7 +1785,7 @@ var ALIAS_GROUPS = {
1423
1785
  };
1424
1786
  var ALIAS_NAMES = Object.keys(ALIAS_GROUPS);
1425
1787
 
1426
- // ../../node_modules/.bun/yuku-ast@0.9.5/node_modules/yuku-ast/dist/context.js
1788
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/context.js
1427
1789
  class WalkContext {
1428
1790
  _ancestors = [];
1429
1791
  _node = null;
@@ -1491,7 +1853,7 @@ class WalkContext {
1491
1853
  }
1492
1854
  }
1493
1855
 
1494
- // ../../node_modules/.bun/yuku-ast@0.9.5/node_modules/yuku-ast/dist/generated.js
1856
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/generated.js
1495
1857
  var KEYS = Object.create(null);
1496
1858
  function ck(type, keys) {
1497
1859
  const prev = KEYS[type];
@@ -1863,7 +2225,7 @@ var TYPES = [
1863
2225
  ];
1864
2226
  var NODE_TYPES = [...new Set(TYPES)];
1865
2227
 
1866
- // ../../node_modules/.bun/yuku-ast@0.9.5/node_modules/yuku-ast/dist/walk.js
2228
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/walk.js
1867
2229
  function createDispatch(visitors) {
1868
2230
  let enter = null;
1869
2231
  let leave = null;
@@ -2258,6 +2620,124 @@ function deadCodeElimination(transformed, originalCode, lang) {
2258
2620
  return pruned;
2259
2621
  }
2260
2622
 
2623
+ // src/plugin/hmr-dependencies.ts
2624
+ import { readFileSync } from "fs";
2625
+ import { dirname, isAbsolute, resolve } from "path";
2626
+ var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
2627
+ function hmrDependencySignature(imports, filename) {
2628
+ const routePath = resolve(filename);
2629
+ const visited = new Set;
2630
+ const hash = new Bun.CryptoHasher("sha256");
2631
+ const visit = (specifier, importer) => {
2632
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
2633
+ return true;
2634
+ }
2635
+ const path = Bun.resolveSync(specifier, dirname(importer));
2636
+ if (path === routePath) {
2637
+ return false;
2638
+ }
2639
+ hash.update(JSON.stringify([specifier, path]));
2640
+ if (!isAbsolute(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
2641
+ return true;
2642
+ }
2643
+ visited.add(path);
2644
+ const source = readFileSync(path, "utf8");
2645
+ hash.update(source);
2646
+ if (SCRIPT_FILE.test(path)) {
2647
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
2648
+ for (const dependency of transpiler.scanImports(source)) {
2649
+ if (!visit(dependency.path, path)) {
2650
+ return false;
2651
+ }
2652
+ }
2653
+ }
2654
+ return true;
2655
+ };
2656
+ try {
2657
+ for (const specifier of imports) {
2658
+ if (!visit(specifier, routePath)) {
2659
+ return;
2660
+ }
2661
+ }
2662
+ return hash.digest("hex");
2663
+ } catch {}
2664
+ }
2665
+
2666
+ // src/plugin/transform-client-module.ts
2667
+ import { realpathSync } from "fs";
2668
+ import { dirname as dirname2 } from "path";
2669
+ var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2670
+ var SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
2671
+ function clientModuleKey(modulePath) {
2672
+ const realPath = realpathSync(modulePath).replaceAll("\\", "/");
2673
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
2674
+ }
2675
+ function collectClientModuleBindings(program) {
2676
+ const bindings = new Set;
2677
+ for (const statement of program.body) {
2678
+ if (statement.type !== "ImportDeclaration") {
2679
+ continue;
2680
+ }
2681
+ const declaration = statement;
2682
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
2683
+ continue;
2684
+ }
2685
+ for (const specifier of declaration.specifiers) {
2686
+ const imported = specifier.imported;
2687
+ const local = specifier.local;
2688
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
2689
+ bindings.add(local.name);
2690
+ }
2691
+ }
2692
+ }
2693
+ return bindings;
2694
+ }
2695
+ function dynamicImportSpecifier(loader) {
2696
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
2697
+ return null;
2698
+ }
2699
+ const body = loader.body;
2700
+ const source = body.type === "ImportExpression" ? body.source : null;
2701
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
2702
+ }
2703
+ function transformClientModules(source, filename, environment) {
2704
+ if (!source.includes("clientModule")) {
2705
+ return source;
2706
+ }
2707
+ const { program } = parseSource(source, detectLangFromPath(filename));
2708
+ const bindings = collectClientModuleBindings(program);
2709
+ if (bindings.size === 0) {
2710
+ return source;
2711
+ }
2712
+ const transformed = new MagicString(source);
2713
+ walk(program, {
2714
+ CallExpression(node, context) {
2715
+ const call = node;
2716
+ const [loader, ...rest] = call.arguments;
2717
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
2718
+ return;
2719
+ }
2720
+ const unwrapped = unwrapTSExpression(loader);
2721
+ const specifier = dynamicImportSpecifier(unwrapped);
2722
+ if (specifier === null) {
2723
+ return;
2724
+ }
2725
+ let key;
2726
+ try {
2727
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname2(filename))));
2728
+ } catch (error) {
2729
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
2730
+ }
2731
+ if (environment === "client") {
2732
+ transformed.appendLeft(loader.end, `, ${key}`);
2733
+ } else {
2734
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
2735
+ }
2736
+ }
2737
+ });
2738
+ return transformed.toString();
2739
+ }
2740
+
2261
2741
  // src/plugin/transform-isomorphic.ts
2262
2742
  var FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
2263
2743
  function importedName(specifier) {
@@ -2479,11 +2959,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
2479
2959
  }
2480
2960
  });
2481
2961
  }
2482
- function transformIsomorphicFunctions(source, filename, environment) {
2962
+ function transformIsomorphicFunctions(input, filename, environment) {
2483
2963
  const lang = detectLangFromPath(filename);
2484
2964
  if (lang === "dts") {
2485
- return { code: source, map: null, transformed: false };
2965
+ return { code: input, map: null, transformed: false };
2486
2966
  }
2967
+ const source = transformClientModules(input, filename, environment);
2968
+ const clientModulesTransformed = source !== input;
2487
2969
  const { program, diagnostics } = parseSource(source, lang);
2488
2970
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
2489
2971
  if (firstError) {
@@ -2495,7 +2977,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
2495
2977
  assertNoSplitChains(source, filename, program, builders);
2496
2978
  const candidates = collectCandidates(source, filename, program, bindings);
2497
2979
  if (candidates.length === 0) {
2498
- return { code: source, map: null, transformed: false };
2980
+ return { code: source, map: null, transformed: clientModulesTransformed };
2499
2981
  }
2500
2982
  const transformed = new MagicString(source);
2501
2983
  for (const candidate of candidates) {
@@ -2511,12 +2993,13 @@ function transformIsomorphicFunctions(source, filename, environment) {
2511
2993
  }
2512
2994
 
2513
2995
  // src/plugin/transform-client.ts
2514
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2996
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
2515
2997
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
2516
2998
  var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
2517
2999
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
2518
3000
  var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
2519
3001
  var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
3002
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
2520
3003
  var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
2521
3004
  ["TSAsExpression", ["expression"]],
2522
3005
  ["TSInstantiationExpression", ["expression"]],
@@ -2526,7 +3009,7 @@ var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
2526
3009
  ["TSTypeAssertion", ["expression"]]
2527
3010
  ]);
2528
3011
  function isFurinRouteModule(source) {
2529
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
3012
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
2530
3013
  }
2531
3014
  function importedName2(specifier) {
2532
3015
  const { imported } = specifier;
@@ -2626,8 +3109,51 @@ function chainRootIsDefineRoute(node, bindings, ancestors) {
2626
3109
  }
2627
3110
  return false;
2628
3111
  }
2629
- function removeChainedServerCalls(source, program, bindings) {
3112
+ function assertCompleteRouteChains(program, bindings, filename) {
3113
+ const namespaces = new Set;
3114
+ for (const statement of program.body) {
3115
+ if (statement.type !== "ImportDeclaration") {
3116
+ continue;
3117
+ }
3118
+ const declaration = statement;
3119
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
3120
+ continue;
3121
+ }
3122
+ for (const specifier of declaration.specifiers) {
3123
+ const name = localName2(specifier);
3124
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
3125
+ namespaces.add(name);
3126
+ }
3127
+ }
3128
+ }
3129
+ walk(program, {
3130
+ MemberExpression(node, context) {
3131
+ const object = asAstNode(node.object);
3132
+ const property = asAstNode(node.property);
3133
+ const method = property?.type === "Identifier" ? property.name : property?.value;
3134
+ if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
3135
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
3136
+ }
3137
+ if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
3138
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
3139
+ }
3140
+ },
3141
+ VariableDeclarator(node, context) {
3142
+ const initializer = asAstNode(node.init);
3143
+ if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
3144
+ return;
3145
+ }
3146
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
3147
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
3148
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
3149
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
3150
+ }
3151
+ }
3152
+ });
3153
+ }
3154
+ function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
2630
3155
  let transformed = rewriteClientImports(source, program, bindings);
3156
+ const { declarations } = collectModuleBindings(program);
2631
3157
  walk(program, {
2632
3158
  CallExpression(call, context) {
2633
3159
  const callee = asAstNode(call.callee);
@@ -2642,12 +3168,93 @@ function removeChainedServerCalls(source, program, bindings) {
2642
3168
  if (!object) {
2643
3169
  return;
2644
3170
  }
3171
+ if (property.name === "config" && Array.isArray(call.arguments)) {
3172
+ const config = asAstNode(call.arguments[0]);
3173
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3174
+ collectConfigBindings(config, declarations, configBindings);
3175
+ const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
3176
+ if (remount) {
3177
+ source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
3178
+ transformed = true;
3179
+ return;
3180
+ }
3181
+ }
3182
+ }
2645
3183
  source.remove(object.end, call.end);
2646
3184
  transformed = true;
2647
3185
  }
2648
3186
  });
2649
3187
  return transformed;
2650
3188
  }
3189
+ function collectConfigBindings(config, declarations, names) {
3190
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
3191
+ names.add(config.name);
3192
+ const declaration = declarations.get(config.name);
3193
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
3194
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3195
+ for (const property of config.properties) {
3196
+ const entry = asAstNode(property);
3197
+ if (entry?.type === "SpreadElement") {
3198
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
3199
+ }
3200
+ }
3201
+ }
3202
+ }
3203
+ function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
3204
+ if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
3205
+ visiting.add(config.name);
3206
+ configBindings.add(config.name);
3207
+ const declaration = declarations.get(config.name);
3208
+ const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
3209
+ visiting.delete(config.name);
3210
+ return result;
3211
+ }
3212
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
3213
+ throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
3214
+ }
3215
+ for (let index = config.properties.length - 1;index >= 0; index -= 1) {
3216
+ const entry = asAstNode(config.properties[index]);
3217
+ if (entry?.type === "SpreadElement") {
3218
+ const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
3219
+ if (remount) {
3220
+ return remount;
3221
+ }
3222
+ } else if (entry?.type === "Property") {
3223
+ const key = asAstNode(entry.key);
3224
+ if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
3225
+ return entry;
3226
+ }
3227
+ }
3228
+ }
3229
+ return null;
3230
+ }
3231
+ function pruneUnusedConfigBindings(source, filename, names) {
3232
+ let result = source;
3233
+ let pruned = true;
3234
+ while (pruned) {
3235
+ pruned = false;
3236
+ const code = result.toString();
3237
+ const { program } = parseSource(code, detectLangFromPath(filename));
3238
+ const references = new Set;
3239
+ walkWithAncestors(program, [], (node, ancestors) => {
3240
+ if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
3241
+ references.add(node.name);
3242
+ }
3243
+ });
3244
+ result = new MagicString(code);
3245
+ for (const statement of program.body) {
3246
+ if (statement.type !== "VariableDeclaration") {
3247
+ continue;
3248
+ }
3249
+ const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
3250
+ if (retained.length !== statement.declarations.length) {
3251
+ result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
3252
+ pruned = true;
3253
+ }
3254
+ }
3255
+ }
3256
+ return result;
3257
+ }
2651
3258
  function collectBindingNames(pattern, names) {
2652
3259
  const node = asAstNode(pattern);
2653
3260
  if (!node) {
@@ -2699,13 +3306,13 @@ function collectDeclarationBindings(declaration, declarations) {
2699
3306
  }
2700
3307
  function collectModuleBindings(program) {
2701
3308
  const declarations = new Map;
2702
- const imports = new Set;
3309
+ const imports = new Map;
2703
3310
  for (const statement of program.body) {
2704
3311
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
2705
3312
  for (const specifier of statement.specifiers) {
2706
3313
  const local = localName2(specifier);
2707
3314
  if (local) {
2708
- imports.add(local);
3315
+ imports.set(local, statement);
2709
3316
  }
2710
3317
  }
2711
3318
  continue;
@@ -2793,13 +3400,16 @@ function walkWithAncestors(value, ancestors, visitor) {
2793
3400
  }
2794
3401
  }
2795
3402
  function collectDependencyIdentifier(child, ancestors, trackImports, state) {
2796
- if (child.type !== "Identifier" || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
3403
+ const parent = ancestors.at(-1);
3404
+ const jsxReference = child.type === "JSXIdentifier" && (parent?.type === "JSXOpeningElement" && parent.name === child && typeof child.name === "string" && child.name[0] === child.name[0]?.toUpperCase() || parent?.type === "JSXMemberExpression" && parent.object === child);
3405
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
2797
3406
  return;
2798
3407
  }
2799
3408
  const declaration = state.moduleBindings.declarations.get(child.name);
2800
3409
  if (!declaration) {
2801
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
2802
- state.hasUnresolvedImport = true;
3410
+ const imported = state.moduleBindings.imports.get(child.name);
3411
+ if (trackImports && imported) {
3412
+ state.imports.add(imported);
2803
3413
  }
2804
3414
  return;
2805
3415
  }
@@ -2820,13 +3430,20 @@ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
2820
3430
  function collectDependencies(node, trackImports, state) {
2821
3431
  walkWithAncestors(node, [], (child, ancestors) => {
2822
3432
  collectDependencyIdentifier(child, ancestors, trackImports, state);
3433
+ if (trackImports && child.type === "ImportExpression") {
3434
+ const specifier = asAstNode(child.source)?.value;
3435
+ if (typeof specifier === "string") {
3436
+ state.dynamicImports.add(specifier);
3437
+ }
3438
+ }
2823
3439
  });
2824
3440
  }
2825
- function createHmrDataSignature(code, program, bindings) {
3441
+ function createHmrDataSignature(code, program, bindings, filename) {
2826
3442
  const serverStages = [];
2827
3443
  const dependencyState = {
2828
3444
  dependencies: new Map,
2829
- hasUnresolvedImport: false,
3445
+ dynamicImports: new Set,
3446
+ imports: new Set,
2830
3447
  importTrackedDependencies: new Set,
2831
3448
  moduleBindings: collectModuleBindings(program)
2832
3449
  };
@@ -2860,6 +3477,10 @@ function createHmrDataSignature(code, program, bindings) {
2860
3477
  });
2861
3478
  const dataSource = [
2862
3479
  ...serverStages,
3480
+ ...[...dependencyState.imports].map((imported) => ({
3481
+ source: code.slice(imported.start, imported.end),
3482
+ start: imported.start
3483
+ })),
2863
3484
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
2864
3485
  source: code.slice(dependency.start, dependency.end),
2865
3486
  start: dependency.start
@@ -2867,7 +3488,14 @@ function createHmrDataSignature(code, program, bindings) {
2867
3488
  ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
2868
3489
  `);
2869
3490
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
2870
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
3491
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
3492
+ return hash;
3493
+ }
3494
+ const dependencies = hmrDependencySignature(new Set([
3495
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
3496
+ ...dependencyState.dynamicImports
3497
+ ]), filename);
3498
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
2871
3499
  }
2872
3500
  function calledHookName(call) {
2873
3501
  const callee = asAstNode(call.callee);
@@ -3085,9 +3713,14 @@ function transformForClient(code, filename) {
3085
3713
  }
3086
3714
  let source = new MagicString(clientSource);
3087
3715
  const routeBindings = collectDefineRouteBindings(program);
3088
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
3716
+ assertCompleteRouteChains(program, routeBindings, filename);
3717
+ const configBindings = new Set;
3718
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
3089
3719
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
3090
3720
  if (removedServerCode) {
3721
+ if (configBindings.size > 0) {
3722
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
3723
+ }
3091
3724
  source = deadCodeElimination(source, code, lang);
3092
3725
  }
3093
3726
  const transformedCode = source.toString();
@@ -3106,11 +3739,16 @@ function transformForClient(code, filename) {
3106
3739
  if (originalError) {
3107
3740
  throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
3108
3741
  }
3109
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program));
3742
+ const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
3110
3743
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
3111
3744
  source.append(`
3112
3745
  if (import.meta.hot && route?.component) {
3113
3746
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
3747
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
3748
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
3749
+ configurable: true,
3750
+ value: previousSourceSignature,
3751
+ });
3114
3752
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
3115
3753
  configurable: true,
3116
3754
  value: previousDataSignature,
@@ -3126,10 +3764,14 @@ if (import.meta.hot && route?.component) {
3126
3764
  updatedRoute,
3127
3765
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
3128
3766
  );
3767
+ // An unchanged source can be re-evaluated by Bun after an import edit
3768
+ // without rerunning this transform. Its embedded dependency hash is stale.
3129
3769
  const dataChanged =
3130
3770
  previousDataSignature.startsWith("external:") ||
3131
3771
  typeof updatedDataSignature !== "string" ||
3132
3772
  updatedDataSignature.startsWith("external:") ||
3773
+ (updatedDataSignature.startsWith("imports:") &&
3774
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
3133
3775
  updatedDataSignature !== previousDataSignature;
3134
3776
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
3135
3777
  }
@@ -3157,6 +3799,9 @@ export default {};
3157
3799
  var plugin = {
3158
3800
  name: "furin-strip-server",
3159
3801
  setup(build) {
3802
+ environmentGuardPlugin("client").setup(build);
3803
+ const topologyPaths = new Set;
3804
+ const loadedSources = new Map;
3160
3805
  build.onResolve({ filter: ELYSIA_FILTER }, () => ({
3161
3806
  namespace: "furin-stubs",
3162
3807
  path: "elysia-stub"
@@ -3173,12 +3818,33 @@ var plugin = {
3173
3818
  if (args.path.includes("node_modules")) {
3174
3819
  return;
3175
3820
  }
3176
- const source = await Bun.file(args.path).text();
3821
+ let source;
3822
+ try {
3823
+ source = await Bun.file(args.path).text();
3824
+ } catch (error) {
3825
+ const loaded = loadedSources.get(args.path);
3826
+ if (loaded?.isRouteModule && error instanceof Error && "code" in error && error.code === "ENOENT") {
3827
+ return loaded;
3828
+ }
3829
+ throw error;
3830
+ }
3831
+ const normalizedPath = args.path.replaceAll("\\", "/");
3832
+ if (normalizedPath.includes("/.furin/") && normalizedPath.endsWith("/_hydrate.tsx")) {
3833
+ const transpiler = new Bun.Transpiler({ loader: "tsx" });
3834
+ for (const imported of transpiler.scanImports(source)) {
3835
+ if (isAbsolute2(imported.path) || imported.path.startsWith(".")) {
3836
+ topologyPaths.add(resolve2(dirname3(args.path), imported.path));
3837
+ }
3838
+ }
3839
+ }
3177
3840
  const result = transformForClient(source, args.path);
3178
- return {
3841
+ const loaded = {
3179
3842
  contents: result.code,
3843
+ isRouteModule: topologyPaths.has(args.path),
3180
3844
  loader: detectLoaderFromPath(args.path)
3181
3845
  };
3846
+ loadedSources.set(args.path, loaded);
3847
+ return loaded;
3182
3848
  });
3183
3849
  }
3184
3850
  };