@teyik0/furin 0.7.0-alpha.3 → 0.9.0-alpha.0

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 (541) hide show
  1. package/README.md +38 -1
  2. package/dist/adapter/build.d.ts +9 -0
  3. package/dist/adapter/bun/app.d.ts +1 -0
  4. package/dist/adapter/bun/server.d.ts +1 -0
  5. package/dist/adapter/bun.d.ts +9 -3
  6. package/dist/adapter/package.d.ts +1 -0
  7. package/dist/adapter/prerender.d.ts +21 -0
  8. package/dist/adapter/runtime-build.d.ts +31 -14
  9. package/dist/adapter/server-bundle.d.ts +20 -0
  10. package/dist/adapter/static.d.ts +2 -2
  11. package/dist/adapter/types.d.ts +81 -0
  12. package/dist/adapter/vercel/bootstrap.d.ts +5 -0
  13. package/dist/adapter/vercel/data.d.ts +23 -0
  14. package/dist/adapter/vercel/handler.d.ts +10 -0
  15. package/dist/adapter/vercel.d.ts +13 -3
  16. package/dist/adapter/vercel.js +516 -0
  17. package/dist/build/bun-build.d.ts +4 -0
  18. package/dist/build/client.d.ts +2 -2
  19. package/dist/build/compile-entry.ts +1 -0
  20. package/dist/build/discover-mounts-process.d.ts +1 -0
  21. package/dist/build/discover-mounts.d.ts +6 -0
  22. package/dist/build/discover-pages-process.d.ts +1 -0
  23. package/dist/build/discover-pages.d.ts +11 -0
  24. package/dist/build/discovery-module.d.ts +3 -0
  25. package/dist/build/discovery-plugins.d.ts +34 -0
  26. package/dist/build/elysia-aot-worker.d.ts +4 -0
  27. package/dist/build/elysia-aot.d.ts +8 -2
  28. package/dist/build/entry-template.d.ts +14 -7
  29. package/dist/build/entry-template.ts +39 -19
  30. package/dist/build/hydrate.d.ts +17 -3
  31. package/dist/build/index.d.ts +7 -3
  32. package/dist/build/index.js +8852 -16175
  33. package/dist/build/preload-manifest.d.ts +2 -2
  34. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  35. package/dist/build/route-metadata.d.ts +31 -0
  36. package/dist/build/route-types.d.ts +8 -2
  37. package/dist/build/server-app-entry.d.ts +2 -2
  38. package/dist/build/shared.d.ts +5 -7
  39. package/dist/build/types.d.ts +27 -16
  40. package/dist/cache.js +117 -32
  41. package/dist/cli/config.d.ts +2 -2
  42. package/dist/cli/dev-worker.d.ts +1 -0
  43. package/dist/cli/dev-worker.ts +123 -0
  44. package/dist/cli/dev.d.ts +1 -0
  45. package/dist/cli/index.js +9104 -16086
  46. package/dist/client/browser-events-runtime.d.ts +2 -2
  47. package/dist/client/browser-events.d.ts +2 -0
  48. package/dist/client/chunks/client-k29262a4.js +59 -0
  49. package/dist/client/chunks/client-k88668k7.js +159 -0
  50. package/dist/client/chunks/client-rjhxgt64.js +1035 -0
  51. package/dist/client/chunks/client-xy6g38kx.js +317 -0
  52. package/dist/client/default-screens.d.ts +0 -11
  53. package/dist/client/define-route.d.ts +2 -1
  54. package/dist/client/dev-error-overlay.ts +18 -1
  55. package/dist/client/hmr.d.ts +1 -1
  56. package/dist/client/internal/runtime-types.d.ts +7 -1
  57. package/dist/client/link.d.ts +1 -0
  58. package/dist/client/link.js +1738 -4184
  59. package/dist/client/mutation.d.ts +5 -0
  60. package/dist/client/query-store.d.ts +22 -7
  61. package/dist/client/query.d.ts +6 -8
  62. package/dist/client/request-id.d.ts +1 -0
  63. package/dist/client/route-api.d.ts +4 -4
  64. package/dist/client/route-element.d.ts +51 -0
  65. package/dist/client/router/boundary-tree.d.ts +1 -9
  66. package/dist/client/router/cache-generation.d.ts +15 -0
  67. package/dist/client/router/context.d.ts +13 -2
  68. package/dist/client/router/fetch-observers.d.ts +9 -0
  69. package/dist/client/router/hmr-refresh.d.ts +12 -0
  70. package/dist/client/router/index.d.ts +5 -7
  71. package/dist/client/router/link-utils.d.ts +0 -2
  72. package/dist/client/router/navigation-controller.d.ts +78 -0
  73. package/dist/client/router/navigation.d.ts +1 -0
  74. package/dist/client/router/page-fetch.d.ts +38 -0
  75. package/dist/client/router/provider.d.ts +2 -3
  76. package/dist/client/router/search/index.d.ts +11 -4
  77. package/dist/client/router/search/index.js +60 -0
  78. package/dist/client/router/spa-response.d.ts +9 -26
  79. package/dist/client/router/transport.d.ts +4 -0
  80. package/dist/client/router/types.d.ts +120 -46
  81. package/dist/client/router/use-fetch-interception.d.ts +12 -0
  82. package/dist/client/router/use-history-sync.d.ts +7 -0
  83. package/dist/client/router/use-hmr-refresh.d.ts +8 -0
  84. package/dist/client/router/use-sync-stream.d.ts +16 -0
  85. package/dist/client/server-error.d.ts +4 -7
  86. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +7 -4
  87. package/dist/client/sync-client.d.ts +74 -0
  88. package/dist/client/sync.d.ts +43 -30
  89. package/dist/client.d.ts +3 -1
  90. package/dist/client.js +775 -937
  91. package/dist/config.d.ts +17 -13
  92. package/dist/config.js +3 -31
  93. package/dist/define-route.d.ts +262 -517
  94. package/dist/devtools/protocol.d.ts +4 -3
  95. package/dist/furin.d.ts +42 -31
  96. package/dist/furin.js +21464 -19101
  97. package/dist/plugin/binding-scope.d.ts +15 -2
  98. package/dist/plugin/client-plugin.d.ts +19 -0
  99. package/dist/plugin/dead-code-elimination.d.ts +14 -3
  100. package/dist/plugin/dev-routes.d.ts +22 -0
  101. package/dist/plugin/hmr-data-signature.d.ts +3 -0
  102. package/dist/plugin/hmr-hook-signature.d.ts +9 -0
  103. package/dist/plugin/index.d.ts +1 -6
  104. package/dist/plugin/index.js +1757 -1218
  105. package/dist/plugin/module-bindings.d.ts +11 -0
  106. package/dist/plugin/module-transform.d.ts +29 -0
  107. package/dist/plugin/preflight.d.ts +8 -0
  108. package/dist/plugin/route-chains.d.ts +35 -0
  109. package/dist/plugin/route-config.d.ts +28 -0
  110. package/dist/plugin/route-modules.d.ts +35 -0
  111. package/dist/plugin/route-registry.d.ts +32 -0
  112. package/dist/plugin/route-tree.d.ts +43 -0
  113. package/dist/plugin/strip-server-stages.d.ts +10 -0
  114. package/dist/plugin/strip-server.d.ts +10 -0
  115. package/dist/plugin/transform-client-module.d.ts +3 -0
  116. package/dist/plugin/transform-client.d.ts +0 -2
  117. package/dist/plugin/transform-isomorphic.d.ts +3 -2
  118. package/dist/routes.d.ts +15 -5
  119. package/dist/rsc/build/client-references.d.ts +8 -0
  120. package/dist/rsc/build/discover.d.ts +7 -0
  121. package/dist/rsc/build/flight-loader.d.ts +1 -0
  122. package/dist/rsc/build/index.d.ts +8 -4
  123. package/dist/rsc/build/paths.d.ts +2 -0
  124. package/dist/rsc/bundled-client-codec.d.ts +1 -0
  125. package/dist/rsc/client-codec.d.ts +3 -0
  126. package/dist/rsc/client-references.d.ts +22 -0
  127. package/dist/rsc/server-client-codec.d.ts +1 -0
  128. package/dist/rsc/server-codec.js +3889 -2
  129. package/dist/rsc/slot-proxy.d.ts +11 -0
  130. package/dist/rsc/transport-benchmark.d.ts +2 -1
  131. package/dist/rsc-client.js +16 -164
  132. package/dist/rsc-server.d.ts +1 -5
  133. package/dist/rsc.d.ts +1 -5
  134. package/dist/rsc.js +233 -73
  135. package/dist/server/assets/client-dir.d.ts +1 -0
  136. package/dist/server/auto-invalidate/index.d.ts +2 -2
  137. package/dist/server/auto-invalidate/plugin.d.ts +21 -15
  138. package/dist/server/auto-invalidate/types.d.ts +0 -2
  139. package/dist/server/bounded-body.d.ts +6 -0
  140. package/dist/server/browser-events/plugin.d.ts +4 -1
  141. package/dist/server/browser-events/shutdown.d.ts +1 -1
  142. package/dist/server/cache/dev-loader.d.ts +6 -1
  143. package/dist/server/cache/index.d.ts +4 -9
  144. package/dist/server/cache/invalidation.d.ts +7 -2
  145. package/dist/server/cache/isr-ssg.d.ts +6 -1
  146. package/dist/server/cache/page-cache.d.ts +5 -0
  147. package/dist/server/cache/purger.d.ts +14 -4
  148. package/dist/server/cache/redis/index.d.ts +1 -34
  149. package/dist/server/cache/redis/index.js +51 -25
  150. package/dist/server/cache/redis/scripts.d.ts +1 -1
  151. package/dist/server/cache/route-cache.d.ts +18 -2
  152. package/dist/server/cache/runtime-cache.d.ts +7 -0
  153. package/dist/server/context-logger.d.ts +6 -1
  154. package/dist/server/dev/graph.d.ts +4 -3
  155. package/dist/server/dev/runtime.d.ts +4 -0
  156. package/dist/server/dev/runtime.production.d.ts +1 -0
  157. package/dist/server/dev/server-only-module.d.ts +5 -0
  158. package/dist/server/dev/stack-location.d.ts +9 -0
  159. package/dist/server/dev-page-imports.d.ts +42 -0
  160. package/dist/server/dev-page-plugin.d.ts +2 -49
  161. package/dist/server/devtools/instrumentation.d.ts +1 -3
  162. package/dist/server/devtools/instrumentation.production.d.ts +0 -2
  163. package/dist/server/devtools/request-context.d.ts +7 -0
  164. package/dist/server/evlog.d.ts +18 -6
  165. package/dist/server/instance.d.ts +52 -44
  166. package/dist/server/internal.d.ts +51 -14
  167. package/dist/server/internal.js +9852 -2088
  168. package/dist/server/lang-detect.d.ts +4 -4
  169. package/dist/server/logging/ingest-plugin.d.ts +31 -0
  170. package/dist/server/mode.d.ts +17 -0
  171. package/dist/server/prerender.d.ts +32 -0
  172. package/dist/server/prod/runtime.d.ts +5 -0
  173. package/dist/server/production-server.js +1000 -731
  174. package/dist/server/registrations.d.ts +14 -0
  175. package/dist/server/render/assemble.d.ts +0 -22
  176. package/dist/server/render/buffered-render.d.ts +20 -0
  177. package/dist/server/render/document-stream.d.ts +45 -0
  178. package/dist/server/render/document.d.ts +1 -1
  179. package/dist/server/render/element.d.ts +2 -5
  180. package/dist/server/render/index.d.ts +4 -5
  181. package/dist/server/render/index.ts +4 -21
  182. package/dist/server/render/isr-revalidation.d.ts +5 -0
  183. package/dist/server/render/isr-shared-cache.d.ts +23 -0
  184. package/dist/server/render/isr.d.ts +19 -1
  185. package/dist/server/render/loader-errors.d.ts +33 -0
  186. package/dist/server/render/loader-segments.d.ts +40 -0
  187. package/dist/server/render/loaders.d.ts +16 -32
  188. package/dist/server/render/mixed-cache.d.ts +2 -2
  189. package/dist/server/render/navigation-head.d.ts +13 -0
  190. package/dist/server/render/not-found-plugin.d.ts +18 -0
  191. package/dist/server/render/observe-loader.d.ts +1 -0
  192. package/dist/server/render/ppr-document.d.ts +1 -1
  193. package/dist/server/render/ppr-request.d.ts +0 -2
  194. package/dist/server/render/ppr-route.d.ts +13 -2
  195. package/dist/server/render/prepare-render.d.ts +57 -0
  196. package/dist/server/render/request-loaders.d.ts +19 -0
  197. package/dist/server/render/route-frame-transport.d.ts +7 -1
  198. package/dist/server/render/shell.d.ts +1 -1
  199. package/dist/server/render/shell.ts +1 -1
  200. package/dist/server/render/ssr-transport.d.ts +11 -0
  201. package/dist/server/render/ssr.d.ts +1 -116
  202. package/dist/server/render/static-params.d.ts +15 -0
  203. package/dist/server/router/discovery.d.ts +1 -0
  204. package/dist/server/router/dispatch.d.ts +96 -0
  205. package/dist/server/router/hmr.d.ts +14 -24
  206. package/dist/server/router/patterns.d.ts +15 -20
  207. package/dist/server/router/plugin.d.ts +26 -24
  208. package/dist/server/router/schemas.d.ts +6 -24
  209. package/dist/server/router/types.d.ts +0 -2
  210. package/dist/server/runtime-env.d.ts +6 -1
  211. package/dist/server/server-entry.d.ts +5 -0
  212. package/dist/server/server-entry.js +36 -0
  213. package/dist/server/static-export.d.ts +38 -0
  214. package/dist/server/static-export.js +10777 -0
  215. package/dist/server/sync/adapter.d.ts +13 -1
  216. package/dist/server/sync/atomic.d.ts +0 -2
  217. package/dist/server/sync/config.d.ts +7 -1
  218. package/dist/server/sync/connection.d.ts +13 -0
  219. package/dist/server/sync/drizzle/index.js +113 -68
  220. package/dist/server/sync/fingerprint.d.ts +0 -1
  221. package/dist/server/sync/index.d.ts +5 -6
  222. package/dist/server/sync/index.js +2763 -1320
  223. package/dist/server/sync/invalidate-sync.d.ts +14 -0
  224. package/dist/server/sync/local-client.d.ts +9 -0
  225. package/dist/server/sync/plugin.d.ts +18 -55
  226. package/dist/server/sync/postgres/execute.d.ts +2 -2
  227. package/dist/server/sync/postgres/index.d.ts +3 -1
  228. package/dist/server/sync/postgres/index.js +68 -37
  229. package/dist/server/sync/postgres/migration.sql +2 -0
  230. package/dist/server/sync/principal-journal.d.ts +11 -0
  231. package/dist/server/sync/prisma/index.js +74 -39
  232. package/dist/server/sync/queries.d.ts +57 -16
  233. package/dist/server/sync/redis/index.d.ts +2 -1
  234. package/dist/server/sync/redis/index.js +50 -5
  235. package/dist/server/sync/redis/scripts.d.ts +2 -1
  236. package/dist/server/sync/response.d.ts +3 -0
  237. package/dist/server/sync/runtime.d.ts +8 -1
  238. package/dist/server/sync/sqlite/index.d.ts +3 -1
  239. package/dist/server/sync/sqlite/index.js +59 -27
  240. package/dist/server/sync/stream.d.ts +32 -7
  241. package/dist/server/weak-registry.d.ts +9 -0
  242. package/dist/shared/await.d.ts +2 -1
  243. package/dist/shared/browser-events.d.ts +4 -0
  244. package/dist/shared/compact-json.d.ts +1 -0
  245. package/dist/shared/defer.d.ts +1 -1
  246. package/dist/shared/deferred-ndjson.d.ts +3 -2
  247. package/dist/shared/elysia-contract.d.ts +2 -0
  248. package/dist/shared/in-memory-apps.d.ts +7 -0
  249. package/dist/shared/invalidation-header.d.ts +13 -0
  250. package/dist/shared/navigation-data.d.ts +7 -0
  251. package/dist/shared/prefix.d.ts +11 -5
  252. package/dist/shared/route-frame.d.ts +3 -0
  253. package/dist/shared/route-map.d.ts +7 -0
  254. package/dist/shared/route-matches.d.ts +41 -0
  255. package/dist/shared/route-specificity.d.ts +2 -0
  256. package/dist/shared/search-params.d.ts +2 -3
  257. package/dist/shared/sync-query.d.ts +6 -13
  258. package/dist/shared/utils/ast-walk.d.ts +3 -11
  259. package/dist/sync-client.d.ts +3 -0
  260. package/dist/sync-client.js +1600 -0
  261. package/package.json +39 -23
  262. package/src/adapter/README.md +43 -15
  263. package/src/adapter/build.ts +270 -0
  264. package/src/adapter/bun/app.ts +5 -0
  265. package/src/adapter/bun/server.ts +14 -0
  266. package/src/adapter/bun.ts +104 -264
  267. package/src/adapter/furin-app.d.ts +15 -0
  268. package/src/adapter/package.ts +32 -27
  269. package/src/adapter/prerender.ts +97 -0
  270. package/src/adapter/runtime-build.ts +98 -102
  271. package/src/adapter/server-bundle.ts +110 -0
  272. package/src/adapter/static.ts +276 -260
  273. package/src/adapter/types.ts +89 -0
  274. package/src/adapter/vercel/bootstrap.ts +85 -0
  275. package/src/adapter/vercel/data.ts +21 -0
  276. package/src/adapter/vercel/handler.ts +132 -0
  277. package/src/adapter/vercel.ts +329 -659
  278. package/src/build/bun-build.ts +3 -0
  279. package/src/build/client.ts +27 -63
  280. package/src/build/compile-entry.ts +1 -0
  281. package/src/build/discover-mounts-process.ts +17 -0
  282. package/src/build/discover-mounts.ts +40 -0
  283. package/src/build/discover-pages-process.ts +151 -0
  284. package/src/build/discover-pages.ts +69 -0
  285. package/src/build/discovery-module.ts +70 -0
  286. package/src/build/discovery-plugins.ts +101 -0
  287. package/src/build/elysia-aot-worker.ts +92 -9
  288. package/src/build/elysia-aot.ts +164 -70
  289. package/src/build/entry-template.ts +39 -19
  290. package/src/build/hydrate.ts +131 -50
  291. package/src/build/index.ts +136 -132
  292. package/src/build/preload-manifest.ts +3 -3
  293. package/src/build/private-server-sourcemaps.ts +5 -0
  294. package/src/build/production-instrumentation.ts +22 -19
  295. package/src/build/route-metadata.ts +90 -0
  296. package/src/build/route-types.ts +93 -11
  297. package/src/build/server-app-entry.ts +4 -21
  298. package/src/build/shared.ts +15 -49
  299. package/src/build/types.ts +23 -20
  300. package/src/build/virtual-entry.ts +2 -4
  301. package/src/cli/config.ts +137 -6
  302. package/src/cli/dev-worker.ts +123 -0
  303. package/src/cli/dev.ts +91 -0
  304. package/src/cli/index.ts +82 -21
  305. package/src/cli/preview.ts +2 -1
  306. package/src/client/boundaries.tsx +5 -14
  307. package/src/client/browser-events-runtime.ts +97 -23
  308. package/src/client/browser-events.ts +8 -0
  309. package/src/client/default-screens.tsx +2 -2
  310. package/src/client/define-route.ts +3 -2
  311. package/src/client/dev-error-overlay.ts +18 -1
  312. package/src/client/hmr.ts +1 -1
  313. package/src/client/internal/runtime-types.ts +7 -1
  314. package/src/client/link.tsx +80 -43
  315. package/src/client/mutation.ts +98 -3
  316. package/src/client/query-store.ts +213 -31
  317. package/src/client/query.tsx +12 -29
  318. package/src/client/request-id.ts +10 -0
  319. package/src/client/route-api.tsx +6 -6
  320. package/src/client/route-element.tsx +155 -0
  321. package/src/client/router/boundary-tree.tsx +2 -93
  322. package/src/client/router/cache-generation.ts +37 -0
  323. package/src/client/router/context.ts +40 -4
  324. package/src/client/router/fetch-observers.ts +46 -0
  325. package/src/client/router/hmr-refresh.ts +50 -0
  326. package/src/client/router/index.ts +7 -29
  327. package/src/client/router/link-utils.ts +19 -31
  328. package/src/client/router/navigation-controller.ts +580 -0
  329. package/src/client/router/navigation.ts +3 -2
  330. package/src/client/router/optimistic.ts +2 -3
  331. package/src/client/router/page-fetch.ts +272 -0
  332. package/src/client/router/provider.tsx +227 -1079
  333. package/src/client/router/search/index.ts +38 -14
  334. package/src/client/router/spa-response.ts +19 -70
  335. package/src/client/router/transport.ts +23 -0
  336. package/src/client/router/types.ts +203 -61
  337. package/src/client/router/use-fetch-interception.ts +52 -0
  338. package/src/client/router/use-history-sync.ts +56 -0
  339. package/src/client/router/use-hmr-refresh.ts +51 -0
  340. package/src/client/router/use-sync-stream.ts +181 -0
  341. package/src/client/server-error.ts +2 -40
  342. package/src/client/sync-catch-up.ts +194 -0
  343. package/src/client/sync-client.ts +528 -0
  344. package/src/client/sync.ts +275 -378
  345. package/src/client.ts +10 -5
  346. package/src/config.ts +34 -49
  347. package/src/define-route.ts +487 -882
  348. package/src/devtools/devtools-element.js +10 -3
  349. package/src/devtools/protocol.ts +3 -3
  350. package/src/furin.ts +258 -1086
  351. package/src/plugin/binding-scope.ts +219 -94
  352. package/src/plugin/client-plugin.ts +145 -0
  353. package/src/plugin/dead-code-elimination.ts +390 -111
  354. package/src/plugin/dev-routes.ts +453 -0
  355. package/src/plugin/hmr-data-signature.ts +161 -0
  356. package/src/plugin/hmr-dependencies.ts +2 -4
  357. package/src/plugin/hmr-hook-signature.ts +252 -0
  358. package/src/plugin/index.ts +3 -96
  359. package/src/plugin/module-bindings.ts +216 -0
  360. package/src/plugin/module-transform.ts +63 -0
  361. package/src/plugin/preflight.ts +66 -0
  362. package/src/plugin/route-chains.ts +309 -0
  363. package/src/plugin/route-config.ts +451 -0
  364. package/src/plugin/route-modules.ts +209 -0
  365. package/src/plugin/route-registry.ts +362 -0
  366. package/src/plugin/route-tree.ts +248 -0
  367. package/src/plugin/strip-server-stages.ts +197 -0
  368. package/src/plugin/strip-server.ts +22 -0
  369. package/src/plugin/transform-client-module.ts +36 -31
  370. package/src/plugin/transform-client.ts +33 -1114
  371. package/src/plugin/transform-dev-page.ts +84 -92
  372. package/src/plugin/transform-isomorphic.ts +396 -185
  373. package/src/routes.ts +15 -5
  374. package/src/rsc/build/client-references.ts +267 -0
  375. package/src/rsc/build/discover.ts +226 -0
  376. package/src/rsc/build/flight-loader.ts +69 -0
  377. package/src/rsc/build/index.ts +59 -34
  378. package/src/rsc/build/paths.ts +7 -0
  379. package/src/rsc/bundled-client-codec.ts +4 -0
  380. package/src/rsc/client-codec.ts +12 -3
  381. package/src/rsc/client-references.ts +138 -0
  382. package/src/rsc/codec.ts +30 -21
  383. package/src/rsc/flight-drain.ts +6 -29
  384. package/src/rsc/react-server-dom-webpack.d.ts +1 -1
  385. package/src/rsc/server-client-codec.ts +14 -0
  386. package/src/rsc/server-codec.ts +5 -8
  387. package/src/rsc/slot-proxy.ts +34 -0
  388. package/src/rsc/transport-benchmark.ts +1 -1
  389. package/src/rsc-server.tsx +5 -23
  390. package/src/rsc.tsx +5 -29
  391. package/src/server/assets/client-dir.ts +110 -0
  392. package/src/server/assets/production.ts +1 -1
  393. package/src/server/auto-invalidate/index.ts +2 -7
  394. package/src/server/auto-invalidate/plugin.ts +43 -15
  395. package/src/server/auto-invalidate/registry.ts +6 -6
  396. package/src/server/auto-invalidate/runtime.ts +16 -98
  397. package/src/server/auto-invalidate/types.ts +0 -6
  398. package/src/server/bounded-body.ts +38 -0
  399. package/src/server/browser-events/plugin.ts +167 -26
  400. package/src/server/browser-events/shutdown.ts +28 -9
  401. package/src/server/cache/dev-loader.ts +30 -16
  402. package/src/server/cache/index.ts +2 -15
  403. package/src/server/cache/invalidation.ts +27 -46
  404. package/src/server/cache/isr-ssg.ts +6 -1
  405. package/src/server/cache/isr.ts +11 -11
  406. package/src/server/cache/page-cache-state.ts +2 -2
  407. package/src/server/cache/page-cache.ts +13 -9
  408. package/src/server/cache/purger.ts +64 -8
  409. package/src/server/cache/redis/index.ts +17 -27
  410. package/src/server/cache/redis/scripts.ts +21 -4
  411. package/src/server/cache/registry.ts +3 -3
  412. package/src/server/cache/route-cache.ts +47 -13
  413. package/src/server/cache/runtime-cache.ts +144 -24
  414. package/src/server/cache/ssg.ts +7 -5
  415. package/src/server/context-logger.ts +46 -8
  416. package/src/server/dev/diagnostics.ts +6 -56
  417. package/src/server/dev/error.ts +3 -34
  418. package/src/server/dev/graph.ts +35 -22
  419. package/src/server/dev/rewrite-module-specifiers.ts +16 -19
  420. package/src/server/dev/runtime.production.ts +4 -0
  421. package/src/server/dev/runtime.ts +404 -0
  422. package/src/server/dev/server-only-module.ts +23 -0
  423. package/src/server/dev/stack-location.ts +46 -0
  424. package/src/server/dev/symbolicate.ts +4 -3
  425. package/src/server/dev-page-imports.ts +185 -0
  426. package/src/server/dev-page-plugin.ts +57 -303
  427. package/src/server/devtools/hub.ts +3 -3
  428. package/src/server/devtools/instrumentation.production.ts +0 -8
  429. package/src/server/devtools/instrumentation.ts +6 -8
  430. package/src/server/devtools/plugin.ts +2 -1
  431. package/src/server/devtools/request-context.ts +67 -16
  432. package/src/server/evlog.ts +119 -55
  433. package/src/server/instance.ts +187 -138
  434. package/src/server/internal.ts +66 -62
  435. package/src/server/lang-detect.ts +31 -22
  436. package/src/server/logging/ingest-plugin.ts +117 -0
  437. package/src/server/mode.ts +19 -0
  438. package/src/server/prerender.ts +122 -0
  439. package/src/server/prod/runtime.ts +181 -0
  440. package/src/server/production-server.ts +43 -17
  441. package/src/server/registrations.ts +38 -0
  442. package/src/server/render/assemble.ts +5 -8
  443. package/src/server/render/buffered-render.ts +171 -0
  444. package/src/server/render/document-stream.ts +188 -0
  445. package/src/server/render/document.tsx +5 -3
  446. package/src/server/render/element.tsx +6 -73
  447. package/src/server/render/index.ts +4 -21
  448. package/src/server/render/isr-revalidation.ts +246 -0
  449. package/src/server/render/isr-shared-cache.ts +141 -0
  450. package/src/server/render/isr.ts +212 -516
  451. package/src/server/render/loader-errors.ts +183 -0
  452. package/src/server/render/loader-segments.ts +149 -0
  453. package/src/server/render/loaders.ts +126 -547
  454. package/src/server/render/mixed-cache.ts +28 -27
  455. package/src/server/render/navigation-head.ts +33 -0
  456. package/src/server/render/not-found-plugin.ts +31 -0
  457. package/src/server/render/not-found.ts +32 -8
  458. package/src/server/render/observe-loader.ts +46 -0
  459. package/src/server/render/ppr-document.ts +36 -14
  460. package/src/server/render/ppr-request.ts +2 -2
  461. package/src/server/render/ppr-route.ts +79 -18
  462. package/src/server/render/prepare-render.ts +251 -0
  463. package/src/server/render/request-loaders.ts +216 -0
  464. package/src/server/render/route-frame-transport.ts +41 -4
  465. package/src/server/render/shell.ts +1 -1
  466. package/src/server/render/ssg.ts +9 -20
  467. package/src/server/render/ssr-transport.ts +221 -0
  468. package/src/server/render/ssr.ts +95 -956
  469. package/src/server/render/static-params.ts +32 -0
  470. package/src/server/render/template.ts +7 -7
  471. package/src/server/router/discovery.ts +82 -159
  472. package/src/server/router/dispatch.ts +337 -0
  473. package/src/server/router/hmr.ts +177 -190
  474. package/src/server/router/patterns.ts +39 -65
  475. package/src/server/router/plugin.ts +234 -359
  476. package/src/server/router/schemas.ts +6 -39
  477. package/src/server/router/source-version.ts +5 -4
  478. package/src/server/router/types.ts +0 -2
  479. package/src/server/runtime-env.ts +6 -1
  480. package/src/server/server-entry.ts +39 -0
  481. package/src/server/static-export.ts +143 -0
  482. package/src/server/sync/adapter.ts +16 -1
  483. package/src/server/sync/atomic.ts +16 -36
  484. package/src/server/sync/config.ts +12 -14
  485. package/src/server/sync/connection.ts +71 -0
  486. package/src/server/sync/drizzle/index.ts +12 -20
  487. package/src/server/sync/fingerprint.ts +1 -1
  488. package/src/server/sync/index.ts +5 -10
  489. package/src/server/sync/invalidate-sync.ts +56 -0
  490. package/src/server/sync/local-client.ts +84 -0
  491. package/src/server/sync/mutation-handler.ts +6 -0
  492. package/src/server/sync/plugin.ts +193 -144
  493. package/src/server/sync/postgres/execute.ts +9 -1
  494. package/src/server/sync/postgres/index.ts +78 -39
  495. package/src/server/sync/postgres/migration.sql +2 -0
  496. package/src/server/sync/principal-journal.ts +78 -0
  497. package/src/server/sync/prisma/index.ts +1 -0
  498. package/src/server/sync/queries.ts +133 -40
  499. package/src/server/sync/query-context.ts +38 -5
  500. package/src/server/sync/redis/index.ts +38 -6
  501. package/src/server/sync/redis/scripts.ts +10 -1
  502. package/src/server/sync/response.ts +47 -67
  503. package/src/server/sync/runtime.ts +74 -19
  504. package/src/server/sync/sqlite/index.ts +96 -61
  505. package/src/server/sync/sqlite/migration.sql +1 -0
  506. package/src/server/sync/stream.ts +62 -29
  507. package/src/server/sync/validation.ts +1 -1
  508. package/src/server/weak-registry.ts +37 -0
  509. package/src/shared/await.tsx +2 -1
  510. package/src/shared/browser-events.ts +1 -1
  511. package/src/shared/compact-json.ts +1 -1
  512. package/src/shared/defer.ts +1 -1
  513. package/src/shared/deferred-ndjson.ts +142 -120
  514. package/src/shared/elysia-contract.ts +7 -0
  515. package/src/shared/error.ts +1 -4
  516. package/src/shared/in-memory-apps.ts +24 -0
  517. package/src/shared/invalidation-header.ts +38 -0
  518. package/src/shared/navigation-data.ts +29 -0
  519. package/src/shared/prefix.ts +42 -6
  520. package/src/shared/route-frame.ts +82 -26
  521. package/src/shared/route-map.ts +23 -39
  522. package/src/shared/route-matches.ts +59 -0
  523. package/src/shared/route-specificity.ts +28 -0
  524. package/src/shared/search-params.ts +6 -35
  525. package/src/shared/sync-query.ts +30 -23
  526. package/src/shared/utils/ast-walk.ts +9 -25
  527. package/src/shared/utils/index.ts +1 -1
  528. package/src/sync-client.ts +14 -0
  529. package/dist/build/scan-server.d.ts +0 -14
  530. package/dist/build/ssg-cache.d.ts +0 -18
  531. package/dist/plugin/route-config-autofix.d.ts +0 -31
  532. package/dist/plugin/routes.d.ts +0 -34
  533. package/dist/server/logger.d.ts +0 -4
  534. package/dist/server/router/hmr.production.d.ts +0 -7
  535. package/src/build/scan-server.ts +0 -112
  536. package/src/build/ssg-cache.ts +0 -126
  537. package/src/client/router/sync-catch-up.ts +0 -120
  538. package/src/plugin/route-config-autofix.ts +0 -1149
  539. package/src/plugin/routes.ts +0 -1140
  540. package/src/server/logger.ts +0 -21
  541. package/src/server/router/hmr.production.ts +0 -18
@@ -11,190 +11,208 @@ var __esm = (fn, res, err) => () => {
11
11
  return res;
12
12
  };
13
13
 
14
+ // src/shared/sync-query.ts
15
+ function serializeQueryHeader(identity) {
16
+ return JSON.stringify(identity).replace(/[^\u0020-\u007e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
17
+ }
18
+ function queryTag(identity) {
19
+ for (const [key, value] of Object.entries(identity.scope)) {
20
+ if (value === undefined) {
21
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
22
+ }
23
+ }
24
+ return PREFIX + JSON.stringify([
25
+ identity.id,
26
+ Object.entries(identity.scope).map(([key, value]) => [key, typeof value === "number" ? String(value) : value]).sort(([a], [b]) => {
27
+ if (a === b) {
28
+ return 0;
29
+ }
30
+ return a < b ? -1 : 1;
31
+ })
32
+ ]);
33
+ }
34
+ function queryTags(identity) {
35
+ let scopes = [{}];
36
+ for (const [key, value] of Object.entries(identity.scope)) {
37
+ scopes = scopes.concat(scopes.map((scope) => ({ ...scope, [key]: value })));
38
+ }
39
+ return scopes.map((scope) => queryTag({ id: identity.id, scope }));
40
+ }
41
+ function queryFromTag(tag) {
42
+ if (!tag.startsWith(PREFIX)) {
43
+ return;
44
+ }
45
+ try {
46
+ const value = JSON.parse(tag.slice(PREFIX.length));
47
+ if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !Array.isArray(value[1]) || value[1].some((entry) => !Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !(entry[1] === null || typeof entry[1] === "string" || typeof entry[1] === "number" || typeof entry[1] === "boolean"))) {
48
+ return;
49
+ }
50
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
51
+ } catch {}
52
+ }
53
+ function queryUrl(url, origin) {
54
+ const parsed = new URL(url, origin);
55
+ parsed.searchParams.sort();
56
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
57
+ }
58
+ var PREFIX = "__furin.query:";
59
+
60
+ // src/shared/invalidation-header.ts
61
+ function encodeInvalidationEntry(path, type) {
62
+ const encoded = encodeURI(path.toWellFormed()).replace(PATH_DELIMITERS_RE, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
63
+ return type === "layout" ? `${encoded}:layout` : encoded;
64
+ }
65
+ function decodeInvalidationEntry(entry) {
66
+ const trimmed = entry.trim();
67
+ const type = trimmed.endsWith(":layout") ? "layout" : "page";
68
+ const path = type === "layout" ? trimmed.slice(0, -":layout".length) : trimmed;
69
+ try {
70
+ return { path: decodeURIComponent(path), type };
71
+ } catch {
72
+ return { path, type };
73
+ }
74
+ }
75
+ function serializeInvalidationPaths(paths) {
76
+ return paths.join(",");
77
+ }
78
+ var PATH_DELIMITERS_RE;
79
+ var init_invalidation_header = __esm(() => {
80
+ PATH_DELIMITERS_RE = /[,:?#]/g;
81
+ });
82
+
83
+ // src/shared/prefix.ts
84
+ function physicalPath(prefix, path) {
85
+ if (prefix === "") {
86
+ return path;
87
+ }
88
+ return path === "/" ? prefix : `${prefix}${path}`;
89
+ }
90
+ var init_prefix = () => {};
91
+
92
+ // src/server/runtime-env.ts
93
+ var IS_DEV = true;
94
+
95
+ // src/server/weak-registry.ts
96
+ class WeakRegistry {
97
+ entries = new Set;
98
+ references = new WeakMap;
99
+ add(value) {
100
+ let reference = this.references.get(value);
101
+ if (!reference) {
102
+ reference = new WeakRef(value);
103
+ this.references.set(value, reference);
104
+ }
105
+ this.entries.add(reference);
106
+ }
107
+ clear() {
108
+ this.entries.clear();
109
+ }
110
+ delete(value) {
111
+ const reference = this.references.get(value);
112
+ if (reference) {
113
+ this.entries.delete(reference);
114
+ this.references.delete(value);
115
+ }
116
+ }
117
+ *values() {
118
+ for (const reference of this.entries) {
119
+ const value = reference.deref();
120
+ if (value) {
121
+ yield value;
122
+ } else {
123
+ this.entries.delete(reference);
124
+ }
125
+ }
126
+ }
127
+ }
128
+
14
129
  // src/server/instance.ts
15
130
  import { AsyncLocalStorage } from "async_hooks";
16
- function createInstance(prefix, pagesDir) {
17
- return {
18
- buildId: "",
19
- pagesDir,
20
- prefix,
21
- registrationEpoch: 0,
22
- state: new Map,
23
- syncPath: undefined
24
- };
25
- }
26
- function defaultInstance() {
131
+ function defaultInstanceBucket() {
27
132
  if (!_defaultInstance) {
28
- _defaultInstance = createInstance("", "");
133
+ _defaultInstance = {
134
+ buildId: "",
135
+ get development() {
136
+ return IS_DEV;
137
+ },
138
+ pagesDir: "",
139
+ prefix: "",
140
+ state: new Map,
141
+ syncPath: undefined
142
+ };
29
143
  }
30
144
  return _defaultInstance;
31
145
  }
146
+ function ensureRequestScope(fn) {
147
+ if (_scope.getStore()) {
148
+ return fn();
149
+ }
150
+ return _scope.run({
151
+ navigationData: false,
152
+ pending: new Set,
153
+ peers: undefined,
154
+ requests: new WeakSet,
155
+ runtime: undefined
156
+ }, fn);
157
+ }
32
158
  function currentInstance() {
33
- const scope = _requestScope.getStore();
34
- if (scope) {
35
- return scope.instance;
159
+ const scope = _scope.getStore();
160
+ if (scope?.runtime) {
161
+ return scope.runtime;
36
162
  }
37
- if (_instances.size === 1) {
38
- const only = _instances.values().next().value;
39
- if (only) {
40
- return only;
41
- }
163
+ if (_runtimes.values().next().done) {
164
+ return defaultInstanceBucket();
42
165
  }
43
- return defaultInstance();
166
+ throw new Error("[furin] No Furin runtime is bound here. Runtime state is only available while a Furin route handles a request, or inside withInstance().");
44
167
  }
45
168
  function allInstances() {
46
- if (_instances.size === 0) {
47
- return [defaultInstance()];
169
+ const peers = _scope.getStore()?.peers;
170
+ if (peers) {
171
+ return [...peers];
48
172
  }
49
- return [..._instances.values()];
173
+ const instances = [..._runtimes.values()];
174
+ return instances.length > 0 ? instances : [defaultInstanceBucket()];
50
175
  }
51
176
  function requestPendingInvalidations() {
52
- return _requestScope.getStore()?.pending;
53
- }
54
- function runWithInstanceScope(instance, fn) {
55
- return _requestScope.run({ instance, pending: new Set }, fn);
177
+ return _scope.getStore()?.pending;
56
178
  }
57
179
  function withInstance(instance, fn) {
58
- return runWithInstanceScope(instance, fn);
180
+ const scope = _scope.getStore();
181
+ return _scope.run({
182
+ navigationData: false,
183
+ pending: scope?.pending ?? new Set,
184
+ peers: scope?.peers,
185
+ requests: new WeakSet,
186
+ runtime: instance
187
+ }, fn);
59
188
  }
60
189
  function instanceSlot(init) {
61
190
  const key = Symbol("furin-instance-slot");
62
191
  return (instance) => {
63
- const target = instance ?? currentInstance();
64
- if (target.state.has(key)) {
65
- return target.state.get(key);
192
+ if (instance.state.has(key)) {
193
+ return instance.state.get(key);
66
194
  }
67
- const value = init(target);
68
- target.state.set(key, value);
195
+ const value = init(instance);
196
+ instance.state.set(key, value);
69
197
  return value;
70
198
  };
71
199
  }
72
- var _requestScope, _instances, _defaultInstance = null;
200
+ var _scope, _runtimes, _defaultInstance = null;
73
201
  var init_instance = __esm(() => {
74
- _requestScope = new AsyncLocalStorage;
75
- _instances = new Map;
202
+ _scope = new AsyncLocalStorage;
203
+ _runtimes = new WeakRegistry;
76
204
  });
77
205
 
78
- // src/server/sync/config.ts
79
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
80
- function resolveSyncPath(sync) {
81
- if (!sync) {
82
- return;
83
- }
84
- return sync.path ?? SYNC_DEFAULT_PATH;
85
- }
86
- function getSyncPath() {
87
- const override = requestSyncPath.getStore();
88
- if (override !== undefined) {
89
- return override;
90
- }
91
- return currentInstance().syncPath;
92
- }
93
- function runWithSyncPath(path, fn) {
94
- return requestSyncPath.run(path, fn);
95
- }
96
- function syncRuntimeOptions(sync) {
97
- return { adapter: sync.adapter, notifier: sync.notifier, principal: sync.principal };
206
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/error-brand-D4i1NkSd.mjs
207
+ function isEvlogError(error) {
208
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
98
209
  }
99
- var SYNC_DEFAULT_PATH = "/_furin/sync", requestSyncPath;
100
- var init_config = __esm(() => {
101
- init_instance();
102
- requestSyncPath = new AsyncLocalStorage2;
210
+ var evlogErrorBrand;
211
+ var init_error_brand_D4i1NkSd = __esm(() => {
212
+ evlogErrorBrand = Symbol.for("evlog.error.brand");
103
213
  });
104
214
 
105
- // src/server/sync/notifier.ts
106
- class PollingSyncNotifier {
107
- recovery = "self";
108
- adapter;
109
- intervalMs;
110
- listeners = new Set;
111
- cursor;
112
- initialization;
113
- polling;
114
- revision = 0;
115
- timer;
116
- constructor(adapter, intervalMs) {
117
- this.adapter = adapter;
118
- this.intervalMs = intervalMs;
119
- }
120
- publish(cursor) {
121
- this.revision += 1;
122
- this.emit(cursor);
123
- return Promise.resolve();
124
- }
125
- async subscribe(listener) {
126
- const subscription = { listener };
127
- this.listeners.add(subscription);
128
- try {
129
- await this.start();
130
- } catch (error) {
131
- this.listeners.delete(subscription);
132
- throw error;
133
- }
134
- return {
135
- unsubscribe: () => {
136
- this.listeners.delete(subscription);
137
- if (this.listeners.size === 0 && this.timer) {
138
- clearTimeout(this.timer);
139
- this.timer = undefined;
140
- }
141
- return Promise.resolve();
142
- }
143
- };
144
- }
145
- emit(cursor) {
146
- if (cursor === this.cursor) {
147
- return;
148
- }
149
- this.cursor = cursor;
150
- for (const subscription of [...this.listeners]) {
151
- try {
152
- subscription.listener(cursor);
153
- } catch {}
154
- }
155
- }
156
- async poll() {
157
- const { revision } = this;
158
- try {
159
- const cursor = await this.adapter.currentCursor();
160
- if (revision === this.revision && this.listeners.size > 0) {
161
- this.emit(cursor);
162
- }
163
- } catch {}
164
- }
165
- async start() {
166
- if (this.timer || this.polling) {
167
- return;
168
- }
169
- if (!this.initialization) {
170
- const { revision } = this;
171
- this.initialization = this.adapter.currentCursor().then((cursor) => {
172
- if (revision === this.revision) {
173
- this.cursor = cursor;
174
- }
175
- }).finally(() => {
176
- this.initialization = undefined;
177
- });
178
- }
179
- await this.initialization;
180
- this.schedulePoll();
181
- }
182
- schedulePoll() {
183
- if (this.listeners.size === 0 || this.timer || this.polling) {
184
- return;
185
- }
186
- this.timer = setTimeout(() => {
187
- this.timer = undefined;
188
- this.polling = this.poll().finally(() => {
189
- this.polling = undefined;
190
- this.schedulePoll();
191
- });
192
- }, this.intervalMs);
193
- this.timer.unref?.();
194
- }
195
- }
196
-
197
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
215
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/utils.mjs
198
216
  function elapsedMs(startTime) {
199
217
  return Math.max(0, Date.now() - startTime);
200
218
  }
@@ -203,9 +221,6 @@ function formatDuration(ms) {
203
221
  return `${Math.round(ms)}ms`;
204
222
  return `${(ms / 1000).toFixed(2)}s`;
205
223
  }
206
- function isServer() {
207
- return typeof window === "undefined";
208
- }
209
224
  function isBrowser() {
210
225
  if (typeof window === "undefined")
211
226
  return false;
@@ -237,6 +252,10 @@ function isLevelEnabled(level, minLevel) {
237
252
  return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
238
253
  }
239
254
  function getConsoleMethod(level) {
255
+ if (level === "fatal")
256
+ return "error";
257
+ if (level === "trace")
258
+ return "log";
240
259
  return level;
241
260
  }
242
261
  function getLevelColor(level) {
@@ -248,6 +267,49 @@ function getCssLevelColor(level) {
248
267
  function escapeFormatString(str) {
249
268
  return str.replace(/%/g, "%%");
250
269
  }
270
+ function hasMessageSpecifiers(format) {
271
+ return /%[sdj]/.test(format);
272
+ }
273
+ function formatMessage(format, args) {
274
+ if (args.length === 0)
275
+ return format;
276
+ let argIndex = 0;
277
+ const interpolated = format.replace(/%(.)/g, (specifier, char) => {
278
+ if (char === "%")
279
+ return "%";
280
+ if (char !== "s" && char !== "d" && char !== "j")
281
+ return specifier;
282
+ if (argIndex >= args.length)
283
+ return specifier;
284
+ return renderMessageValue(char, args[argIndex++]);
285
+ });
286
+ if (argIndex >= args.length)
287
+ return interpolated;
288
+ const extras = [];
289
+ while (argIndex < args.length)
290
+ extras.push(renderMessageValue("s", args[argIndex++]));
291
+ return `${interpolated} ${extras.join(" ")}`;
292
+ }
293
+ function renderMessageValue(specifier, value) {
294
+ if (specifier === "j")
295
+ return renderMessageJson(value);
296
+ if (typeof value === "bigint")
297
+ return `${value}n`;
298
+ if (specifier === "d")
299
+ return String(Number(value));
300
+ if (typeof value === "string")
301
+ return value;
302
+ if (value === null || typeof value !== "object")
303
+ return String(value);
304
+ return renderMessageJson(value);
305
+ }
306
+ function renderMessageJson(value) {
307
+ try {
308
+ return JSON.stringify(value) ?? String(value);
309
+ } catch {
310
+ return String(value);
311
+ }
312
+ }
251
313
  function filterSafeHeaders(headers) {
252
314
  const safeHeaders = {};
253
315
  for (const [key, value] of Object.entries(headers))
@@ -280,13 +342,25 @@ function isoNow() {
280
342
  }
281
343
  return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
282
344
  }
345
+ function readErrorField(error, key) {
346
+ if (isEvlogError(error)) {
347
+ if (key === "statusCode")
348
+ return error.status;
349
+ if (key === "statusText" || key === "statusMessage")
350
+ return error.message;
351
+ }
352
+ return error[key];
353
+ }
283
354
  var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, SENSITIVE_HEADER_SET, patternCache, _isoDate, _isoCachedSecond = -1, _isoCachedPrefix = "";
284
355
  var init_utils = __esm(() => {
356
+ init_error_brand_D4i1NkSd();
285
357
  LEVEL_ORDER = {
358
+ trace: 0,
286
359
  debug: 0,
287
360
  info: 1,
288
361
  warn: 2,
289
- error: 3
362
+ error: 3,
363
+ fatal: 4
290
364
  };
291
365
  colors = {
292
366
  reset: "\x1B[0m",
@@ -303,9 +377,11 @@ var init_utils = __esm(() => {
303
377
  };
304
378
  levelColorMap = {
305
379
  error: colors.red,
380
+ fatal: colors.red,
306
381
  warn: colors.yellow,
307
382
  info: colors.cyan,
308
- debug: colors.gray
383
+ debug: colors.gray,
384
+ trace: colors.gray
309
385
  };
310
386
  cssColors = {
311
387
  dim: "color: #6b7280",
@@ -318,9 +394,11 @@ var init_utils = __esm(() => {
318
394
  };
319
395
  cssLevelColorMap = {
320
396
  error: cssColors.red,
397
+ fatal: cssColors.red,
321
398
  warn: cssColors.yellow,
322
399
  info: cssColors.cyan,
323
- debug: cssColors.gray
400
+ debug: cssColors.gray,
401
+ trace: cssColors.gray
324
402
  };
325
403
  SENSITIVE_HEADERS = [
326
404
  "authorization",
@@ -335,324 +413,15 @@ var init_utils = __esm(() => {
335
413
  _isoDate = /* @__PURE__ */ new Date;
336
414
  });
337
415
 
338
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
339
- function normalizeRedactPathPattern(pattern) {
340
- if (!pattern.includes("*") && !pattern.includes("."))
341
- return `**.${pattern}`;
342
- return pattern;
416
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/globalRegistry-DxlJ7DCO.mjs
417
+ function logPluginError(name, hook, err) {
418
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
343
419
  }
344
- function compileRedactPathMatchers(patterns) {
345
- if (!patterns?.length)
346
- return;
347
- const exactPaths = /* @__PURE__ */ new Set;
348
- const pathGlobs = [];
349
- const keyGlobs = [];
350
- const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
351
- for (const raw of patterns) {
352
- if (!raw.includes("*")) {
353
- if (raw.includes("."))
354
- exactPaths.add(raw);
355
- else
356
- addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
357
- continue;
358
- }
359
- if (!raw.includes("."))
360
- keyGlobs.push(globToRegExp(raw, "."));
361
- else
362
- addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
363
- }
364
- if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
365
- return;
366
- return {
367
- exactPaths,
368
- pathGlobs,
369
- keyGlobs,
370
- caseInsensitiveLeaves
371
- };
372
- }
373
- function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
374
- pathGlobs.push(globToRegExp(pattern, "."));
375
- const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
376
- if (leaf) {
377
- exactPaths.add(leaf[1]);
378
- caseInsensitiveLeaves.add(leaf[1].toLowerCase());
379
- }
380
- }
381
- function matchesRedactPath(fullPath, leafKey, matchers) {
382
- if (matchers.exactPaths.has(fullPath))
383
- return true;
384
- if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
385
- return true;
386
- for (const glob of matchers.pathGlobs) {
387
- glob.lastIndex = 0;
388
- if (glob.test(fullPath))
389
- return true;
390
- }
391
- for (const glob of matchers.keyGlobs) {
392
- glob.lastIndex = 0;
393
- if (glob.test(leafKey))
394
- return true;
395
- }
396
- return false;
397
- }
398
- function resolveReplacement(replacement, matched, ctx) {
399
- if (typeof replacement === "string")
400
- return replacement;
401
- try {
402
- const result = replacement(matched, ctx);
403
- if (typeof result !== "string") {
404
- console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
405
- return DEFAULT_REPLACEMENT;
406
- }
407
- return result;
408
- } catch (err) {
409
- console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
410
- return DEFAULT_REPLACEMENT;
411
- }
412
- }
413
- function redactPathsInTree(obj, matchers, replacement, prefix = "") {
414
- if (obj === null || obj === undefined)
415
- return;
416
- if (Array.isArray(obj)) {
417
- for (let i = 0;i < obj.length; i++) {
418
- const segment = String(i);
419
- const fullPath = prefix ? `${prefix}.${segment}` : segment;
420
- redactPathsInTree(obj[i], matchers, replacement, fullPath);
421
- }
422
- return;
423
- }
424
- if (typeof obj === "object") {
425
- const record = obj;
426
- for (const key of redactableKeys(record)) {
427
- const fullPath = prefix ? `${prefix}.${key}` : key;
428
- if (matchesRedactPath(fullPath, key, matchers))
429
- setRedacted(record, key, resolveReplacement(replacement, record[key], {
430
- path: fullPath,
431
- key
432
- }), fullPath);
433
- else
434
- redactPathsInTree(record[key], matchers, replacement, fullPath);
435
- }
436
- }
437
- }
438
- function redactableKeys(record) {
439
- return Object.keys(record);
440
- }
441
- function setRedacted(record, key, value, path) {
442
- if (Reflect.set(record, key, value))
443
- return;
444
- const desc = Object.getOwnPropertyDescriptor(record, key);
445
- if (desc && "value" in desc && desc.configurable) {
446
- Object.defineProperty(record, key, {
447
- ...desc,
448
- value
449
- });
450
- return;
451
- }
452
- console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
453
- }
454
- function resolveRedactConfig(input) {
455
- if (input === undefined || input === false)
456
- return;
457
- if (input === true)
458
- return { _maskers: allBuiltinMaskers() };
459
- if (input.builtins === false)
460
- return {
461
- ...input,
462
- _pathMatchers: compileRedactPathMatchers(input.paths)
463
- };
464
- const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
465
- return {
466
- ...input,
467
- _maskers: maskers,
468
- _pathMatchers: compileRedactPathMatchers(input.paths)
469
- };
470
- }
471
- function allBuiltinMaskers() {
472
- return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
473
- }
474
- function cloneRegex(re) {
475
- return new RegExp(re.source, re.flags);
476
- }
477
- function markGloballyRedacted(event) {
478
- Object.defineProperty(event, globallyRedacted, {
479
- value: true,
480
- enumerable: false,
481
- configurable: true
482
- });
483
- }
484
- function isGloballyRedacted(event) {
485
- return Reflect.has(event, globallyRedacted);
486
- }
487
- function cloneForRedaction(event) {
488
- try {
489
- return structuredClone(event);
490
- } catch {
491
- try {
492
- return JSON.parse(JSON.stringify(event));
493
- } catch {
494
- console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
495
- return { ...event };
496
- }
497
- }
498
- }
499
- function redactEvent(event, config) {
500
- const clone = cloneForRedaction(event);
501
- const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
502
- if (config.transform)
503
- try {
504
- config.transform(clone);
505
- } catch (err) {
506
- console.error("[evlog] redact transform failed:", err);
507
- }
508
- const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
509
- if (pathMatchers)
510
- redactPathsInTree(clone, pathMatchers, replacement);
511
- if (config._maskers?.length)
512
- applyMaskersToTree(clone, config._maskers);
513
- if (config.patterns?.length)
514
- redactPatterns(clone, config.patterns, replacement);
515
- return clone;
516
- }
517
- function redactPatterns(obj, patterns, replacement, prefix = "") {
518
- if (obj === null || obj === undefined)
519
- return;
520
- if (Array.isArray(obj)) {
521
- for (let i = 0;i < obj.length; i++) {
522
- const key = String(i);
523
- const fullPath = prefix ? `${prefix}.${key}` : key;
524
- if (typeof obj[i] === "string")
525
- obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
526
- else if (typeof obj[i] === "object")
527
- redactPatterns(obj[i], patterns, replacement, fullPath);
528
- }
529
- return;
530
- }
531
- if (typeof obj === "object") {
532
- const record = obj;
533
- for (const key of redactableKeys(record)) {
534
- const val = record[key];
535
- const fullPath = prefix ? `${prefix}.${key}` : key;
536
- if (typeof val === "string")
537
- setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
538
- else if (typeof val === "object")
539
- redactPatterns(val, patterns, replacement, fullPath);
540
- }
541
- }
542
- }
543
- function applyPatterns(value, patterns, replacement, path, key) {
544
- let result = value;
545
- for (const pattern of patterns) {
546
- if (typeof replacement === "string") {
547
- result = result.replace(pattern, replacement);
548
- continue;
549
- }
550
- result = result.replace(pattern, (...args) => {
551
- const match = args[0];
552
- return resolveReplacement(replacement, match, {
553
- path,
554
- key,
555
- groups: captureGroups(args)
556
- });
557
- });
558
- }
559
- return result;
560
- }
561
- function captureGroups(args) {
562
- const last = args.at(-1);
563
- const trailing = typeof last === "object" && last !== null ? 3 : 2;
564
- return args.slice(1, Math.max(1, args.length - trailing));
565
- }
566
- function applyMaskersToTree(obj, maskers) {
567
- if (obj === null || obj === undefined)
568
- return;
569
- if (Array.isArray(obj)) {
570
- for (let i = 0;i < obj.length; i++)
571
- if (typeof obj[i] === "string")
572
- obj[i] = applyMaskers(obj[i], maskers);
573
- else if (typeof obj[i] === "object")
574
- applyMaskersToTree(obj[i], maskers);
575
- return;
576
- }
577
- if (typeof obj === "object") {
578
- const record = obj;
579
- for (const key of redactableKeys(record)) {
580
- const val = record[key];
581
- if (typeof val === "string")
582
- setRedacted(record, key, applyMaskers(val, maskers), key);
583
- else if (typeof val === "object")
584
- applyMaskersToTree(val, maskers);
585
- }
586
- }
587
- }
588
- function applyMaskers(value, maskers) {
589
- let result = value;
590
- for (const [pattern, mask] of maskers)
591
- result = result.replace(pattern, mask);
592
- return result;
593
- }
594
- var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, globallyRedacted;
595
- var init_redact_C7FmdhwI = __esm(() => {
596
- init_utils();
597
- builtinPatterns = {
598
- creditCard: {
599
- pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
600
- mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
601
- },
602
- email: {
603
- pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
604
- mask: (m) => {
605
- if (m.indexOf("@") < 1)
606
- return "***@***";
607
- const tld = m.slice(m.lastIndexOf("."));
608
- return `${m[0]}***@***${tld}`;
609
- }
610
- },
611
- ipv4: {
612
- pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
613
- mask: (m) => `***.***.***.${m.split(".").pop()}`
614
- },
615
- phone: {
616
- pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
617
- mask: (m) => {
618
- const digits = m.replace(/[^\d]/g, "");
619
- if (m.startsWith("+") && digits.length > 4) {
620
- const ccMatch = m.match(/^\+\d{1,3}/);
621
- return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
622
- }
623
- if (digits.length > 2)
624
- return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
625
- return "***";
626
- }
627
- },
628
- jwt: {
629
- pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
630
- mask: () => "eyJ***.***"
631
- },
632
- bearer: {
633
- pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
634
- mask: () => "Bearer ***"
635
- },
636
- iban: {
637
- pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
638
- mask: (m) => {
639
- const clean = m.replace(/[\s-]/g, "");
640
- return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
641
- }
642
- }
643
- };
644
- globallyRedacted = Symbol.for("evlog.globallyRedacted");
645
- });
646
-
647
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
648
- function logPluginError(name, hook, err) {
649
- console.error(`[evlog/${name}] ${hook} failed:`, err);
650
- }
651
- function createPluginRunner(plugins = []) {
652
- const byName = /* @__PURE__ */ new Map;
653
- for (const plugin of plugins)
654
- byName.set(plugin.name, plugin);
655
- const list = Array.from(byName.values());
420
+ function createPluginRunner(plugins = []) {
421
+ const byName = /* @__PURE__ */ new Map;
422
+ for (const plugin of plugins)
423
+ byName.set(plugin.name, plugin);
424
+ const list = Array.from(byName.values());
656
425
  return {
657
426
  plugins: list,
658
427
  hasEnrich: list.some((p) => typeof p.enrich === "function"),
@@ -777,6 +546,7 @@ function createConfig() {
777
546
  minLevel: "debug",
778
547
  locked: false,
779
548
  initialized: false,
549
+ warnedUninitialized: false,
780
550
  pluginRunner: getEmptyPluginRunner()
781
551
  };
782
552
  }
@@ -806,7 +576,7 @@ function getSharedStorage(id, create) {
806
576
  return storage;
807
577
  }
808
578
  var emptyRunner, EVLOG_MAJOR = 2, REGISTRY_KEY, MAJORS_KEY, globalConfig;
809
- var init_globalRegistry_Bh3bIGwA = __esm(() => {
579
+ var init_globalRegistry_DxlJ7DCO = __esm(() => {
810
580
  init_utils();
811
581
  emptyRunner = createPluginRunner([]);
812
582
  REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
@@ -814,7 +584,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
814
584
  globalConfig = getRegistry().config;
815
585
  });
816
586
 
817
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
587
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/pretty-error-DnkXIALi.mjs
818
588
  function pushTreeSpacer(children) {
819
589
  children.push(PRETTY_ERROR_TREE_SPACER);
820
590
  }
@@ -887,8 +657,6 @@ function isAppPath(file) {
887
657
  return false;
888
658
  if (SKIP_PATH_RE.test(normalized))
889
659
  return false;
890
- if (normalized.includes("/node_modules/"))
891
- return false;
892
660
  if (isFrameworkRuntimePath(normalized))
893
661
  return false;
894
662
  return true;
@@ -1108,14 +876,14 @@ function buildErrorEntries(error, options = {}) {
1108
876
  }];
1109
877
  }
1110
878
  var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
1111
- var init_pretty_error_D8rlWNL1 = __esm(() => {
879
+ var init_pretty_error_DnkXIALi = __esm(() => {
1112
880
  init_utils();
1113
881
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1114
882
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1115
883
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1116
884
  });
1117
885
 
1118
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
886
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/dev-terminal-CDXEC6Wl.mjs
1119
887
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1120
888
  const compact = partial.compact ?? (inDev && pretty);
1121
889
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1150,7 +918,7 @@ function resolveDevTerminal(input = {}) {
1150
918
  };
1151
919
  }
1152
920
  var DEV_PRESETS;
1153
- var init_dev_terminal_Brarc6vc = __esm(() => {
921
+ var init_dev_terminal_CDXEC6Wl = __esm(() => {
1154
922
  init_utils();
1155
923
  DEV_PRESETS = {
1156
924
  evlog: {
@@ -1168,7 +936,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1168
936
  };
1169
937
  });
1170
938
 
1171
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
939
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/wideEventChannel-BABjYpvc.mjs
1172
940
  function hasWideEventPublisher() {
1173
941
  return publisher !== null;
1174
942
  }
@@ -1182,127 +950,154 @@ function publishWideEvent(event) {
1182
950
  }
1183
951
  }
1184
952
  var publisher = null;
1185
- var init_wideEventChannel_BUDW48oP = () => {};
953
+ var init_wideEventChannel_BABjYpvc = () => {};
1186
954
 
1187
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1188
- function isEvlogError(error) {
1189
- return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1190
- }
1191
- var evlogErrorBrand;
1192
- var init_error_brand_D0_DCPvr = __esm(() => {
1193
- evlogErrorBrand = Symbol.for("evlog.error.brand");
1194
- });
1195
-
1196
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
1197
- var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1198
- var init_error = __esm(() => {
1199
- init_utils();
1200
- init_error_brand_D0_DCPvr();
1201
- evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1202
- evlogErrorDataKey = Symbol.for("evlog.error.data");
1203
- EvlogError = class EvlogError extends Error {
1204
- static isEvlogError(error) {
1205
- return isEvlogError(error);
1206
- }
1207
- code;
1208
- status;
1209
- why;
1210
- fix;
1211
- link;
1212
- get internal() {
1213
- return this[evlogErrorInternalKey];
1214
- }
1215
- constructor(options) {
1216
- const opts = typeof options === "string" ? { message: options } : options;
1217
- super(opts.message, { cause: opts.cause });
1218
- this.name = "EvlogError";
1219
- this.code = opts.code;
1220
- this.status = opts.status ?? 500;
1221
- this.why = opts.why;
1222
- this.fix = opts.fix;
1223
- this.link = opts.link;
1224
- if (opts.internal !== undefined)
1225
- Object.defineProperty(this, evlogErrorInternalKey, {
1226
- value: opts.internal,
1227
- enumerable: false,
1228
- writable: false,
1229
- configurable: true
1230
- });
1231
- if (opts.data !== undefined)
1232
- Object.defineProperty(this, evlogErrorDataKey, {
1233
- value: opts.data,
1234
- enumerable: false,
1235
- writable: false,
1236
- configurable: true
1237
- });
1238
- if (Error.captureStackTrace)
1239
- Error.captureStackTrace(this, EvlogError);
1240
- }
1241
- get statusText() {
1242
- return this.message;
1243
- }
1244
- get statusCode() {
1245
- return this.status;
1246
- }
1247
- get statusMessage() {
1248
- return this.message;
1249
- }
1250
- get data() {
1251
- const extra = this[evlogErrorDataKey];
1252
- if (!extra && !this.code && !this.why && !this.fix && !this.link)
1253
- return;
1254
- return {
1255
- ...extra,
1256
- ...this.code !== undefined && { code: this.code },
1257
- ...this.why !== undefined && { why: this.why },
1258
- ...this.fix !== undefined && { fix: this.fix },
1259
- ...this.link !== undefined && { link: this.link }
1260
- };
955
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/serialize-error-CHmRO35i.mjs
956
+ function payloadFieldsHiddenBy(error) {
957
+ const { toJSON } = error;
958
+ if (typeof toJSON !== "function" || isEvlogError(error))
959
+ return NONE;
960
+ const shown = toJSON.call(error);
961
+ return ["data", "internal"].filter((key) => typeof shown !== "object" || shown === null || !(key in shown));
962
+ }
963
+ function isWrapperOf(error, cause) {
964
+ return cause instanceof Error && cause !== error && cause.message === error.message && cause.stack === error.stack;
965
+ }
966
+ function isH3InputOf(error, cause) {
967
+ if (typeof cause !== "object" || cause === null || cause instanceof Error || Array.isArray(cause))
968
+ return false;
969
+ const keys = Object.keys(cause);
970
+ if (keys.length === 0)
971
+ return false;
972
+ const causeRecord = cause;
973
+ return keys.every((key) => {
974
+ const target = H3_INPUT_FIELDS[key];
975
+ if (!target)
976
+ return false;
977
+ const value = causeRecord[key];
978
+ if (value === undefined || value === readErrorField(error, target))
979
+ return true;
980
+ return target === "statusCode" && Number(value) === readErrorField(error, "statusCode");
981
+ });
982
+ }
983
+ function createErrorSerializer(formatStack = (stack) => stack) {
984
+ function serialize(error, ancestors) {
985
+ const { cause } = error;
986
+ ancestors.add(error);
987
+ if (isWrapperOf(error, cause) && !ancestors.has(cause)) {
988
+ const serialized = serialize(cause, ancestors);
989
+ const hidden = payloadFieldsHiddenBy(error);
990
+ for (const key of [
991
+ "statusCode",
992
+ "statusMessage",
993
+ "data"
994
+ ]) {
995
+ const value = readErrorField(error, key);
996
+ if (value !== undefined && !hidden.includes(key))
997
+ serialized[key] = walk(value, ancestors);
998
+ }
999
+ ancestors.delete(error);
1000
+ return serialized;
1261
1001
  }
1262
- toString() {
1263
- const useColors = isServer();
1264
- const red = useColors ? colors.red : "";
1265
- const yellow = useColors ? colors.yellow : "";
1266
- const cyan = useColors ? colors.cyan : "";
1267
- const dim = useColors ? colors.dim : "";
1268
- const reset = useColors ? colors.reset : "";
1269
- const bold = useColors ? colors.bold : "";
1270
- const lines = [];
1271
- lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1272
- if (this.code)
1273
- lines.push(`${dim}Code:${reset} ${this.code}`);
1274
- if (this.why)
1275
- lines.push(`${yellow}Why:${reset} ${this.why}`);
1276
- if (this.fix)
1277
- lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1278
- if (this.link)
1279
- lines.push(`${dim}More info:${reset} ${this.link}`);
1280
- if (this.cause)
1281
- lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1282
- return lines.join(`
1283
- `);
1002
+ const serialized = {
1003
+ name: error.name,
1004
+ message: error.message,
1005
+ stack: formatStack(error.stack)
1006
+ };
1007
+ const hidden = payloadFieldsHiddenBy(error);
1008
+ for (const key of ERROR_FIELDS) {
1009
+ const value = readErrorField(error, key);
1010
+ if (value !== undefined && !hidden.includes(key))
1011
+ serialized[key] = walk(value, ancestors);
1284
1012
  }
1285
- toJSON() {
1286
- const { data } = this;
1287
- return {
1288
- name: this.name,
1289
- message: this.message,
1290
- status: this.status,
1291
- ...data && { data },
1292
- ...this.cause instanceof Error && { cause: {
1293
- name: this.cause.name,
1294
- message: this.cause.message
1295
- } }
1296
- };
1013
+ if (isH3InputOf(error, cause)) {
1014
+ if (cause.fatal !== undefined)
1015
+ serialized.fatal = cause.fatal;
1016
+ if (cause.unhandled !== undefined)
1017
+ serialized.unhandled = cause.unhandled;
1018
+ } else if (cause !== undefined)
1019
+ serialized.cause = walk(cause, ancestors);
1020
+ ancestors.delete(error);
1021
+ return serialized;
1022
+ }
1023
+ function walk(value, ancestors) {
1024
+ if (value === null || typeof value !== "object")
1025
+ return value;
1026
+ if (ancestors.has(value))
1027
+ return "[Circular]";
1028
+ if (value instanceof Error)
1029
+ return serialize(value, ancestors);
1030
+ if (typeof value.toJSON === "function")
1031
+ return value;
1032
+ ancestors.add(value);
1033
+ let copy;
1034
+ if (Array.isArray(value)) {
1035
+ let items;
1036
+ for (let i = 0;i < value.length; i++) {
1037
+ const item = value[i];
1038
+ const result = walk(item, ancestors);
1039
+ if (items)
1040
+ items[i] = result;
1041
+ else if (!Object.is(result, item))
1042
+ (items = value.slice())[i] = result;
1043
+ }
1044
+ copy = items;
1045
+ } else {
1046
+ const entries = Object.entries(value);
1047
+ let changed = false;
1048
+ for (const entry of entries) {
1049
+ const result = walk(entry[1], ancestors);
1050
+ if (!Object.is(result, entry[1])) {
1051
+ entry[1] = result;
1052
+ changed = true;
1053
+ }
1054
+ }
1055
+ if (changed) {
1056
+ const proto = Object.getPrototypeOf(value);
1057
+ copy = Object.fromEntries(entries);
1058
+ if (proto !== Object.prototype)
1059
+ Object.setPrototypeOf(copy, proto);
1060
+ }
1297
1061
  }
1062
+ ancestors.delete(value);
1063
+ return copy ?? value;
1064
+ }
1065
+ return {
1066
+ serializeError: (error) => serialize(error, /* @__PURE__ */ new WeakSet),
1067
+ serializeErrorsIn: (value) => walk(value, /* @__PURE__ */ new WeakSet)
1068
+ };
1069
+ }
1070
+ var ERROR_FIELDS, NONE, H3_INPUT_FIELDS;
1071
+ var init_serialize_error_CHmRO35i = __esm(() => {
1072
+ init_error_brand_D4i1NkSd();
1073
+ init_utils();
1074
+ ERROR_FIELDS = [
1075
+ "code",
1076
+ "status",
1077
+ "statusText",
1078
+ "statusCode",
1079
+ "statusMessage",
1080
+ "data",
1081
+ "internal",
1082
+ "why",
1083
+ "fix",
1084
+ "link"
1085
+ ];
1086
+ NONE = [];
1087
+ H3_INPUT_FIELDS = {
1088
+ message: "message",
1089
+ stack: "stack",
1090
+ statusCode: "statusCode",
1091
+ status: "statusCode",
1092
+ statusMessage: "statusMessage",
1093
+ statusText: "statusMessage",
1094
+ data: "data",
1095
+ fatal: "fatal",
1096
+ unhandled: "unhandled"
1298
1097
  };
1299
- Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1300
- value: true,
1301
- enumerable: false
1302
- });
1303
1098
  });
1304
1099
 
1305
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1100
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/headers-DpB4nPAJ.mjs
1306
1101
  function extractSafeHeaders(headers) {
1307
1102
  const raw = {};
1308
1103
  headers.forEach((value, key) => {
@@ -1319,36 +1114,359 @@ function extractSafeNodeHeaders(headers) {
1319
1114
  }
1320
1115
  return filterSafeHeaders(raw);
1321
1116
  }
1322
- var init_headers_Bx1ieR_m = __esm(() => {
1117
+ var init_headers_DpB4nPAJ = __esm(() => {
1323
1118
  init_utils();
1324
1119
  });
1325
1120
 
1326
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
1327
- function writePrettyStdout(text) {
1328
- (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1121
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/audit-D3F0XCdQ.mjs
1122
+ function normalizeRedactPathPattern(pattern) {
1123
+ if (!pattern.includes("*") && !pattern.includes("."))
1124
+ return `**.${pattern}`;
1125
+ return pattern;
1126
+ }
1127
+ function compileRedactPathMatchers(patterns) {
1128
+ if (!patterns?.length)
1129
+ return;
1130
+ const exactPaths = /* @__PURE__ */ new Set;
1131
+ const pathGlobs = [];
1132
+ const keyGlobs = [];
1133
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
1134
+ for (const raw of patterns) {
1135
+ if (!raw.includes("*")) {
1136
+ if (raw.includes("."))
1137
+ exactPaths.add(raw);
1138
+ else
1139
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
1140
+ continue;
1141
+ }
1142
+ if (!raw.includes("."))
1143
+ keyGlobs.push(globToRegExp(raw, "."));
1144
+ else
1145
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
1146
+ }
1147
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
1148
+ return;
1149
+ return {
1150
+ exactPaths,
1151
+ pathGlobs,
1152
+ keyGlobs,
1153
+ caseInsensitiveLeaves
1154
+ };
1155
+ }
1156
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
1157
+ pathGlobs.push(globToRegExp(pattern, "."));
1158
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
1159
+ if (leaf) {
1160
+ exactPaths.add(leaf[1]);
1161
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
1162
+ }
1163
+ }
1164
+ function matchesRedactPath(fullPath, leafKey, matchers) {
1165
+ if (matchers.exactPaths.has(fullPath))
1166
+ return true;
1167
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
1168
+ return true;
1169
+ for (const glob of matchers.pathGlobs) {
1170
+ glob.lastIndex = 0;
1171
+ if (glob.test(fullPath))
1172
+ return true;
1173
+ }
1174
+ for (const glob of matchers.keyGlobs) {
1175
+ glob.lastIndex = 0;
1176
+ if (glob.test(leafKey))
1177
+ return true;
1178
+ }
1179
+ return false;
1180
+ }
1181
+ function resolveReplacement(replacement, matched, ctx) {
1182
+ if (typeof replacement === "string")
1183
+ return replacement;
1184
+ try {
1185
+ const result = replacement(matched, ctx);
1186
+ if (typeof result !== "string") {
1187
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
1188
+ return DEFAULT_REPLACEMENT;
1189
+ }
1190
+ return result;
1191
+ } catch (err) {
1192
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
1193
+ return DEFAULT_REPLACEMENT;
1194
+ }
1195
+ }
1196
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
1197
+ if (obj === null || obj === undefined)
1198
+ return;
1199
+ if (Array.isArray(obj)) {
1200
+ for (let i = 0;i < obj.length; i++) {
1201
+ const segment = String(i);
1202
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
1203
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
1204
+ }
1205
+ return;
1206
+ }
1207
+ if (typeof obj === "object") {
1208
+ const record = obj;
1209
+ for (const key of redactableKeys(record)) {
1210
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1211
+ if (matchesRedactPath(fullPath, key, matchers))
1212
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
1213
+ path: fullPath,
1214
+ key
1215
+ }), fullPath);
1216
+ else
1217
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
1218
+ }
1219
+ }
1220
+ }
1221
+ function redactableKeys(record) {
1222
+ return Object.keys(record);
1223
+ }
1224
+ function setRedacted(record, key, value, path) {
1225
+ if (Reflect.set(record, key, value))
1226
+ return;
1227
+ const desc = Object.getOwnPropertyDescriptor(record, key);
1228
+ if (desc && "value" in desc && desc.configurable) {
1229
+ Object.defineProperty(record, key, {
1230
+ ...desc,
1231
+ value
1232
+ });
1233
+ return;
1234
+ }
1235
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
1236
+ }
1237
+ function redactSecretKeys(obj, replacement, prefix = "") {
1238
+ if (obj === null || typeof obj !== "object")
1239
+ return;
1240
+ if (Array.isArray(obj)) {
1241
+ for (let i = 0;i < obj.length; i++)
1242
+ redactSecretKeys(obj[i], replacement, prefix ? `${prefix}.${i}` : String(i));
1243
+ return;
1244
+ }
1245
+ const record = obj;
1246
+ for (const key of redactableKeys(record)) {
1247
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1248
+ const value = record[key];
1249
+ if (SECRET_KEY.test(key) && value !== null && value !== undefined && typeof value !== "boolean")
1250
+ setRedacted(record, key, resolveReplacement(replacement, value, {
1251
+ path: fullPath,
1252
+ key
1253
+ }), fullPath);
1254
+ else
1255
+ redactSecretKeys(value, replacement, fullPath);
1256
+ }
1257
+ }
1258
+ function resolveRedactConfig(input) {
1259
+ if (input === undefined || input === false)
1260
+ return;
1261
+ if (input === true)
1262
+ return {
1263
+ _maskers: allBuiltinMaskers(),
1264
+ _secretKeys: true
1265
+ };
1266
+ if (input.builtins === false)
1267
+ return {
1268
+ ...input,
1269
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1270
+ };
1271
+ const { builtins } = input;
1272
+ const maskers = Array.isArray(builtins) ? Object.keys(builtinPatterns).filter((name) => builtins.includes(name)).map((name) => builtinPatterns[name]).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1273
+ return {
1274
+ ...input,
1275
+ _maskers: maskers,
1276
+ _secretKeys: !Array.isArray(input.builtins) || input.builtins.includes("secrets"),
1277
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1278
+ };
1279
+ }
1280
+ function allBuiltinMaskers() {
1281
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
1282
+ }
1283
+ function cloneRegex(re) {
1284
+ return new RegExp(re.source, re.flags);
1285
+ }
1286
+ function markGloballyRedacted(event) {
1287
+ Object.defineProperty(event, globallyRedacted, {
1288
+ value: true,
1289
+ enumerable: false,
1290
+ configurable: true
1291
+ });
1292
+ }
1293
+ function isGloballyRedacted(event) {
1294
+ return Reflect.has(event, globallyRedacted);
1295
+ }
1296
+ function cloneForRedaction(event) {
1297
+ try {
1298
+ return structuredClone(event);
1299
+ } catch {
1300
+ try {
1301
+ return JSON.parse(JSON.stringify(event));
1302
+ } catch {
1303
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
1304
+ return { ...event };
1305
+ }
1306
+ }
1307
+ }
1308
+ function redactEvent(event, config) {
1309
+ const clone = cloneForRedaction(event);
1310
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
1311
+ if (config.transform)
1312
+ try {
1313
+ config.transform(clone);
1314
+ } catch (err) {
1315
+ console.error("[evlog] redact transform failed:", err);
1316
+ }
1317
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
1318
+ if (pathMatchers)
1319
+ redactPathsInTree(clone, pathMatchers, replacement);
1320
+ if (config._secretKeys)
1321
+ redactSecretKeys(clone, replacement);
1322
+ if (config._maskers?.length)
1323
+ applyMaskersToTree(clone, config._maskers);
1324
+ if (config.patterns?.length)
1325
+ redactPatterns(clone, config.patterns, replacement);
1326
+ return clone;
1327
+ }
1328
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
1329
+ if (obj === null || obj === undefined)
1330
+ return;
1331
+ if (Array.isArray(obj)) {
1332
+ for (let i = 0;i < obj.length; i++) {
1333
+ const key = String(i);
1334
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1335
+ if (typeof obj[i] === "string")
1336
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
1337
+ else if (typeof obj[i] === "object")
1338
+ redactPatterns(obj[i], patterns, replacement, fullPath);
1339
+ }
1340
+ return;
1341
+ }
1342
+ if (typeof obj === "object") {
1343
+ const record = obj;
1344
+ for (const key of redactableKeys(record)) {
1345
+ const val = record[key];
1346
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1347
+ if (typeof val === "string")
1348
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
1349
+ else if (typeof val === "object")
1350
+ redactPatterns(val, patterns, replacement, fullPath);
1351
+ }
1352
+ }
1353
+ }
1354
+ function applyPatterns(value, patterns, replacement, path, key) {
1355
+ let result = value;
1356
+ for (const pattern of patterns) {
1357
+ if (typeof replacement === "string") {
1358
+ result = result.replace(pattern, replacement);
1359
+ continue;
1360
+ }
1361
+ result = result.replace(pattern, (...args) => {
1362
+ const match = args[0];
1363
+ return resolveReplacement(replacement, match, {
1364
+ path,
1365
+ key,
1366
+ groups: captureGroups(args)
1367
+ });
1368
+ });
1369
+ }
1370
+ return result;
1371
+ }
1372
+ function captureGroups(args) {
1373
+ const last = args.at(-1);
1374
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
1375
+ return args.slice(1, Math.max(1, args.length - trailing));
1376
+ }
1377
+ function applyMaskersToTree(obj, maskers) {
1378
+ if (obj === null || obj === undefined)
1379
+ return;
1380
+ if (Array.isArray(obj)) {
1381
+ for (let i = 0;i < obj.length; i++)
1382
+ if (typeof obj[i] === "string")
1383
+ obj[i] = applyMaskers(obj[i], maskers);
1384
+ else if (typeof obj[i] === "object")
1385
+ applyMaskersToTree(obj[i], maskers);
1386
+ return;
1387
+ }
1388
+ if (typeof obj === "object") {
1389
+ const record = obj;
1390
+ for (const key of redactableKeys(record)) {
1391
+ const val = record[key];
1392
+ if (typeof val === "string")
1393
+ setRedacted(record, key, applyMaskers(val, maskers), key);
1394
+ else if (typeof val === "object")
1395
+ applyMaskersToTree(val, maskers);
1396
+ }
1397
+ }
1398
+ }
1399
+ function applyMaskers(value, maskers) {
1400
+ let result = value;
1401
+ for (const [pattern, mask] of maskers)
1402
+ result = result.replace(pattern, mask);
1403
+ return result;
1404
+ }
1405
+ function writeOwnOutput(write) {
1406
+ const global = globalThis;
1407
+ global.__evlogOwnOutput = true;
1408
+ try {
1409
+ write();
1410
+ } finally {
1411
+ global.__evlogOwnOutput = false;
1412
+ }
1329
1413
  }
1330
1414
  function isPlainObject$1(val) {
1331
1415
  return val !== null && typeof val === "object" && !Array.isArray(val);
1332
1416
  }
1417
+ function isPlainRecord(val) {
1418
+ if (!isPlainObject$1(val))
1419
+ return false;
1420
+ const proto = Object.getPrototypeOf(val);
1421
+ return proto === Object.prototype || proto === null;
1422
+ }
1333
1423
  function warnPostEmit(method, detail) {
1334
1424
  console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
1335
1425
  }
1426
+ function setField(target, key, value) {
1427
+ if (key === "__proto__")
1428
+ Reflect.defineProperty(target, key, {
1429
+ value,
1430
+ enumerable: true,
1431
+ writable: true,
1432
+ configurable: true
1433
+ });
1434
+ else
1435
+ Reflect.set(target, key, value);
1436
+ }
1437
+ function writableChild(target, key) {
1438
+ const child = target[key];
1439
+ const copy = { ...child };
1440
+ const { toJSON } = child;
1441
+ if (typeof toJSON === "function" && !Object.hasOwn(copy, "toJSON"))
1442
+ Object.defineProperty(copy, "toJSON", {
1443
+ value: toJSON,
1444
+ enumerable: false,
1445
+ writable: true,
1446
+ configurable: true
1447
+ });
1448
+ setField(target, key, copy);
1449
+ return copy;
1450
+ }
1336
1451
  function mergeInto(target, source) {
1337
1452
  for (const key in source) {
1338
1453
  const sourceVal = source[key];
1339
1454
  if (sourceVal === undefined || sourceVal === null)
1340
1455
  continue;
1341
- const targetVal = target[key];
1456
+ const targetVal = key === "__proto__" && !Object.hasOwn(target, key) ? undefined : target[key];
1342
1457
  if (sourceVal === targetVal)
1343
1458
  continue;
1344
- if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1345
- mergeInto(targetVal, sourceVal);
1459
+ if (isPlainRecord(sourceVal) && isPlainRecord(targetVal))
1460
+ mergeInto(writableChild(target, key), sourceVal);
1346
1461
  else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1347
- target[key] = [...targetVal, ...sourceVal];
1462
+ setField(target, key, [...targetVal, ...sourceVal]);
1348
1463
  else
1349
- Reflect.set(target, key, sourceVal);
1464
+ setField(target, key, sourceVal);
1350
1465
  }
1351
1466
  }
1467
+ function mergeFields(target, fields) {
1468
+ mergeInto(target, serializeErrorsIn(fields));
1469
+ }
1352
1470
  function isAiOnlyFieldUpdate(data) {
1353
1471
  const keys = Object.keys(data);
1354
1472
  return keys.length === 1 && keys[0] === "ai";
@@ -1396,10 +1514,12 @@ function getGlobalDrain() {
1396
1514
  return state.drain;
1397
1515
  }
1398
1516
  function shouldSample(level) {
1517
+ if (level === "fatal")
1518
+ return true;
1399
1519
  const { rates } = state.sampling;
1400
1520
  if (!rates)
1401
- return true;
1402
- const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1521
+ return level !== "trace";
1522
+ const percentage = level === "error" && rates.error === undefined ? 100 : level === "trace" && rates.trace === undefined ? 0 : rates[level] ?? 100;
1403
1523
  if (percentage <= 0)
1404
1524
  return false;
1405
1525
  if (percentage >= 100)
@@ -1420,10 +1540,17 @@ function shouldKeep(ctx) {
1420
1540
  return false;
1421
1541
  });
1422
1542
  }
1543
+ function warnOnceUninitializedProduction() {
1544
+ if (state.initialized || isDev() || state.warnedUninitialized)
1545
+ return;
1546
+ state.warnedUninitialized = true;
1547
+ console.warn("[evlog] running in production without initLogger(). Events are emitted with the default service and environment, without redaction, and no drain is configured so nothing reaches observability. Call initLogger({ drain }) once at startup, or wire a framework hook (evlog:drain).");
1548
+ }
1423
1549
  function emitWideEvent(level, event, options = {}) {
1424
1550
  const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1425
1551
  if (!state.enabled)
1426
1552
  return null;
1553
+ warnOnceUninitializedProduction();
1427
1554
  if (!ownsEvent) {
1428
1555
  if (!isLevelEnabled(level, state.minLevel))
1429
1556
  return null;
@@ -1457,15 +1584,8 @@ function emitWideEvent(level, event, options = {}) {
1457
1584
  formatted = redactEvent(formatted, state.redact);
1458
1585
  markGloballyRedacted(formatted);
1459
1586
  }
1460
- if (!state.silent) {
1461
- if (state.pretty)
1462
- prettyPrintWideEvent(formatted);
1463
- else if (state.stringify)
1464
- console[getConsoleMethod(level)](JSON.stringify(formatted));
1465
- else
1466
- console[getConsoleMethod(level)](formatted);
1467
- }
1468
1587
  if (!deferDrain) {
1588
+ outputWideEvent(formatted);
1469
1589
  publishWideEvent(formatted);
1470
1590
  const drainPromises = [];
1471
1591
  if (state.drain)
@@ -1483,6 +1603,16 @@ function emitWideEvent(level, event, options = {}) {
1483
1603
  }
1484
1604
  return formatted;
1485
1605
  }
1606
+ function outputWideEvent(event) {
1607
+ if (state.silent)
1608
+ return;
1609
+ if (state.pretty)
1610
+ prettyPrintWideEvent(event);
1611
+ else if (state.stringify)
1612
+ writeOwnOutput(() => console[getConsoleMethod(event.level)](JSON.stringify(event)));
1613
+ else
1614
+ writeOwnOutput(() => console[getConsoleMethod(event.level)](event));
1615
+ }
1486
1616
  function emitTaggedLog(level, tag, message) {
1487
1617
  if (!state.enabled)
1488
1618
  return;
@@ -1498,7 +1628,7 @@ function emitTaggedLog(level, tag, message) {
1498
1628
  } else {
1499
1629
  const color = getLevelColor(level);
1500
1630
  const timestamp = isoNow().slice(11, 23);
1501
- console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1631
+ writeOwnOutput(() => console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`));
1502
1632
  }
1503
1633
  return;
1504
1634
  }
@@ -1774,15 +1904,14 @@ function buildAIEntries(ai) {
1774
1904
  function flushPrettyLines(lines) {
1775
1905
  if (lines.length === 0)
1776
1906
  return;
1777
- const text = `${lines.join(`
1778
- `)}
1779
- `;
1780
1907
  if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
1781
- writePrettyStdout(text);
1908
+ writeOwnOutput(() => nativeStdoutWrite(`${lines.join(`
1909
+ `)}
1910
+ `));
1782
1911
  return;
1783
1912
  }
1784
- console.log(lines.join(`
1785
- `));
1913
+ writeOwnOutput(() => console.log(lines.join(`
1914
+ `)));
1786
1915
  }
1787
1916
  function prettyPrintWideEvent(event) {
1788
1917
  const { timestamp, level, service, environment, version, ...rest } = event;
@@ -1889,65 +2018,19 @@ function prettyPrintWideEvent(event) {
1889
2018
  if (!browser && lines.length > 0)
1890
2019
  flushPrettyLines(lines);
1891
2020
  }
1892
- function removeErrorCycles(value, ancestors) {
1893
- if (value === null || typeof value !== "object")
1894
- return value;
1895
- if (ancestors.has(value))
1896
- return "[Circular]";
1897
- ancestors.add(value);
1898
- let changed = false;
1899
- const visit = (item) => {
1900
- const result = removeErrorCycles(item, ancestors);
1901
- if (!Object.is(result, item))
1902
- changed = true;
1903
- return result;
1904
- };
1905
- const copy = Array.isArray(value) ? value.map(visit) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
1906
- ancestors.delete(value);
1907
- return changed ? copy : value;
1908
- }
1909
- function serializeError(err) {
1910
- const errorObj = {
1911
- name: err.name,
1912
- message: err.message,
1913
- stack: isDev() ? compactStackForStorage(err.stack) : err.stack
1914
- };
1915
- const errRecord = err;
1916
- const ancestors = new WeakSet([err]);
1917
- for (const k of [
1918
- "code",
1919
- "status",
1920
- "statusText",
1921
- "statusCode",
1922
- "statusMessage",
1923
- "data",
1924
- "cause",
1925
- "internal"
1926
- ])
1927
- if (k in err)
1928
- errorObj[k] = removeErrorCycles(errRecord[k], ancestors);
1929
- if (EvlogError.isEvlogError(err)) {
1930
- if (err.code)
1931
- errorObj.code = err.code;
1932
- if (err.why)
1933
- errorObj.why = err.why;
1934
- if (err.fix)
1935
- errorObj.fix = err.fix;
1936
- if (err.link)
1937
- errorObj.link = err.link;
1938
- if (err.status)
1939
- errorObj.status = err.status;
1940
- }
1941
- return errorObj;
1942
- }
1943
2021
  function createLogMethod(level) {
1944
- return function logMethod(tagOrEvent, message) {
1945
- if (typeof tagOrEvent === "string" && message !== undefined)
1946
- emitTaggedLog(level, tagOrEvent, message);
1947
- else if (tagOrEvent instanceof Error)
2022
+ return function logMethod(tagOrEvent, message, ...args) {
2023
+ if (typeof tagOrEvent === "string") {
2024
+ if (message === undefined)
2025
+ emitTaggedLog(level, "log", formatMessage(tagOrEvent, args));
2026
+ else if (hasMessageSpecifiers(tagOrEvent))
2027
+ emitTaggedLog(level, "log", formatMessage(tagOrEvent, [message, ...args]));
2028
+ else
2029
+ emitTaggedLog(level, tagOrEvent, formatMessage(message, args));
2030
+ } else if (tagOrEvent instanceof Error)
1948
2031
  emitWideEvent(level, { error: serializeError(tagOrEvent) });
1949
2032
  else if (typeof tagOrEvent === "object")
1950
- emitWideEvent(level, tagOrEvent);
2033
+ emitWideEvent(level, serializeErrorsIn(tagOrEvent));
1951
2034
  else
1952
2035
  emitTaggedLog(level, "log", String(tagOrEvent));
1953
2036
  };
@@ -1958,8 +2041,9 @@ function createLogger(initialContext = {}, internalOptions) {
1958
2041
  const deferDrain = internalOptions?._deferDrain ?? false;
1959
2042
  const waitUntil = internalOptions?.waitUntil;
1960
2043
  const startTime = Date.now();
1961
- const context = { ...initialContext };
2044
+ const context = { ...serializeErrorsIn(initialContext) };
1962
2045
  let hasError = false;
2046
+ let hasFatal = false;
1963
2047
  let hasWarn = false;
1964
2048
  let manualLevel;
1965
2049
  let emitted = false;
@@ -1979,10 +2063,10 @@ function createLogger(initialContext = {}, internalOptions) {
1979
2063
  return;
1980
2064
  }
1981
2065
  const fields = buildAuditFields(input);
1982
- if (!isPlainObject$1(context.audit))
2066
+ if (!isPlainRecord(context.audit))
1983
2067
  context.audit = fields;
1984
2068
  else
1985
- mergeInto(context.audit, fields);
2069
+ mergeInto(writableChild(context, "audit"), fields);
1986
2070
  context._auditForceKeep = true;
1987
2071
  };
1988
2072
  auditMethod.deny = function deny(reason, input) {
@@ -2006,7 +2090,7 @@ function createLogger(initialContext = {}, internalOptions) {
2006
2090
  warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
2007
2091
  return;
2008
2092
  }
2009
- mergeInto(context, data);
2093
+ mergeFields(context, data);
2010
2094
  },
2011
2095
  setLevel(level) {
2012
2096
  if (emitted) {
@@ -2023,13 +2107,25 @@ function createLogger(initialContext = {}, internalOptions) {
2023
2107
  hasError = true;
2024
2108
  const err = typeof error === "string" ? new Error(error) : error;
2025
2109
  if (errorContext)
2026
- mergeInto(context, errorContext);
2110
+ mergeFields(context, errorContext);
2027
2111
  const errorObj = serializeError(err);
2028
- if (isPlainObject$1(context.error))
2029
- mergeInto(context.error, errorObj);
2112
+ if (isPlainRecord(context.error))
2113
+ mergeInto(writableChild(context, "error"), errorObj);
2030
2114
  else
2031
2115
  context.error = errorObj;
2032
2116
  },
2117
+ fatal(message, fatalContext) {
2118
+ if (emitted) {
2119
+ warnPostEmit("log.fatal()", `Keys dropped: ${(fatalContext ? ["message", ...Object.keys(fatalContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2120
+ return;
2121
+ }
2122
+ hasFatal = true;
2123
+ addLog("fatal", message);
2124
+ if (fatalContext) {
2125
+ const { requestLogs: _, ...rest } = fatalContext;
2126
+ mergeFields(context, rest);
2127
+ }
2128
+ },
2033
2129
  info(message, infoContext) {
2034
2130
  if (emitted) {
2035
2131
  warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
@@ -2038,7 +2134,7 @@ function createLogger(initialContext = {}, internalOptions) {
2038
2134
  addLog("info", message);
2039
2135
  if (infoContext) {
2040
2136
  const { requestLogs: _, ...rest } = infoContext;
2041
- mergeInto(context, rest);
2137
+ mergeFields(context, rest);
2042
2138
  }
2043
2139
  },
2044
2140
  warn(message, warnContext) {
@@ -2050,7 +2146,29 @@ function createLogger(initialContext = {}, internalOptions) {
2050
2146
  addLog("warn", message);
2051
2147
  if (warnContext) {
2052
2148
  const { requestLogs: _, ...rest } = warnContext;
2053
- mergeInto(context, rest);
2149
+ mergeFields(context, rest);
2150
+ }
2151
+ },
2152
+ debug(message, debugContext) {
2153
+ if (emitted) {
2154
+ warnPostEmit("log.debug()", `Keys dropped: ${(debugContext ? ["message", ...Object.keys(debugContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2155
+ return;
2156
+ }
2157
+ addLog("debug", message);
2158
+ if (debugContext) {
2159
+ const { requestLogs: _, ...rest } = debugContext;
2160
+ mergeFields(context, rest);
2161
+ }
2162
+ },
2163
+ trace(message, traceContext) {
2164
+ if (emitted) {
2165
+ warnPostEmit("log.trace()", `Keys dropped: ${(traceContext ? ["message", ...Object.keys(traceContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2166
+ return;
2167
+ }
2168
+ addLog("trace", message);
2169
+ if (traceContext) {
2170
+ const { requestLogs: _, ...rest } = traceContext;
2171
+ mergeFields(context, rest);
2054
2172
  }
2055
2173
  },
2056
2174
  emit(overrides) {
@@ -2058,8 +2176,8 @@ function createLogger(initialContext = {}, internalOptions) {
2058
2176
  warnPostEmit("log.emit()", "Ignoring duplicate emit.");
2059
2177
  return null;
2060
2178
  }
2061
- const durationMs = elapsedMs(startTime);
2062
- const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
2179
+ const durationMs = overrides?._durationMs ?? elapsedMs(startTime);
2180
+ const level = manualLevel ?? (hasFatal ? "fatal" : hasError ? "error" : hasWarn ? "warn" : "info");
2063
2181
  let forceKeep = false;
2064
2182
  const auditForceKeep = consumeAuditForceKeep(context);
2065
2183
  if (overrides?._forceKeep)
@@ -2080,9 +2198,9 @@ function createLogger(initialContext = {}, internalOptions) {
2080
2198
  return null;
2081
2199
  }
2082
2200
  if (overrides) {
2083
- const obj = overrides;
2201
+ const obj = serializeErrorsIn(overrides);
2084
2202
  for (const key in obj)
2085
- if (key !== "_forceKeep")
2203
+ if (key !== "_forceKeep" && key !== "_durationMs")
2086
2204
  context[key] = obj[key];
2087
2205
  }
2088
2206
  context.durationMs = durationMs;
@@ -2209,15 +2327,64 @@ function finalizeAudit(event) {
2209
2327
  event.audit = decorated;
2210
2328
  _testCollector?.(decorated, event);
2211
2329
  }
2212
- var nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2213
- var init_audit_C8euLMvu = __esm(() => {
2330
+ var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, SECRET_KEY, globallyRedacted, serializeError, serializeErrorsIn, nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
2331
+ var init_audit_D3F0XCdQ = __esm(() => {
2214
2332
  init_utils();
2215
- init_redact_C7FmdhwI();
2216
- init_globalRegistry_Bh3bIGwA();
2217
- init_pretty_error_D8rlWNL1();
2218
- init_dev_terminal_Brarc6vc();
2219
- init_wideEventChannel_BUDW48oP();
2220
- init_error();
2333
+ init_globalRegistry_DxlJ7DCO();
2334
+ init_pretty_error_DnkXIALi();
2335
+ init_dev_terminal_CDXEC6Wl();
2336
+ init_wideEventChannel_BABjYpvc();
2337
+ init_serialize_error_CHmRO35i();
2338
+ builtinPatterns = {
2339
+ bearer: {
2340
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
2341
+ mask: () => "Bearer ***"
2342
+ },
2343
+ iban: {
2344
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
2345
+ mask: (m) => {
2346
+ const clean = m.replace(/[\s-]/g, "");
2347
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
2348
+ }
2349
+ },
2350
+ creditCard: {
2351
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
2352
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
2353
+ },
2354
+ email: {
2355
+ pattern: /[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})*\.[a-zA-Z]{2,63}\b/g,
2356
+ mask: (m) => {
2357
+ if (m.indexOf("@") < 1)
2358
+ return "***@***";
2359
+ const tld = m.slice(m.lastIndexOf("."));
2360
+ return `${m[0]}***@***${tld}`;
2361
+ }
2362
+ },
2363
+ ipv4: {
2364
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
2365
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
2366
+ },
2367
+ phone: {
2368
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
2369
+ mask: (m) => {
2370
+ const digits = m.replace(/[^\d]/g, "");
2371
+ if (m.startsWith("+") && digits.length > 4) {
2372
+ const ccMatch = m.match(/^\+\d{1,3}/);
2373
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
2374
+ }
2375
+ if (digits.length > 2)
2376
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
2377
+ return "***";
2378
+ }
2379
+ },
2380
+ jwt: {
2381
+ pattern: /\beyJ(?:(?!-eyJ)[\w-])*\.[\w-]*\.[\w-]*\b/g,
2382
+ mask: () => "eyJ***.***"
2383
+ }
2384
+ };
2385
+ SECRET_KEY = /(?:password|passwd|secret|token)$/i;
2386
+ globallyRedacted = Symbol.for("evlog.globallyRedacted");
2387
+ ({ serializeError, serializeErrorsIn } = createErrorSerializer((stack) => isDev() ? compactStackForStorage(stack) : stack));
2221
2388
  nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2222
2389
  pendingDrainState = /* @__PURE__ */ new WeakMap;
2223
2390
  state = globalConfig;
@@ -2225,14 +2392,19 @@ var init_audit_C8euLMvu = __esm(() => {
2225
2392
  info: createLogMethod("info"),
2226
2393
  error: createLogMethod("error"),
2227
2394
  warn: createLogMethod("warn"),
2228
- debug: createLogMethod("debug")
2395
+ debug: createLogMethod("debug"),
2396
+ fatal: createLogMethod("fatal"),
2397
+ trace: createLogMethod("trace")
2229
2398
  };
2230
2399
  noopLogger = {
2231
2400
  set() {},
2232
2401
  setLevel() {},
2233
2402
  error() {},
2403
+ fatal() {},
2234
2404
  info() {},
2235
2405
  warn() {},
2406
+ debug() {},
2407
+ trace() {},
2236
2408
  emit() {
2237
2409
  return null;
2238
2410
  },
@@ -2245,12 +2417,45 @@ var init_audit_C8euLMvu = __esm(() => {
2245
2417
  initLogger(__EVLOG_CONFIG__);
2246
2418
  });
2247
2419
 
2248
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
2420
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/index.mjs
2249
2421
  var init_dist = __esm(() => {
2250
- init_audit_C8euLMvu();
2422
+ init_audit_D3F0XCdQ();
2251
2423
  });
2252
2424
 
2253
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2425
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/errors-Cl1GMJa_.mjs
2426
+ function extractErrorStatus(error) {
2427
+ if (error === null || typeof error !== "object")
2428
+ return 500;
2429
+ const raw = error.status ?? error.statusCode;
2430
+ const status = Number(raw);
2431
+ return Number.isFinite(status) ? status : 500;
2432
+ }
2433
+ var init_errors_Cl1GMJa_ = () => {};
2434
+
2435
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/middleware-fmopETyt.mjs
2436
+ function shouldLog(path, include, exclude) {
2437
+ if (exclude && exclude.length > 0) {
2438
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2439
+ return false;
2440
+ }
2441
+ if (!include || include.length === 0)
2442
+ return true;
2443
+ return include.some((pattern) => matchesPattern(path, pattern));
2444
+ }
2445
+ function getServiceForPath(path, routes) {
2446
+ if (!routes)
2447
+ return;
2448
+ for (const [pattern, config] of Object.entries(routes))
2449
+ if (matchesPattern(path, pattern))
2450
+ return config.service;
2451
+ }
2452
+ function extendDeferredDrain(drainPromise, waitUntil) {
2453
+ drainPromise.catch((err) => {
2454
+ console.error("[evlog] background drain failed:", err);
2455
+ });
2456
+ if (typeof waitUntil === "function")
2457
+ waitUntil(drainPromise);
2458
+ }
2254
2459
  function shouldDeferEmitForResponse(response) {
2255
2460
  if (!response.body)
2256
2461
  return false;
@@ -2328,47 +2533,6 @@ function bindStreamingResponseLifecycle(response, onComplete) {
2328
2533
  headers: response.headers
2329
2534
  });
2330
2535
  }
2331
- var init_streamResponse_OlirMA5P = () => {};
2332
-
2333
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2334
- function extractErrorStatus(error) {
2335
- if (error === null || typeof error !== "object")
2336
- return 500;
2337
- const raw = error.status ?? error.statusCode;
2338
- const status = Number(raw);
2339
- return Number.isFinite(status) ? status : 500;
2340
- }
2341
- var init_errors_CL8dDgIi = () => {};
2342
-
2343
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2344
- function shouldLog(path, include, exclude) {
2345
- if (exclude && exclude.length > 0) {
2346
- if (exclude.some((pattern) => matchesPattern(path, pattern)))
2347
- return false;
2348
- }
2349
- if (!include || include.length === 0)
2350
- return true;
2351
- return include.some((pattern) => matchesPattern(path, pattern));
2352
- }
2353
- function getServiceForPath(path, routes) {
2354
- if (!routes)
2355
- return;
2356
- for (const [pattern, config] of Object.entries(routes))
2357
- if (matchesPattern(path, pattern))
2358
- return config.service;
2359
- }
2360
- function extendDeferredDrain(drainPromise, waitUntil) {
2361
- drainPromise.catch((err) => {
2362
- console.error("[evlog] background drain failed:", err);
2363
- });
2364
- if (typeof waitUntil === "function")
2365
- waitUntil(drainPromise);
2366
- }
2367
- var init_deferred_drain_CfRYimo5 = __esm(() => {
2368
- init_utils();
2369
- });
2370
-
2371
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2372
2536
  function resolveMiddlewarePluginRunner(options) {
2373
2537
  const global = getGlobalPluginRunner();
2374
2538
  const local = options.plugins;
@@ -2418,6 +2582,7 @@ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseSta
2418
2582
  if (runner.hasEnrich)
2419
2583
  await runner.runEnrich(enrichCtx);
2420
2584
  }
2585
+ outputWideEvent(emittedEvent);
2421
2586
  publishWideEvent(emittedEvent);
2422
2587
  markWideEventDrainStarted(emittedEvent);
2423
2588
  const drain = options.drain ?? getGlobalDrain();
@@ -2492,14 +2657,37 @@ function createMiddlewareLogger(options) {
2492
2657
  await performFinish(logger, { status });
2493
2658
  return response;
2494
2659
  }
2495
- return bindStreamingResponseLifecycle(response, async (meta) => {
2496
- await performFinish(logger, {
2497
- status: meta.status ?? status,
2498
- error: meta.error
2660
+ const { waitUntil } = options;
2661
+ if (!waitUntil)
2662
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2663
+ await performFinish(logger, {
2664
+ status: meta.status ?? status,
2665
+ error: meta.error
2666
+ });
2499
2667
  });
2668
+ const drains = [];
2669
+ let markFinished;
2670
+ waitUntil(new Promise((resolve) => {
2671
+ markFinished = resolve;
2672
+ }).then(() => Promise.allSettled(drains)));
2673
+ const drainOptions = {
2674
+ ...options,
2675
+ waitUntil: (promise) => {
2676
+ drains.push(promise);
2677
+ }
2678
+ };
2679
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2680
+ try {
2681
+ await performFinish(logger, {
2682
+ status: meta.status ?? status,
2683
+ error: meta.error
2684
+ }, drainOptions);
2685
+ } finally {
2686
+ markFinished();
2687
+ }
2500
2688
  });
2501
2689
  };
2502
- async function performFinish(requestLogger, opts) {
2690
+ async function performFinish(requestLogger, opts, drainOptions = options) {
2503
2691
  const { status, error } = opts ?? {};
2504
2692
  if (error) {
2505
2693
  requestLogger.error(error);
@@ -2522,9 +2710,16 @@ function createMiddlewareLogger(options) {
2522
2710
  if (pluginRunner.hasKeep)
2523
2711
  await pluginRunner.runKeep(tailCtx);
2524
2712
  const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
2525
- const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
2526
- if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher()))
2527
- await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
2713
+ const emittedEvent = requestLogger.emit({
2714
+ _forceKeep: forceKeep,
2715
+ _durationMs: durationMs
2716
+ });
2717
+ if (emittedEvent) {
2718
+ if (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher())
2719
+ await runEnrichAndDrain(emittedEvent, drainOptions, requestInfo, resolvedStatus, pluginRunner);
2720
+ else
2721
+ outputWideEvent(emittedEvent);
2722
+ }
2528
2723
  if (pluginRunner.hasRequestLifecycle)
2529
2724
  pluginRunner.runOnRequestFinish({
2530
2725
  logger: requestLogger,
@@ -2545,15 +2740,12 @@ function createMiddlewareLogger(options) {
2545
2740
  };
2546
2741
  }
2547
2742
  var noopResult, runnerCache;
2548
- var init_middleware_fam3VyaL = __esm(() => {
2743
+ var init_middleware_fmopETyt = __esm(() => {
2549
2744
  init_utils();
2550
- init_redact_C7FmdhwI();
2551
- init_globalRegistry_Bh3bIGwA();
2552
- init_wideEventChannel_BUDW48oP();
2553
- init_audit_C8euLMvu();
2554
- init_errors_CL8dDgIi();
2555
- init_deferred_drain_CfRYimo5();
2556
- init_streamResponse_OlirMA5P();
2745
+ init_audit_D3F0XCdQ();
2746
+ init_globalRegistry_DxlJ7DCO();
2747
+ init_wideEventChannel_BABjYpvc();
2748
+ init_errors_Cl1GMJa_();
2557
2749
  noopResult = {
2558
2750
  logger: noopLogger,
2559
2751
  finish: () => Promise.resolve(null),
@@ -2563,22 +2755,20 @@ var init_middleware_fam3VyaL = __esm(() => {
2563
2755
  runnerCache = /* @__PURE__ */ new WeakMap;
2564
2756
  });
2565
2757
 
2566
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
2758
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/integration-D9IUwqvW.mjs
2567
2759
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2568
- const log = parent;
2569
- log.fork = (label, fn) => {
2570
- forkBackgroundLogger({
2571
- storage,
2572
- parent,
2573
- middlewareOptions,
2574
- label,
2575
- fn,
2576
- lifecycle
2577
- });
2578
- };
2760
+ parent.fork = (label, fn) => forkBackgroundLogger({
2761
+ storage,
2762
+ parent,
2763
+ middlewareOptions,
2764
+ label,
2765
+ fn,
2766
+ lifecycle
2767
+ });
2579
2768
  }
2580
2769
  function forkBackgroundLogger(options) {
2581
- const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2770
+ const { storage, parent, label, fn, lifecycle } = options;
2771
+ const { waitUntil, ...middlewareOptions } = options.middlewareOptions;
2582
2772
  const parentCtx = parent.getContext();
2583
2773
  const parentRequestId = parentCtx.requestId;
2584
2774
  if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
@@ -2599,26 +2789,36 @@ function forkBackgroundLogger(options) {
2599
2789
  path,
2600
2790
  requestId: child.getContext().requestId
2601
2791
  };
2602
- storage.run(child, () => {
2792
+ const lifetime = storage.run(child, () => {
2603
2793
  lifecycle?.onChildEnter?.(child);
2604
- Promise.resolve().then(() => fn()).then(async () => {
2605
- const emittedEvent = child.emit();
2794
+ return Promise.resolve().then(() => fn()).then(() => {
2606
2795
  const ctxStatus = child.getContext().status;
2607
- const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
2608
- if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2609
- await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2610
- }).catch(async (err) => {
2796
+ return typeof ctxStatus === "number" ? ctxStatus : undefined;
2797
+ }, (err) => {
2611
2798
  const error = err instanceof Error ? err : new Error(String(err));
2799
+ const status = extractErrorStatus(error);
2612
2800
  child.error(error);
2613
- child.set({ status: extractErrorStatus(error) });
2801
+ child.set({ status });
2802
+ return status;
2803
+ }).then(async (status) => {
2614
2804
  const emittedEvent = child.emit();
2615
- const status = extractErrorStatus(error);
2616
- if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2617
- await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2805
+ if (!emittedEvent)
2806
+ return;
2807
+ if (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain())
2808
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, emittedEvent.status ?? status);
2809
+ else
2810
+ outputWideEvent(emittedEvent);
2811
+ }).catch((err) => {
2812
+ console.error("[evlog] log.fork() failed to emit the child event:", err);
2618
2813
  }).finally(() => {
2619
2814
  lifecycle?.onChildExit?.(child);
2620
2815
  });
2621
2816
  });
2817
+ if (waitUntil) {
2818
+ const { settled } = middlewareOptions.drain ?? getGlobalDrain() ?? {};
2819
+ waitUntil(typeof settled === "function" ? lifetime.then(() => settled()) : lifetime);
2820
+ }
2821
+ return lifetime;
2622
2822
  }
2623
2823
  function normalizeHeaders(headers) {
2624
2824
  if (!headers)
@@ -2659,17 +2859,17 @@ function defineFrameworkIntegration(spec) {
2659
2859
  };
2660
2860
  } };
2661
2861
  }
2662
- var init_integration_CGD18W8r = __esm(() => {
2663
- init_audit_C8euLMvu();
2664
- init_headers_Bx1ieR_m();
2665
- init_errors_CL8dDgIi();
2666
- init_middleware_fam3VyaL();
2862
+ var init_integration_D9IUwqvW = __esm(() => {
2863
+ init_audit_D3F0XCdQ();
2864
+ init_headers_DpB4nPAJ();
2865
+ init_errors_Cl1GMJa_();
2866
+ init_middleware_fmopETyt();
2667
2867
  });
2668
2868
 
2669
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
2670
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2869
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/toolkit/storage.mjs
2870
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2671
2871
  function createLoggerStorage(contextHint, id = contextHint) {
2672
- const storage = getSharedStorage(id, () => new AsyncLocalStorage4);
2872
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
2673
2873
  function useLogger() {
2674
2874
  const logger = storage.getStore();
2675
2875
  if (!logger)
@@ -2682,21 +2882,28 @@ function createLoggerStorage(contextHint, id = contextHint) {
2682
2882
  };
2683
2883
  }
2684
2884
  var init_storage = __esm(() => {
2685
- init_globalRegistry_Bh3bIGwA();
2885
+ init_globalRegistry_DxlJ7DCO();
2686
2886
  });
2687
2887
 
2688
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
2888
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/toolkit.mjs
2689
2889
  var init_toolkit = __esm(() => {
2690
- init_integration_CGD18W8r();
2890
+ init_integration_D9IUwqvW();
2691
2891
  init_storage();
2692
2892
  });
2693
2893
 
2694
2894
  // src/server/evlog.ts
2695
- import { Elysia } from "elysia";
2696
- var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2895
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2896
+ import { Elysia as Elysia3 } from "elysia";
2897
+ function getRequestLogger() {
2898
+ const logger = loggerStorage.storage.getStore() ?? requestLogSlots.getStore()?.handle?.logger;
2899
+ return logger ?? loggerStorage.useLogger();
2900
+ }
2901
+ var loggerStorage, requestLogSlots, integration, instanceOptions, runtimeWaitUntil, requestWaitUntil;
2697
2902
  var init_evlog = __esm(() => {
2698
2903
  init_toolkit();
2904
+ init_instance();
2699
2905
  loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2906
+ requestLogSlots = new AsyncLocalStorage4;
2700
2907
  integration = defineFrameworkIntegration({
2701
2908
  attachLogger: () => {
2702
2909
  return;
@@ -2713,8 +2920,11 @@ var init_evlog = __esm(() => {
2713
2920
  name: "furin",
2714
2921
  storage: loggerStorage.storage
2715
2922
  });
2716
- getRequestLogger = loggerStorage.useLogger;
2923
+ instanceOptions = instanceSlot(() => ({
2924
+ options: undefined
2925
+ }));
2717
2926
  runtimeWaitUntil = new Set;
2927
+ requestWaitUntil = new WeakMap;
2718
2928
  });
2719
2929
 
2720
2930
  // src/server/context-logger.ts
@@ -2731,50 +2941,466 @@ var init_context_logger = __esm(() => {
2731
2941
  init_dist();
2732
2942
  init_evlog();
2733
2943
  noopLogger2 = {
2944
+ debug: () => {},
2734
2945
  emit: () => null,
2735
2946
  error: () => {},
2736
- fork: (_label, fn) => fn(),
2947
+ fatal: () => {},
2948
+ fork: async (_label, fn) => {
2949
+ await fn();
2950
+ },
2737
2951
  getContext: () => ({}),
2738
2952
  info: () => {},
2739
2953
  set: () => {},
2740
2954
  setLevel: () => {},
2955
+ trace: () => {},
2741
2956
  warn: () => {}
2742
2957
  };
2743
- syntheticRenderStorage = new AsyncLocalStorage5;
2958
+ syntheticRenderStorage = new AsyncLocalStorage5;
2959
+ });
2960
+
2961
+ // src/server/sync/config.ts
2962
+ function syncRuntimeOptions(sync) {
2963
+ return sync;
2964
+ }
2965
+ var init_config = () => {};
2966
+
2967
+ // src/server/sync/connection.ts
2968
+ async function verifiedSyncPrincipal(sync, context) {
2969
+ try {
2970
+ const principal = await sync.principal(context);
2971
+ return principal.length > 0 ? principal : undefined;
2972
+ } catch {
2973
+ return;
2974
+ }
2975
+ }
2976
+ function releaseLease(lease) {
2977
+ try {
2978
+ lease?.release();
2979
+ } catch (error) {
2980
+ _log.warn({ action: "sync_connection_release_failed", error: String(error) });
2981
+ }
2982
+ }
2983
+ function createSyncConnectionLifetime(sync, context, changed) {
2984
+ let closed = false;
2985
+ let lease;
2986
+ const onAbort = () => {
2987
+ if (!closed) {
2988
+ changed();
2989
+ }
2990
+ };
2991
+ return {
2992
+ async acquire() {
2993
+ if (closed) {
2994
+ return;
2995
+ }
2996
+ const acquired = await sync.connection?.(context);
2997
+ if (closed) {
2998
+ releaseLease(acquired);
2999
+ return;
3000
+ }
3001
+ lease = acquired;
3002
+ lease?.signal.addEventListener("abort", onAbort, { once: true });
3003
+ if (lease?.signal.aborted) {
3004
+ onAbort();
3005
+ }
3006
+ },
3007
+ close() {
3008
+ if (closed) {
3009
+ return;
3010
+ }
3011
+ closed = true;
3012
+ lease?.signal.removeEventListener("abort", onAbort);
3013
+ releaseLease(lease);
3014
+ lease = undefined;
3015
+ }
3016
+ };
3017
+ }
3018
+ var LOCAL_SYNC_CONNECTION;
3019
+ var init_connection = __esm(() => {
3020
+ init_dist();
3021
+ LOCAL_SYNC_CONNECTION = Symbol.for("furin.sync.local-connection.v1");
3022
+ });
3023
+
3024
+ // src/server/sync/notifier.ts
3025
+ class PollingSyncNotifier {
3026
+ recovery = "self";
3027
+ adapter;
3028
+ intervalMs;
3029
+ listeners = new Set;
3030
+ cursor;
3031
+ initialization;
3032
+ polling;
3033
+ revision = 0;
3034
+ timer;
3035
+ constructor(adapter, intervalMs) {
3036
+ this.adapter = adapter;
3037
+ this.intervalMs = intervalMs;
3038
+ }
3039
+ publish(cursor) {
3040
+ this.revision += 1;
3041
+ this.emit(cursor);
3042
+ return Promise.resolve();
3043
+ }
3044
+ async subscribe(listener) {
3045
+ const subscription = { listener };
3046
+ this.listeners.add(subscription);
3047
+ try {
3048
+ await this.start();
3049
+ } catch (error) {
3050
+ this.listeners.delete(subscription);
3051
+ throw error;
3052
+ }
3053
+ return {
3054
+ unsubscribe: () => {
3055
+ this.listeners.delete(subscription);
3056
+ if (this.listeners.size === 0 && this.timer) {
3057
+ clearTimeout(this.timer);
3058
+ this.timer = undefined;
3059
+ }
3060
+ return Promise.resolve();
3061
+ }
3062
+ };
3063
+ }
3064
+ emit(cursor) {
3065
+ if (cursor === this.cursor) {
3066
+ return;
3067
+ }
3068
+ this.cursor = cursor;
3069
+ for (const subscription of [...this.listeners]) {
3070
+ try {
3071
+ subscription.listener(cursor);
3072
+ } catch {}
3073
+ }
3074
+ }
3075
+ async poll() {
3076
+ const { revision } = this;
3077
+ try {
3078
+ const cursor = await this.adapter.currentCursor();
3079
+ if (revision === this.revision && this.listeners.size > 0) {
3080
+ this.emit(cursor);
3081
+ }
3082
+ } catch {}
3083
+ }
3084
+ async start() {
3085
+ if (this.timer || this.polling) {
3086
+ return;
3087
+ }
3088
+ if (!this.initialization) {
3089
+ const { revision } = this;
3090
+ this.initialization = this.adapter.currentCursor().then((cursor) => {
3091
+ if (revision === this.revision) {
3092
+ this.cursor = cursor;
3093
+ }
3094
+ }).finally(() => {
3095
+ this.initialization = undefined;
3096
+ });
3097
+ }
3098
+ await this.initialization;
3099
+ this.schedulePoll();
3100
+ }
3101
+ schedulePoll() {
3102
+ if (this.listeners.size === 0 || this.timer || this.polling) {
3103
+ return;
3104
+ }
3105
+ this.timer = setTimeout(() => {
3106
+ this.timer = undefined;
3107
+ this.polling = this.poll().finally(() => {
3108
+ this.polling = undefined;
3109
+ this.schedulePoll();
3110
+ });
3111
+ }, this.intervalMs);
3112
+ this.timer.unref?.();
3113
+ }
3114
+ }
3115
+
3116
+ // src/server/sync/principal-journal.ts
3117
+ function configurePrincipalSecret(adapter, secret, development) {
3118
+ if (secret !== undefined && (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH)) {
3119
+ throw new Error(`[furin] sync.secret must be a string of at least ${MIN_SECRET_LENGTH} characters.`);
3120
+ }
3121
+ if (principalSecrets.has(adapter)) {
3122
+ if (principalSecrets.get(adapter) !== secret) {
3123
+ throw new Error("[furin] Sync runtimes sharing a SyncAdapter must use the same secret.");
3124
+ }
3125
+ return;
3126
+ }
3127
+ principalSecrets.set(adapter, secret);
3128
+ if (secret === undefined && !development) {
3129
+ console.warn("[furin] sync.secret is not set: principal hashes sent to browsers and stored in the sync journal are unkeyed SHA-256 and can be reversed with a dictionary. Set sync.secret to a random value of at least 32 characters.");
3130
+ }
3131
+ }
3132
+ function principalHash(adapter, principal) {
3133
+ const secret = principalSecrets.get(adapter);
3134
+ const hasher = secret === undefined ? new Bun.CryptoHasher("sha256") : new Bun.CryptoHasher("sha256", secret);
3135
+ return hasher.update(principal).digest("hex");
3136
+ }
3137
+ async function readPrincipalChanges(adapter, input, principal) {
3138
+ if (principalJournals.has(adapter)) {
3139
+ const page = await adapter.readChanges(input);
3140
+ const hash = principalHash(adapter, principal);
3141
+ if (page.changes.every((change) => changePrincipals.get(change) === hash)) {
3142
+ return page;
3143
+ }
3144
+ }
3145
+ const cursor = await adapter.currentCursor();
3146
+ return {
3147
+ changes: [],
3148
+ cursor,
3149
+ hasMore: false,
3150
+ reset: input.after !== undefined && input.after !== cursor
3151
+ };
3152
+ }
3153
+ var MIN_SECRET_LENGTH = 32, principalJournals, changePrincipals, principalSecrets;
3154
+ var init_principal_journal = __esm(() => {
3155
+ principalJournals = new WeakSet;
3156
+ changePrincipals = new WeakMap;
3157
+ principalSecrets = new WeakMap;
2744
3158
  });
2745
3159
 
2746
- // src/server/runtime-env.ts
2747
- var IS_DEV = true;
2748
-
2749
3160
  // src/server/sync/runtime.ts
2750
- function resolveSyncRuntime(options) {
2751
- if (!IS_DEV && options.adapter.scope === "process-local") {
2752
- throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
3161
+ import { inAotBuild } from "elysia";
3162
+ function publishCursor(runtime, cursor) {
3163
+ const alreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
3164
+ if (!alreadyPublished) {
3165
+ runtime.notifier.publish(cursor).catch(() => {
3166
+ return;
3167
+ });
2753
3168
  }
2754
- if (options.notifier) {
2755
- if (options.adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && options.adapter.notificationChannel !== options.notifier.notificationChannel) {
2756
- throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
3169
+ }
3170
+ function prepareSyncRuntime(options, development) {
3171
+ if (inAotBuild()) {
3172
+ return;
3173
+ }
3174
+ if (typeof options.adapter === "function" && !factoryAdapters.has(options)) {
3175
+ const adapter = options.adapter();
3176
+ if (adapter instanceof Promise) {
3177
+ throw new Error("[furin] Sync adapter factories must return an adapter synchronously.");
2757
3178
  }
2758
- return { adapter: options.adapter, notifier: options.notifier };
3179
+ factoryAdapters.set(options, adapter);
3180
+ }
3181
+ resolveSyncRuntime(options, development);
3182
+ }
3183
+ function resolveSyncRuntime(options, development) {
3184
+ if (inAotBuild()) {
3185
+ throw new Error("[furin] Sync runtime is unavailable during AOT compilation.");
3186
+ }
3187
+ const existingRuntime = runtimes.get(options)?.get(development);
3188
+ if (existingRuntime) {
3189
+ return existingRuntime;
3190
+ }
3191
+ const adapter = typeof options.adapter === "function" ? factoryAdapters.get(options) : options.adapter;
3192
+ if (!adapter) {
3193
+ throw new Error("[furin] Compose furinSync(sync) or furin({ sync }) before using a Sync adapter factory.");
3194
+ }
3195
+ if (!development && adapter.scope === "process-local") {
3196
+ throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
3197
+ }
3198
+ configurePrincipalSecret(adapter, options.secret, development);
3199
+ if (options.notifier && adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && adapter.notificationChannel !== options.notifier.notificationChannel) {
3200
+ throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
2759
3201
  }
2760
- if (!IS_DEV && options.adapter.scope === "distributed") {
3202
+ if (!(options.notifier || development) && adapter.scope === "distributed") {
2761
3203
  throw new Error("[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback.");
2762
3204
  }
2763
- const existing = pollingNotifiers.get(options.adapter);
2764
- if (existing) {
2765
- return { adapter: options.adapter, notifier: existing };
3205
+ let notifier = options.notifier ?? pollingNotifiers.get(adapter);
3206
+ if (!notifier) {
3207
+ const polling = new PollingSyncNotifier(adapter, POLL_INTERVAL_MS);
3208
+ pollingNotifiers.set(adapter, polling);
3209
+ notifier = polling;
3210
+ }
3211
+ const runtime = { adapter, development, notifier };
3212
+ let modes = runtimes.get(options);
3213
+ if (!modes) {
3214
+ modes = new Map;
3215
+ runtimes.set(options, modes);
2766
3216
  }
2767
- const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
2768
- pollingNotifiers.set(options.adapter, notifier);
2769
- return { adapter: options.adapter, notifier };
3217
+ modes.set(development, runtime);
3218
+ return runtime;
2770
3219
  }
2771
- var POLL_INTERVAL_MS = 250, pollingNotifiers;
3220
+ var POLL_INTERVAL_MS = 250, pollingNotifiers, factoryAdapters, runtimes;
2772
3221
  var init_runtime = __esm(() => {
3222
+ init_principal_journal();
2773
3223
  pollingNotifiers = new WeakMap;
3224
+ factoryAdapters = new WeakMap;
3225
+ runtimes = new WeakMap;
3226
+ });
3227
+
3228
+ // src/server/sync/queries.ts
3229
+ function isMutationMethod(method) {
3230
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
3231
+ }
3232
+ function markInternalRead(request) {
3233
+ internalReads.add(request);
3234
+ }
3235
+ function isInternalRead(request) {
3236
+ return internalReads.has(request);
3237
+ }
3238
+ function sealInvalidations(request) {
3239
+ sealed.add(request);
3240
+ }
3241
+ function requestInvalidate(request) {
3242
+ return (target, params) => {
3243
+ if (!isMutationMethod(request.method)) {
3244
+ throw new Error(`[furin] invalidate() was called while handling a ${request.method}: only a mutation invalidates.`);
3245
+ }
3246
+ if (sealed.has(request)) {
3247
+ if (IS_DEV) {
3248
+ throw new Error("[furin] invalidate() was called after mutation() resolved: call it inside the mutation() callback to commit it with the transaction.");
3249
+ }
3250
+ return;
3251
+ }
3252
+ let invalidations = collected.get(request);
3253
+ if (!invalidations) {
3254
+ invalidations = { queries: [], rules: [] };
3255
+ collected.set(request, invalidations);
3256
+ }
3257
+ if (typeof target !== "string") {
3258
+ invalidations.rules.push(target);
3259
+ return;
3260
+ }
3261
+ const identity = { id: target, scope: params ?? {} };
3262
+ queryTag(identity);
3263
+ invalidations.queries.push(identity);
3264
+ };
3265
+ }
3266
+ function urlIdentity(context) {
3267
+ const scope = Object.fromEntries(Object.entries(context.params ?? {}).filter(([, value]) => value !== undefined));
3268
+ return { id: context.route ?? context.path, scope };
3269
+ }
3270
+ function resolveSyncInvalidations(context) {
3271
+ const invalidations = collected.get(context.request);
3272
+ return [
3273
+ ...invalidations?.rules ?? [],
3274
+ { tags: [...invalidations?.queries ?? [], urlIdentity(context)].map(queryTag) }
3275
+ ];
3276
+ }
3277
+ function appendQueryInvalidations(input, context) {
3278
+ if (input === undefined) {
3279
+ return;
3280
+ }
3281
+ const queries = [];
3282
+ for (const rule of Array.isArray(input) ? input : [input]) {
3283
+ for (const tag of rule.tags ?? []) {
3284
+ const identity = queryFromTag(tag);
3285
+ if (identity) {
3286
+ queries.push(identity);
3287
+ }
3288
+ }
3289
+ }
3290
+ if (queries.length > 0) {
3291
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
3292
+ }
3293
+ }
3294
+ var collected, sealed, internalReads;
3295
+ var init_queries = __esm(() => {
3296
+ collected = new WeakMap;
3297
+ sealed = new WeakSet;
3298
+ internalReads = new WeakSet;
2774
3299
  });
2775
3300
 
2776
3301
  // src/server/sync/stream.ts
2777
- import { Elysia as Elysia2 } from "elysia";
3302
+ import { Elysia as Elysia4 } from "elysia";
3303
+ function trackUnsubscription(subscription) {
3304
+ const existing = unsubscriptions.get(subscription);
3305
+ if (existing) {
3306
+ return existing;
3307
+ }
3308
+ const pending = subscription.unsubscribe();
3309
+ unsubscriptions.set(subscription, pending);
3310
+ pendingUnsubscriptions.add(pending);
3311
+ pending.finally(() => pendingUnsubscriptions.delete(pending)).catch(() => {
3312
+ return;
3313
+ });
3314
+ return pending;
3315
+ }
3316
+ function broadcastState(state) {
3317
+ state.broadcast = undefined;
3318
+ if (state.cursor === state.latest) {
3319
+ return;
3320
+ }
3321
+ state.cursor = state.latest;
3322
+ for (const listener of state.listeners) {
3323
+ try {
3324
+ listener(state.cursor);
3325
+ } catch {}
3326
+ }
3327
+ }
3328
+ function notifyState(state, cursor) {
3329
+ state.latest = cursor;
3330
+ if (state.broadcast || state.cursor === cursor) {
3331
+ return;
3332
+ }
3333
+ state.broadcast = setTimeout(() => broadcastState(state), BROADCAST_WINDOW_MS);
3334
+ state.broadcast.unref?.();
3335
+ }
3336
+ function stopState(state) {
3337
+ clearInterval(state.safetyPoll);
3338
+ clearTimeout(state.broadcast);
3339
+ }
3340
+ async function createCursorState(runtime) {
3341
+ const state = {};
3342
+ state.cursor = await runtime.adapter.currentCursor();
3343
+ state.latest = state.cursor;
3344
+ state.broadcast = undefined;
3345
+ state.listeners = new Set;
3346
+ state.safetyPoll = undefined;
3347
+ let subscriptionFailed = false;
3348
+ state.subscription = await runtime.notifier.subscribe((cursor) => notifyState(state, cursor)).catch(() => {
3349
+ subscriptionFailed = true;
3350
+ return noOpSubscription;
3351
+ });
3352
+ if (runtime.notifier.recovery !== "self" || subscriptionFailed) {
3353
+ const interval = runtime.development ? DEVELOPMENT_SAFETY_POLL_INTERVAL_MS : PRODUCTION_SAFETY_POLL_INTERVAL_MS;
3354
+ state.safetyPoll = setInterval(() => {
3355
+ runtime.adapter.currentCursor().then((cursor) => notifyState(state, cursor)).catch(() => {
3356
+ return;
3357
+ });
3358
+ }, interval);
3359
+ state.safetyPoll.unref?.();
3360
+ }
3361
+ resolvedStates.add(state);
3362
+ return state;
3363
+ }
3364
+ async function subscribeSyncCursor(options, development, listener) {
3365
+ const runtime = resolveSyncRuntime(syncRuntimeOptions(options), development);
3366
+ const statePromise = getCursorState(runtime);
3367
+ const state = await statePromise;
3368
+ state.listeners.add(listener);
3369
+ listener(state.cursor);
3370
+ let subscribed = true;
3371
+ return {
3372
+ unsubscribe: () => {
3373
+ if (!subscribed) {
3374
+ return;
3375
+ }
3376
+ subscribed = false;
3377
+ state.listeners.delete(listener);
3378
+ if (state.listeners.size > 0) {
3379
+ return;
3380
+ }
3381
+ if (cursorStates.get(runtime.adapter) === statePromise) {
3382
+ cursorStates.delete(runtime.adapter);
3383
+ }
3384
+ resolvedStates.delete(state);
3385
+ stopState(state);
3386
+ trackUnsubscription(state.subscription);
3387
+ }
3388
+ };
3389
+ }
3390
+ function getCursorState(runtime) {
3391
+ const existing = cursorStates.get(runtime.adapter);
3392
+ if (existing) {
3393
+ return existing;
3394
+ }
3395
+ const state = createCursorState(runtime);
3396
+ cursorStates.set(runtime.adapter, state);
3397
+ state.catch(() => {
3398
+ if (cursorStates.get(runtime.adapter) === state) {
3399
+ cursorStates.delete(runtime.adapter);
3400
+ }
3401
+ });
3402
+ return state;
3403
+ }
2778
3404
  function parseChangeQuery(request) {
2779
3405
  const url = new URL(request.url);
2780
3406
  const after = url.searchParams.get("after") ?? undefined;
@@ -2792,86 +3418,59 @@ function parseChangeQuery(request) {
2792
3418
  return { after, limit };
2793
3419
  }
2794
3420
  function createSyncChangesPlugin(options) {
3421
+ return createRuntimeSyncChangesPlugin(options, IS_DEV);
3422
+ }
3423
+ function createRuntimeSyncChangesPlugin(options, development) {
2795
3424
  const syncPath = options.path ?? defaultSyncPath;
2796
- const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
2797
- return new Elysia2({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
3425
+ prepareSyncRuntime(options, development);
3426
+ return new Elysia4({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
3427
+ const runtime = resolveSyncRuntime(options, development);
2798
3428
  const { request, set } = context;
3429
+ markInternalRead(request);
2799
3430
  set.headers["cache-control"] = "no-store";
2800
3431
  const query = parseChangeQuery(request);
2801
3432
  if ("error" in query) {
2802
3433
  return query.error;
2803
3434
  }
2804
- const principal = await options.principal(context);
2805
- if (principal.length === 0) {
3435
+ const principal = await verifiedSyncPrincipal(options, context);
3436
+ if (principal === undefined) {
2806
3437
  return new Response("Unauthorized", { status: 401 });
2807
3438
  }
2808
- const cursor = await runtime.adapter.currentCursor();
2809
- return {
2810
- changes: [],
2811
- cursor,
2812
- hasMore: false,
2813
- reset: query.after !== undefined && query.after !== cursor
2814
- };
3439
+ set.headers["x-furin-sync-session"] = principalHash(runtime.adapter, principal);
3440
+ const connect = request[LOCAL_SYNC_CONNECTION];
3441
+ if (connect) {
3442
+ await connect(context, options);
3443
+ return new Response(null, { status: 204 });
3444
+ }
3445
+ return readPrincipalChanges(runtime.adapter, query, principal);
2815
3446
  });
2816
3447
  }
2817
- var DEFAULT_CHANGE_LIMIT = 100, MAX_CHANGE_LIMIT = 500, MAX_CURSOR_LENGTH = 128, UNSIGNED_INTEGER_PATTERN, defaultSyncPath = "/_furin/sync", cursorStates, resolvedStates, pendingUnsubscriptions, unsubscriptions;
3448
+ var BROADCAST_WINDOW_MS = 100, DEFAULT_CHANGE_LIMIT = 100, MAX_CHANGE_LIMIT = 500, MAX_CURSOR_LENGTH = 128, DEVELOPMENT_SAFETY_POLL_INTERVAL_MS = 250, PRODUCTION_SAFETY_POLL_INTERVAL_MS = 15000, UNSIGNED_INTEGER_PATTERN, defaultSyncPath = "/_furin/sync", noOpSubscription, cursorStates, resolvedStates, pendingUnsubscriptions, unsubscriptions;
2818
3449
  var init_stream = __esm(() => {
2819
3450
  init_config();
3451
+ init_connection();
3452
+ init_principal_journal();
3453
+ init_queries();
2820
3454
  init_runtime();
2821
3455
  UNSIGNED_INTEGER_PATTERN = /^\d+$/;
3456
+ noOpSubscription = {
3457
+ unsubscribe: () => Promise.resolve()
3458
+ };
2822
3459
  cursorStates = new Map;
2823
3460
  resolvedStates = new Set;
2824
3461
  pendingUnsubscriptions = new Set;
2825
3462
  unsubscriptions = new WeakMap;
2826
3463
  });
3464
+ // src/server/auto-invalidate/runtime.ts
3465
+ init_invalidation_header();
3466
+ init_prefix();
2827
3467
 
2828
- // src/server/sync/index.ts
2829
- init_config();
2830
-
2831
- // src/server/sync/plugin.ts
2832
- import { Elysia as Elysia3, ElysiaStatus as ElysiaStatus3 } from "elysia";
2833
-
2834
- // src/shared/sync-query.ts
2835
- function serializeQueryHeader(identity) {
2836
- return JSON.stringify(identity).replace(/[^\u0020-\u007e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
2837
- }
2838
- var PREFIX = "__furin.query:";
2839
- function queryTag(identity) {
2840
- for (const [key, value] of Object.entries(identity.scope)) {
2841
- if (value === undefined) {
2842
- throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
2843
- }
2844
- }
2845
- return PREFIX + JSON.stringify([
2846
- identity.id,
2847
- Object.entries(identity.scope).sort(([a], [b]) => {
2848
- if (a === b) {
2849
- return 0;
2850
- }
2851
- return a < b ? -1 : 1;
2852
- })
2853
- ]);
2854
- }
2855
- function queryFromTag(tag) {
2856
- if (!tag.startsWith(PREFIX)) {
2857
- return;
2858
- }
2859
- try {
2860
- const value = JSON.parse(tag.slice(PREFIX.length));
2861
- if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !Array.isArray(value[1]) || value[1].some((entry) => !Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !(entry[1] === null || typeof entry[1] === "string" || typeof entry[1] === "number" || typeof entry[1] === "boolean"))) {
2862
- return;
2863
- }
2864
- return { id: value[0], scope: Object.fromEntries(value[1]) };
2865
- } catch {}
2866
- }
3468
+ // src/server/cache/invalidation.ts
3469
+ init_invalidation_header();
3470
+ init_prefix();
2867
3471
 
2868
- // src/shared/prefix.ts
2869
- function physicalPath(prefix, path) {
2870
- if (prefix === "") {
2871
- return path;
2872
- }
2873
- return path === "/" ? prefix : `${prefix}${path}`;
2874
- }
3472
+ // src/server/devtools/instrumentation.ts
3473
+ import { Elysia as Elysia2 } from "elysia";
2875
3474
 
2876
3475
  // src/devtools/protocol.ts
2877
3476
  var DEVTOOLS_PROTOCOL_VERSION = 2;
@@ -2885,7 +3484,7 @@ function devtoolsInstanceId() {
2885
3484
  return Bun.hash(`${instance.prefix}\x00${instance.pagesDir}`).toString(16);
2886
3485
  }
2887
3486
  function appendDevtoolsEvent(event) {
2888
- const hub = instanceDevtoolsHub();
3487
+ const hub = instanceDevtoolsHub(currentInstance());
2889
3488
  hub.sequence += 1;
2890
3489
  const complete = {
2891
3490
  ...event,
@@ -2990,14 +3589,14 @@ class AutoInvalidateRegistry {
2990
3589
  }
2991
3590
  var instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
2992
3591
  function getAutoInvalidateRegistry(instance) {
2993
- return instanceAutoInvalidateRegistry(instance);
3592
+ return instanceAutoInvalidateRegistry(instance ?? currentInstance());
2994
3593
  }
2995
3594
 
2996
3595
  // src/server/cache/registry.ts
2997
3596
  init_instance();
2998
3597
  var instanceInvalidators = instanceSlot(() => new Map);
2999
3598
  function getCacheInvalidators(instance) {
3000
- return instanceInvalidators(instance).values();
3599
+ return instanceInvalidators(instance ?? currentInstance()).values();
3001
3600
  }
3002
3601
 
3003
3602
  // src/server/cache/route-cache.ts
@@ -3006,43 +3605,611 @@ function pathWithoutSearch(path) {
3006
3605
  if (searchStart === -1) {
3007
3606
  return path;
3008
3607
  }
3009
- return path.slice(0, searchStart);
3010
- }
3011
-
3012
- // src/server/devtools/request-context.ts
3013
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3014
- var requestContext = new AsyncLocalStorage3;
3015
- function currentDevtoolsRequest() {
3016
- return requestContext.getStore();
3017
- }
3018
-
3019
- // src/server/devtools/instrumentation.ts
3020
- function emitCacheInvalidated(event) {
3021
- appendDevtoolsEvent({ ...event, timestamp: Date.now(), type: "cache.invalidated" });
3022
- }
3023
- function currentInstrumentationRequest() {
3024
- return currentDevtoolsRequest();
3608
+ return path.slice(0, searchStart);
3609
+ }
3610
+
3611
+ // src/server/devtools/request-context.ts
3612
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3613
+ import { Elysia } from "elysia";
3614
+ var requestContext = new AsyncLocalStorage2;
3615
+ var requestSlots = new AsyncLocalStorage2;
3616
+ function currentDevtoolsRequest() {
3617
+ return requestContext.getStore() ?? requestSlots.getStore()?.started?.context;
3618
+ }
3619
+
3620
+ // src/server/devtools/instrumentation.ts
3621
+ function emitCacheInvalidated(event) {
3622
+ appendDevtoolsEvent({ ...event, timestamp: Date.now(), type: "cache.invalidated" });
3623
+ }
3624
+ function currentInstrumentationRequest() {
3625
+ return currentDevtoolsRequest();
3626
+ }
3627
+
3628
+ // src/server/cache/invalidation.ts
3629
+ init_instance();
3630
+ // src/client/request-id.ts
3631
+ function createRequestId() {
3632
+ if (typeof globalThis.crypto?.randomUUID === "function") {
3633
+ return globalThis.crypto.randomUUID();
3634
+ }
3635
+ if (typeof globalThis.crypto?.getRandomValues === "function") {
3636
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
3637
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
3638
+ }
3639
+ return `${Date.now()}-${Math.random()}`;
3640
+ }
3641
+
3642
+ // src/client/query-store.ts
3643
+ var LIVE_QUERY = Symbol.for("furin.query.live.v1");
3644
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
3645
+ function readUrl(reference, options) {
3646
+ const url = new URL(reference.url);
3647
+ const query = options?.query;
3648
+ const append = (key, value) => {
3649
+ if (value === undefined || value === null) {
3650
+ return;
3651
+ }
3652
+ let serialized = String(value);
3653
+ if (value instanceof Date) {
3654
+ serialized = value.toISOString();
3655
+ } else if (typeof value === "object") {
3656
+ serialized = JSON.stringify(value);
3657
+ }
3658
+ url.searchParams.append(key, serialized);
3659
+ };
3660
+ for (const [key, value] of Object.entries(query ?? {})) {
3661
+ if (Array.isArray(value)) {
3662
+ for (const item of value) {
3663
+ append(key, item);
3664
+ }
3665
+ } else {
3666
+ append(key, value);
3667
+ }
3668
+ }
3669
+ url.searchParams.sort();
3670
+ return url.href;
3671
+ }
3672
+
3673
+ class QueryStore {
3674
+ entries = new Map;
3675
+ requests = [];
3676
+ optionObjects = new WeakMap;
3677
+ requestScope = createRequestId();
3678
+ nextRequest = 0;
3679
+ nextOptionObject = 0;
3680
+ listeners = new Set;
3681
+ revisionValue = 0;
3682
+ projections = new Set;
3683
+ session;
3684
+ epoch = 0;
3685
+ origin;
3686
+ constructor(origin) {
3687
+ this.origin = origin;
3688
+ }
3689
+ key(url) {
3690
+ const absolute = new URL(url, this.origin);
3691
+ return queryUrl(absolute.href, undefined) + (absolute.hash.startsWith("#furin-query:") ? absolute.hash : "");
3692
+ }
3693
+ optionValue(value) {
3694
+ if (value instanceof Headers) {
3695
+ return [...value.entries()].sort(([left], [right]) => left.localeCompare(right));
3696
+ }
3697
+ if (Array.isArray(value)) {
3698
+ return value.map((entry) => this.optionValue(entry));
3699
+ }
3700
+ if (value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
3701
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, this.optionValue(entry)]));
3702
+ }
3703
+ if (value !== null && typeof value === "object" || typeof value === "function") {
3704
+ let id = this.optionObjects.get(value);
3705
+ if (id === undefined) {
3706
+ this.nextOptionObject += 1;
3707
+ id = this.nextOptionObject;
3708
+ this.optionObjects.set(value, id);
3709
+ }
3710
+ return { object: id };
3711
+ }
3712
+ return value;
3713
+ }
3714
+ headerValue(value) {
3715
+ if (value instanceof Headers) {
3716
+ return Object.fromEntries(value.entries());
3717
+ }
3718
+ if (typeof value === "function") {
3719
+ return value;
3720
+ }
3721
+ if (Array.isArray(value)) {
3722
+ if (value.length === 2 && typeof value[0] === "string") {
3723
+ try {
3724
+ return [value[0].toLowerCase(), String(value[1])];
3725
+ } catch {
3726
+ return value;
3727
+ }
3728
+ }
3729
+ return value.map((source) => this.headerValue(source));
3730
+ }
3731
+ if (value !== null && typeof value === "object") {
3732
+ try {
3733
+ return Object.fromEntries(Object.entries(value).map(([name, header]) => [name.toLowerCase(), String(header)]));
3734
+ } catch {
3735
+ return value;
3736
+ }
3737
+ }
3738
+ return value;
3739
+ }
3740
+ readKey(reference, options) {
3741
+ const url = readUrl(reference, options);
3742
+ const requestOptions = Object.fromEntries(Object.entries(options ?? {}).filter(([option, value]) => option !== "query" && option !== "select" && value !== undefined).map(([option, value]) => [option, option === "headers" ? this.headerValue(value) : value]));
3743
+ const signature = JSON.stringify(this.optionValue(requestOptions));
3744
+ const existing = this.requests.find((request) => request.url === url && request.client === reference.client && request.options === signature);
3745
+ if (existing) {
3746
+ return existing.key;
3747
+ }
3748
+ const useUrl = signature === "{}" && !this.requests.some((request) => request.url === url && request.key === url);
3749
+ if (!useUrl) {
3750
+ this.nextRequest += 1;
3751
+ }
3752
+ const key = useUrl ? url : `${url}#furin-query:${this.requestScope}:${this.nextRequest}`;
3753
+ this.requests.push({ client: reference.client, options: signature, url, key });
3754
+ return key;
3755
+ }
3756
+ entry(url) {
3757
+ const key = this.key(url);
3758
+ let entry = this.entries.get(key);
3759
+ if (!entry) {
3760
+ entry = {
3761
+ base: undefined,
3762
+ listeners: new Set,
3763
+ snapshot: { data: undefined, error: null, isFetching: false },
3764
+ stale: true,
3765
+ version: 0
3766
+ };
3767
+ this.entries.set(key, entry);
3768
+ }
3769
+ return entry;
3770
+ }
3771
+ publish(entry) {
3772
+ let data = entry.base;
3773
+ for (const projection of this.projections) {
3774
+ const transform = projection.transforms.get(entry);
3775
+ if (transform && data !== undefined) {
3776
+ data = transform(data);
3777
+ }
3778
+ }
3779
+ entry.snapshot = { ...entry.snapshot, data };
3780
+ for (const listener of entry.listeners) {
3781
+ listener();
3782
+ }
3783
+ this.revisionValue += 1;
3784
+ for (const listener of this.listeners) {
3785
+ listener();
3786
+ }
3787
+ }
3788
+ revision = () => this.revisionValue;
3789
+ subscribeAll = (listener) => {
3790
+ this.listeners.add(listener);
3791
+ return () => this.listeners.delete(listener);
3792
+ };
3793
+ observe(url, result, epoch, version) {
3794
+ const existing = this.entries.get(this.key(url));
3795
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
3796
+ return;
3797
+ }
3798
+ const header = result.response?.headers.get("x-furin-query");
3799
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
3800
+ if (identity) {
3801
+ this.setSession(identity.session, url);
3802
+ }
3803
+ const entry = this.entry(url);
3804
+ entry.base = result.data;
3805
+ entry.version += 1;
3806
+ entry.identity = identity;
3807
+ entry.local = result.local ?? result.response?.url === "";
3808
+ entry.stale = false;
3809
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
3810
+ for (const projection of this.projections) {
3811
+ if (!projection.pending) {
3812
+ projection.transforms.delete(entry);
3813
+ if (projection.transforms.size === 0) {
3814
+ this.projections.delete(projection);
3815
+ projection.onRemove?.();
3816
+ }
3817
+ }
3818
+ }
3819
+ this.publish(entry);
3820
+ if (this.entries.size > 100) {
3821
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
3822
+ if (oldest) {
3823
+ this.entries.delete(oldest[0]);
3824
+ this.requests = this.requests.filter((request) => this.key(request.key) !== oldest[0]);
3825
+ }
3826
+ }
3827
+ }
3828
+ setSession(session, url) {
3829
+ let keys;
3830
+ if (new URL(url, this.origin).hash.startsWith("#furin-query:")) {
3831
+ const key = this.key(url);
3832
+ const request = this.requests.find((item) => this.key(item.key) === key);
3833
+ keys = new Set(request ? this.requests.filter((item) => item.client === request.client && item.options === request.options).map((item) => this.key(item.key)) : [key]);
3834
+ }
3835
+ const entries = [...this.entries].filter(([key]) => keys === undefined || keys.has(key)).map(([, entry]) => entry);
3836
+ const changed = keys === undefined ? this.session !== undefined && this.session !== session : entries.some((entry) => entry.identity !== undefined && entry.identity.session !== session);
3837
+ if (changed) {
3838
+ this.epoch += 1;
3839
+ for (const projection of this.projections) {
3840
+ for (const entry of entries) {
3841
+ projection.transforms.delete(entry);
3842
+ }
3843
+ if (projection.transforms.size === 0) {
3844
+ this.projections.delete(projection);
3845
+ projection.onRemove?.();
3846
+ }
3847
+ }
3848
+ for (const entry of entries) {
3849
+ entry.base = undefined;
3850
+ entry.identity = undefined;
3851
+ entry.stale = true;
3852
+ entry.version += 1;
3853
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
3854
+ this.publish(entry);
3855
+ }
3856
+ }
3857
+ if (keys === undefined) {
3858
+ this.session = session;
3859
+ }
3860
+ }
3861
+ generation() {
3862
+ return this.epoch;
3863
+ }
3864
+ clear(preserveData) {
3865
+ this.epoch += 1;
3866
+ if (!preserveData) {
3867
+ this.session = undefined;
3868
+ }
3869
+ this.projections.clear();
3870
+ for (const entry of this.entries.values()) {
3871
+ if (!preserveData) {
3872
+ entry.base = undefined;
3873
+ entry.identity = undefined;
3874
+ }
3875
+ entry.promise = undefined;
3876
+ entry.stale = true;
3877
+ entry.version += 1;
3878
+ entry.snapshot = { data: entry.base, error: null, isFetching: false };
3879
+ this.publish(entry);
3880
+ }
3881
+ }
3882
+ dispose() {
3883
+ this.epoch += 1;
3884
+ for (const entry of this.entries.values()) {
3885
+ entry.listeners.clear();
3886
+ }
3887
+ this.entries.clear();
3888
+ this.requests = [];
3889
+ this.projections.clear();
3890
+ this.listeners.clear();
3891
+ }
3892
+ setError(url, error) {
3893
+ const entry = this.entry(url);
3894
+ entry.base = undefined;
3895
+ entry.stale = false;
3896
+ entry.version += 1;
3897
+ entry.snapshot = { data: undefined, error, isFetching: false };
3898
+ for (const projection of this.projections) {
3899
+ projection.transforms.delete(entry);
3900
+ }
3901
+ this.publish(entry);
3902
+ }
3903
+ version(url) {
3904
+ return this.entry(url).version;
3905
+ }
3906
+ snapshot(url) {
3907
+ return this.entry(url).snapshot;
3908
+ }
3909
+ subscribe(url, listener) {
3910
+ const entry = this.entry(url);
3911
+ entry.listeners.add(listener);
3912
+ return () => entry.listeners.delete(listener);
3913
+ }
3914
+ bind(url, load, client) {
3915
+ const entry = this.entry(url);
3916
+ if (client && entry.client && client !== entry.client) {
3917
+ entry.base = undefined;
3918
+ entry.identity = undefined;
3919
+ entry.stale = true;
3920
+ entry.version += 1;
3921
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
3922
+ for (const projection of this.projections) {
3923
+ projection.transforms.delete(entry);
3924
+ }
3925
+ }
3926
+ entry.client = client ?? entry.client;
3927
+ entry.load = load;
3928
+ }
3929
+ pending(entry) {
3930
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
3931
+ }
3932
+ fetch(url) {
3933
+ const entry = this.entry(url);
3934
+ if (entry.promise) {
3935
+ return entry.promise;
3936
+ }
3937
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
3938
+ return Promise.resolve();
3939
+ }
3940
+ const { version } = entry;
3941
+ const { epoch } = this;
3942
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
3943
+ this.publish(entry);
3944
+ const promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
3945
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
3946
+ return;
3947
+ }
3948
+ if (result.error === null) {
3949
+ this.observe(url, result, epoch);
3950
+ } else {
3951
+ entry.snapshot = { ...entry.snapshot, error: result.error };
3952
+ }
3953
+ }).catch((error) => {
3954
+ if (epoch === this.epoch && version === entry.version) {
3955
+ entry.snapshot = { ...entry.snapshot, error };
3956
+ }
3957
+ }).finally(() => {
3958
+ if (entry.promise !== promise) {
3959
+ return;
3960
+ }
3961
+ entry.promise = undefined;
3962
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
3963
+ this.publish(entry);
3964
+ if (entry.stale && (version !== entry.version || epoch !== this.epoch) && entry.listeners.size > 0) {
3965
+ this.fetch(url);
3966
+ }
3967
+ });
3968
+ entry.promise = promise;
3969
+ return promise;
3970
+ }
3971
+ invalidate(identities) {
3972
+ const tags = new Set(identities.map(queryTag));
3973
+ let affected = false;
3974
+ for (const [url, entry] of this.entries) {
3975
+ if (entry.identity && queryTags(entry.identity).some((tag) => tags.has(tag)) || !entry.identity && entry.load && identities.length > 0) {
3976
+ affected = true;
3977
+ this.invalidateEntry(url, entry);
3978
+ }
3979
+ }
3980
+ return affected;
3981
+ }
3982
+ invalidateEntry(url, entry) {
3983
+ entry.stale = true;
3984
+ entry.version += 1;
3985
+ if (entry.listeners.size > 0) {
3986
+ this.fetch(url);
3987
+ }
3988
+ }
3989
+ invalidateAll() {
3990
+ for (const [url, entry] of this.entries) {
3991
+ this.invalidateEntry(url, entry);
3992
+ }
3993
+ }
3994
+ begin() {
3995
+ return { pending: true, transforms: new Map };
3996
+ }
3997
+ update(projection, url, transform) {
3998
+ const entry = this.entries.get(this.key(url));
3999
+ if (!entry || entry.base === undefined) {
4000
+ return;
4001
+ }
4002
+ const previous = projection.transforms.get(entry);
4003
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
4004
+ entry.version += 1;
4005
+ this.projections.add(projection);
4006
+ this.publish(entry);
4007
+ }
4008
+ finish(projection, outcome) {
4009
+ projection.pending = false;
4010
+ const entries = [...projection.transforms.keys()];
4011
+ if (outcome === "error") {
4012
+ this.projections.delete(projection);
4013
+ projection.onRemove?.();
4014
+ }
4015
+ for (const entry of entries) {
4016
+ this.publish(entry);
4017
+ if (outcome !== "error") {
4018
+ entry.stale = true;
4019
+ }
4020
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
4021
+ if (url && entry.stale) {
4022
+ this.fetch(url);
4023
+ }
4024
+ }
4025
+ }
4026
+ dehydrate() {
4027
+ return [...this.entries].flatMap(([url, entry]) => {
4028
+ if (!entry.identity || entry.base === undefined) {
4029
+ return [];
4030
+ }
4031
+ return [{ url, data: entry.base, identity: entry.identity, local: entry.local }];
4032
+ });
4033
+ }
4034
+ seedUrl(seed, localOrigin) {
4035
+ const original = new URL(seed.url, this.origin);
4036
+ return seed.local && localOrigin ? new URL(original.pathname + original.search + original.hash, localOrigin).href : original.href;
4037
+ }
4038
+ captureHydration() {
4039
+ const { epoch } = this;
4040
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
4041
+ return (seeds, localOrigin) => {
4042
+ if (epoch === this.epoch) {
4043
+ this.hydrate(seeds.filter((seed) => {
4044
+ const url = this.seedUrl(seed, localOrigin);
4045
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
4046
+ }), localOrigin);
4047
+ }
4048
+ };
4049
+ }
4050
+ hydrate(seeds, localOrigin) {
4051
+ for (const seed of seeds) {
4052
+ if (seed.data === undefined) {
4053
+ continue;
4054
+ }
4055
+ const url = this.seedUrl(seed, localOrigin);
4056
+ this.observe(url, {
4057
+ data: seed.data,
4058
+ error: null,
4059
+ identity: seed.identity,
4060
+ local: seed.local ?? false
4061
+ }, this.epoch);
4062
+ }
4063
+ }
3025
4064
  }
3026
4065
 
3027
- // src/server/cache/invalidation.ts
3028
- init_instance();
3029
-
3030
4066
  // src/server/cache/page-cache-state.ts
3031
4067
  init_instance();
3032
4068
  var instancePageCacheAdapter = instanceSlot(() => ({
3033
4069
  adapter: undefined
3034
4070
  }));
3035
4071
  function getPageCacheAdapter(instance) {
3036
- return instancePageCacheAdapter(instance).adapter;
4072
+ return instancePageCacheAdapter(instance ?? currentInstance()).adapter;
4073
+ }
4074
+
4075
+ // src/client/sync-catch-up.ts
4076
+ init_invalidation_header();
4077
+ var LAYOUT_SUFFIX_RE = /:layout$/;
4078
+ var RESET_REFRESH_INTERVAL_MS = 1000;
4079
+ function changeInvalidations(change) {
4080
+ const paths = [];
4081
+ const queries = [...change.queries ?? []];
4082
+ for (const entry of change.invalidations) {
4083
+ if (typeof entry === "string") {
4084
+ const trimmed = entry.trim();
4085
+ const type = trimmed.endsWith(":layout") ? "layout" : "page";
4086
+ const path = trimmed.replace(LAYOUT_SUFFIX_RE, "");
4087
+ paths.push(encodeInvalidationEntry(path, type));
4088
+ } else if (entry.kind === "path") {
4089
+ paths.push(encodeInvalidationEntry(entry.path, entry.type));
4090
+ } else {
4091
+ for (const tag of entry.tags) {
4092
+ const identity = queryFromTag(tag);
4093
+ if (identity) {
4094
+ queries.push(identity);
4095
+ } else {
4096
+ paths.push("/:layout");
4097
+ }
4098
+ }
4099
+ }
4100
+ }
4101
+ return { paths, queries };
4102
+ }
4103
+ function createSyncCatchUp(options) {
4104
+ let currentCursor;
4105
+ let running;
4106
+ let requested = false;
4107
+ let lastReset = Number.NEGATIVE_INFINITY;
4108
+ let pendingReset;
4109
+ let closed = false;
4110
+ const refreshAfterReset = () => {
4111
+ pendingReset = undefined;
4112
+ lastReset = Date.now();
4113
+ options.onReset?.();
4114
+ options.onInvalidations(["/:layout"]);
4115
+ };
4116
+ const scheduleResetRefresh = () => {
4117
+ if (pendingReset) {
4118
+ return;
4119
+ }
4120
+ const wait = lastReset + RESET_REFRESH_INTERVAL_MS - Date.now();
4121
+ if (wait <= 0) {
4122
+ refreshAfterReset();
4123
+ } else {
4124
+ pendingReset = setTimeout(refreshAfterReset, wait);
4125
+ }
4126
+ };
4127
+ const readUntilCurrent = async () => {
4128
+ do {
4129
+ requested = false;
4130
+ let page;
4131
+ do {
4132
+ page = await options.fetchPage(currentCursor ?? "0");
4133
+ if (closed) {
4134
+ return;
4135
+ }
4136
+ if (page.reset) {
4137
+ currentCursor = page.cursor;
4138
+ scheduleResetRefresh();
4139
+ break;
4140
+ }
4141
+ for (const change of page.changes) {
4142
+ applyChange(change);
4143
+ }
4144
+ currentCursor = page.cursor;
4145
+ } while (page.hasMore);
4146
+ } while (requested && !closed);
4147
+ };
4148
+ const applyChange = (change) => {
4149
+ const { paths, queries } = changeInvalidations(change);
4150
+ options.onInvalidations(paths);
4151
+ if (queries.length > 0) {
4152
+ options.onQueries?.(queries);
4153
+ }
4154
+ };
4155
+ return {
4156
+ catchUp() {
4157
+ if (closed) {
4158
+ return Promise.resolve();
4159
+ }
4160
+ requested = true;
4161
+ if (!running) {
4162
+ running = readUntilCurrent().finally(() => {
4163
+ running = undefined;
4164
+ });
4165
+ }
4166
+ return running;
4167
+ },
4168
+ cursor: () => currentCursor,
4169
+ close() {
4170
+ closed = true;
4171
+ clearTimeout(pendingReset);
4172
+ },
4173
+ seed(cursor) {
4174
+ currentCursor ??= cursor;
4175
+ }
4176
+ };
3037
4177
  }
4178
+
3038
4179
  // src/server/cache/purger.ts
4180
+ init_instance();
3039
4181
  var pathPurger;
3040
4182
  var tagPurger;
3041
- function callCachePurger(paths) {
3042
- dispatch(pathPurger, paths);
3043
- }
3044
- function callCacheTagPurger(tags) {
3045
- dispatch(tagPurger, tags);
4183
+ var instancePathPurger = instanceSlot(() => ({
4184
+ purger: undefined
4185
+ }));
4186
+ var instanceTagPurger = instanceSlot(() => ({
4187
+ purger: undefined
4188
+ }));
4189
+ function callCachePurger(purges) {
4190
+ dispatchBatches([...purges].map(([instance, paths]) => [
4191
+ instancePathPurger(instance).purger ?? pathPurger,
4192
+ paths
4193
+ ]));
4194
+ }
4195
+ function callCacheTagPurger(instances, tags) {
4196
+ dispatchBatches(instances.map((instance) => [instanceTagPurger(instance).purger ?? tagPurger, tags]));
4197
+ }
4198
+ function dispatchBatches(purges) {
4199
+ const batches = new Map;
4200
+ for (const [purger, keys] of purges) {
4201
+ if (!purger) {
4202
+ continue;
4203
+ }
4204
+ const batch = batches.get(purger) ?? new Set;
4205
+ for (const key of keys) {
4206
+ batch.add(key);
4207
+ }
4208
+ batches.set(purger, batch);
4209
+ }
4210
+ for (const [purger, keys] of batches) {
4211
+ dispatch(purger, [...keys]);
4212
+ }
3046
4213
  }
3047
4214
  function dispatch(purger, keys) {
3048
4215
  if (!purger || keys.length === 0) {
@@ -3058,13 +4225,9 @@ function dispatch(purger, keys) {
3058
4225
  }
3059
4226
 
3060
4227
  // src/server/cache/invalidation.ts
3061
- var _globalPendingInvalidations = new Set;
3062
- function _activeInvalidationSet() {
3063
- return requestPendingInvalidations() ?? _globalPendingInvalidations;
3064
- }
3065
4228
  function consumePendingInvalidations() {
3066
- const set = _activeInvalidationSet();
3067
- if (set.size === 0) {
4229
+ const set = requestPendingInvalidations();
4230
+ if (set === undefined || set.size === 0) {
3068
4231
  return [];
3069
4232
  }
3070
4233
  const paths = [...set];
@@ -3072,13 +4235,13 @@ function consumePendingInvalidations() {
3072
4235
  return paths;
3073
4236
  }
3074
4237
  function peekPendingInvalidations() {
3075
- return [..._activeInvalidationSet()];
4238
+ return [...requestPendingInvalidations() ?? []];
3076
4239
  }
3077
- function callCachePurger2(paths) {
3078
- callCachePurger(paths);
4240
+ function callCachePurger2(purges) {
4241
+ callCachePurger(purges);
3079
4242
  }
3080
4243
  function emitPathInvalidation(instance, path, deleted, purgedPaths) {
3081
- if (!IS_DEV) {
4244
+ if (!instance.development) {
3082
4245
  return;
3083
4246
  }
3084
4247
  withInstance(instance, () => {
@@ -3118,18 +4281,13 @@ async function invalidateInstancePath(instance, path, type) {
3118
4281
  return { deleted, purgedPaths };
3119
4282
  }
3120
4283
  async function revalidatePath(path, type) {
3121
- let deleted = false;
3122
- const purgedPaths = [];
3123
- const results = await Promise.all(allInstances().map((instance) => invalidateInstancePath(instance, path, type)));
3124
- for (const result of results) {
3125
- deleted = result.deleted || deleted;
3126
- purgedPaths.push(...result.purgedPaths);
3127
- }
3128
- callCachePurger2(dedupePaths(purgedPaths));
3129
- return deleted;
4284
+ const instances = allInstances();
4285
+ const results = await Promise.all(instances.map((instance) => invalidateInstancePath(instance, path, type)));
4286
+ callCachePurger2(new Map(instances.map((instance, index) => [instance, results[index]?.purgedPaths ?? []])));
4287
+ return results.some((result) => result.deleted);
3130
4288
  }
3131
4289
  function revalidatePathForInstance(instance, path, type, emitPathEvent) {
3132
- _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
4290
+ requestPendingInvalidations()?.add(encodeInvalidationEntry(path, type));
3133
4291
  let deleted = false;
3134
4292
  const purgedPaths = [];
3135
4293
  withInstance(instance, () => {
@@ -3138,231 +4296,52 @@ function revalidatePathForInstance(instance, path, type, emitPathEvent) {
3138
4296
  deleted = result.deleted || deleted;
3139
4297
  purgedPaths.push(...result.purgedPaths);
3140
4298
  }
3141
- if (IS_DEV && emitPathEvent !== false) {
4299
+ if (emitPathEvent !== false) {
3142
4300
  emitPathInvalidation(instance, path, deleted, purgedPaths);
3143
4301
  }
3144
4302
  });
3145
4303
  return { deleted, purgedPaths };
3146
4304
  }
3147
- function dedupePaths(paths) {
3148
- return [...new Set(paths)];
3149
- }
3150
4305
 
3151
4306
  // src/server/auto-invalidate/runtime.ts
3152
4307
  init_instance();
3153
- function toRules(input) {
3154
- return Array.isArray(input) ? input : [input];
3155
- }
3156
- function statusFromResponseValue(responseValue) {
3157
- if (responseValue instanceof Response) {
3158
- return responseValue.status;
3159
- }
3160
- if (responseValue && typeof responseValue === "object" && "status" in responseValue) {
3161
- const { status } = responseValue;
3162
- if (typeof status === "number") {
3163
- return status;
3164
- }
3165
- }
3166
- if (responseValue && typeof responseValue === "object" && "code" in responseValue) {
3167
- const { code } = responseValue;
3168
- if (typeof code === "number") {
3169
- return code;
3170
- }
3171
- }
3172
- }
3173
- function isSuccessfulMutationResponse(ctx) {
3174
- const responseStatus = statusFromResponseValue(ctx.responseValue) ?? statusFromResponseValue(ctx.response);
3175
- if (responseStatus !== undefined) {
3176
- return responseStatus >= 200 && responseStatus < 400;
3177
- }
3178
- const setStatus = ctx.set.status;
3179
- if (typeof setStatus === "number") {
3180
- return setStatus >= 200 && setStatus < 400;
3181
- }
3182
- if (typeof setStatus === "string") {
3183
- const errorStatusTexts = new Set([
3184
- "Bad Request",
3185
- "Unauthorized",
3186
- "Payment Required",
3187
- "Forbidden",
3188
- "Not Found",
3189
- "Method Not Allowed",
3190
- "Not Acceptable",
3191
- "Proxy Authentication Required",
3192
- "Request Timeout",
3193
- "Conflict",
3194
- "Gone",
3195
- "Length Required",
3196
- "Precondition Failed",
3197
- "Payload Too Large",
3198
- "URI Too Long",
3199
- "Unsupported Media Type",
3200
- "Range Not Satisfiable",
3201
- "Expectation Failed",
3202
- "I'm a teapot",
3203
- "Misdirected Request",
3204
- "Unprocessable Content",
3205
- "Locked",
3206
- "Failed Dependency",
3207
- "Too Early",
3208
- "Upgrade Required",
3209
- "Precondition Required",
3210
- "Too Many Requests",
3211
- "Enhance Your Calm",
3212
- "Request Header Fields Too Large",
3213
- "Unavailable For Legal Reasons",
3214
- "Internal Server Error",
3215
- "Not Implemented",
3216
- "Bad Gateway",
3217
- "Service Unavailable",
3218
- "Gateway Timeout",
3219
- "HTTP Version Not Supported",
3220
- "Variant Also Negotiates",
3221
- "Insufficient Storage",
3222
- "Loop Detected",
3223
- "Not Extended",
3224
- "Network Authentication Required"
3225
- ]);
3226
- return !errorStatusTexts.has(setStatus);
3227
- }
3228
- return true;
3229
- }
3230
- function appendPendingInvalidationHeader(set) {
3231
- const pending = consumePendingInvalidations();
3232
- if (pending.length === 0) {
3233
- return [];
3234
- }
3235
- const headerName = "x-furin-revalidate";
3236
- const existing = set.headers[headerName];
3237
- set.headers[headerName] = typeof existing === "string" && existing.length > 0 ? `${existing},${pending.join(",")}` : pending.join(",");
3238
- return pending;
3239
- }
3240
- async function invalidateTagsForInstance(instance, tagList) {
3241
- let deleted = false;
3242
- const purgedPaths = new Set;
3243
- const logicalPurgedPaths = new Set;
3244
- const sharedInvalidations = [];
3245
- const pageCache = getPageCacheAdapter(instance);
3246
- const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
3247
- kind: "tags",
3248
- scope: instance.prefix,
3249
- tags: tagList
3250
- });
3251
- if (sharedResult !== undefined) {
3252
- deleted = sharedResult.invalidated;
3253
- }
3254
- const taggedPaths = new Set([
3255
- ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
3256
- ...sharedResult?.paths ?? []
3257
- ]);
3258
- const tags = new Set(tagList);
3259
- for (const path of taggedPaths) {
3260
- const logicalPath = pathWithoutSearch(path);
3261
- const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
3262
- const result = revalidatePathForInstance(instance, logicalPath, "page", false);
3263
- if (pageCache !== undefined && registered) {
3264
- sharedInvalidations.push(pageCache.invalidate({
3265
- kind: "path",
3266
- scope: instance.prefix,
3267
- path: logicalPath,
3268
- type: "page"
3269
- }));
3270
- }
3271
- deleted = result.deleted || deleted;
3272
- purgedPaths.add(physicalPath(instance.prefix, logicalPath));
3273
- logicalPurgedPaths.add(logicalPath);
3274
- for (const purged of result.purgedPaths) {
3275
- purgedPaths.add(physicalPath(instance.prefix, purged));
3276
- logicalPurgedPaths.add(purged);
3277
- }
3278
- }
3279
- const pathResults = await Promise.all(sharedInvalidations);
3280
- deleted = pathResults.some((result) => result.invalidated) || deleted;
3281
- if (IS_DEV) {
3282
- withInstance(instance, () => {
3283
- const request = currentInstrumentationRequest();
3284
- const operationId = request === undefined ? null : request.operationId;
3285
- const requestId = request === undefined ? null : request.requestId;
3286
- emitCacheInvalidated({
3287
- deleted,
3288
- operationId,
3289
- purgedPaths: logicalPurgedPaths.size,
3290
- reason: "tag",
3291
- requestId,
3292
- target: tagList.join(",")
3293
- });
3294
- });
3295
- }
3296
- return { deleted, purgedPaths: [...purgedPaths] };
3297
- }
3298
- async function revalidateTag(tags) {
3299
- const tagList = typeof tags === "string" ? [tags] : [...tags];
3300
- callCacheTagPurger(tagList);
3301
- const results = await Promise.all(allInstances().map((instance) => invalidateTagsForInstance(instance, tagList)));
3302
- const purgedPaths = new Set;
3303
- let deleted = false;
3304
- for (const result of results) {
3305
- deleted = result.deleted || deleted;
3306
- for (const path of result.purgedPaths) {
3307
- purgedPaths.add(path);
3308
- }
3309
- }
3310
- callCachePurger2([...purgedPaths]);
3311
- return deleted;
3312
- }
3313
- async function runInvalidationRules(input) {
3314
- const operations = toRules(input).flatMap((rule) => {
3315
- const pending = [];
3316
- if ("path" in rule && rule.path) {
3317
- pending.push(revalidatePath(rule.path, rule.type));
3318
- }
3319
- if (rule.tags && rule.tags.length > 0) {
3320
- pending.push(revalidateTag(rule.tags));
3321
- }
3322
- return pending;
3323
- });
3324
- return (await Promise.all(operations)).some(Boolean);
3325
- }
3326
-
3327
- // src/server/sync/plugin.ts
3328
- init_context_logger();
3329
4308
 
3330
- // src/server/sync/atomic.ts
3331
- import { ElysiaStatus as ElysiaStatus2, StatusMap as StatusMap2, Validator } from "elysia";
3332
- init_context_logger();
4309
+ // src/server/sync/response.ts
4310
+ import { ElysiaStatus, StatusMap } from "elysia";
3333
4311
 
3334
- // src/server/sync/queries.ts
3335
- function resolveSyncInvalidations(input, context, value) {
3336
- if (input === undefined) {
3337
- return;
3338
- }
3339
- const selected = typeof input === "function" ? input(Object.assign(Object.create(Object.getPrototypeOf(context)), context, {
3340
- responseValue: value
3341
- })) : input;
3342
- const rules = Array.isArray(selected) ? selected : [selected];
3343
- return rules.map((rule) => ("id" in rule) ? { tags: [queryTag(rule)] } : rule);
3344
- }
3345
- function appendQueryInvalidations(input, context) {
3346
- if (input === undefined) {
3347
- return;
3348
- }
3349
- const queries = [];
3350
- for (const rule of Array.isArray(input) ? input : [input]) {
3351
- for (const tag of rule.tags ?? []) {
3352
- const identity = queryFromTag(tag);
3353
- if (identity) {
3354
- queries.push(identity);
4312
+ // src/server/bounded-body.ts
4313
+ async function readBoundedBytes(stream, maxBytes) {
4314
+ const reader = stream.getReader();
4315
+ const chunks = [];
4316
+ let total = 0;
4317
+ try {
4318
+ for (;; ) {
4319
+ const { done, value } = await reader.read();
4320
+ if (done) {
4321
+ break;
4322
+ }
4323
+ total += value.byteLength;
4324
+ if (total > maxBytes) {
4325
+ await reader.cancel().catch(() => {
4326
+ return;
4327
+ });
4328
+ return;
3355
4329
  }
4330
+ chunks.push(value);
3356
4331
  }
4332
+ } finally {
4333
+ reader.releaseLock();
3357
4334
  }
3358
- if (queries.length > 0) {
3359
- context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
3360
- context.set.headers["x-furin-sync"] = "1";
4335
+ const bytes = new Uint8Array(total);
4336
+ let offset = 0;
4337
+ for (const chunk of chunks) {
4338
+ bytes.set(chunk, offset);
4339
+ offset += chunk.byteLength;
3361
4340
  }
4341
+ return bytes;
3362
4342
  }
3363
4343
 
3364
4344
  // src/server/sync/response.ts
3365
- import { ElysiaStatus, StatusMap } from "elysia";
3366
4345
  var NON_REPLAYABLE_HEADERS = new Set([
3367
4346
  "authorization",
3368
4347
  "connection",
@@ -3377,7 +4356,7 @@ var NON_REPLAYABLE_HEADERS = new Set([
3377
4356
  var MAX_SYNC_REPLAY_RESPONSE_BYTES = 1024 * 1024;
3378
4357
  var UNREPLAYABLE_SYNC_RESPONSE_BODY = new TextEncoder().encode(JSON.stringify({
3379
4358
  code: "FURIN_UNREPLAYABLE_SYNC_RESPONSE",
3380
- message: "This mutation response cannot be replayed safely. Return a small bounded response or set sync: false on the route."
4359
+ message: "This mutation response cannot be replayed safely. Return a small bounded response or set idempotent: false on the route."
3381
4360
  }));
3382
4361
  function statusCode(status) {
3383
4362
  if (typeof status === "number") {
@@ -3385,11 +4364,24 @@ function statusCode(status) {
3385
4364
  }
3386
4365
  return status === undefined ? 200 : StatusMap[status];
3387
4366
  }
3388
- function unwrapStatusResponse(value) {
3389
- if (!(value instanceof ElysiaStatus)) {
3390
- return;
4367
+ function effectiveResponseStatus(value, set) {
4368
+ if (value instanceof ElysiaStatus || value instanceof Response && value.status !== 200) {
4369
+ return value.status;
4370
+ }
4371
+ const status = statusCode(set.status);
4372
+ return value instanceof Error && status === 200 ? 500 : status;
4373
+ }
4374
+ function effectiveResponseHeaders(value, set) {
4375
+ const entries = Object.entries(set.headers);
4376
+ if (value instanceof Response) {
4377
+ entries.push(...value.headers);
4378
+ } else if (value instanceof ElysiaStatus) {
4379
+ entries.push(...Object.entries(value.headers ?? {}));
3391
4380
  }
3392
- return { status: value.status, value: value.response };
4381
+ return Object.fromEntries(entries.map(([name, header]) => [name.toLowerCase(), header]));
4382
+ }
4383
+ function replayableHeaders(entries) {
4384
+ return new Headers(Array.from(entries, ([name, value]) => [name, value]).filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
3393
4385
  }
3394
4386
  function responseHeaders(headers) {
3395
4387
  const result = new Headers;
@@ -3421,42 +4413,17 @@ function responseContentLength(response) {
3421
4413
  return;
3422
4414
  }
3423
4415
  const parsed = Number(header);
3424
- return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
3425
- }
3426
- async function readBoundedResponseBody(response) {
3427
- if (response.body === null) {
3428
- return new Uint8Array;
3429
- }
3430
- const contentLength = responseContentLength(response);
3431
- if (contentLength === undefined || contentLength > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
3432
- return;
3433
- }
3434
- const reader = response.body.getReader();
3435
- const chunks = [];
3436
- let total = 0;
3437
- try {
3438
- for (;; ) {
3439
- const { done, value } = await reader.read();
3440
- if (done) {
3441
- break;
3442
- }
3443
- total += value.byteLength;
3444
- if (total > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
3445
- await reader.cancel();
3446
- return;
3447
- }
3448
- chunks.push(value);
3449
- }
3450
- } finally {
3451
- reader.releaseLock();
4416
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
4417
+ }
4418
+ async function readBoundedResponseBody(response) {
4419
+ if (response.body === null) {
4420
+ return new Uint8Array;
3452
4421
  }
3453
- const body = new Uint8Array(total);
3454
- let offset = 0;
3455
- for (const chunk of chunks) {
3456
- body.set(chunk, offset);
3457
- offset += chunk.byteLength;
4422
+ const contentLength = responseContentLength(response);
4423
+ if (contentLength === undefined || contentLength > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
4424
+ return;
3458
4425
  }
3459
- return body;
4426
+ return await readBoundedBytes(response.body, MAX_SYNC_REPLAY_RESPONSE_BYTES);
3460
4427
  }
3461
4428
  function unreplayable() {
3462
4429
  return {
@@ -3469,13 +4436,7 @@ function unreplayable() {
3469
4436
  };
3470
4437
  }
3471
4438
  function mergeStoredResponseHeaders(storedResponse, headers) {
3472
- const headerEntries = [];
3473
- for (const [name, value] of storedResponse.headers) {
3474
- if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
3475
- headerEntries.push([name, value]);
3476
- }
3477
- }
3478
- const merged = new Headers(headerEntries);
4439
+ const merged = replayableHeaders(storedResponse.headers);
3479
4440
  for (const [name, value] of Object.entries(headers)) {
3480
4441
  if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
3481
4442
  merged.delete(name);
@@ -3496,8 +4457,8 @@ async function storeResponse(responseValue, set) {
3496
4457
  if (body === undefined) {
3497
4458
  return unreplayable();
3498
4459
  }
3499
- const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
3500
- return storedResponseResult(headers, body, clone.status);
4460
+ const headers = replayableHeaders(clone.headers);
4461
+ return storedResponseResult(headers, body, effectiveResponseStatus(responseValue, set));
3501
4462
  }
3502
4463
  return storeResponseSync(responseValue, set);
3503
4464
  }
@@ -3506,39 +4467,136 @@ function storeResponseSync(responseValue, set) {
3506
4467
  if (responseValue.body !== null) {
3507
4468
  return unreplayable();
3508
4469
  }
3509
- return storedResponseResult(new Headers([...responseValue.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))), new Uint8Array, responseValue.status);
4470
+ return storedResponseResult(replayableHeaders(responseValue.headers), new Uint8Array, effectiveResponseStatus(responseValue, set));
3510
4471
  }
3511
- const headers = responseHeaders(set.headers);
3512
- const statusResponse = unwrapStatusResponse(responseValue);
3513
- const value = statusResponse?.value ?? responseValue;
3514
- const responseStatus = statusResponse ? statusResponse.status : statusCode(set.status);
4472
+ const headers = responseHeaders(effectiveResponseHeaders(responseValue, set));
4473
+ const value = responseValue instanceof ElysiaStatus ? responseValue.response : responseValue;
4474
+ const responseStatus = responseValue instanceof ElysiaStatus ? responseValue.status : statusCode(set.status);
3515
4475
  let body;
3516
4476
  if (value === undefined || value === null) {
3517
4477
  body = new Uint8Array;
3518
- } else if (typeof value === "string") {
3519
- headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
3520
- body = new TextEncoder().encode(value);
4478
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
4479
+ const contentType = new Response(String(value)).headers.get("content-type");
4480
+ if (!headers.has("content-type") && contentType !== null) {
4481
+ headers.set("content-type", contentType);
4482
+ }
4483
+ body = new TextEncoder().encode(String(value));
3521
4484
  } else {
3522
- headers.set("content-type", headers.get("content-type") ?? "application/json");
4485
+ headers.set("content-type", headers.get("content-type") ?? "application/json;charset=utf-8");
3523
4486
  body = new TextEncoder().encode(JSON.stringify(value));
3524
4487
  }
3525
4488
  return storedResponseResult(headers, body, responseStatus);
3526
4489
  }
3527
4490
  function replayResponse(stored) {
3528
4491
  const body = stored.status === 204 || stored.status === 205 || stored.status === 304 ? null : stored.body.slice();
3529
- const headerEntries = [];
3530
- for (const [name, value] of stored.headers) {
3531
- if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
3532
- headerEntries.push([name, value]);
3533
- }
3534
- }
3535
4492
  return new Response(body, {
3536
- headers: new Headers(headerEntries),
4493
+ headers: replayableHeaders(stored.headers),
3537
4494
  status: stored.status
3538
4495
  });
3539
4496
  }
3540
4497
 
4498
+ // src/server/auto-invalidate/runtime.ts
4499
+ function toRules(input) {
4500
+ return Array.isArray(input) ? input : [input];
4501
+ }
4502
+ function isSuccessfulMutationResponse(ctx) {
4503
+ const status = effectiveResponseStatus(ctx.responseValue ?? ctx.response, ctx.set);
4504
+ return status >= 200 && status < 400;
4505
+ }
4506
+ function appendPendingInvalidationHeader(set) {
4507
+ const pending = consumePendingInvalidations();
4508
+ if (pending.length === 0) {
4509
+ return [];
4510
+ }
4511
+ const headerName = "x-furin-revalidate";
4512
+ const existing = set.headers[headerName];
4513
+ set.headers[headerName] = typeof existing === "string" && existing.length > 0 ? `${existing},${serializeInvalidationPaths(pending)}` : serializeInvalidationPaths(pending);
4514
+ return pending;
4515
+ }
4516
+ async function invalidateTagsForInstance(instance, tagList) {
4517
+ let deleted = false;
4518
+ const purgedPaths = new Set;
4519
+ const logicalPurgedPaths = new Set;
4520
+ const sharedInvalidations = [];
4521
+ const pageCache = getPageCacheAdapter(instance);
4522
+ const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
4523
+ kind: "tags",
4524
+ scope: instance.prefix,
4525
+ tags: tagList
4526
+ });
4527
+ if (sharedResult !== undefined) {
4528
+ deleted = sharedResult.invalidated;
4529
+ }
4530
+ const taggedPaths = new Set([
4531
+ ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
4532
+ ...sharedResult?.paths ?? []
4533
+ ]);
4534
+ const tags = new Set(tagList);
4535
+ for (const path of taggedPaths) {
4536
+ const logicalPath = pathWithoutSearch(path);
4537
+ const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
4538
+ const result = revalidatePathForInstance(instance, logicalPath, "page", false);
4539
+ if (pageCache !== undefined && registered) {
4540
+ sharedInvalidations.push(pageCache.invalidate({
4541
+ kind: "path",
4542
+ scope: instance.prefix,
4543
+ path: logicalPath,
4544
+ type: "page"
4545
+ }));
4546
+ }
4547
+ deleted = result.deleted || deleted;
4548
+ purgedPaths.add(physicalPath(instance.prefix, logicalPath));
4549
+ logicalPurgedPaths.add(logicalPath);
4550
+ for (const purged of result.purgedPaths) {
4551
+ purgedPaths.add(physicalPath(instance.prefix, purged));
4552
+ logicalPurgedPaths.add(purged);
4553
+ }
4554
+ }
4555
+ const pathResults = await Promise.all(sharedInvalidations);
4556
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
4557
+ if (instance.development) {
4558
+ withInstance(instance, () => {
4559
+ const request = currentInstrumentationRequest();
4560
+ const operationId = request === undefined ? null : request.operationId;
4561
+ const requestId = request === undefined ? null : request.requestId;
4562
+ emitCacheInvalidated({
4563
+ deleted,
4564
+ operationId,
4565
+ purgedPaths: logicalPurgedPaths.size,
4566
+ reason: "tag",
4567
+ requestId,
4568
+ target: tagList.join(",")
4569
+ });
4570
+ });
4571
+ }
4572
+ return { deleted, purgedPaths: [...purgedPaths] };
4573
+ }
4574
+ async function revalidateTag(tags) {
4575
+ const tagList = typeof tags === "string" ? [tags] : [...tags];
4576
+ const instances = allInstances();
4577
+ callCacheTagPurger(instances, tagList);
4578
+ const results = await Promise.all(instances.map((instance) => invalidateTagsForInstance(instance, tagList)));
4579
+ callCachePurger2(new Map(instances.map((instance, index) => [instance, results[index]?.purgedPaths ?? []])));
4580
+ return results.some((result) => result.deleted);
4581
+ }
4582
+ async function runInvalidationRules(input) {
4583
+ const operations = toRules(input).flatMap((rule) => {
4584
+ const pending = [];
4585
+ if ("path" in rule && rule.path) {
4586
+ pending.push(revalidatePath(rule.path, rule.type));
4587
+ }
4588
+ if (rule.tags && rule.tags.length > 0) {
4589
+ pending.push(revalidateTag(rule.tags));
4590
+ }
4591
+ return pending;
4592
+ });
4593
+ return (await Promise.all(operations)).some(Boolean);
4594
+ }
3541
4595
  // src/server/sync/atomic.ts
4596
+ init_invalidation_header();
4597
+ import { ElysiaStatus as ElysiaStatus2, Validator } from "elysia";
4598
+ init_context_logger();
4599
+ init_queries();
3542
4600
  var TRAILING_SLASH_PATTERN = /\/$/;
3543
4601
 
3544
4602
  class RejectedMutation {
@@ -3547,18 +4605,6 @@ class RejectedMutation {
3547
4605
  this.value = value;
3548
4606
  }
3549
4607
  }
3550
- function responseStatus(context, value) {
3551
- if (value instanceof Response && value.status !== 200) {
3552
- return value.status;
3553
- }
3554
- if (value instanceof ElysiaStatus2) {
3555
- return value.status;
3556
- }
3557
- if (typeof context.set.status === "string") {
3558
- return StatusMap2[context.set.status];
3559
- }
3560
- return context.set.status ?? 200;
3561
- }
3562
4608
  function withStatus(original, value) {
3563
4609
  return original instanceof ElysiaStatus2 ? new ElysiaStatus2(original.status, value, original.headers) : value;
3564
4610
  }
@@ -3588,7 +4634,7 @@ function validateResult(execution, value) {
3588
4634
  sanitize: app["~config"]?.sanitize,
3589
4635
  schemas: route?.hooks.schemas?.flatMap((schema) => schema.response ? [schema.response] : [])
3590
4636
  });
3591
- const validator = validators?.[responseStatus(context, value)];
4637
+ const validator = validators?.get(effectiveResponseStatus(value, context.set));
3592
4638
  if (!validator) {
3593
4639
  return value;
3594
4640
  }
@@ -3605,11 +4651,11 @@ function validateResult(execution, value) {
3605
4651
  }
3606
4652
  function prepare(execution, value, original) {
3607
4653
  const { context } = execution;
3608
- const status = responseStatus(context, value);
4654
+ const status = effectiveResponseStatus(value, context.set);
3609
4655
  if (status < 200 || status >= 400) {
3610
4656
  throw new RejectedMutation(original);
3611
4657
  }
3612
- const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
4658
+ const invalidate = resolveSyncInvalidations(context);
3613
4659
  execution.resolvedInvalidate = invalidate;
3614
4660
  appendQueryInvalidations(invalidate, context);
3615
4661
  const invalidations = [
@@ -3619,20 +4665,15 @@ function prepare(execution, value, original) {
3619
4665
  if (invalidations.length > 0) {
3620
4666
  context.set.headers["x-furin-sync"] = "1";
3621
4667
  }
3622
- const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => entry.type === "layout" ? `${entry.path}:layout` : entry.path);
4668
+ const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => encodeInvalidationEntry(entry.path, entry.type));
3623
4669
  if (paths.length > 0) {
3624
- context.set.headers["x-furin-revalidate"] = paths.join(",");
4670
+ context.set.headers["x-furin-revalidate"] = serializeInvalidationPaths(paths);
3625
4671
  }
3626
4672
  const finish = (stored) => {
3627
4673
  if (stored.kind === "unreplayable") {
3628
4674
  throw new Error("[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses.");
3629
4675
  }
3630
- let { headers } = context.set;
3631
- if (value instanceof ElysiaStatus2) {
3632
- headers = { ...headers, ...value.headers };
3633
- } else if (value instanceof Response) {
3634
- headers = { ...headers, ...Object.fromEntries(value.headers) };
3635
- }
4676
+ const headers = effectiveResponseHeaders(value, context.set);
3636
4677
  return {
3637
4678
  invalidations,
3638
4679
  response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
@@ -3726,9 +4767,30 @@ function normalizedInvalidations(input) {
3726
4767
  return invalidations;
3727
4768
  }
3728
4769
  function pendingPathInvalidations(entries) {
3729
- return entries.map((entry) => entry.endsWith(":layout") ? { kind: "path", path: entry.slice(0, -":layout".length), type: "layout" } : { kind: "path", path: entry, type: "page" });
4770
+ return entries.map((entry) => ({ kind: "path", ...decodeInvalidationEntry(entry) }));
3730
4771
  }
3731
4772
 
4773
+ // src/server/sync/invalidate-sync.ts
4774
+ init_runtime();
4775
+ async function invalidateSync(sync, target, paramsOrOptions, options) {
4776
+ const provenance = typeof target === "string" ? options : paramsOrOptions;
4777
+ if (provenance?.principal === "") {
4778
+ throw new Error("[furin] Sync invalidation principal must not be empty.");
4779
+ }
4780
+ const runtime = resolveSyncRuntime(sync, IS_DEV);
4781
+ const rule = typeof target === "string" ? {
4782
+ tags: [
4783
+ queryTag({ id: target, scope: paramsOrOptions ?? {} })
4784
+ ]
4785
+ } : target;
4786
+ await runInvalidationRules(rule);
4787
+ publishCursor(runtime, await runtime.adapter.appendInvalidations(normalizedInvalidations(rule), provenance?.principal));
4788
+ }
4789
+ // src/server/sync/plugin.ts
4790
+ import { Elysia as Elysia5, ElysiaStatus as ElysiaStatus3 } from "elysia";
4791
+ init_context_logger();
4792
+ init_instance();
4793
+
3732
4794
  // src/server/sync/execution-error.ts
3733
4795
  class MutationLeaseLost extends Error {
3734
4796
  }
@@ -3816,9 +4878,16 @@ function installMutationHandlers(app) {
3816
4878
  };
3817
4879
  return compileHandler(index, immediate, [method, path, wrapped, owner, hooks, chain, inherited, macroScope], aliases, table);
3818
4880
  };
4881
+ const dispatch = app["~dispatch"].bind(app);
4882
+ app["~dispatch"] = (index, context) => {
4883
+ app.handler(index, false, undefined, undefined, app["~routeTable"]);
4884
+ return dispatch(index, context);
4885
+ };
3819
4886
  }
3820
4887
 
3821
4888
  // src/server/sync/plugin.ts
4889
+ init_principal_journal();
4890
+ init_queries();
3822
4891
  init_runtime();
3823
4892
 
3824
4893
  // src/server/sync/validation.ts
@@ -3836,7 +4905,7 @@ function bindSyncValidation(app) {
3836
4905
  applications.set(createContext2(app), app);
3837
4906
  return fetch;
3838
4907
  });
3839
- app.setup((root) => {
4908
+ app.onStart((root) => {
3840
4909
  applications.set(createContext2(root), root);
3841
4910
  });
3842
4911
  }
@@ -3849,24 +4918,26 @@ function syncValidationApp(context) {
3849
4918
  }
3850
4919
 
3851
4920
  // src/server/sync/plugin.ts
3852
- var routeMetadata = new WeakMap;
4921
+ var nonIdempotent = new WeakSet;
3853
4922
  var activeMutations = new WeakMap;
3854
4923
  var atomicCalls = new WeakSet;
3855
4924
  var atomicResponses = new WeakMap;
4925
+ var syncOwners = new WeakMap;
4926
+ var requestOwners = new WeakMap;
4927
+ var ownerId = 0;
3856
4928
  function hideTransportResponse(hook) {
3857
4929
  return hook;
3858
4930
  }
3859
- function invalidationInputFromSync(input) {
3860
- if (input && typeof input === "object" && "invalidate" in input) {
3861
- return input.invalidate;
3862
- }
3863
- if ("id" in input) {
3864
- return;
3865
- }
3866
- return input;
3867
- }
3868
- function isMutationMethod(method) {
3869
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
4931
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
4932
+ var PRINTABLE_ASCII = /^[\x20-\x7e]+$/;
4933
+ function invalidIdempotencyKeyResponse() {
4934
+ return Response.json({
4935
+ code: "FURIN_INVALID_IDEMPOTENCY_KEY",
4936
+ detail: `Idempotency-Key must be 1-${MAX_IDEMPOTENCY_KEY_LENGTH} printable ASCII characters.`,
4937
+ status: 400,
4938
+ title: "Bad Request",
4939
+ type: "about:blank"
4940
+ }, { headers: { "content-type": "application/problem+json" }, status: 400 });
3870
4941
  }
3871
4942
  function getIdempotencyKey(ctx) {
3872
4943
  const fromCtxHeaders = ctx.headers["idempotency-key"];
@@ -3887,11 +4958,21 @@ function leaseLostResponse() {
3887
4958
  message: "The mutation lease was lost before its response could be committed."
3888
4959
  }, { status: 503 });
3889
4960
  }
3890
- function createSyncPlugin(options) {
3891
- const runtime = resolveSyncRuntime(options);
3892
- const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
4961
+ function idempotentRouteMacro(_idempotent) {
4962
+ return {
4963
+ transform({ request }) {
4964
+ nonIdempotent.add(request);
4965
+ }
4966
+ };
4967
+ }
4968
+ function createSyncPlugin(options, owner) {
4969
+ const development = IS_DEV;
4970
+ prepareSyncRuntime(options, development);
4971
+ const runtime = () => resolveSyncRuntime(options, development);
3893
4972
  function mutationFor(ctx) {
3894
4973
  const mutation = async (callback) => {
4974
+ const resolved = runtime();
4975
+ const transactional = "executeMutation" in resolved.adapter ? resolved.adapter : undefined;
3895
4976
  const active = activeMutations.get(ctx.request);
3896
4977
  if (!(transactional && active)) {
3897
4978
  throw new Error("[furin] mutation() requires a transactional sync adapter and an enabled mutation route.");
@@ -3906,11 +4987,11 @@ function createSyncPlugin(options) {
3906
4987
  app: syncValidationApp(ctx),
3907
4988
  context: ctx,
3908
4989
  lease: active.lease,
3909
- invalidate: routeMetadata.get(ctx.request)?.invalidate,
3910
- runtime,
4990
+ runtime: resolved,
3911
4991
  onCommit: (result) => atomicResponses.set(ctx.request, result)
3912
4992
  }, callback);
3913
4993
  } finally {
4994
+ sealInvalidations(ctx.request);
3914
4995
  if (atomicResponses.has(ctx.request)) {
3915
4996
  releaseMutation(ctx.request);
3916
4997
  } else {
@@ -3924,20 +5005,14 @@ function createSyncPlugin(options) {
3924
5005
  return mutation;
3925
5006
  }
3926
5007
  async function beginMutation(ctx) {
3927
- if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
3928
- return;
3929
- }
3930
- const idempotencyKey = getIdempotencyKey(ctx);
3931
- if (!idempotencyKey) {
3932
- return new Response("Missing Idempotency-Key header", {
3933
- headers: { "content-type": "text/plain; charset=utf-8" },
3934
- status: 428
3935
- });
5008
+ const idempotencyKey = getIdempotencyKey(ctx) ?? crypto.randomUUID();
5009
+ if (idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH || !PRINTABLE_ASCII.test(idempotencyKey)) {
5010
+ return invalidIdempotencyKeyResponse();
3936
5011
  }
3937
5012
  if (!supportsReplayBody(ctx.request)) {
3938
5013
  return Response.json({
3939
5014
  code: "FURIN_UNSUPPORTED_SYNC_BODY",
3940
- message: "This request body cannot be replayed. Set sync: false on the route."
5015
+ message: "This request body cannot be replayed. Set idempotent: false on the route."
3941
5016
  }, { status: 415 });
3942
5017
  }
3943
5018
  const url = new URL(ctx.request.url);
@@ -3947,7 +5022,7 @@ function createSyncPlugin(options) {
3947
5022
  }
3948
5023
  const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
3949
5024
  const fingerprint = createMutationFingerprint({ body: ctx.body, request: ctx.request });
3950
- const result = await runtime.adapter.beginMutation({ fingerprint, key, principal });
5025
+ const result = await runtime().adapter.beginMutation({ fingerprint, key, principal });
3951
5026
  if (result.kind === "replay") {
3952
5027
  return replayResponse(result.response);
3953
5028
  }
@@ -3961,7 +5036,7 @@ function createSyncPlugin(options) {
3961
5036
  if (activeMutations.get(ctx.request) === active) {
3962
5037
  scheduleRenewal();
3963
5038
  }
3964
- await runtime.adapter.renewMutation(result.lease).catch(() => {
5039
+ await runtime().adapter.renewMutation(result.lease).catch(() => {
3965
5040
  return;
3966
5041
  });
3967
5042
  }, renewAfter);
@@ -3981,36 +5056,31 @@ function createSyncPlugin(options) {
3981
5056
  async function abortMutation(request) {
3982
5057
  const active = releaseMutation(request);
3983
5058
  if (active) {
3984
- await runtime.adapter.abortMutation(active.lease);
5059
+ await runtime().adapter.abortMutation(active.lease);
3985
5060
  }
3986
5061
  }
3987
- async function persistMutation(ctx, active) {
3988
- const result = await storeResponse(ctx.responseValue, ctx.set);
5062
+ async function applyInvalidations(ctx) {
3989
5063
  const manualPending = peekPendingInvalidations();
3990
- const invalidate = resolveSyncInvalidations(routeMetadata.get(ctx.request)?.invalidate, ctx, ctx.responseValue);
5064
+ const invalidate = resolveSyncInvalidations(ctx);
3991
5065
  appendQueryInvalidations(invalidate, ctx);
3992
- const logger = getLogger();
3993
- if (invalidate) {
3994
- try {
3995
- await runInvalidationRules(invalidate);
3996
- } catch {
3997
- logger.warn("Sync cache invalidation failed after mutation; preserving the idempotent result");
3998
- }
3999
- }
4000
- const pending = appendPendingInvalidationHeader(ctx.set);
4001
- if (pending.length > 0) {
4002
- ctx.set.headers["x-furin-sync"] = "1";
5066
+ try {
5067
+ await runInvalidationRules(invalidate);
5068
+ } catch {
5069
+ getLogger().warn("Sync cache invalidation failed after mutation; preserving its result");
4003
5070
  }
4004
- const response = mergeStoredResponseHeaders(result.response, ctx.set.headers);
5071
+ appendPendingInvalidationHeader(ctx.set);
5072
+ ctx.set.headers["x-furin-sync"] = "1";
4005
5073
  const semanticInvalidations = normalizedInvalidations(invalidate);
4006
- const invalidations = [...semanticInvalidations];
4007
- for (const manual of pendingPathInvalidations(manualPending)) {
4008
- const duplicated = semanticInvalidations.some((semantic) => semantic.kind === "path" && semantic.path === manual.path && semantic.type === manual.type);
4009
- if (!duplicated) {
4010
- invalidations.push(manual);
4011
- }
4012
- }
4013
- const completion = await runtime.adapter.completeMutation({
5074
+ return [
5075
+ ...semanticInvalidations,
5076
+ ...pendingPathInvalidations(manualPending).filter((manual) => !semanticInvalidations.some((semantic) => semantic.kind === "path" && semantic.path === manual.path && semantic.type === manual.type))
5077
+ ];
5078
+ }
5079
+ async function persistMutation(ctx, active) {
5080
+ const result = await storeResponse(ctx.responseValue, ctx.set);
5081
+ const invalidations = await applyInvalidations(ctx);
5082
+ const response = mergeStoredResponseHeaders(result.response, result.kind === "unreplayable" ? ctx.set.headers : effectiveResponseHeaders(ctx.responseValue, ctx.set));
5083
+ const completion = await runtime().adapter.completeMutation({
4014
5084
  invalidations,
4015
5085
  lease: active.lease,
4016
5086
  response
@@ -4018,16 +5088,24 @@ function createSyncPlugin(options) {
4018
5088
  if (completion.kind === "lost") {
4019
5089
  return leaseLostResponse();
4020
5090
  }
4021
- const notificationAlreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
4022
- if (completion.cursor !== undefined && !notificationAlreadyPublished) {
4023
- runtime.notifier.publish(completion.cursor).catch(() => {
4024
- return;
4025
- });
5091
+ if (completion.cursor !== undefined) {
5092
+ publishCursor(runtime(), completion.cursor);
4026
5093
  }
4027
5094
  if (result.kind === "unreplayable") {
4028
5095
  return replayResponse(response);
4029
5096
  }
4030
5097
  }
5098
+ async function journalMutation(ctx) {
5099
+ if (!(isMutationMethod(ctx.request.method) && isSuccessfulMutationResponse(ctx))) {
5100
+ return;
5101
+ }
5102
+ const invalidations = await applyInvalidations(ctx);
5103
+ try {
5104
+ publishCursor(runtime(), await runtime().adapter.appendInvalidations(invalidations));
5105
+ } catch {
5106
+ getLogger().warn("Sync journal append failed after a non-idempotent mutation");
5107
+ }
5108
+ }
4031
5109
  async function finishMutation(ctx) {
4032
5110
  const atomic = atomicResponses.get(ctx.request);
4033
5111
  atomicResponses.delete(ctx.request);
@@ -4048,12 +5126,12 @@ function createSyncPlugin(options) {
4048
5126
  }
4049
5127
  try {
4050
5128
  if (!isSuccessfulMutationResponse(ctx)) {
4051
- await runtime.adapter.abortMutation(active.lease);
5129
+ await runtime().adapter.abortMutation(active.lease);
4052
5130
  return;
4053
5131
  }
4054
5132
  return await persistMutation(ctx, active);
4055
5133
  } catch (error) {
4056
- await runtime.adapter.abortMutation(active.lease).catch(() => {
5134
+ await runtime().adapter.abortMutation(active.lease).catch(() => {
4057
5135
  return;
4058
5136
  });
4059
5137
  throw error;
@@ -4064,16 +5142,26 @@ function createSyncPlugin(options) {
4064
5142
  }
4065
5143
  }
4066
5144
  }
4067
- const finishMutationHook = hideTransportResponse(finishMutation);
4068
- const plugin = new Elysia3({ name: "furin-sync" }).derive("global", (ctx) => ({ mutation: mutationFor(ctx) })).beforeHandle("global", (context) => {
4069
- if (isMutationMethod(context.request.method) && !routeMetadata.get(context.request)?.disabled) {
5145
+ owner.mutationFor = mutationFor;
5146
+ const plugin = new Elysia5({ name: `furin-sync:${owner.id}` }).wrap((fetch) => (request, ...rest) => ensureRequestScope(() => fetch(request, ...rest))).derive("global", (ctx) => ({
5147
+ mutation: (requestOwners.get(ctx.request) ?? owner).mutationFor(ctx),
5148
+ invalidate: requestInvalidate(ctx.request)
5149
+ })).onBeforeHandle("global", (context) => {
5150
+ if (requestOwners.get(context.request) === owner && isMutationMethod(context.request.method) && !nonIdempotent.has(context.request)) {
4070
5151
  prepareMutationHandler(context, () => beginMutation(context));
4071
5152
  }
4072
- }).afterHandle("global", finishMutationHook).afterHandle("global", async (ctx) => {
4073
- const read = routeMetadata.get(ctx.request)?.read;
4074
- if (ctx.request.method !== "GET" || !read || !isSuccessfulMutationResponse({
5153
+ }).onAfterHandle("global", hideTransportResponse((context) => {
5154
+ if (requestOwners.get(context.request) !== owner) {
5155
+ return Promise.resolve(undefined);
5156
+ }
5157
+ return nonIdempotent.has(context.request) ? journalMutation(context) : finishMutation(context);
5158
+ })).onAfterHandle("global", async (ctx) => {
5159
+ if (requestOwners.get(ctx.request) !== owner) {
5160
+ return;
5161
+ }
5162
+ if (ctx.request.method !== "GET" || isInternalRead(ctx.request) || ctx.responseValue instanceof Response || !isSuccessfulMutationResponse({
4075
5163
  set: ctx.set,
4076
- responseValue: ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
5164
+ responseValue: ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
4077
5165
  })) {
4078
5166
  return;
4079
5167
  }
@@ -4082,54 +5170,409 @@ function createSyncPlugin(options) {
4082
5170
  throw new Error("[furin] Sync principal must not be empty.");
4083
5171
  }
4084
5172
  const identity = {
4085
- id: read.id,
4086
- scope: typeof read.scope === "function" ? read.scope(ctx) : read.scope ?? {},
4087
- session: new Bun.CryptoHasher("sha256").update(principal).digest("hex")
5173
+ ...urlIdentity(ctx),
5174
+ session: principalHash(runtime().adapter, principal)
4088
5175
  };
4089
- queryTag(identity);
4090
5176
  ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
4091
- }).error("global", MutationLeaseLost, hideTransportResponse(() => Promise.resolve(leaseLostResponse()))).error("global", hideTransportResponse(async ({ request }) => {
5177
+ }).onError("global", MutationLeaseLost, hideTransportResponse(({ request }) => Promise.resolve(requestOwners.get(request) === owner ? leaseLostResponse() : undefined))).onError("global", hideTransportResponse(async ({ request }) => {
5178
+ if (requestOwners.get(request) !== owner) {
5179
+ return;
5180
+ }
4092
5181
  atomicResponses.delete(request);
4093
5182
  atomicCalls.delete(request);
4094
5183
  await abortMutation(request);
4095
- })).macro({
4096
- sync(input) {
4097
- return {
4098
- transform({ request }) {
4099
- routeMetadata.set(request, input === false ? { disabled: true } : {
4100
- disabled: false,
4101
- invalidate: invalidationInputFromSync(input),
4102
- read: "id" in input ? input : undefined
4103
- });
4104
- }
4105
- };
4106
- }
4107
- });
5184
+ })).macro({ idempotent: idempotentRouteMacro });
4108
5185
  return plugin;
4109
5186
  }
4110
5187
  function furinSync(options) {
4111
5188
  return (app) => {
4112
- installMutationHandlers(app);
4113
- if ("executeMutation" in options.adapter) {
4114
- bindSyncValidation(app);
5189
+ let owner = syncOwners.get(options);
5190
+ if (!owner) {
5191
+ ownerId += 1;
5192
+ owner = { id: ownerId, mutationFor: () => {
5193
+ return;
5194
+ } };
5195
+ syncOwners.set(options, owner);
4115
5196
  }
4116
- return app.use(createSyncPlugin(options));
5197
+ const routeOwner = owner;
5198
+ app.onTransform(({ request }) => {
5199
+ requestOwners.set(request, routeOwner);
5200
+ });
5201
+ installMutationHandlers(app);
5202
+ bindSyncValidation(app);
5203
+ return app.use(createSyncPlugin(options, owner));
4117
5204
  };
4118
5205
  }
4119
5206
 
4120
5207
  // src/server/sync/index.ts
4121
5208
  init_stream();
5209
+
5210
+ // src/client/sync-client.ts
5211
+ function isEdenError(error) {
5212
+ return error instanceof Error && "status" in error && typeof error.status === "number" && "value" in error;
5213
+ }
5214
+ class SyncClientError extends Error {
5215
+ status;
5216
+ static [Symbol.hasInstance](error) {
5217
+ return error instanceof Error && error.name === "SyncClientError" && "status" in error;
5218
+ }
5219
+ constructor(message, status, cause) {
5220
+ super(message, { cause });
5221
+ this.name = "SyncClientError";
5222
+ this.status = status;
5223
+ }
5224
+ }
5225
+ function createSyncClientRuntime(options, transport) {
5226
+ const queries = new QueryStore(undefined);
5227
+ const listeners = new Set;
5228
+ const subscriptions = new Map;
5229
+ let state = { status: "idle", error: null };
5230
+ let controller = new AbortController;
5231
+ let ready = Promise.withResolvers();
5232
+ let connection;
5233
+ let timer;
5234
+ let attempt = 0;
5235
+ let generation = 0;
5236
+ let session;
5237
+ const publish = (status, error, reason) => {
5238
+ state = { status, error, reason };
5239
+ for (const listener of listeners) {
5240
+ listener(state);
5241
+ }
5242
+ };
5243
+ const headers = async () => new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
5244
+ const asError = (error) => error instanceof SyncClientError ? error : new SyncClientError("Sync connection failed", undefined, error);
5245
+ const unauthorized = (error) => error.status === 401 || error.status === 403;
5246
+ const active = () => state.status !== "closed" && state.status !== "unauthorized";
5247
+ const createRecovery = () => createSyncCatchUp({
5248
+ fetchPage: async (after) => {
5249
+ const { signal } = controller;
5250
+ const requestHeaders = await headers();
5251
+ signal.throwIfAborted();
5252
+ const response = await transport.fetchChanges(after, requestHeaders, signal);
5253
+ signal.throwIfAborted();
5254
+ if (!response.ok) {
5255
+ throw new SyncClientError("Sync recovery refused", response.status);
5256
+ }
5257
+ const page = await response.json();
5258
+ signal.throwIfAborted();
5259
+ const identity = response.headers.get("x-furin-sync-session");
5260
+ if (identity !== null) {
5261
+ if (session !== undefined && identity !== session) {
5262
+ reconnect();
5263
+ }
5264
+ session = identity;
5265
+ }
5266
+ return page;
5267
+ },
5268
+ onInvalidations: (paths) => {
5269
+ if (paths.includes("/:layout")) {
5270
+ queries.invalidateAll();
5271
+ }
5272
+ },
5273
+ onQueries: (identities) => queries.invalidate(identities)
5274
+ });
5275
+ let recovery = createRecovery();
5276
+ const releaseConnection = () => {
5277
+ connection?.stop?.();
5278
+ connection = undefined;
5279
+ clearTimeout(timer);
5280
+ timer = undefined;
5281
+ };
5282
+ const fail = (value) => {
5283
+ if (!active()) {
5284
+ return;
5285
+ }
5286
+ const error = asError(value);
5287
+ releaseConnection();
5288
+ if (unauthorized(error)) {
5289
+ generation += 1;
5290
+ const epoch = generation;
5291
+ recovery.close();
5292
+ state = { status: "unauthorized", error };
5293
+ controller.abort();
5294
+ ready.resolve();
5295
+ queries.clear();
5296
+ if (epoch === generation) {
5297
+ publish("unauthorized", error);
5298
+ }
5299
+ return;
5300
+ }
5301
+ const delay = Math.min(250 * 2 ** attempt, 5000);
5302
+ attempt += 1;
5303
+ timer = setTimeout(() => {
5304
+ timer = undefined;
5305
+ connect();
5306
+ }, delay);
5307
+ publish("reconnecting", error, "network");
5308
+ };
5309
+ const checkAccess = (url, status, error) => {
5310
+ if (status === 403) {
5311
+ queries.setError(url, error);
5312
+ } else if (status === 401) {
5313
+ fail(new SyncClientError("Live query access refused", status));
5314
+ if (state.status === "unauthorized") {
5315
+ queries.setError(url, error);
5316
+ }
5317
+ }
5318
+ };
5319
+ const connect = async () => {
5320
+ const epoch = generation;
5321
+ try {
5322
+ await recovery.catchUp();
5323
+ if (epoch !== generation || !active()) {
5324
+ return;
5325
+ }
5326
+ const requestHeaders = await headers();
5327
+ if (epoch !== generation || !active()) {
5328
+ return;
5329
+ }
5330
+ const current = {};
5331
+ connection = current;
5332
+ const stop = await transport.subscribe({
5333
+ headers: requestHeaders,
5334
+ signal: controller.signal,
5335
+ onContextChange: () => {
5336
+ if (epoch === generation && connection === current && active()) {
5337
+ reconnect(undefined, true);
5338
+ }
5339
+ },
5340
+ onCursor: () => {
5341
+ recovery.catchUp().then(() => {
5342
+ if (epoch === generation && active() && connection === current) {
5343
+ const reconnecting = state.status === "reconnecting";
5344
+ attempt = 0;
5345
+ ready.resolve();
5346
+ publish("connected", null);
5347
+ if (reconnecting && epoch === generation && connection === current) {
5348
+ for (const url of subscriptions.values()) {
5349
+ queries.fetch(url);
5350
+ }
5351
+ }
5352
+ }
5353
+ }).catch((error) => {
5354
+ if (epoch === generation && connection === current) {
5355
+ fail(error);
5356
+ }
5357
+ });
5358
+ },
5359
+ onError: (error) => {
5360
+ if (epoch === generation && connection === current) {
5361
+ fail(error);
5362
+ }
5363
+ }
5364
+ });
5365
+ if (epoch !== generation || !active() || connection !== current) {
5366
+ stop();
5367
+ return;
5368
+ }
5369
+ current.stop = stop;
5370
+ } catch (error) {
5371
+ if (epoch === generation) {
5372
+ fail(error);
5373
+ }
5374
+ }
5375
+ };
5376
+ function reconnect(reconnectOptions, automatic) {
5377
+ if (state.status === "closed") {
5378
+ return;
5379
+ }
5380
+ generation += 1;
5381
+ const epoch = generation;
5382
+ releaseConnection();
5383
+ const cursor = reconnectOptions?.preserveCache ? recovery.cursor() : undefined;
5384
+ recovery.close();
5385
+ controller.abort();
5386
+ ready.resolve();
5387
+ controller = new AbortController;
5388
+ ready = Promise.withResolvers();
5389
+ recovery = createRecovery();
5390
+ if (cursor === undefined) {
5391
+ session = undefined;
5392
+ } else {
5393
+ recovery.seed(cursor);
5394
+ }
5395
+ const delay = Math.min(250 * 2 ** attempt, 5000);
5396
+ attempt = automatic ? attempt + 1 : 0;
5397
+ queries.clear(reconnectOptions?.preserveCache);
5398
+ if (epoch !== generation) {
5399
+ return;
5400
+ }
5401
+ publish(automatic ? "reconnecting" : "connecting", null, reconnectOptions?.preserveCache ? "credentials" : "context");
5402
+ if (epoch !== generation) {
5403
+ return;
5404
+ }
5405
+ if (automatic) {
5406
+ timer = setTimeout(() => {
5407
+ timer = undefined;
5408
+ connect();
5409
+ }, delay);
5410
+ } else {
5411
+ connect();
5412
+ }
5413
+ queries.invalidateAll();
5414
+ }
5415
+ return {
5416
+ subscribe(query, listener) {
5417
+ if (state.status === "closed") {
5418
+ throw new SyncClientError("Sync client is closed", undefined);
5419
+ }
5420
+ const { reference, options: readOptions } = query[LIVE_QUERY];
5421
+ if (!transport.accepts(reference)) {
5422
+ throw new SyncClientError("Live query belongs to a different server", undefined);
5423
+ }
5424
+ const url = queries.readKey(reference, readOptions);
5425
+ queries.bind(url, async () => {
5426
+ const { signal } = controller;
5427
+ try {
5428
+ await ready.promise;
5429
+ signal.throwIfAborted();
5430
+ const read = readOptions;
5431
+ const fetch = { ...options.fetch, ...read?.fetch };
5432
+ fetch.signal = fetch.signal ? AbortSignal.any([signal, fetch.signal]) : signal;
5433
+ const result = await reference.load({
5434
+ ...read,
5435
+ ...options.headers === undefined ? {} : { headers: [read?.headers, await headers()] },
5436
+ fetch
5437
+ });
5438
+ signal.throwIfAborted();
5439
+ checkAccess(url, result.response?.status, result.error);
5440
+ return result;
5441
+ } catch (error) {
5442
+ if (signal.aborted) {
5443
+ throw asError(signal.reason);
5444
+ }
5445
+ if (isEdenError(error)) {
5446
+ checkAccess(url, error.status, error);
5447
+ return { data: null, error };
5448
+ }
5449
+ throw asError(error);
5450
+ }
5451
+ }, reference.client);
5452
+ let stopped = false;
5453
+ const unlisten = queries.subscribe(url, () => {
5454
+ if (!stopped) {
5455
+ listener(queries.snapshot(url));
5456
+ }
5457
+ });
5458
+ const stop = () => {
5459
+ stopped = true;
5460
+ unlisten();
5461
+ subscriptions.delete(stop);
5462
+ };
5463
+ subscriptions.set(stop, url);
5464
+ listener(queries.snapshot(url));
5465
+ if (!subscriptions.has(stop)) {
5466
+ return stop;
5467
+ }
5468
+ if (state.status === "idle") {
5469
+ publish("connecting", null);
5470
+ connect();
5471
+ }
5472
+ queries.fetch(url);
5473
+ return stop;
5474
+ },
5475
+ getConnectionState: () => state,
5476
+ subscribeConnection(listener) {
5477
+ if (state.status === "closed") {
5478
+ listener(state);
5479
+ return () => {
5480
+ return;
5481
+ };
5482
+ }
5483
+ listeners.add(listener);
5484
+ listener(state);
5485
+ return () => {
5486
+ listeners.delete(listener);
5487
+ };
5488
+ },
5489
+ reconnect,
5490
+ close() {
5491
+ if (state.status === "closed") {
5492
+ return;
5493
+ }
5494
+ generation += 1;
5495
+ publish("closed", null);
5496
+ releaseConnection();
5497
+ recovery.close();
5498
+ controller.abort();
5499
+ ready.resolve();
5500
+ for (const stop of subscriptions.keys()) {
5501
+ stop();
5502
+ }
5503
+ listeners.clear();
5504
+ queries.dispose();
5505
+ }
5506
+ };
5507
+ }
5508
+
5509
+ // src/server/sync/local-client.ts
5510
+ init_connection();
5511
+ init_stream();
5512
+ function createLocalSyncClient(options) {
5513
+ const changesUrl = new URL(`${options.syncPath ?? options.sync.path ?? "/_furin/sync"}/changes`, "http://e.ly");
5514
+ return createSyncClientRuntime(options, {
5515
+ accepts: (reference) => reference.application === options.app,
5516
+ fetchChanges: (after, headers, signal) => {
5517
+ const url = new URL(changesUrl);
5518
+ url.searchParams.set("after", after ?? "0");
5519
+ return options.app.handle(new Request(url, { ...options.fetch, headers, signal }));
5520
+ },
5521
+ subscribe: async ({ headers, signal, onCursor, onContextChange }) => {
5522
+ let access;
5523
+ let unsubscribe;
5524
+ const stop = () => {
5525
+ signal.removeEventListener("abort", stop);
5526
+ access?.close();
5527
+ unsubscribe?.();
5528
+ };
5529
+ signal.addEventListener("abort", stop, { once: true });
5530
+ const request = new Request(changesUrl, {
5531
+ ...options.fetch,
5532
+ headers,
5533
+ signal
5534
+ });
5535
+ request[LOCAL_SYNC_CONNECTION] = async (context, sync) => {
5536
+ access = createSyncConnectionLifetime(sync, context, onContextChange);
5537
+ await access.acquire();
5538
+ if (signal.aborted) {
5539
+ return;
5540
+ }
5541
+ const subscription = await subscribeSyncCursor(sync, IS_DEV, onCursor);
5542
+ if (signal.aborted) {
5543
+ subscription.unsubscribe();
5544
+ } else {
5545
+ ({ unsubscribe } = subscription);
5546
+ }
5547
+ };
5548
+ try {
5549
+ signal.throwIfAborted();
5550
+ const response = await options.app.handle(request);
5551
+ signal.throwIfAborted();
5552
+ if (!response.ok) {
5553
+ throw new SyncClientError("Local sync connection refused", response.status);
5554
+ }
5555
+ if (!access) {
5556
+ throw new SyncClientError("Local sync endpoint does not support event connections", undefined);
5557
+ }
5558
+ return stop;
5559
+ } catch (error) {
5560
+ stop();
5561
+ throw error;
5562
+ }
5563
+ }
5564
+ });
5565
+ }
5566
+
5567
+ // src/server/sync/index.ts
4122
5568
  var createSyncChangesPlugin2 = createSyncChangesPlugin;
4123
5569
  var furinSync2 = furinSync;
4124
- var getSyncPath2 = getSyncPath;
5570
+ var invalidateSync2 = invalidateSync;
4125
5571
  var PollingSyncNotifier2 = PollingSyncNotifier;
4126
- var resolveSyncPath2 = resolveSyncPath;
4127
- var runWithSyncPath2 = runWithSyncPath;
4128
5572
  export {
4129
5573
  PollingSyncNotifier2 as PollingSyncNotifier,
5574
+ createLocalSyncClient,
4130
5575
  createSyncChangesPlugin2 as createSyncChangesPlugin,
4131
5576
  furinSync2 as furinSync,
4132
- getSyncPath2 as getSyncPath,
4133
- resolveSyncPath2 as resolveSyncPath,
4134
- runWithSyncPath2 as runWithSyncPath
5577
+ invalidateSync2 as invalidateSync
4135
5578
  };