@teyik0/furin 0.7.0-alpha.3 → 0.8.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 (497) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/build.d.ts +9 -0
  3. package/dist/adapter/bun/server.d.ts +1 -0
  4. package/dist/adapter/bun.d.ts +7 -3
  5. package/dist/adapter/package.d.ts +1 -0
  6. package/dist/adapter/prerender.d.ts +21 -0
  7. package/dist/adapter/runtime-build.d.ts +24 -10
  8. package/dist/adapter/server-bundle.d.ts +20 -0
  9. package/dist/adapter/static.d.ts +2 -2
  10. package/dist/adapter/types.d.ts +81 -0
  11. package/dist/adapter/vercel/bootstrap.d.ts +5 -0
  12. package/dist/adapter/vercel/data.d.ts +23 -0
  13. package/dist/adapter/vercel/handler.d.ts +10 -0
  14. package/dist/adapter/vercel.d.ts +13 -3
  15. package/dist/adapter/vercel.js +516 -0
  16. package/dist/build/bun-build.d.ts +4 -0
  17. package/dist/build/compile-entry.ts +1 -0
  18. package/dist/build/discover-mounts-process.d.ts +1 -0
  19. package/dist/build/discover-mounts.d.ts +6 -0
  20. package/dist/build/elysia-aot-worker.d.ts +4 -0
  21. package/dist/build/elysia-aot.d.ts +7 -1
  22. package/dist/build/entry-template.d.ts +14 -7
  23. package/dist/build/entry-template.ts +33 -18
  24. package/dist/build/hydrate.d.ts +15 -2
  25. package/dist/build/index.d.ts +7 -3
  26. package/dist/build/index.js +8842 -15395
  27. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  28. package/dist/build/route-types.d.ts +8 -2
  29. package/dist/build/server-app-entry.d.ts +2 -2
  30. package/dist/build/shared.d.ts +3 -5
  31. package/dist/build/types.d.ts +16 -16
  32. package/dist/cache.js +117 -32
  33. package/dist/cli/config.d.ts +2 -2
  34. package/dist/cli/index.js +8953 -15269
  35. package/dist/client/chunks/client-brdfd773.js +852 -0
  36. package/dist/client/chunks/client-k29262a4.js +59 -0
  37. package/dist/client/chunks/client-k88668k7.js +159 -0
  38. package/dist/client/chunks/client-xy6g38kx.js +317 -0
  39. package/dist/client/default-screens.d.ts +0 -11
  40. package/dist/client/define-route.d.ts +2 -1
  41. package/dist/client/hmr.d.ts +1 -1
  42. package/dist/client/internal/runtime-types.d.ts +7 -1
  43. package/dist/client/link.d.ts +1 -0
  44. package/dist/client/link.js +1790 -4190
  45. package/dist/client/mutation.d.ts +5 -0
  46. package/dist/client/query-store.d.ts +17 -7
  47. package/dist/client/query.d.ts +6 -8
  48. package/dist/client/request-id.d.ts +1 -0
  49. package/dist/client/route-api.d.ts +4 -4
  50. package/dist/client/route-element.d.ts +51 -0
  51. package/dist/client/router/boundary-tree.d.ts +1 -9
  52. package/dist/client/router/cache-generation.d.ts +15 -0
  53. package/dist/client/router/context.d.ts +13 -2
  54. package/dist/client/router/fetch-observers.d.ts +9 -0
  55. package/dist/client/router/hmr-refresh.d.ts +12 -0
  56. package/dist/client/router/index.d.ts +5 -7
  57. package/dist/client/router/link-utils.d.ts +0 -2
  58. package/dist/client/router/navigation-controller.d.ts +76 -0
  59. package/dist/client/router/navigation.d.ts +1 -0
  60. package/dist/client/router/page-fetch.d.ts +38 -0
  61. package/dist/client/router/provider.d.ts +2 -3
  62. package/dist/client/router/search/index.d.ts +11 -4
  63. package/dist/client/router/search/index.js +60 -0
  64. package/dist/client/router/spa-response.d.ts +9 -26
  65. package/dist/client/router/sync-catch-up.d.ts +3 -2
  66. package/dist/client/router/transport.d.ts +4 -0
  67. package/dist/client/router/types.d.ts +120 -46
  68. package/dist/client/router/use-fetch-interception.d.ts +12 -0
  69. package/dist/client/router/use-history-sync.d.ts +7 -0
  70. package/dist/client/router/use-hmr-refresh.d.ts +8 -0
  71. package/dist/client/router/use-sync-stream.d.ts +16 -0
  72. package/dist/client/server-error.d.ts +4 -7
  73. package/dist/client/sync.d.ts +43 -30
  74. package/dist/client.d.ts +2 -1
  75. package/dist/client.js +279 -829
  76. package/dist/config.d.ts +11 -12
  77. package/dist/config.js +0 -30
  78. package/dist/define-route.d.ts +262 -517
  79. package/dist/devtools/protocol.d.ts +4 -3
  80. package/dist/furin.d.ts +41 -31
  81. package/dist/furin.js +20560 -18970
  82. package/dist/plugin/binding-scope.d.ts +15 -2
  83. package/dist/plugin/client-plugin.d.ts +19 -0
  84. package/dist/plugin/dead-code-elimination.d.ts +14 -3
  85. package/dist/plugin/dev-routes.d.ts +22 -0
  86. package/dist/plugin/hmr-data-signature.d.ts +3 -0
  87. package/dist/plugin/hmr-hook-signature.d.ts +9 -0
  88. package/dist/plugin/index.d.ts +1 -6
  89. package/dist/plugin/index.js +1753 -1214
  90. package/dist/plugin/module-bindings.d.ts +11 -0
  91. package/dist/plugin/module-transform.d.ts +29 -0
  92. package/dist/plugin/preflight.d.ts +8 -0
  93. package/dist/plugin/route-chains.d.ts +35 -0
  94. package/dist/plugin/route-config.d.ts +28 -0
  95. package/dist/plugin/route-modules.d.ts +35 -0
  96. package/dist/plugin/route-registry.d.ts +12 -0
  97. package/dist/plugin/route-tree.d.ts +43 -0
  98. package/dist/plugin/strip-server-stages.d.ts +10 -0
  99. package/dist/plugin/strip-server.d.ts +10 -0
  100. package/dist/plugin/transform-client-module.d.ts +3 -0
  101. package/dist/plugin/transform-client.d.ts +0 -2
  102. package/dist/plugin/transform-isomorphic.d.ts +3 -2
  103. package/dist/routes.d.ts +15 -5
  104. package/dist/rsc/build/client-references.d.ts +8 -0
  105. package/dist/rsc/build/discover.d.ts +7 -0
  106. package/dist/rsc/build/flight-loader.d.ts +1 -0
  107. package/dist/rsc/build/index.d.ts +4 -1
  108. package/dist/rsc/build/paths.d.ts +2 -0
  109. package/dist/rsc/bundled-client-codec.d.ts +1 -0
  110. package/dist/rsc/client-codec.d.ts +3 -0
  111. package/dist/rsc/client-references.d.ts +22 -0
  112. package/dist/rsc/server-client-codec.d.ts +1 -0
  113. package/dist/rsc/server-codec.js +3889 -2
  114. package/dist/rsc/slot-proxy.d.ts +11 -0
  115. package/dist/rsc/transport-benchmark.d.ts +2 -1
  116. package/dist/rsc-client.js +16 -164
  117. package/dist/rsc-server.d.ts +1 -5
  118. package/dist/rsc.d.ts +1 -5
  119. package/dist/rsc.js +233 -73
  120. package/dist/server/assets/client-dir.d.ts +1 -0
  121. package/dist/server/auto-invalidate/index.d.ts +2 -2
  122. package/dist/server/auto-invalidate/plugin.d.ts +21 -15
  123. package/dist/server/auto-invalidate/types.d.ts +0 -2
  124. package/dist/server/bounded-body.d.ts +6 -0
  125. package/dist/server/browser-events/plugin.d.ts +4 -1
  126. package/dist/server/browser-events/shutdown.d.ts +1 -1
  127. package/dist/server/cache/dev-loader.d.ts +6 -1
  128. package/dist/server/cache/index.d.ts +4 -9
  129. package/dist/server/cache/invalidation.d.ts +7 -2
  130. package/dist/server/cache/isr-ssg.d.ts +6 -1
  131. package/dist/server/cache/page-cache.d.ts +5 -0
  132. package/dist/server/cache/purger.d.ts +14 -4
  133. package/dist/server/cache/redis/index.d.ts +1 -34
  134. package/dist/server/cache/redis/index.js +51 -25
  135. package/dist/server/cache/redis/scripts.d.ts +1 -1
  136. package/dist/server/cache/route-cache.d.ts +18 -2
  137. package/dist/server/cache/runtime-cache.d.ts +7 -0
  138. package/dist/server/context-logger.d.ts +6 -1
  139. package/dist/server/dev/graph.d.ts +4 -3
  140. package/dist/server/dev/runtime.d.ts +4 -0
  141. package/dist/server/dev/runtime.production.d.ts +1 -0
  142. package/dist/server/dev/stack-location.d.ts +9 -0
  143. package/dist/server/dev-page-imports.d.ts +42 -0
  144. package/dist/server/dev-page-plugin.d.ts +2 -49
  145. package/dist/server/devtools/instrumentation.d.ts +1 -3
  146. package/dist/server/devtools/instrumentation.production.d.ts +0 -2
  147. package/dist/server/devtools/request-context.d.ts +7 -0
  148. package/dist/server/evlog.d.ts +18 -6
  149. package/dist/server/instance.d.ts +52 -44
  150. package/dist/server/internal.d.ts +51 -14
  151. package/dist/server/internal.js +9749 -2095
  152. package/dist/server/lang-detect.d.ts +4 -4
  153. package/dist/server/logger.d.ts +6 -0
  154. package/dist/server/logging/ingest-plugin.d.ts +32 -0
  155. package/dist/server/mode.d.ts +17 -0
  156. package/dist/server/prerender.d.ts +32 -0
  157. package/dist/server/prod/runtime.d.ts +5 -0
  158. package/dist/server/production-server.js +992 -726
  159. package/dist/server/registrations.d.ts +14 -0
  160. package/dist/server/render/assemble.d.ts +0 -22
  161. package/dist/server/render/buffered-render.d.ts +20 -0
  162. package/dist/server/render/document-stream.d.ts +45 -0
  163. package/dist/server/render/document.d.ts +1 -1
  164. package/dist/server/render/element.d.ts +2 -5
  165. package/dist/server/render/index.d.ts +4 -5
  166. package/dist/server/render/index.ts +4 -21
  167. package/dist/server/render/isr-revalidation.d.ts +5 -0
  168. package/dist/server/render/isr-shared-cache.d.ts +23 -0
  169. package/dist/server/render/isr.d.ts +19 -1
  170. package/dist/server/render/loader-errors.d.ts +33 -0
  171. package/dist/server/render/loader-segments.d.ts +40 -0
  172. package/dist/server/render/loaders.d.ts +16 -32
  173. package/dist/server/render/mixed-cache.d.ts +2 -2
  174. package/dist/server/render/navigation-head.d.ts +13 -0
  175. package/dist/server/render/not-found-plugin.d.ts +18 -0
  176. package/dist/server/render/observe-loader.d.ts +1 -0
  177. package/dist/server/render/ppr-document.d.ts +1 -1
  178. package/dist/server/render/ppr-request.d.ts +0 -2
  179. package/dist/server/render/ppr-route.d.ts +13 -2
  180. package/dist/server/render/prepare-render.d.ts +57 -0
  181. package/dist/server/render/request-loaders.d.ts +19 -0
  182. package/dist/server/render/route-frame-transport.d.ts +7 -1
  183. package/dist/server/render/shell.d.ts +1 -1
  184. package/dist/server/render/shell.ts +1 -1
  185. package/dist/server/render/ssr-transport.d.ts +11 -0
  186. package/dist/server/render/ssr.d.ts +1 -116
  187. package/dist/server/render/static-params.d.ts +15 -0
  188. package/dist/server/router/discovery.d.ts +1 -0
  189. package/dist/server/router/dispatch.d.ts +96 -0
  190. package/dist/server/router/hmr.d.ts +14 -24
  191. package/dist/server/router/patterns.d.ts +15 -20
  192. package/dist/server/router/plugin.d.ts +26 -24
  193. package/dist/server/router/schemas.d.ts +6 -24
  194. package/dist/server/router/types.d.ts +0 -2
  195. package/dist/server/runtime-env.d.ts +6 -1
  196. package/dist/server/static-export.d.ts +38 -0
  197. package/dist/server/static-export.js +10667 -0
  198. package/dist/server/sync/adapter.d.ts +11 -0
  199. package/dist/server/sync/atomic.d.ts +0 -2
  200. package/dist/server/sync/config.d.ts +0 -1
  201. package/dist/server/sync/drizzle/index.js +112 -68
  202. package/dist/server/sync/fingerprint.d.ts +0 -1
  203. package/dist/server/sync/index.d.ts +2 -6
  204. package/dist/server/sync/index.js +1689 -1364
  205. package/dist/server/sync/invalidate-sync.d.ts +10 -0
  206. package/dist/server/sync/plugin.d.ts +18 -55
  207. package/dist/server/sync/postgres/execute.d.ts +2 -2
  208. package/dist/server/sync/postgres/index.d.ts +3 -1
  209. package/dist/server/sync/postgres/index.js +68 -37
  210. package/dist/server/sync/postgres/migration.sql +2 -0
  211. package/dist/server/sync/principal-journal.d.ts +11 -0
  212. package/dist/server/sync/prisma/index.js +74 -39
  213. package/dist/server/sync/queries.d.ts +57 -16
  214. package/dist/server/sync/redis/index.d.ts +2 -1
  215. package/dist/server/sync/redis/index.js +49 -5
  216. package/dist/server/sync/redis/scripts.d.ts +2 -1
  217. package/dist/server/sync/response.d.ts +3 -0
  218. package/dist/server/sync/runtime.d.ts +5 -1
  219. package/dist/server/sync/sqlite/index.d.ts +3 -1
  220. package/dist/server/sync/sqlite/index.js +58 -27
  221. package/dist/server/sync/stream.d.ts +32 -7
  222. package/dist/server/weak-registry.d.ts +9 -0
  223. package/dist/shared/await.d.ts +2 -1
  224. package/dist/shared/compact-json.d.ts +1 -0
  225. package/dist/shared/defer.d.ts +1 -1
  226. package/dist/shared/deferred-ndjson.d.ts +3 -2
  227. package/dist/shared/elysia-contract.d.ts +2 -0
  228. package/dist/shared/in-memory-apps.d.ts +7 -0
  229. package/dist/shared/invalidation-header.d.ts +13 -0
  230. package/dist/shared/navigation-data.d.ts +7 -0
  231. package/dist/shared/prefix.d.ts +11 -5
  232. package/dist/shared/route-frame.d.ts +3 -0
  233. package/dist/shared/route-map.d.ts +7 -0
  234. package/dist/shared/route-matches.d.ts +41 -0
  235. package/dist/shared/route-specificity.d.ts +2 -0
  236. package/dist/shared/search-params.d.ts +2 -3
  237. package/dist/shared/sync-query.d.ts +6 -13
  238. package/dist/shared/utils/ast-walk.d.ts +3 -11
  239. package/package.json +32 -21
  240. package/src/adapter/README.md +37 -16
  241. package/src/adapter/build.ts +269 -0
  242. package/src/adapter/bun/server.ts +14 -0
  243. package/src/adapter/bun.ts +89 -265
  244. package/src/adapter/furin-app.d.ts +14 -0
  245. package/src/adapter/package.ts +31 -27
  246. package/src/adapter/prerender.ts +97 -0
  247. package/src/adapter/runtime-build.ts +83 -93
  248. package/src/adapter/server-bundle.ts +110 -0
  249. package/src/adapter/static.ts +259 -247
  250. package/src/adapter/types.ts +89 -0
  251. package/src/adapter/vercel/bootstrap.ts +85 -0
  252. package/src/adapter/vercel/data.ts +21 -0
  253. package/src/adapter/vercel/handler.ts +132 -0
  254. package/src/adapter/vercel.ts +329 -659
  255. package/src/build/bun-build.ts +3 -0
  256. package/src/build/client.ts +22 -60
  257. package/src/build/compile-entry.ts +1 -0
  258. package/src/build/discover-mounts-process.ts +13 -0
  259. package/src/build/discover-mounts.ts +40 -0
  260. package/src/build/elysia-aot-worker.ts +84 -2
  261. package/src/build/elysia-aot.ts +61 -2
  262. package/src/build/entry-template.ts +33 -18
  263. package/src/build/hydrate.ts +122 -44
  264. package/src/build/index.ts +156 -108
  265. package/src/build/private-server-sourcemaps.ts +5 -0
  266. package/src/build/production-instrumentation.ts +22 -19
  267. package/src/build/route-types.ts +93 -11
  268. package/src/build/server-app-entry.ts +4 -21
  269. package/src/build/shared.ts +9 -41
  270. package/src/build/types.ts +14 -20
  271. package/src/build/virtual-entry.ts +2 -4
  272. package/src/cli/config.ts +133 -6
  273. package/src/cli/index.ts +59 -21
  274. package/src/cli/preview.ts +2 -1
  275. package/src/client/boundaries.tsx +5 -14
  276. package/src/client/default-screens.tsx +2 -2
  277. package/src/client/define-route.ts +3 -2
  278. package/src/client/hmr.ts +1 -1
  279. package/src/client/internal/runtime-types.ts +7 -1
  280. package/src/client/link.tsx +80 -43
  281. package/src/client/mutation.ts +98 -3
  282. package/src/client/query-store.ts +160 -29
  283. package/src/client/query.tsx +12 -29
  284. package/src/client/request-id.ts +10 -0
  285. package/src/client/route-api.tsx +6 -6
  286. package/src/client/route-element.tsx +155 -0
  287. package/src/client/router/boundary-tree.tsx +2 -93
  288. package/src/client/router/cache-generation.ts +37 -0
  289. package/src/client/router/context.ts +40 -4
  290. package/src/client/router/fetch-observers.ts +46 -0
  291. package/src/client/router/hmr-refresh.ts +50 -0
  292. package/src/client/router/index.ts +7 -29
  293. package/src/client/router/link-utils.ts +19 -31
  294. package/src/client/router/navigation-controller.ts +547 -0
  295. package/src/client/router/navigation.ts +3 -2
  296. package/src/client/router/optimistic.ts +2 -3
  297. package/src/client/router/page-fetch.ts +272 -0
  298. package/src/client/router/provider.tsx +223 -1079
  299. package/src/client/router/search/index.ts +38 -14
  300. package/src/client/router/spa-response.ts +19 -70
  301. package/src/client/router/sync-catch-up.ts +65 -7
  302. package/src/client/router/transport.ts +23 -0
  303. package/src/client/router/types.ts +203 -61
  304. package/src/client/router/use-fetch-interception.ts +52 -0
  305. package/src/client/router/use-history-sync.ts +56 -0
  306. package/src/client/router/use-hmr-refresh.ts +51 -0
  307. package/src/client/router/use-sync-stream.ts +129 -0
  308. package/src/client/server-error.ts +2 -40
  309. package/src/client/sync.ts +268 -378
  310. package/src/client.ts +2 -7
  311. package/src/config.ts +23 -45
  312. package/src/define-route.ts +487 -882
  313. package/src/devtools/devtools-element.js +10 -3
  314. package/src/devtools/protocol.ts +3 -3
  315. package/src/furin.ts +253 -1086
  316. package/src/plugin/binding-scope.ts +219 -94
  317. package/src/plugin/client-plugin.ts +145 -0
  318. package/src/plugin/dead-code-elimination.ts +390 -111
  319. package/src/plugin/dev-routes.ts +453 -0
  320. package/src/plugin/hmr-data-signature.ts +161 -0
  321. package/src/plugin/hmr-dependencies.ts +2 -4
  322. package/src/plugin/hmr-hook-signature.ts +252 -0
  323. package/src/plugin/index.ts +3 -96
  324. package/src/plugin/module-bindings.ts +216 -0
  325. package/src/plugin/module-transform.ts +63 -0
  326. package/src/plugin/preflight.ts +66 -0
  327. package/src/plugin/route-chains.ts +309 -0
  328. package/src/plugin/route-config.ts +451 -0
  329. package/src/plugin/route-modules.ts +209 -0
  330. package/src/plugin/route-registry.ts +316 -0
  331. package/src/plugin/route-tree.ts +248 -0
  332. package/src/plugin/strip-server-stages.ts +197 -0
  333. package/src/plugin/strip-server.ts +22 -0
  334. package/src/plugin/transform-client-module.ts +36 -31
  335. package/src/plugin/transform-client.ts +33 -1114
  336. package/src/plugin/transform-dev-page.ts +84 -92
  337. package/src/plugin/transform-isomorphic.ts +396 -185
  338. package/src/routes.ts +15 -5
  339. package/src/rsc/build/client-references.ts +267 -0
  340. package/src/rsc/build/discover.ts +226 -0
  341. package/src/rsc/build/flight-loader.ts +69 -0
  342. package/src/rsc/build/index.ts +53 -31
  343. package/src/rsc/build/paths.ts +7 -0
  344. package/src/rsc/bundled-client-codec.ts +4 -0
  345. package/src/rsc/client-codec.ts +12 -3
  346. package/src/rsc/client-references.ts +138 -0
  347. package/src/rsc/codec.ts +30 -21
  348. package/src/rsc/flight-drain.ts +6 -29
  349. package/src/rsc/react-server-dom-webpack.d.ts +1 -1
  350. package/src/rsc/server-client-codec.ts +14 -0
  351. package/src/rsc/server-codec.ts +5 -8
  352. package/src/rsc/slot-proxy.ts +34 -0
  353. package/src/rsc/transport-benchmark.ts +1 -1
  354. package/src/rsc-server.tsx +5 -23
  355. package/src/rsc.tsx +5 -29
  356. package/src/server/assets/client-dir.ts +110 -0
  357. package/src/server/assets/production.ts +1 -1
  358. package/src/server/auto-invalidate/index.ts +2 -7
  359. package/src/server/auto-invalidate/plugin.ts +43 -15
  360. package/src/server/auto-invalidate/registry.ts +6 -6
  361. package/src/server/auto-invalidate/runtime.ts +16 -98
  362. package/src/server/auto-invalidate/types.ts +0 -6
  363. package/src/server/bounded-body.ts +38 -0
  364. package/src/server/browser-events/plugin.ts +109 -22
  365. package/src/server/browser-events/shutdown.ts +28 -9
  366. package/src/server/cache/dev-loader.ts +30 -16
  367. package/src/server/cache/index.ts +2 -15
  368. package/src/server/cache/invalidation.ts +27 -46
  369. package/src/server/cache/isr-ssg.ts +6 -1
  370. package/src/server/cache/isr.ts +11 -11
  371. package/src/server/cache/page-cache-state.ts +2 -2
  372. package/src/server/cache/page-cache.ts +13 -9
  373. package/src/server/cache/purger.ts +64 -8
  374. package/src/server/cache/redis/index.ts +17 -27
  375. package/src/server/cache/redis/scripts.ts +21 -4
  376. package/src/server/cache/registry.ts +3 -3
  377. package/src/server/cache/route-cache.ts +47 -13
  378. package/src/server/cache/runtime-cache.ts +144 -24
  379. package/src/server/cache/ssg.ts +7 -5
  380. package/src/server/context-logger.ts +46 -8
  381. package/src/server/dev/diagnostics.ts +6 -56
  382. package/src/server/dev/error.ts +3 -34
  383. package/src/server/dev/graph.ts +35 -22
  384. package/src/server/dev/rewrite-module-specifiers.ts +15 -19
  385. package/src/server/dev/runtime.production.ts +4 -0
  386. package/src/server/dev/runtime.ts +404 -0
  387. package/src/server/dev/stack-location.ts +46 -0
  388. package/src/server/dev-page-imports.ts +183 -0
  389. package/src/server/dev-page-plugin.ts +39 -302
  390. package/src/server/devtools/hub.ts +3 -3
  391. package/src/server/devtools/instrumentation.production.ts +0 -8
  392. package/src/server/devtools/instrumentation.ts +6 -8
  393. package/src/server/devtools/plugin.ts +2 -1
  394. package/src/server/devtools/request-context.ts +67 -16
  395. package/src/server/evlog.ts +119 -55
  396. package/src/server/instance.ts +187 -138
  397. package/src/server/internal.ts +66 -62
  398. package/src/server/lang-detect.ts +31 -22
  399. package/src/server/logger.ts +20 -7
  400. package/src/server/logging/ingest-plugin.ts +123 -0
  401. package/src/server/mode.ts +19 -0
  402. package/src/server/prerender.ts +122 -0
  403. package/src/server/prod/runtime.ts +181 -0
  404. package/src/server/production-server.ts +43 -17
  405. package/src/server/registrations.ts +38 -0
  406. package/src/server/render/assemble.ts +5 -8
  407. package/src/server/render/buffered-render.ts +171 -0
  408. package/src/server/render/document-stream.ts +188 -0
  409. package/src/server/render/document.tsx +5 -3
  410. package/src/server/render/element.tsx +6 -73
  411. package/src/server/render/index.ts +4 -21
  412. package/src/server/render/isr-revalidation.ts +246 -0
  413. package/src/server/render/isr-shared-cache.ts +141 -0
  414. package/src/server/render/isr.ts +212 -516
  415. package/src/server/render/loader-errors.ts +183 -0
  416. package/src/server/render/loader-segments.ts +149 -0
  417. package/src/server/render/loaders.ts +126 -547
  418. package/src/server/render/mixed-cache.ts +28 -27
  419. package/src/server/render/navigation-head.ts +33 -0
  420. package/src/server/render/not-found-plugin.ts +31 -0
  421. package/src/server/render/not-found.ts +32 -8
  422. package/src/server/render/observe-loader.ts +46 -0
  423. package/src/server/render/ppr-document.ts +36 -14
  424. package/src/server/render/ppr-request.ts +2 -2
  425. package/src/server/render/ppr-route.ts +79 -18
  426. package/src/server/render/prepare-render.ts +251 -0
  427. package/src/server/render/request-loaders.ts +216 -0
  428. package/src/server/render/route-frame-transport.ts +41 -4
  429. package/src/server/render/shell.ts +1 -1
  430. package/src/server/render/ssg.ts +9 -20
  431. package/src/server/render/ssr-transport.ts +221 -0
  432. package/src/server/render/ssr.ts +95 -956
  433. package/src/server/render/static-params.ts +32 -0
  434. package/src/server/render/template.ts +7 -7
  435. package/src/server/router/discovery.ts +82 -159
  436. package/src/server/router/dispatch.ts +337 -0
  437. package/src/server/router/hmr.ts +177 -190
  438. package/src/server/router/patterns.ts +39 -65
  439. package/src/server/router/plugin.ts +234 -359
  440. package/src/server/router/schemas.ts +6 -39
  441. package/src/server/router/source-version.ts +5 -4
  442. package/src/server/router/types.ts +0 -2
  443. package/src/server/runtime-env.ts +6 -1
  444. package/src/server/static-export.ts +143 -0
  445. package/src/server/sync/adapter.ts +11 -0
  446. package/src/server/sync/atomic.ts +16 -36
  447. package/src/server/sync/config.ts +6 -14
  448. package/src/server/sync/drizzle/index.ts +12 -20
  449. package/src/server/sync/fingerprint.ts +1 -1
  450. package/src/server/sync/index.ts +2 -10
  451. package/src/server/sync/invalidate-sync.ts +31 -0
  452. package/src/server/sync/mutation-handler.ts +6 -0
  453. package/src/server/sync/plugin.ts +171 -129
  454. package/src/server/sync/postgres/execute.ts +9 -1
  455. package/src/server/sync/postgres/index.ts +71 -39
  456. package/src/server/sync/postgres/migration.sql +2 -0
  457. package/src/server/sync/principal-journal.ts +78 -0
  458. package/src/server/sync/prisma/index.ts +1 -0
  459. package/src/server/sync/queries.ts +133 -40
  460. package/src/server/sync/query-context.ts +38 -5
  461. package/src/server/sync/redis/index.ts +34 -6
  462. package/src/server/sync/redis/scripts.ts +10 -1
  463. package/src/server/sync/response.ts +47 -67
  464. package/src/server/sync/runtime.ts +24 -7
  465. package/src/server/sync/sqlite/index.ts +92 -61
  466. package/src/server/sync/sqlite/migration.sql +1 -0
  467. package/src/server/sync/stream.ts +47 -26
  468. package/src/server/sync/validation.ts +1 -1
  469. package/src/server/weak-registry.ts +37 -0
  470. package/src/shared/await.tsx +2 -1
  471. package/src/shared/compact-json.ts +1 -1
  472. package/src/shared/defer.ts +1 -1
  473. package/src/shared/deferred-ndjson.ts +142 -120
  474. package/src/shared/elysia-contract.ts +7 -0
  475. package/src/shared/error.ts +1 -4
  476. package/src/shared/in-memory-apps.ts +24 -0
  477. package/src/shared/invalidation-header.ts +38 -0
  478. package/src/shared/navigation-data.ts +29 -0
  479. package/src/shared/prefix.ts +42 -6
  480. package/src/shared/route-frame.ts +82 -26
  481. package/src/shared/route-map.ts +23 -39
  482. package/src/shared/route-matches.ts +59 -0
  483. package/src/shared/route-specificity.ts +28 -0
  484. package/src/shared/search-params.ts +6 -35
  485. package/src/shared/sync-query.ts +30 -23
  486. package/src/shared/utils/ast-walk.ts +9 -25
  487. package/src/shared/utils/index.ts +1 -1
  488. package/dist/build/scan-server.d.ts +0 -14
  489. package/dist/build/ssg-cache.d.ts +0 -18
  490. package/dist/plugin/route-config-autofix.d.ts +0 -31
  491. package/dist/plugin/routes.d.ts +0 -34
  492. package/dist/server/router/hmr.production.d.ts +0 -7
  493. package/src/build/scan-server.ts +0 -112
  494. package/src/build/ssg-cache.ts +0 -126
  495. package/src/plugin/route-config-autofix.ts +0 -1149
  496. package/src/plugin/routes.ts +0 -1140
  497. package/src/server/router/hmr.production.ts +0 -18
@@ -11,190 +11,196 @@ 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 queryFromTag(tag) {
35
+ if (!tag.startsWith(PREFIX)) {
36
+ return;
37
+ }
38
+ try {
39
+ const value = JSON.parse(tag.slice(PREFIX.length));
40
+ 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"))) {
41
+ return;
42
+ }
43
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
44
+ } catch {}
45
+ }
46
+ var PREFIX = "__furin.query:";
47
+
48
+ // src/shared/invalidation-header.ts
49
+ function encodeInvalidationEntry(path, type) {
50
+ const encoded = encodeURI(path.toWellFormed()).replace(PATH_DELIMITERS_RE, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
51
+ return type === "layout" ? `${encoded}:layout` : encoded;
52
+ }
53
+ function decodeInvalidationEntry(entry) {
54
+ const trimmed = entry.trim();
55
+ const type = trimmed.endsWith(":layout") ? "layout" : "page";
56
+ const path = type === "layout" ? trimmed.slice(0, -":layout".length) : trimmed;
57
+ try {
58
+ return { path: decodeURIComponent(path), type };
59
+ } catch {
60
+ return { path, type };
61
+ }
62
+ }
63
+ function serializeInvalidationPaths(paths) {
64
+ return paths.join(",");
65
+ }
66
+ var PATH_DELIMITERS_RE;
67
+ var init_invalidation_header = __esm(() => {
68
+ PATH_DELIMITERS_RE = /[,:?#]/g;
69
+ });
70
+
71
+ // src/shared/prefix.ts
72
+ function physicalPath(prefix, path) {
73
+ if (prefix === "") {
74
+ return path;
75
+ }
76
+ return path === "/" ? prefix : `${prefix}${path}`;
77
+ }
78
+ var init_prefix = () => {};
79
+
80
+ // src/server/runtime-env.ts
81
+ var IS_DEV = true;
82
+
83
+ // src/server/weak-registry.ts
84
+ class WeakRegistry {
85
+ entries = new Set;
86
+ references = new WeakMap;
87
+ add(value) {
88
+ let reference = this.references.get(value);
89
+ if (!reference) {
90
+ reference = new WeakRef(value);
91
+ this.references.set(value, reference);
92
+ }
93
+ this.entries.add(reference);
94
+ }
95
+ clear() {
96
+ this.entries.clear();
97
+ }
98
+ delete(value) {
99
+ const reference = this.references.get(value);
100
+ if (reference) {
101
+ this.entries.delete(reference);
102
+ this.references.delete(value);
103
+ }
104
+ }
105
+ *values() {
106
+ for (const reference of this.entries) {
107
+ const value = reference.deref();
108
+ if (value) {
109
+ yield value;
110
+ } else {
111
+ this.entries.delete(reference);
112
+ }
113
+ }
114
+ }
115
+ }
116
+
14
117
  // src/server/instance.ts
15
118
  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() {
119
+ function defaultInstanceBucket() {
27
120
  if (!_defaultInstance) {
28
- _defaultInstance = createInstance("", "");
121
+ _defaultInstance = {
122
+ buildId: "",
123
+ get development() {
124
+ return IS_DEV;
125
+ },
126
+ pagesDir: "",
127
+ prefix: "",
128
+ state: new Map,
129
+ syncPath: undefined
130
+ };
29
131
  }
30
132
  return _defaultInstance;
31
133
  }
134
+ function ensureRequestScope(fn) {
135
+ if (_scope.getStore()) {
136
+ return fn();
137
+ }
138
+ return _scope.run({
139
+ navigationData: false,
140
+ pending: new Set,
141
+ peers: undefined,
142
+ requests: new WeakSet,
143
+ runtime: undefined
144
+ }, fn);
145
+ }
32
146
  function currentInstance() {
33
- const scope = _requestScope.getStore();
34
- if (scope) {
35
- return scope.instance;
36
- }
37
- if (_instances.size === 1) {
38
- const only = _instances.values().next().value;
39
- if (only) {
40
- return only;
41
- }
147
+ const scope = _scope.getStore();
148
+ if (scope?.runtime) {
149
+ return scope.runtime;
42
150
  }
43
- return defaultInstance();
151
+ if (_runtimes.values().next().done) {
152
+ return defaultInstanceBucket();
153
+ }
154
+ 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
155
  }
45
156
  function allInstances() {
46
- if (_instances.size === 0) {
47
- return [defaultInstance()];
157
+ const peers = _scope.getStore()?.peers;
158
+ if (peers) {
159
+ return [...peers];
48
160
  }
49
- return [..._instances.values()];
161
+ const instances = [..._runtimes.values()];
162
+ return instances.length > 0 ? instances : [defaultInstanceBucket()];
50
163
  }
51
164
  function requestPendingInvalidations() {
52
- return _requestScope.getStore()?.pending;
53
- }
54
- function runWithInstanceScope(instance, fn) {
55
- return _requestScope.run({ instance, pending: new Set }, fn);
165
+ return _scope.getStore()?.pending;
56
166
  }
57
167
  function withInstance(instance, fn) {
58
- return runWithInstanceScope(instance, fn);
168
+ const scope = _scope.getStore();
169
+ return _scope.run({
170
+ navigationData: false,
171
+ pending: scope?.pending ?? new Set,
172
+ peers: scope?.peers,
173
+ requests: new WeakSet,
174
+ runtime: instance
175
+ }, fn);
59
176
  }
60
177
  function instanceSlot(init) {
61
178
  const key = Symbol("furin-instance-slot");
62
179
  return (instance) => {
63
- const target = instance ?? currentInstance();
64
- if (target.state.has(key)) {
65
- return target.state.get(key);
180
+ if (instance.state.has(key)) {
181
+ return instance.state.get(key);
66
182
  }
67
- const value = init(target);
68
- target.state.set(key, value);
183
+ const value = init(instance);
184
+ instance.state.set(key, value);
69
185
  return value;
70
186
  };
71
187
  }
72
- var _requestScope, _instances, _defaultInstance = null;
188
+ var _scope, _runtimes, _defaultInstance = null;
73
189
  var init_instance = __esm(() => {
74
- _requestScope = new AsyncLocalStorage;
75
- _instances = new Map;
190
+ _scope = new AsyncLocalStorage;
191
+ _runtimes = new WeakRegistry;
76
192
  });
77
193
 
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 };
194
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
195
+ function isEvlogError(error) {
196
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
98
197
  }
99
- var SYNC_DEFAULT_PATH = "/_furin/sync", requestSyncPath;
100
- var init_config = __esm(() => {
101
- init_instance();
102
- requestSyncPath = new AsyncLocalStorage2;
198
+ var evlogErrorBrand;
199
+ var init_error_brand_D0_DCPvr = __esm(() => {
200
+ evlogErrorBrand = Symbol.for("evlog.error.brand");
103
201
  });
104
202
 
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
203
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/utils.mjs
198
204
  function elapsedMs(startTime) {
199
205
  return Math.max(0, Date.now() - startTime);
200
206
  }
@@ -203,9 +209,6 @@ function formatDuration(ms) {
203
209
  return `${Math.round(ms)}ms`;
204
210
  return `${(ms / 1000).toFixed(2)}s`;
205
211
  }
206
- function isServer() {
207
- return typeof window === "undefined";
208
- }
209
212
  function isBrowser() {
210
213
  if (typeof window === "undefined")
211
214
  return false;
@@ -237,6 +240,10 @@ function isLevelEnabled(level, minLevel) {
237
240
  return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
238
241
  }
239
242
  function getConsoleMethod(level) {
243
+ if (level === "fatal")
244
+ return "error";
245
+ if (level === "trace")
246
+ return "log";
240
247
  return level;
241
248
  }
242
249
  function getLevelColor(level) {
@@ -248,6 +255,49 @@ function getCssLevelColor(level) {
248
255
  function escapeFormatString(str) {
249
256
  return str.replace(/%/g, "%%");
250
257
  }
258
+ function hasMessageSpecifiers(format) {
259
+ return /%[sdj]/.test(format);
260
+ }
261
+ function formatMessage(format, args) {
262
+ if (args.length === 0)
263
+ return format;
264
+ let argIndex = 0;
265
+ const interpolated = format.replace(/%(.)/g, (specifier, char) => {
266
+ if (char === "%")
267
+ return "%";
268
+ if (char !== "s" && char !== "d" && char !== "j")
269
+ return specifier;
270
+ if (argIndex >= args.length)
271
+ return specifier;
272
+ return renderMessageValue(char, args[argIndex++]);
273
+ });
274
+ if (argIndex >= args.length)
275
+ return interpolated;
276
+ const extras = [];
277
+ while (argIndex < args.length)
278
+ extras.push(renderMessageValue("s", args[argIndex++]));
279
+ return `${interpolated} ${extras.join(" ")}`;
280
+ }
281
+ function renderMessageValue(specifier, value) {
282
+ if (specifier === "j")
283
+ return renderMessageJson(value);
284
+ if (typeof value === "bigint")
285
+ return `${value}n`;
286
+ if (specifier === "d")
287
+ return String(Number(value));
288
+ if (typeof value === "string")
289
+ return value;
290
+ if (value === null || typeof value !== "object")
291
+ return String(value);
292
+ return renderMessageJson(value);
293
+ }
294
+ function renderMessageJson(value) {
295
+ try {
296
+ return JSON.stringify(value) ?? String(value);
297
+ } catch {
298
+ return String(value);
299
+ }
300
+ }
251
301
  function filterSafeHeaders(headers) {
252
302
  const safeHeaders = {};
253
303
  for (const [key, value] of Object.entries(headers))
@@ -280,13 +330,25 @@ function isoNow() {
280
330
  }
281
331
  return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
282
332
  }
333
+ function readErrorField(error, key) {
334
+ if (isEvlogError(error)) {
335
+ if (key === "statusCode")
336
+ return error.status;
337
+ if (key === "statusText" || key === "statusMessage")
338
+ return error.message;
339
+ }
340
+ return error[key];
341
+ }
283
342
  var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, SENSITIVE_HEADER_SET, patternCache, _isoDate, _isoCachedSecond = -1, _isoCachedPrefix = "";
284
343
  var init_utils = __esm(() => {
344
+ init_error_brand_D0_DCPvr();
285
345
  LEVEL_ORDER = {
346
+ trace: 0,
286
347
  debug: 0,
287
348
  info: 1,
288
349
  warn: 2,
289
- error: 3
350
+ error: 3,
351
+ fatal: 4
290
352
  };
291
353
  colors = {
292
354
  reset: "\x1B[0m",
@@ -303,9 +365,11 @@ var init_utils = __esm(() => {
303
365
  };
304
366
  levelColorMap = {
305
367
  error: colors.red,
368
+ fatal: colors.red,
306
369
  warn: colors.yellow,
307
370
  info: colors.cyan,
308
- debug: colors.gray
371
+ debug: colors.gray,
372
+ trace: colors.gray
309
373
  };
310
374
  cssColors = {
311
375
  dim: "color: #6b7280",
@@ -318,9 +382,11 @@ var init_utils = __esm(() => {
318
382
  };
319
383
  cssLevelColorMap = {
320
384
  error: cssColors.red,
385
+ fatal: cssColors.red,
321
386
  warn: cssColors.yellow,
322
387
  info: cssColors.cyan,
323
- debug: cssColors.gray
388
+ debug: cssColors.gray,
389
+ trace: cssColors.gray
324
390
  };
325
391
  SENSITIVE_HEADERS = [
326
392
  "authorization",
@@ -335,324 +401,15 @@ var init_utils = __esm(() => {
335
401
  _isoDate = /* @__PURE__ */ new Date;
336
402
  });
337
403
 
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;
404
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/globalRegistry--27hBAWF.mjs
405
+ function logPluginError(name, hook, err) {
406
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
343
407
  }
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());
408
+ function createPluginRunner(plugins = []) {
409
+ const byName = /* @__PURE__ */ new Map;
410
+ for (const plugin of plugins)
411
+ byName.set(plugin.name, plugin);
412
+ const list = Array.from(byName.values());
656
413
  return {
657
414
  plugins: list,
658
415
  hasEnrich: list.some((p) => typeof p.enrich === "function"),
@@ -777,6 +534,7 @@ function createConfig() {
777
534
  minLevel: "debug",
778
535
  locked: false,
779
536
  initialized: false,
537
+ warnedUninitialized: false,
780
538
  pluginRunner: getEmptyPluginRunner()
781
539
  };
782
540
  }
@@ -806,7 +564,7 @@ function getSharedStorage(id, create) {
806
564
  return storage;
807
565
  }
808
566
  var emptyRunner, EVLOG_MAJOR = 2, REGISTRY_KEY, MAJORS_KEY, globalConfig;
809
- var init_globalRegistry_Bh3bIGwA = __esm(() => {
567
+ var init_globalRegistry_27hBAWF = __esm(() => {
810
568
  init_utils();
811
569
  emptyRunner = createPluginRunner([]);
812
570
  REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
@@ -814,7 +572,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
814
572
  globalConfig = getRegistry().config;
815
573
  });
816
574
 
817
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
575
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/pretty-error-CRPxjp4p.mjs
818
576
  function pushTreeSpacer(children) {
819
577
  children.push(PRETTY_ERROR_TREE_SPACER);
820
578
  }
@@ -887,8 +645,6 @@ function isAppPath(file) {
887
645
  return false;
888
646
  if (SKIP_PATH_RE.test(normalized))
889
647
  return false;
890
- if (normalized.includes("/node_modules/"))
891
- return false;
892
648
  if (isFrameworkRuntimePath(normalized))
893
649
  return false;
894
650
  return true;
@@ -1108,14 +864,14 @@ function buildErrorEntries(error, options = {}) {
1108
864
  }];
1109
865
  }
1110
866
  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(() => {
867
+ var init_pretty_error_CRPxjp4p = __esm(() => {
1112
868
  init_utils();
1113
869
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
1114
870
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
1115
871
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1116
872
  });
1117
873
 
1118
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
874
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1119
875
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1120
876
  const compact = partial.compact ?? (inDev && pretty);
1121
877
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1168,7 +924,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1168
924
  };
1169
925
  });
1170
926
 
1171
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
927
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1172
928
  function hasWideEventPublisher() {
1173
929
  return publisher !== null;
1174
930
  }
@@ -1184,171 +940,518 @@ function publishWideEvent(event) {
1184
940
  var publisher = null;
1185
941
  var init_wideEventChannel_BUDW48oP = () => {};
1186
942
 
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;
943
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/serialize-error-DHkLgVsh.mjs
944
+ function payloadFieldsHiddenBy(error) {
945
+ const { toJSON } = error;
946
+ if (typeof toJSON !== "function" || isEvlogError(error))
947
+ return NONE;
948
+ const shown = toJSON.call(error);
949
+ return ["data", "internal"].filter((key) => typeof shown !== "object" || shown === null || !(key in shown));
950
+ }
951
+ function isWrapperOf(error, cause) {
952
+ return cause instanceof Error && cause !== error && cause.message === error.message && cause.stack === error.stack;
953
+ }
954
+ function isH3InputOf(error, cause) {
955
+ if (typeof cause !== "object" || cause === null || cause instanceof Error || Array.isArray(cause))
956
+ return false;
957
+ const keys = Object.keys(cause);
958
+ if (keys.length === 0)
959
+ return false;
960
+ const causeRecord = cause;
961
+ return keys.every((key) => {
962
+ const target = H3_INPUT_FIELDS[key];
963
+ if (!target)
964
+ return false;
965
+ const value = causeRecord[key];
966
+ if (value === undefined || value === readErrorField(error, target))
967
+ return true;
968
+ return target === "statusCode" && Number(value) === readErrorField(error, "statusCode");
969
+ });
1190
970
  }
1191
- var evlogErrorBrand;
1192
- var init_error_brand_D0_DCPvr = __esm(() => {
1193
- evlogErrorBrand = Symbol.for("evlog.error.brand");
971
+ function createErrorSerializer(formatStack = (stack) => stack) {
972
+ function serialize(error, ancestors) {
973
+ const { cause } = error;
974
+ ancestors.add(error);
975
+ if (isWrapperOf(error, cause) && !ancestors.has(cause)) {
976
+ const serialized = serialize(cause, ancestors);
977
+ const hidden = payloadFieldsHiddenBy(error);
978
+ for (const key of [
979
+ "statusCode",
980
+ "statusMessage",
981
+ "data"
982
+ ]) {
983
+ const value = readErrorField(error, key);
984
+ if (value !== undefined && !hidden.includes(key))
985
+ serialized[key] = walk(value, ancestors);
986
+ }
987
+ ancestors.delete(error);
988
+ return serialized;
989
+ }
990
+ const serialized = {
991
+ name: error.name,
992
+ message: error.message,
993
+ stack: formatStack(error.stack)
994
+ };
995
+ const hidden = payloadFieldsHiddenBy(error);
996
+ for (const key of ERROR_FIELDS) {
997
+ const value = readErrorField(error, key);
998
+ if (value !== undefined && !hidden.includes(key))
999
+ serialized[key] = walk(value, ancestors);
1000
+ }
1001
+ if (isH3InputOf(error, cause)) {
1002
+ if (cause.fatal !== undefined)
1003
+ serialized.fatal = cause.fatal;
1004
+ if (cause.unhandled !== undefined)
1005
+ serialized.unhandled = cause.unhandled;
1006
+ } else if (cause !== undefined)
1007
+ serialized.cause = walk(cause, ancestors);
1008
+ ancestors.delete(error);
1009
+ return serialized;
1010
+ }
1011
+ function walk(value, ancestors) {
1012
+ if (value === null || typeof value !== "object")
1013
+ return value;
1014
+ if (ancestors.has(value))
1015
+ return "[Circular]";
1016
+ if (value instanceof Error)
1017
+ return serialize(value, ancestors);
1018
+ if (typeof value.toJSON === "function")
1019
+ return value;
1020
+ ancestors.add(value);
1021
+ let copy;
1022
+ if (Array.isArray(value)) {
1023
+ let items;
1024
+ for (let i = 0;i < value.length; i++) {
1025
+ const item = value[i];
1026
+ const result = walk(item, ancestors);
1027
+ if (items)
1028
+ items[i] = result;
1029
+ else if (!Object.is(result, item))
1030
+ (items = value.slice())[i] = result;
1031
+ }
1032
+ copy = items;
1033
+ } else {
1034
+ const entries = Object.entries(value);
1035
+ let changed = false;
1036
+ for (const entry of entries) {
1037
+ const result = walk(entry[1], ancestors);
1038
+ if (!Object.is(result, entry[1])) {
1039
+ entry[1] = result;
1040
+ changed = true;
1041
+ }
1042
+ }
1043
+ if (changed)
1044
+ copy = Object.fromEntries(entries);
1045
+ }
1046
+ ancestors.delete(value);
1047
+ return copy ?? value;
1048
+ }
1049
+ return {
1050
+ serializeError: (error) => serialize(error, /* @__PURE__ */ new WeakSet),
1051
+ serializeErrorsIn: (value) => walk(value, /* @__PURE__ */ new WeakSet)
1052
+ };
1053
+ }
1054
+ var ERROR_FIELDS, NONE, H3_INPUT_FIELDS;
1055
+ var init_serialize_error_DHkLgVsh = __esm(() => {
1056
+ init_error_brand_D0_DCPvr();
1057
+ init_utils();
1058
+ ERROR_FIELDS = [
1059
+ "code",
1060
+ "status",
1061
+ "statusText",
1062
+ "statusCode",
1063
+ "statusMessage",
1064
+ "data",
1065
+ "internal",
1066
+ "why",
1067
+ "fix",
1068
+ "link"
1069
+ ];
1070
+ NONE = [];
1071
+ H3_INPUT_FIELDS = {
1072
+ message: "message",
1073
+ stack: "stack",
1074
+ statusCode: "statusCode",
1075
+ status: "statusCode",
1076
+ statusMessage: "statusMessage",
1077
+ statusText: "statusMessage",
1078
+ data: "data",
1079
+ fatal: "fatal",
1080
+ unhandled: "unhandled"
1081
+ };
1194
1082
  });
1195
1083
 
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(() => {
1084
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1085
+ function extractSafeHeaders(headers) {
1086
+ const raw = {};
1087
+ headers.forEach((value, key) => {
1088
+ raw[key] = value;
1089
+ });
1090
+ return filterSafeHeaders(raw);
1091
+ }
1092
+ function extractSafeNodeHeaders(headers) {
1093
+ const raw = {};
1094
+ for (const [key, value] of Object.entries(headers)) {
1095
+ if (value === undefined)
1096
+ continue;
1097
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
1098
+ }
1099
+ return filterSafeHeaders(raw);
1100
+ }
1101
+ var init_headers_Bx1ieR_m = __esm(() => {
1199
1102
  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];
1103
+ });
1104
+
1105
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/audit-C5ZK3s-B.mjs
1106
+ function normalizeRedactPathPattern(pattern) {
1107
+ if (!pattern.includes("*") && !pattern.includes("."))
1108
+ return `**.${pattern}`;
1109
+ return pattern;
1110
+ }
1111
+ function compileRedactPathMatchers(patterns) {
1112
+ if (!patterns?.length)
1113
+ return;
1114
+ const exactPaths = /* @__PURE__ */ new Set;
1115
+ const pathGlobs = [];
1116
+ const keyGlobs = [];
1117
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
1118
+ for (const raw of patterns) {
1119
+ if (!raw.includes("*")) {
1120
+ if (raw.includes("."))
1121
+ exactPaths.add(raw);
1122
+ else
1123
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
1124
+ continue;
1214
1125
  }
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);
1126
+ if (!raw.includes("."))
1127
+ keyGlobs.push(globToRegExp(raw, "."));
1128
+ else
1129
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
1130
+ }
1131
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
1132
+ return;
1133
+ return {
1134
+ exactPaths,
1135
+ pathGlobs,
1136
+ keyGlobs,
1137
+ caseInsensitiveLeaves
1138
+ };
1139
+ }
1140
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
1141
+ pathGlobs.push(globToRegExp(pattern, "."));
1142
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
1143
+ if (leaf) {
1144
+ exactPaths.add(leaf[1]);
1145
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
1146
+ }
1147
+ }
1148
+ function matchesRedactPath(fullPath, leafKey, matchers) {
1149
+ if (matchers.exactPaths.has(fullPath))
1150
+ return true;
1151
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
1152
+ return true;
1153
+ for (const glob of matchers.pathGlobs) {
1154
+ glob.lastIndex = 0;
1155
+ if (glob.test(fullPath))
1156
+ return true;
1157
+ }
1158
+ for (const glob of matchers.keyGlobs) {
1159
+ glob.lastIndex = 0;
1160
+ if (glob.test(leafKey))
1161
+ return true;
1162
+ }
1163
+ return false;
1164
+ }
1165
+ function resolveReplacement(replacement, matched, ctx) {
1166
+ if (typeof replacement === "string")
1167
+ return replacement;
1168
+ try {
1169
+ const result = replacement(matched, ctx);
1170
+ if (typeof result !== "string") {
1171
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
1172
+ return DEFAULT_REPLACEMENT;
1240
1173
  }
1241
- get statusText() {
1242
- return this.message;
1174
+ return result;
1175
+ } catch (err) {
1176
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
1177
+ return DEFAULT_REPLACEMENT;
1178
+ }
1179
+ }
1180
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
1181
+ if (obj === null || obj === undefined)
1182
+ return;
1183
+ if (Array.isArray(obj)) {
1184
+ for (let i = 0;i < obj.length; i++) {
1185
+ const segment = String(i);
1186
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
1187
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
1243
1188
  }
1244
- get statusCode() {
1245
- return this.status;
1189
+ return;
1190
+ }
1191
+ if (typeof obj === "object") {
1192
+ const record = obj;
1193
+ for (const key of redactableKeys(record)) {
1194
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1195
+ if (matchesRedactPath(fullPath, key, matchers))
1196
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
1197
+ path: fullPath,
1198
+ key
1199
+ }), fullPath);
1200
+ else
1201
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
1246
1202
  }
1247
- get statusMessage() {
1248
- return this.message;
1203
+ }
1204
+ }
1205
+ function redactableKeys(record) {
1206
+ return Object.keys(record);
1207
+ }
1208
+ function setRedacted(record, key, value, path) {
1209
+ if (Reflect.set(record, key, value))
1210
+ return;
1211
+ const desc = Object.getOwnPropertyDescriptor(record, key);
1212
+ if (desc && "value" in desc && desc.configurable) {
1213
+ Object.defineProperty(record, key, {
1214
+ ...desc,
1215
+ value
1216
+ });
1217
+ return;
1218
+ }
1219
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
1220
+ }
1221
+ function redactSecretKeys(obj, replacement, prefix = "") {
1222
+ if (obj === null || typeof obj !== "object")
1223
+ return;
1224
+ if (Array.isArray(obj)) {
1225
+ for (let i = 0;i < obj.length; i++)
1226
+ redactSecretKeys(obj[i], replacement, prefix ? `${prefix}.${i}` : String(i));
1227
+ return;
1228
+ }
1229
+ const record = obj;
1230
+ for (const key of redactableKeys(record)) {
1231
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1232
+ const value = record[key];
1233
+ if (SECRET_KEY.test(key) && value !== null && value !== undefined && typeof value !== "boolean")
1234
+ setRedacted(record, key, resolveReplacement(replacement, value, {
1235
+ path: fullPath,
1236
+ key
1237
+ }), fullPath);
1238
+ else
1239
+ redactSecretKeys(value, replacement, fullPath);
1240
+ }
1241
+ }
1242
+ function resolveRedactConfig(input) {
1243
+ if (input === undefined || input === false)
1244
+ return;
1245
+ if (input === true)
1246
+ return {
1247
+ _maskers: allBuiltinMaskers(),
1248
+ _secretKeys: true
1249
+ };
1250
+ if (input.builtins === false)
1251
+ return {
1252
+ ...input,
1253
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1254
+ };
1255
+ const maskers = Array.isArray(input.builtins) ? input.builtins.filter((name) => (name in builtinPatterns)).map((name) => builtinPatterns[name]).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
1256
+ return {
1257
+ ...input,
1258
+ _maskers: maskers,
1259
+ _secretKeys: !Array.isArray(input.builtins) || input.builtins.includes("secrets"),
1260
+ _pathMatchers: compileRedactPathMatchers(input.paths)
1261
+ };
1262
+ }
1263
+ function allBuiltinMaskers() {
1264
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
1265
+ }
1266
+ function cloneRegex(re) {
1267
+ return new RegExp(re.source, re.flags);
1268
+ }
1269
+ function markGloballyRedacted(event) {
1270
+ Object.defineProperty(event, globallyRedacted, {
1271
+ value: true,
1272
+ enumerable: false,
1273
+ configurable: true
1274
+ });
1275
+ }
1276
+ function isGloballyRedacted(event) {
1277
+ return Reflect.has(event, globallyRedacted);
1278
+ }
1279
+ function cloneForRedaction(event) {
1280
+ try {
1281
+ return structuredClone(event);
1282
+ } catch {
1283
+ try {
1284
+ return JSON.parse(JSON.stringify(event));
1285
+ } catch {
1286
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
1287
+ return { ...event };
1249
1288
  }
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
- };
1289
+ }
1290
+ }
1291
+ function redactEvent(event, config) {
1292
+ const clone = cloneForRedaction(event);
1293
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
1294
+ if (config.transform)
1295
+ try {
1296
+ config.transform(clone);
1297
+ } catch (err) {
1298
+ console.error("[evlog] redact transform failed:", err);
1261
1299
  }
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
- `);
1300
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
1301
+ if (pathMatchers)
1302
+ redactPathsInTree(clone, pathMatchers, replacement);
1303
+ if (config._secretKeys)
1304
+ redactSecretKeys(clone, replacement);
1305
+ if (config._maskers?.length)
1306
+ applyMaskersToTree(clone, config._maskers);
1307
+ if (config.patterns?.length)
1308
+ redactPatterns(clone, config.patterns, replacement);
1309
+ return clone;
1310
+ }
1311
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
1312
+ if (obj === null || obj === undefined)
1313
+ return;
1314
+ if (Array.isArray(obj)) {
1315
+ for (let i = 0;i < obj.length; i++) {
1316
+ const key = String(i);
1317
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1318
+ if (typeof obj[i] === "string")
1319
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
1320
+ else if (typeof obj[i] === "object")
1321
+ redactPatterns(obj[i], patterns, replacement, fullPath);
1284
1322
  }
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
- };
1323
+ return;
1324
+ }
1325
+ if (typeof obj === "object") {
1326
+ const record = obj;
1327
+ for (const key of redactableKeys(record)) {
1328
+ const val = record[key];
1329
+ const fullPath = prefix ? `${prefix}.${key}` : key;
1330
+ if (typeof val === "string")
1331
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
1332
+ else if (typeof val === "object")
1333
+ redactPatterns(val, patterns, replacement, fullPath);
1297
1334
  }
1298
- };
1299
- Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1300
- value: true,
1301
- enumerable: false
1302
- });
1303
- });
1304
-
1305
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1306
- function extractSafeHeaders(headers) {
1307
- const raw = {};
1308
- headers.forEach((value, key) => {
1309
- raw[key] = value;
1310
- });
1311
- return filterSafeHeaders(raw);
1335
+ }
1312
1336
  }
1313
- function extractSafeNodeHeaders(headers) {
1314
- const raw = {};
1315
- for (const [key, value] of Object.entries(headers)) {
1316
- if (value === undefined)
1337
+ function applyPatterns(value, patterns, replacement, path, key) {
1338
+ let result = value;
1339
+ for (const pattern of patterns) {
1340
+ if (typeof replacement === "string") {
1341
+ result = result.replace(pattern, replacement);
1317
1342
  continue;
1318
- raw[key] = Array.isArray(value) ? value.join(", ") : value;
1343
+ }
1344
+ result = result.replace(pattern, (...args) => {
1345
+ const match = args[0];
1346
+ return resolveReplacement(replacement, match, {
1347
+ path,
1348
+ key,
1349
+ groups: captureGroups(args)
1350
+ });
1351
+ });
1319
1352
  }
1320
- return filterSafeHeaders(raw);
1353
+ return result;
1321
1354
  }
1322
- var init_headers_Bx1ieR_m = __esm(() => {
1323
- init_utils();
1324
- });
1325
-
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);
1355
+ function captureGroups(args) {
1356
+ const last = args.at(-1);
1357
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
1358
+ return args.slice(1, Math.max(1, args.length - trailing));
1359
+ }
1360
+ function applyMaskersToTree(obj, maskers) {
1361
+ if (obj === null || obj === undefined)
1362
+ return;
1363
+ if (Array.isArray(obj)) {
1364
+ for (let i = 0;i < obj.length; i++)
1365
+ if (typeof obj[i] === "string")
1366
+ obj[i] = applyMaskers(obj[i], maskers);
1367
+ else if (typeof obj[i] === "object")
1368
+ applyMaskersToTree(obj[i], maskers);
1369
+ return;
1370
+ }
1371
+ if (typeof obj === "object") {
1372
+ const record = obj;
1373
+ for (const key of redactableKeys(record)) {
1374
+ const val = record[key];
1375
+ if (typeof val === "string")
1376
+ setRedacted(record, key, applyMaskers(val, maskers), key);
1377
+ else if (typeof val === "object")
1378
+ applyMaskersToTree(val, maskers);
1379
+ }
1380
+ }
1381
+ }
1382
+ function applyMaskers(value, maskers) {
1383
+ let result = value;
1384
+ for (const [pattern, mask] of maskers)
1385
+ result = result.replace(pattern, mask);
1386
+ return result;
1387
+ }
1388
+ function writeOwnOutput(write) {
1389
+ const global = globalThis;
1390
+ global.__evlogOwnOutput = true;
1391
+ try {
1392
+ write();
1393
+ } finally {
1394
+ global.__evlogOwnOutput = false;
1395
+ }
1329
1396
  }
1330
1397
  function isPlainObject$1(val) {
1331
1398
  return val !== null && typeof val === "object" && !Array.isArray(val);
1332
1399
  }
1400
+ function isPlainRecord(val) {
1401
+ if (!isPlainObject$1(val))
1402
+ return false;
1403
+ const proto = Object.getPrototypeOf(val);
1404
+ return proto === Object.prototype || proto === null;
1405
+ }
1333
1406
  function warnPostEmit(method, detail) {
1334
1407
  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
1408
  }
1409
+ function setField(target, key, value) {
1410
+ if (key === "__proto__")
1411
+ Reflect.defineProperty(target, key, {
1412
+ value,
1413
+ enumerable: true,
1414
+ writable: true,
1415
+ configurable: true
1416
+ });
1417
+ else
1418
+ Reflect.set(target, key, value);
1419
+ }
1420
+ function writableChild(target, key) {
1421
+ const child = target[key];
1422
+ if (!isPlainRecord(child))
1423
+ return child;
1424
+ const copy = { ...child };
1425
+ const { toJSON } = child;
1426
+ if (typeof toJSON === "function" && !Object.hasOwn(copy, "toJSON"))
1427
+ Object.defineProperty(copy, "toJSON", {
1428
+ value: toJSON,
1429
+ enumerable: false,
1430
+ writable: true,
1431
+ configurable: true
1432
+ });
1433
+ setField(target, key, copy);
1434
+ return copy;
1435
+ }
1336
1436
  function mergeInto(target, source) {
1337
1437
  for (const key in source) {
1338
1438
  const sourceVal = source[key];
1339
1439
  if (sourceVal === undefined || sourceVal === null)
1340
1440
  continue;
1341
- const targetVal = target[key];
1441
+ const targetVal = key === "__proto__" && !Object.hasOwn(target, key) ? undefined : target[key];
1342
1442
  if (sourceVal === targetVal)
1343
1443
  continue;
1344
1444
  if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1345
- mergeInto(targetVal, sourceVal);
1445
+ mergeInto(writableChild(target, key), sourceVal);
1346
1446
  else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1347
- target[key] = [...targetVal, ...sourceVal];
1447
+ setField(target, key, [...targetVal, ...sourceVal]);
1348
1448
  else
1349
- Reflect.set(target, key, sourceVal);
1449
+ setField(target, key, sourceVal);
1350
1450
  }
1351
1451
  }
1452
+ function mergeFields(target, fields) {
1453
+ mergeInto(target, serializeErrorsIn(fields));
1454
+ }
1352
1455
  function isAiOnlyFieldUpdate(data) {
1353
1456
  const keys = Object.keys(data);
1354
1457
  return keys.length === 1 && keys[0] === "ai";
@@ -1396,10 +1499,12 @@ function getGlobalDrain() {
1396
1499
  return state.drain;
1397
1500
  }
1398
1501
  function shouldSample(level) {
1502
+ if (level === "fatal")
1503
+ return true;
1399
1504
  const { rates } = state.sampling;
1400
1505
  if (!rates)
1401
- return true;
1402
- const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1506
+ return level !== "trace";
1507
+ const percentage = level === "error" && rates.error === undefined ? 100 : level === "trace" && rates.trace === undefined ? 0 : rates[level] ?? 100;
1403
1508
  if (percentage <= 0)
1404
1509
  return false;
1405
1510
  if (percentage >= 100)
@@ -1420,10 +1525,17 @@ function shouldKeep(ctx) {
1420
1525
  return false;
1421
1526
  });
1422
1527
  }
1528
+ function warnOnceUninitializedProduction() {
1529
+ if (state.initialized || isDev() || state.warnedUninitialized)
1530
+ return;
1531
+ state.warnedUninitialized = true;
1532
+ 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).");
1533
+ }
1423
1534
  function emitWideEvent(level, event, options = {}) {
1424
1535
  const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1425
1536
  if (!state.enabled)
1426
1537
  return null;
1538
+ warnOnceUninitializedProduction();
1427
1539
  if (!ownsEvent) {
1428
1540
  if (!isLevelEnabled(level, state.minLevel))
1429
1541
  return null;
@@ -1457,15 +1569,8 @@ function emitWideEvent(level, event, options = {}) {
1457
1569
  formatted = redactEvent(formatted, state.redact);
1458
1570
  markGloballyRedacted(formatted);
1459
1571
  }
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
1572
  if (!deferDrain) {
1573
+ outputWideEvent(formatted);
1469
1574
  publishWideEvent(formatted);
1470
1575
  const drainPromises = [];
1471
1576
  if (state.drain)
@@ -1483,6 +1588,16 @@ function emitWideEvent(level, event, options = {}) {
1483
1588
  }
1484
1589
  return formatted;
1485
1590
  }
1591
+ function outputWideEvent(event) {
1592
+ if (state.silent)
1593
+ return;
1594
+ if (state.pretty)
1595
+ prettyPrintWideEvent(event);
1596
+ else if (state.stringify)
1597
+ writeOwnOutput(() => console[getConsoleMethod(event.level)](JSON.stringify(event)));
1598
+ else
1599
+ writeOwnOutput(() => console[getConsoleMethod(event.level)](event));
1600
+ }
1486
1601
  function emitTaggedLog(level, tag, message) {
1487
1602
  if (!state.enabled)
1488
1603
  return;
@@ -1498,7 +1613,7 @@ function emitTaggedLog(level, tag, message) {
1498
1613
  } else {
1499
1614
  const color = getLevelColor(level);
1500
1615
  const timestamp = isoNow().slice(11, 23);
1501
- console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1616
+ writeOwnOutput(() => console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`));
1502
1617
  }
1503
1618
  return;
1504
1619
  }
@@ -1774,15 +1889,14 @@ function buildAIEntries(ai) {
1774
1889
  function flushPrettyLines(lines) {
1775
1890
  if (lines.length === 0)
1776
1891
  return;
1777
- const text = `${lines.join(`
1778
- `)}
1779
- `;
1780
1892
  if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
1781
- writePrettyStdout(text);
1893
+ writeOwnOutput(() => nativeStdoutWrite(`${lines.join(`
1894
+ `)}
1895
+ `));
1782
1896
  return;
1783
1897
  }
1784
- console.log(lines.join(`
1785
- `));
1898
+ writeOwnOutput(() => console.log(lines.join(`
1899
+ `)));
1786
1900
  }
1787
1901
  function prettyPrintWideEvent(event) {
1788
1902
  const { timestamp, level, service, environment, version, ...rest } = event;
@@ -1889,65 +2003,19 @@ function prettyPrintWideEvent(event) {
1889
2003
  if (!browser && lines.length > 0)
1890
2004
  flushPrettyLines(lines);
1891
2005
  }
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
2006
  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)
2007
+ return function logMethod(tagOrEvent, message, ...args) {
2008
+ if (typeof tagOrEvent === "string") {
2009
+ if (message === undefined)
2010
+ emitTaggedLog(level, "log", formatMessage(tagOrEvent, args));
2011
+ else if (hasMessageSpecifiers(tagOrEvent))
2012
+ emitTaggedLog(level, "log", formatMessage(tagOrEvent, [message, ...args]));
2013
+ else
2014
+ emitTaggedLog(level, tagOrEvent, formatMessage(message, args));
2015
+ } else if (tagOrEvent instanceof Error)
1948
2016
  emitWideEvent(level, { error: serializeError(tagOrEvent) });
1949
2017
  else if (typeof tagOrEvent === "object")
1950
- emitWideEvent(level, tagOrEvent);
2018
+ emitWideEvent(level, serializeErrorsIn(tagOrEvent));
1951
2019
  else
1952
2020
  emitTaggedLog(level, "log", String(tagOrEvent));
1953
2021
  };
@@ -1960,6 +2028,7 @@ function createLogger(initialContext = {}, internalOptions) {
1960
2028
  const startTime = Date.now();
1961
2029
  const context = { ...initialContext };
1962
2030
  let hasError = false;
2031
+ let hasFatal = false;
1963
2032
  let hasWarn = false;
1964
2033
  let manualLevel;
1965
2034
  let emitted = false;
@@ -1982,7 +2051,7 @@ function createLogger(initialContext = {}, internalOptions) {
1982
2051
  if (!isPlainObject$1(context.audit))
1983
2052
  context.audit = fields;
1984
2053
  else
1985
- mergeInto(context.audit, fields);
2054
+ mergeInto(writableChild(context, "audit"), fields);
1986
2055
  context._auditForceKeep = true;
1987
2056
  };
1988
2057
  auditMethod.deny = function deny(reason, input) {
@@ -2006,7 +2075,7 @@ function createLogger(initialContext = {}, internalOptions) {
2006
2075
  warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
2007
2076
  return;
2008
2077
  }
2009
- mergeInto(context, data);
2078
+ mergeFields(context, data);
2010
2079
  },
2011
2080
  setLevel(level) {
2012
2081
  if (emitted) {
@@ -2023,13 +2092,25 @@ function createLogger(initialContext = {}, internalOptions) {
2023
2092
  hasError = true;
2024
2093
  const err = typeof error === "string" ? new Error(error) : error;
2025
2094
  if (errorContext)
2026
- mergeInto(context, errorContext);
2095
+ mergeFields(context, errorContext);
2027
2096
  const errorObj = serializeError(err);
2028
2097
  if (isPlainObject$1(context.error))
2029
- mergeInto(context.error, errorObj);
2098
+ mergeInto(writableChild(context, "error"), errorObj);
2030
2099
  else
2031
2100
  context.error = errorObj;
2032
2101
  },
2102
+ fatal(message, fatalContext) {
2103
+ if (emitted) {
2104
+ warnPostEmit("log.fatal()", `Keys dropped: ${(fatalContext ? ["message", ...Object.keys(fatalContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2105
+ return;
2106
+ }
2107
+ hasFatal = true;
2108
+ addLog("fatal", message);
2109
+ if (fatalContext) {
2110
+ const { requestLogs: _, ...rest } = fatalContext;
2111
+ mergeFields(context, rest);
2112
+ }
2113
+ },
2033
2114
  info(message, infoContext) {
2034
2115
  if (emitted) {
2035
2116
  warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
@@ -2038,7 +2119,7 @@ function createLogger(initialContext = {}, internalOptions) {
2038
2119
  addLog("info", message);
2039
2120
  if (infoContext) {
2040
2121
  const { requestLogs: _, ...rest } = infoContext;
2041
- mergeInto(context, rest);
2122
+ mergeFields(context, rest);
2042
2123
  }
2043
2124
  },
2044
2125
  warn(message, warnContext) {
@@ -2050,7 +2131,29 @@ function createLogger(initialContext = {}, internalOptions) {
2050
2131
  addLog("warn", message);
2051
2132
  if (warnContext) {
2052
2133
  const { requestLogs: _, ...rest } = warnContext;
2053
- mergeInto(context, rest);
2134
+ mergeFields(context, rest);
2135
+ }
2136
+ },
2137
+ debug(message, debugContext) {
2138
+ if (emitted) {
2139
+ warnPostEmit("log.debug()", `Keys dropped: ${(debugContext ? ["message", ...Object.keys(debugContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2140
+ return;
2141
+ }
2142
+ addLog("debug", message);
2143
+ if (debugContext) {
2144
+ const { requestLogs: _, ...rest } = debugContext;
2145
+ mergeFields(context, rest);
2146
+ }
2147
+ },
2148
+ trace(message, traceContext) {
2149
+ if (emitted) {
2150
+ warnPostEmit("log.trace()", `Keys dropped: ${(traceContext ? ["message", ...Object.keys(traceContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2151
+ return;
2152
+ }
2153
+ addLog("trace", message);
2154
+ if (traceContext) {
2155
+ const { requestLogs: _, ...rest } = traceContext;
2156
+ mergeFields(context, rest);
2054
2157
  }
2055
2158
  },
2056
2159
  emit(overrides) {
@@ -2058,8 +2161,8 @@ function createLogger(initialContext = {}, internalOptions) {
2058
2161
  warnPostEmit("log.emit()", "Ignoring duplicate emit.");
2059
2162
  return null;
2060
2163
  }
2061
- const durationMs = elapsedMs(startTime);
2062
- const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
2164
+ const durationMs = overrides?._durationMs ?? elapsedMs(startTime);
2165
+ const level = manualLevel ?? (hasFatal ? "fatal" : hasError ? "error" : hasWarn ? "warn" : "info");
2063
2166
  let forceKeep = false;
2064
2167
  const auditForceKeep = consumeAuditForceKeep(context);
2065
2168
  if (overrides?._forceKeep)
@@ -2082,7 +2185,7 @@ function createLogger(initialContext = {}, internalOptions) {
2082
2185
  if (overrides) {
2083
2186
  const obj = overrides;
2084
2187
  for (const key in obj)
2085
- if (key !== "_forceKeep")
2188
+ if (key !== "_forceKeep" && key !== "_durationMs")
2086
2189
  context[key] = obj[key];
2087
2190
  }
2088
2191
  context.durationMs = durationMs;
@@ -2209,15 +2312,64 @@ function finalizeAudit(event) {
2209
2312
  event.audit = decorated;
2210
2313
  _testCollector?.(decorated, event);
2211
2314
  }
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(() => {
2315
+ 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;
2316
+ var init_audit_C5ZK3s_B = __esm(() => {
2214
2317
  init_utils();
2215
- init_redact_C7FmdhwI();
2216
- init_globalRegistry_Bh3bIGwA();
2217
- init_pretty_error_D8rlWNL1();
2318
+ init_globalRegistry_27hBAWF();
2319
+ init_pretty_error_CRPxjp4p();
2218
2320
  init_dev_terminal_Brarc6vc();
2219
2321
  init_wideEventChannel_BUDW48oP();
2220
- init_error();
2322
+ init_serialize_error_DHkLgVsh();
2323
+ builtinPatterns = {
2324
+ creditCard: {
2325
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
2326
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
2327
+ },
2328
+ email: {
2329
+ pattern: /[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})*\.[a-zA-Z]{2,63}\b/g,
2330
+ mask: (m) => {
2331
+ if (m.indexOf("@") < 1)
2332
+ return "***@***";
2333
+ const tld = m.slice(m.lastIndexOf("."));
2334
+ return `${m[0]}***@***${tld}`;
2335
+ }
2336
+ },
2337
+ ipv4: {
2338
+ 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,
2339
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
2340
+ },
2341
+ phone: {
2342
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
2343
+ mask: (m) => {
2344
+ const digits = m.replace(/[^\d]/g, "");
2345
+ if (m.startsWith("+") && digits.length > 4) {
2346
+ const ccMatch = m.match(/^\+\d{1,3}/);
2347
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
2348
+ }
2349
+ if (digits.length > 2)
2350
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
2351
+ return "***";
2352
+ }
2353
+ },
2354
+ jwt: {
2355
+ pattern: /\beyJ(?:(?!-eyJ)[\w-])*\.[\w-]*\.[\w-]*\b/g,
2356
+ mask: () => "eyJ***.***"
2357
+ },
2358
+ bearer: {
2359
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
2360
+ mask: () => "Bearer ***"
2361
+ },
2362
+ iban: {
2363
+ 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,
2364
+ mask: (m) => {
2365
+ const clean = m.replace(/[\s-]/g, "");
2366
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
2367
+ }
2368
+ }
2369
+ };
2370
+ SECRET_KEY = /(?:password|passwd|secret|token)$/i;
2371
+ globallyRedacted = Symbol.for("evlog.globallyRedacted");
2372
+ ({ serializeError, serializeErrorsIn } = createErrorSerializer((stack) => isDev() ? compactStackForStorage(stack) : stack));
2221
2373
  nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2222
2374
  pendingDrainState = /* @__PURE__ */ new WeakMap;
2223
2375
  state = globalConfig;
@@ -2225,14 +2377,19 @@ var init_audit_C8euLMvu = __esm(() => {
2225
2377
  info: createLogMethod("info"),
2226
2378
  error: createLogMethod("error"),
2227
2379
  warn: createLogMethod("warn"),
2228
- debug: createLogMethod("debug")
2380
+ debug: createLogMethod("debug"),
2381
+ fatal: createLogMethod("fatal"),
2382
+ trace: createLogMethod("trace")
2229
2383
  };
2230
2384
  noopLogger = {
2231
2385
  set() {},
2232
2386
  setLevel() {},
2233
2387
  error() {},
2388
+ fatal() {},
2234
2389
  info() {},
2235
2390
  warn() {},
2391
+ debug() {},
2392
+ trace() {},
2236
2393
  emit() {
2237
2394
  return null;
2238
2395
  },
@@ -2245,12 +2402,45 @@ var init_audit_C8euLMvu = __esm(() => {
2245
2402
  initLogger(__EVLOG_CONFIG__);
2246
2403
  });
2247
2404
 
2248
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
2405
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/index.mjs
2249
2406
  var init_dist = __esm(() => {
2250
- init_audit_C8euLMvu();
2407
+ init_audit_C5ZK3s_B();
2251
2408
  });
2252
2409
 
2253
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2410
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2411
+ function extractErrorStatus(error) {
2412
+ if (error === null || typeof error !== "object")
2413
+ return 500;
2414
+ const raw = error.status ?? error.statusCode;
2415
+ const status = Number(raw);
2416
+ return Number.isFinite(status) ? status : 500;
2417
+ }
2418
+ var init_errors_CL8dDgIi = () => {};
2419
+
2420
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/middleware-CmfmqXwL.mjs
2421
+ function shouldLog(path, include, exclude) {
2422
+ if (exclude && exclude.length > 0) {
2423
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2424
+ return false;
2425
+ }
2426
+ if (!include || include.length === 0)
2427
+ return true;
2428
+ return include.some((pattern) => matchesPattern(path, pattern));
2429
+ }
2430
+ function getServiceForPath(path, routes) {
2431
+ if (!routes)
2432
+ return;
2433
+ for (const [pattern, config] of Object.entries(routes))
2434
+ if (matchesPattern(path, pattern))
2435
+ return config.service;
2436
+ }
2437
+ function extendDeferredDrain(drainPromise, waitUntil) {
2438
+ drainPromise.catch((err) => {
2439
+ console.error("[evlog] background drain failed:", err);
2440
+ });
2441
+ if (typeof waitUntil === "function")
2442
+ waitUntil(drainPromise);
2443
+ }
2254
2444
  function shouldDeferEmitForResponse(response) {
2255
2445
  if (!response.body)
2256
2446
  return false;
@@ -2307,68 +2497,27 @@ function createObservedBody(body, onDone, onError) {
2307
2497
  settle(onDone);
2308
2498
  }
2309
2499
  }
2310
- });
2311
- }
2312
- function bindStreamingResponseLifecycle(response, onComplete) {
2313
- if (!response.body) {
2314
- Promise.resolve(onComplete({ status: response.status })).catch((err) => {
2315
- console.error("[evlog] stream completion handling failed:", err);
2316
- });
2317
- return response;
2318
- }
2319
- const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
2320
- status: response.status,
2321
- error: toError(err)
2322
- }));
2323
- if (!body)
2324
- return response;
2325
- return new Response(body, {
2326
- status: response.status,
2327
- statusText: response.statusText,
2328
- headers: response.headers
2329
- });
2330
- }
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;
2500
+ });
2359
2501
  }
2360
- function extendDeferredDrain(drainPromise, waitUntil) {
2361
- drainPromise.catch((err) => {
2362
- console.error("[evlog] background drain failed:", err);
2502
+ function bindStreamingResponseLifecycle(response, onComplete) {
2503
+ if (!response.body) {
2504
+ Promise.resolve(onComplete({ status: response.status })).catch((err) => {
2505
+ console.error("[evlog] stream completion handling failed:", err);
2506
+ });
2507
+ return response;
2508
+ }
2509
+ const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
2510
+ status: response.status,
2511
+ error: toError(err)
2512
+ }));
2513
+ if (!body)
2514
+ return response;
2515
+ return new Response(body, {
2516
+ status: response.status,
2517
+ statusText: response.statusText,
2518
+ headers: response.headers
2363
2519
  });
2364
- if (typeof waitUntil === "function")
2365
- waitUntil(drainPromise);
2366
2520
  }
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
2521
  function resolveMiddlewarePluginRunner(options) {
2373
2522
  const global = getGlobalPluginRunner();
2374
2523
  const local = options.plugins;
@@ -2418,6 +2567,7 @@ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseSta
2418
2567
  if (runner.hasEnrich)
2419
2568
  await runner.runEnrich(enrichCtx);
2420
2569
  }
2570
+ outputWideEvent(emittedEvent);
2421
2571
  publishWideEvent(emittedEvent);
2422
2572
  markWideEventDrainStarted(emittedEvent);
2423
2573
  const drain = options.drain ?? getGlobalDrain();
@@ -2492,14 +2642,37 @@ function createMiddlewareLogger(options) {
2492
2642
  await performFinish(logger, { status });
2493
2643
  return response;
2494
2644
  }
2495
- return bindStreamingResponseLifecycle(response, async (meta) => {
2496
- await performFinish(logger, {
2497
- status: meta.status ?? status,
2498
- error: meta.error
2645
+ const { waitUntil } = options;
2646
+ if (!waitUntil)
2647
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2648
+ await performFinish(logger, {
2649
+ status: meta.status ?? status,
2650
+ error: meta.error
2651
+ });
2499
2652
  });
2653
+ const drains = [];
2654
+ let markFinished;
2655
+ waitUntil(new Promise((resolve) => {
2656
+ markFinished = resolve;
2657
+ }).then(() => Promise.allSettled(drains)));
2658
+ const drainOptions = {
2659
+ ...options,
2660
+ waitUntil: (promise) => {
2661
+ drains.push(promise);
2662
+ }
2663
+ };
2664
+ return bindStreamingResponseLifecycle(response, async (meta) => {
2665
+ try {
2666
+ await performFinish(logger, {
2667
+ status: meta.status ?? status,
2668
+ error: meta.error
2669
+ }, drainOptions);
2670
+ } finally {
2671
+ markFinished();
2672
+ }
2500
2673
  });
2501
2674
  };
2502
- async function performFinish(requestLogger, opts) {
2675
+ async function performFinish(requestLogger, opts, drainOptions = options) {
2503
2676
  const { status, error } = opts ?? {};
2504
2677
  if (error) {
2505
2678
  requestLogger.error(error);
@@ -2522,9 +2695,16 @@ function createMiddlewareLogger(options) {
2522
2695
  if (pluginRunner.hasKeep)
2523
2696
  await pluginRunner.runKeep(tailCtx);
2524
2697
  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);
2698
+ const emittedEvent = requestLogger.emit({
2699
+ _forceKeep: forceKeep,
2700
+ _durationMs: durationMs
2701
+ });
2702
+ if (emittedEvent) {
2703
+ if (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain() || hasWideEventPublisher())
2704
+ await runEnrichAndDrain(emittedEvent, drainOptions, requestInfo, resolvedStatus, pluginRunner);
2705
+ else
2706
+ outputWideEvent(emittedEvent);
2707
+ }
2528
2708
  if (pluginRunner.hasRequestLifecycle)
2529
2709
  pluginRunner.runOnRequestFinish({
2530
2710
  logger: requestLogger,
@@ -2545,15 +2725,12 @@ function createMiddlewareLogger(options) {
2545
2725
  };
2546
2726
  }
2547
2727
  var noopResult, runnerCache;
2548
- var init_middleware_fam3VyaL = __esm(() => {
2728
+ var init_middleware_CmfmqXwL = __esm(() => {
2549
2729
  init_utils();
2550
- init_redact_C7FmdhwI();
2551
- init_globalRegistry_Bh3bIGwA();
2730
+ init_audit_C5ZK3s_B();
2731
+ init_globalRegistry_27hBAWF();
2552
2732
  init_wideEventChannel_BUDW48oP();
2553
- init_audit_C8euLMvu();
2554
2733
  init_errors_CL8dDgIi();
2555
- init_deferred_drain_CfRYimo5();
2556
- init_streamResponse_OlirMA5P();
2557
2734
  noopResult = {
2558
2735
  logger: noopLogger,
2559
2736
  finish: () => Promise.resolve(null),
@@ -2563,22 +2740,20 @@ var init_middleware_fam3VyaL = __esm(() => {
2563
2740
  runnerCache = /* @__PURE__ */ new WeakMap;
2564
2741
  });
2565
2742
 
2566
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
2743
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/integration-BDRiSZGp.mjs
2567
2744
  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
- };
2745
+ parent.fork = (label, fn) => forkBackgroundLogger({
2746
+ storage,
2747
+ parent,
2748
+ middlewareOptions,
2749
+ label,
2750
+ fn,
2751
+ lifecycle
2752
+ });
2579
2753
  }
2580
2754
  function forkBackgroundLogger(options) {
2581
- const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2755
+ const { storage, parent, label, fn, lifecycle } = options;
2756
+ const { waitUntil, ...middlewareOptions } = options.middlewareOptions;
2582
2757
  const parentCtx = parent.getContext();
2583
2758
  const parentRequestId = parentCtx.requestId;
2584
2759
  if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
@@ -2599,26 +2774,36 @@ function forkBackgroundLogger(options) {
2599
2774
  path,
2600
2775
  requestId: child.getContext().requestId
2601
2776
  };
2602
- storage.run(child, () => {
2777
+ const lifetime = storage.run(child, () => {
2603
2778
  lifecycle?.onChildEnter?.(child);
2604
- Promise.resolve().then(() => fn()).then(async () => {
2605
- const emittedEvent = child.emit();
2779
+ return Promise.resolve().then(() => fn()).then(() => {
2606
2780
  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) => {
2781
+ return typeof ctxStatus === "number" ? ctxStatus : undefined;
2782
+ }, (err) => {
2611
2783
  const error = err instanceof Error ? err : new Error(String(err));
2784
+ const status = extractErrorStatus(error);
2612
2785
  child.error(error);
2613
- child.set({ status: extractErrorStatus(error) });
2786
+ child.set({ status });
2787
+ return status;
2788
+ }).then(async (status) => {
2614
2789
  const emittedEvent = child.emit();
2615
- const status = extractErrorStatus(error);
2616
- if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2617
- await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2790
+ if (!emittedEvent)
2791
+ return;
2792
+ if (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain())
2793
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, emittedEvent.status ?? status);
2794
+ else
2795
+ outputWideEvent(emittedEvent);
2796
+ }).catch((err) => {
2797
+ console.error("[evlog] log.fork() failed to emit the child event:", err);
2618
2798
  }).finally(() => {
2619
2799
  lifecycle?.onChildExit?.(child);
2620
2800
  });
2621
2801
  });
2802
+ if (waitUntil) {
2803
+ const { settled } = middlewareOptions.drain ?? getGlobalDrain() ?? {};
2804
+ waitUntil(typeof settled === "function" ? lifetime.then(() => settled()) : lifetime);
2805
+ }
2806
+ return lifetime;
2622
2807
  }
2623
2808
  function normalizeHeaders(headers) {
2624
2809
  if (!headers)
@@ -2659,122 +2844,364 @@ function defineFrameworkIntegration(spec) {
2659
2844
  };
2660
2845
  } };
2661
2846
  }
2662
- var init_integration_CGD18W8r = __esm(() => {
2663
- init_audit_C8euLMvu();
2847
+ var init_integration_BDRiSZGp = __esm(() => {
2848
+ init_audit_C5ZK3s_B();
2664
2849
  init_headers_Bx1ieR_m();
2665
2850
  init_errors_CL8dDgIi();
2666
- init_middleware_fam3VyaL();
2851
+ init_middleware_CmfmqXwL();
2667
2852
  });
2668
2853
 
2669
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
2670
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2854
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/toolkit/storage.mjs
2855
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2671
2856
  function createLoggerStorage(contextHint, id = contextHint) {
2672
- const storage = getSharedStorage(id, () => new AsyncLocalStorage4);
2857
+ const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
2673
2858
  function useLogger() {
2674
2859
  const logger = storage.getStore();
2675
2860
  if (!logger)
2676
2861
  throw new Error(`[evlog] useLogger() was called outside of an evlog ${contextHint}`);
2677
2862
  return logger;
2678
2863
  }
2679
- return {
2680
- storage,
2681
- useLogger
2682
- };
2864
+ return {
2865
+ storage,
2866
+ useLogger
2867
+ };
2868
+ }
2869
+ var init_storage = __esm(() => {
2870
+ init_globalRegistry_27hBAWF();
2871
+ });
2872
+
2873
+ // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/toolkit.mjs
2874
+ var init_toolkit = __esm(() => {
2875
+ init_integration_BDRiSZGp();
2876
+ init_storage();
2877
+ });
2878
+
2879
+ // src/server/evlog.ts
2880
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2881
+ import { Elysia as Elysia3 } from "elysia";
2882
+ function getRequestLogger() {
2883
+ const logger = loggerStorage.storage.getStore() ?? requestLogSlots.getStore()?.handle?.logger;
2884
+ return logger ?? loggerStorage.useLogger();
2885
+ }
2886
+ var loggerStorage, requestLogSlots, integration, instanceOptions, runtimeWaitUntil, requestWaitUntil;
2887
+ var init_evlog = __esm(() => {
2888
+ init_toolkit();
2889
+ init_instance();
2890
+ loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2891
+ requestLogSlots = new AsyncLocalStorage4;
2892
+ integration = defineFrameworkIntegration({
2893
+ attachLogger: () => {
2894
+ return;
2895
+ },
2896
+ extractRequest: ({ request }) => {
2897
+ const url = new URL(request.url);
2898
+ return {
2899
+ headers: request.headers,
2900
+ method: request.method,
2901
+ path: url.pathname,
2902
+ requestId: request.headers.get("x-request-id") ?? undefined
2903
+ };
2904
+ },
2905
+ name: "furin",
2906
+ storage: loggerStorage.storage
2907
+ });
2908
+ instanceOptions = instanceSlot(() => ({
2909
+ options: undefined
2910
+ }));
2911
+ runtimeWaitUntil = new Set;
2912
+ requestWaitUntil = new WeakMap;
2913
+ });
2914
+
2915
+ // src/server/context-logger.ts
2916
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
2917
+ function getLogger() {
2918
+ try {
2919
+ return getRequestLogger();
2920
+ } catch {
2921
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
2922
+ }
2923
+ }
2924
+ var noopLogger2, syntheticRenderStorage;
2925
+ var init_context_logger = __esm(() => {
2926
+ init_dist();
2927
+ init_evlog();
2928
+ noopLogger2 = {
2929
+ debug: () => {},
2930
+ emit: () => null,
2931
+ error: () => {},
2932
+ fatal: () => {},
2933
+ fork: async (_label, fn) => {
2934
+ await fn();
2935
+ },
2936
+ getContext: () => ({}),
2937
+ info: () => {},
2938
+ set: () => {},
2939
+ setLevel: () => {},
2940
+ trace: () => {},
2941
+ warn: () => {}
2942
+ };
2943
+ syntheticRenderStorage = new AsyncLocalStorage5;
2944
+ });
2945
+
2946
+ // src/server/sync/config.ts
2947
+ function syncRuntimeOptions(sync) {
2948
+ return {
2949
+ adapter: sync.adapter,
2950
+ notifier: sync.notifier,
2951
+ principal: sync.principal,
2952
+ secret: sync.secret
2953
+ };
2954
+ }
2955
+ var init_config = () => {};
2956
+
2957
+ // src/server/sync/principal-journal.ts
2958
+ function configurePrincipalSecret(adapter, secret, development) {
2959
+ if (secret !== undefined && (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH)) {
2960
+ throw new Error(`[furin] sync.secret must be a string of at least ${MIN_SECRET_LENGTH} characters.`);
2961
+ }
2962
+ if (principalSecrets.has(adapter)) {
2963
+ if (principalSecrets.get(adapter) !== secret) {
2964
+ throw new Error("[furin] Sync runtimes sharing a SyncAdapter must use the same secret.");
2965
+ }
2966
+ return;
2967
+ }
2968
+ principalSecrets.set(adapter, secret);
2969
+ if (secret === undefined && !development) {
2970
+ 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.");
2971
+ }
2972
+ }
2973
+ function principalHash(adapter, principal) {
2974
+ const secret = principalSecrets.get(adapter);
2975
+ const hasher = secret === undefined ? new Bun.CryptoHasher("sha256") : new Bun.CryptoHasher("sha256", secret);
2976
+ return hasher.update(principal).digest("hex");
2977
+ }
2978
+ async function readPrincipalChanges(adapter, input, principal) {
2979
+ if (principalJournals.has(adapter)) {
2980
+ const page = await adapter.readChanges(input);
2981
+ const hash = principalHash(adapter, principal);
2982
+ if (page.changes.every((change) => changePrincipals.get(change) === hash)) {
2983
+ return page;
2984
+ }
2985
+ }
2986
+ const cursor = await adapter.currentCursor();
2987
+ return {
2988
+ changes: [],
2989
+ cursor,
2990
+ hasMore: false,
2991
+ reset: input.after !== undefined && input.after !== cursor
2992
+ };
2993
+ }
2994
+ var MIN_SECRET_LENGTH = 32, principalJournals, changePrincipals, principalSecrets;
2995
+ var init_principal_journal = __esm(() => {
2996
+ principalJournals = new WeakSet;
2997
+ changePrincipals = new WeakMap;
2998
+ principalSecrets = new WeakMap;
2999
+ });
3000
+
3001
+ // src/server/sync/queries.ts
3002
+ function isMutationMethod(method) {
3003
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
3004
+ }
3005
+ function markInternalRead(request) {
3006
+ internalReads.add(request);
3007
+ }
3008
+ function isInternalRead(request) {
3009
+ return internalReads.has(request);
3010
+ }
3011
+ function sealInvalidations(request) {
3012
+ sealed.add(request);
3013
+ }
3014
+ function requestInvalidate(request) {
3015
+ return (target, params) => {
3016
+ if (!isMutationMethod(request.method)) {
3017
+ throw new Error(`[furin] invalidate() was called while handling a ${request.method}: only a mutation invalidates.`);
3018
+ }
3019
+ if (sealed.has(request)) {
3020
+ if (IS_DEV) {
3021
+ throw new Error("[furin] invalidate() was called after mutation() resolved: call it inside the mutation() callback to commit it with the transaction.");
3022
+ }
3023
+ return;
3024
+ }
3025
+ let invalidations = collected.get(request);
3026
+ if (!invalidations) {
3027
+ invalidations = { queries: [], rules: [] };
3028
+ collected.set(request, invalidations);
3029
+ }
3030
+ if (typeof target !== "string") {
3031
+ invalidations.rules.push(target);
3032
+ return;
3033
+ }
3034
+ const identity = { id: target, scope: params ?? {} };
3035
+ queryTag(identity);
3036
+ invalidations.queries.push(identity);
3037
+ };
3038
+ }
3039
+ function urlIdentity(context) {
3040
+ const scope = Object.fromEntries(Object.entries(context.params ?? {}).filter(([, value]) => value !== undefined));
3041
+ return { id: context.route ?? context.path, scope };
3042
+ }
3043
+ function resolveSyncInvalidations(context) {
3044
+ const invalidations = collected.get(context.request);
3045
+ return [
3046
+ ...invalidations?.rules ?? [],
3047
+ { tags: [...invalidations?.queries ?? [], urlIdentity(context)].map(queryTag) }
3048
+ ];
3049
+ }
3050
+ function appendQueryInvalidations(input, context) {
3051
+ if (input === undefined) {
3052
+ return;
3053
+ }
3054
+ const queries = [];
3055
+ for (const rule of Array.isArray(input) ? input : [input]) {
3056
+ for (const tag of rule.tags ?? []) {
3057
+ const identity = queryFromTag(tag);
3058
+ if (identity) {
3059
+ queries.push(identity);
3060
+ }
3061
+ }
3062
+ }
3063
+ if (queries.length > 0) {
3064
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
3065
+ }
3066
+ }
3067
+ var collected, sealed, internalReads;
3068
+ var init_queries = __esm(() => {
3069
+ collected = new WeakMap;
3070
+ sealed = new WeakSet;
3071
+ internalReads = new WeakSet;
3072
+ });
3073
+
3074
+ // src/server/sync/notifier.ts
3075
+ class PollingSyncNotifier {
3076
+ recovery = "self";
3077
+ adapter;
3078
+ intervalMs;
3079
+ listeners = new Set;
3080
+ cursor;
3081
+ initialization;
3082
+ polling;
3083
+ revision = 0;
3084
+ timer;
3085
+ constructor(adapter, intervalMs) {
3086
+ this.adapter = adapter;
3087
+ this.intervalMs = intervalMs;
3088
+ }
3089
+ publish(cursor) {
3090
+ this.revision += 1;
3091
+ this.emit(cursor);
3092
+ return Promise.resolve();
3093
+ }
3094
+ async subscribe(listener) {
3095
+ const subscription = { listener };
3096
+ this.listeners.add(subscription);
3097
+ try {
3098
+ await this.start();
3099
+ } catch (error) {
3100
+ this.listeners.delete(subscription);
3101
+ throw error;
3102
+ }
3103
+ return {
3104
+ unsubscribe: () => {
3105
+ this.listeners.delete(subscription);
3106
+ if (this.listeners.size === 0 && this.timer) {
3107
+ clearTimeout(this.timer);
3108
+ this.timer = undefined;
3109
+ }
3110
+ return Promise.resolve();
3111
+ }
3112
+ };
3113
+ }
3114
+ emit(cursor) {
3115
+ if (cursor === this.cursor) {
3116
+ return;
3117
+ }
3118
+ this.cursor = cursor;
3119
+ for (const subscription of [...this.listeners]) {
3120
+ try {
3121
+ subscription.listener(cursor);
3122
+ } catch {}
3123
+ }
3124
+ }
3125
+ async poll() {
3126
+ const { revision } = this;
3127
+ try {
3128
+ const cursor = await this.adapter.currentCursor();
3129
+ if (revision === this.revision && this.listeners.size > 0) {
3130
+ this.emit(cursor);
3131
+ }
3132
+ } catch {}
3133
+ }
3134
+ async start() {
3135
+ if (this.timer || this.polling) {
3136
+ return;
3137
+ }
3138
+ if (!this.initialization) {
3139
+ const { revision } = this;
3140
+ this.initialization = this.adapter.currentCursor().then((cursor) => {
3141
+ if (revision === this.revision) {
3142
+ this.cursor = cursor;
3143
+ }
3144
+ }).finally(() => {
3145
+ this.initialization = undefined;
3146
+ });
3147
+ }
3148
+ await this.initialization;
3149
+ this.schedulePoll();
3150
+ }
3151
+ schedulePoll() {
3152
+ if (this.listeners.size === 0 || this.timer || this.polling) {
3153
+ return;
3154
+ }
3155
+ this.timer = setTimeout(() => {
3156
+ this.timer = undefined;
3157
+ this.polling = this.poll().finally(() => {
3158
+ this.polling = undefined;
3159
+ this.schedulePoll();
3160
+ });
3161
+ }, this.intervalMs);
3162
+ this.timer.unref?.();
3163
+ }
2683
3164
  }
2684
- var init_storage = __esm(() => {
2685
- init_globalRegistry_Bh3bIGwA();
2686
- });
2687
-
2688
- // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
2689
- var init_toolkit = __esm(() => {
2690
- init_integration_CGD18W8r();
2691
- init_storage();
2692
- });
2693
3165
 
2694
- // src/server/evlog.ts
2695
- import { Elysia } from "elysia";
2696
- var loggerStorage, integration, getRequestLogger, runtimeWaitUntil;
2697
- var init_evlog = __esm(() => {
2698
- init_toolkit();
2699
- loggerStorage = createLoggerStorage("Furin request context. Make sure the Furin plugin is registered before your routes.", "@teyik0/furin:evlog");
2700
- integration = defineFrameworkIntegration({
2701
- attachLogger: () => {
3166
+ // src/server/sync/runtime.ts
3167
+ function publishCursor(runtime, cursor) {
3168
+ const alreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
3169
+ if (!alreadyPublished) {
3170
+ runtime.notifier.publish(cursor).catch(() => {
2702
3171
  return;
2703
- },
2704
- extractRequest: ({ request }) => {
2705
- const url = new URL(request.url);
2706
- return {
2707
- headers: request.headers,
2708
- method: request.method,
2709
- path: url.pathname,
2710
- requestId: request.headers.get("x-request-id") ?? undefined
2711
- };
2712
- },
2713
- name: "furin",
2714
- storage: loggerStorage.storage
2715
- });
2716
- getRequestLogger = loggerStorage.useLogger;
2717
- runtimeWaitUntil = new Set;
2718
- });
2719
-
2720
- // src/server/context-logger.ts
2721
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
2722
- function getLogger() {
2723
- try {
2724
- return getRequestLogger();
2725
- } catch {
2726
- return syntheticRenderStorage.getStore() ?? noopLogger2;
3172
+ });
2727
3173
  }
2728
3174
  }
2729
- var noopLogger2, syntheticRenderStorage;
2730
- var init_context_logger = __esm(() => {
2731
- init_dist();
2732
- init_evlog();
2733
- noopLogger2 = {
2734
- emit: () => null,
2735
- error: () => {},
2736
- fork: (_label, fn) => fn(),
2737
- getContext: () => ({}),
2738
- info: () => {},
2739
- set: () => {},
2740
- setLevel: () => {},
2741
- warn: () => {}
2742
- };
2743
- syntheticRenderStorage = new AsyncLocalStorage5;
2744
- });
2745
-
2746
- // src/server/runtime-env.ts
2747
- var IS_DEV = true;
2748
-
2749
- // src/server/sync/runtime.ts
2750
- function resolveSyncRuntime(options) {
2751
- if (!IS_DEV && options.adapter.scope === "process-local") {
3175
+ function resolveSyncRuntime(options, development) {
3176
+ if (!development && options.adapter.scope === "process-local") {
2752
3177
  throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
2753
3178
  }
3179
+ configurePrincipalSecret(options.adapter, options.secret, development);
2754
3180
  if (options.notifier) {
2755
3181
  if (options.adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && options.adapter.notificationChannel !== options.notifier.notificationChannel) {
2756
3182
  throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
2757
3183
  }
2758
- return { adapter: options.adapter, notifier: options.notifier };
3184
+ return { adapter: options.adapter, development, notifier: options.notifier };
2759
3185
  }
2760
- if (!IS_DEV && options.adapter.scope === "distributed") {
3186
+ if (!development && options.adapter.scope === "distributed") {
2761
3187
  throw new Error("[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback.");
2762
3188
  }
2763
3189
  const existing = pollingNotifiers.get(options.adapter);
2764
3190
  if (existing) {
2765
- return { adapter: options.adapter, notifier: existing };
3191
+ return { adapter: options.adapter, development, notifier: existing };
2766
3192
  }
2767
3193
  const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
2768
3194
  pollingNotifiers.set(options.adapter, notifier);
2769
- return { adapter: options.adapter, notifier };
3195
+ return { adapter: options.adapter, development, notifier };
2770
3196
  }
2771
3197
  var POLL_INTERVAL_MS = 250, pollingNotifiers;
2772
3198
  var init_runtime = __esm(() => {
3199
+ init_principal_journal();
2773
3200
  pollingNotifiers = new WeakMap;
2774
3201
  });
2775
3202
 
2776
3203
  // src/server/sync/stream.ts
2777
- import { Elysia as Elysia2 } from "elysia";
3204
+ import { Elysia as Elysia4 } from "elysia";
2778
3205
  function parseChangeQuery(request) {
2779
3206
  const url = new URL(request.url);
2780
3207
  const after = url.searchParams.get("after") ?? undefined;
@@ -2792,10 +3219,14 @@ function parseChangeQuery(request) {
2792
3219
  return { after, limit };
2793
3220
  }
2794
3221
  function createSyncChangesPlugin(options) {
3222
+ return createRuntimeSyncChangesPlugin(options, IS_DEV);
3223
+ }
3224
+ function createRuntimeSyncChangesPlugin(options, development) {
2795
3225
  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) => {
3226
+ const runtime = resolveSyncRuntime(syncRuntimeOptions(options), development);
3227
+ return new Elysia4({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
2798
3228
  const { request, set } = context;
3229
+ markInternalRead(request);
2799
3230
  set.headers["cache-control"] = "no-store";
2800
3231
  const query = parseChangeQuery(request);
2801
3232
  if ("error" in query) {
@@ -2805,18 +3236,14 @@ function createSyncChangesPlugin(options) {
2805
3236
  if (principal.length === 0) {
2806
3237
  return new Response("Unauthorized", { status: 401 });
2807
3238
  }
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
- };
3239
+ return readPrincipalChanges(runtime.adapter, query, principal);
2815
3240
  });
2816
3241
  }
2817
3242
  var DEFAULT_CHANGE_LIMIT = 100, MAX_CHANGE_LIMIT = 500, MAX_CURSOR_LENGTH = 128, UNSIGNED_INTEGER_PATTERN, defaultSyncPath = "/_furin/sync", cursorStates, resolvedStates, pendingUnsubscriptions, unsubscriptions;
2818
3243
  var init_stream = __esm(() => {
2819
3244
  init_config();
3245
+ init_principal_journal();
3246
+ init_queries();
2820
3247
  init_runtime();
2821
3248
  UNSIGNED_INTEGER_PATTERN = /^\d+$/;
2822
3249
  cursorStates = new Map;
@@ -2824,54 +3251,16 @@ var init_stream = __esm(() => {
2824
3251
  pendingUnsubscriptions = new Set;
2825
3252
  unsubscriptions = new WeakMap;
2826
3253
  });
3254
+ // src/server/auto-invalidate/runtime.ts
3255
+ init_invalidation_header();
3256
+ init_prefix();
2827
3257
 
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
- }
3258
+ // src/server/cache/invalidation.ts
3259
+ init_invalidation_header();
3260
+ init_prefix();
2867
3261
 
2868
- // src/shared/prefix.ts
2869
- function physicalPath(prefix, path) {
2870
- if (prefix === "") {
2871
- return path;
2872
- }
2873
- return path === "/" ? prefix : `${prefix}${path}`;
2874
- }
3262
+ // src/server/devtools/instrumentation.ts
3263
+ import { Elysia as Elysia2 } from "elysia";
2875
3264
 
2876
3265
  // src/devtools/protocol.ts
2877
3266
  var DEVTOOLS_PROTOCOL_VERSION = 2;
@@ -2885,7 +3274,7 @@ function devtoolsInstanceId() {
2885
3274
  return Bun.hash(`${instance.prefix}\x00${instance.pagesDir}`).toString(16);
2886
3275
  }
2887
3276
  function appendDevtoolsEvent(event) {
2888
- const hub = instanceDevtoolsHub();
3277
+ const hub = instanceDevtoolsHub(currentInstance());
2889
3278
  hub.sequence += 1;
2890
3279
  const complete = {
2891
3280
  ...event,
@@ -2990,14 +3379,14 @@ class AutoInvalidateRegistry {
2990
3379
  }
2991
3380
  var instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
2992
3381
  function getAutoInvalidateRegistry(instance) {
2993
- return instanceAutoInvalidateRegistry(instance);
3382
+ return instanceAutoInvalidateRegistry(instance ?? currentInstance());
2994
3383
  }
2995
3384
 
2996
3385
  // src/server/cache/registry.ts
2997
3386
  init_instance();
2998
3387
  var instanceInvalidators = instanceSlot(() => new Map);
2999
3388
  function getCacheInvalidators(instance) {
3000
- return instanceInvalidators(instance).values();
3389
+ return instanceInvalidators(instance ?? currentInstance()).values();
3001
3390
  }
3002
3391
 
3003
3392
  // src/server/cache/route-cache.ts
@@ -3010,10 +3399,12 @@ function pathWithoutSearch(path) {
3010
3399
  }
3011
3400
 
3012
3401
  // src/server/devtools/request-context.ts
3013
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3014
- var requestContext = new AsyncLocalStorage3;
3402
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3403
+ import { Elysia } from "elysia";
3404
+ var requestContext = new AsyncLocalStorage2;
3405
+ var requestSlots = new AsyncLocalStorage2;
3015
3406
  function currentDevtoolsRequest() {
3016
- return requestContext.getStore();
3407
+ return requestContext.getStore() ?? requestSlots.getStore()?.started?.context;
3017
3408
  }
3018
3409
 
3019
3410
  // src/server/devtools/instrumentation.ts
@@ -3033,16 +3424,43 @@ var instancePageCacheAdapter = instanceSlot(() => ({
3033
3424
  adapter: undefined
3034
3425
  }));
3035
3426
  function getPageCacheAdapter(instance) {
3036
- return instancePageCacheAdapter(instance).adapter;
3427
+ return instancePageCacheAdapter(instance ?? currentInstance()).adapter;
3037
3428
  }
3429
+
3038
3430
  // src/server/cache/purger.ts
3431
+ init_instance();
3039
3432
  var pathPurger;
3040
3433
  var tagPurger;
3041
- function callCachePurger(paths) {
3042
- dispatch(pathPurger, paths);
3043
- }
3044
- function callCacheTagPurger(tags) {
3045
- dispatch(tagPurger, tags);
3434
+ var instancePathPurger = instanceSlot(() => ({
3435
+ purger: undefined
3436
+ }));
3437
+ var instanceTagPurger = instanceSlot(() => ({
3438
+ purger: undefined
3439
+ }));
3440
+ function callCachePurger(purges) {
3441
+ dispatchBatches([...purges].map(([instance, paths]) => [
3442
+ instancePathPurger(instance).purger ?? pathPurger,
3443
+ paths
3444
+ ]));
3445
+ }
3446
+ function callCacheTagPurger(instances, tags) {
3447
+ dispatchBatches(instances.map((instance) => [instanceTagPurger(instance).purger ?? tagPurger, tags]));
3448
+ }
3449
+ function dispatchBatches(purges) {
3450
+ const batches = new Map;
3451
+ for (const [purger, keys] of purges) {
3452
+ if (!purger) {
3453
+ continue;
3454
+ }
3455
+ const batch = batches.get(purger) ?? new Set;
3456
+ for (const key of keys) {
3457
+ batch.add(key);
3458
+ }
3459
+ batches.set(purger, batch);
3460
+ }
3461
+ for (const [purger, keys] of batches) {
3462
+ dispatch(purger, [...keys]);
3463
+ }
3046
3464
  }
3047
3465
  function dispatch(purger, keys) {
3048
3466
  if (!purger || keys.length === 0) {
@@ -3058,13 +3476,9 @@ function dispatch(purger, keys) {
3058
3476
  }
3059
3477
 
3060
3478
  // src/server/cache/invalidation.ts
3061
- var _globalPendingInvalidations = new Set;
3062
- function _activeInvalidationSet() {
3063
- return requestPendingInvalidations() ?? _globalPendingInvalidations;
3064
- }
3065
3479
  function consumePendingInvalidations() {
3066
- const set = _activeInvalidationSet();
3067
- if (set.size === 0) {
3480
+ const set = requestPendingInvalidations();
3481
+ if (set === undefined || set.size === 0) {
3068
3482
  return [];
3069
3483
  }
3070
3484
  const paths = [...set];
@@ -3072,13 +3486,13 @@ function consumePendingInvalidations() {
3072
3486
  return paths;
3073
3487
  }
3074
3488
  function peekPendingInvalidations() {
3075
- return [..._activeInvalidationSet()];
3489
+ return [...requestPendingInvalidations() ?? []];
3076
3490
  }
3077
- function callCachePurger2(paths) {
3078
- callCachePurger(paths);
3491
+ function callCachePurger2(purges) {
3492
+ callCachePurger(purges);
3079
3493
  }
3080
3494
  function emitPathInvalidation(instance, path, deleted, purgedPaths) {
3081
- if (!IS_DEV) {
3495
+ if (!instance.development) {
3082
3496
  return;
3083
3497
  }
3084
3498
  withInstance(instance, () => {
@@ -3108,261 +3522,77 @@ async function invalidateInstancePath(instance, path, type) {
3108
3522
  kind: "path",
3109
3523
  path,
3110
3524
  scope: instance.prefix,
3111
- type
3112
- });
3113
- for (const purged of sharedResult.paths) {
3114
- purgedPaths.push(physicalPath(instance.prefix, purged));
3115
- }
3116
- const deleted = result.deleted || sharedResult.invalidated;
3117
- emitPathInvalidation(instance, path, deleted, purgedPaths);
3118
- return { deleted, purgedPaths };
3119
- }
3120
- 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;
3130
- }
3131
- function revalidatePathForInstance(instance, path, type, emitPathEvent) {
3132
- _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
3133
- let deleted = false;
3134
- const purgedPaths = [];
3135
- withInstance(instance, () => {
3136
- for (const invalidator of getCacheInvalidators(instance)) {
3137
- const result = invalidator.invalidatePath(path, type);
3138
- deleted = result.deleted || deleted;
3139
- purgedPaths.push(...result.purgedPaths);
3140
- }
3141
- if (IS_DEV && emitPathEvent !== false) {
3142
- emitPathInvalidation(instance, path, deleted, purgedPaths);
3143
- }
3144
- });
3145
- return { deleted, purgedPaths };
3146
- }
3147
- function dedupePaths(paths) {
3148
- return [...new Set(paths)];
3149
- }
3150
-
3151
- // src/server/auto-invalidate/runtime.ts
3152
- 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
- }
3525
+ type
3526
+ });
3527
+ for (const purged of sharedResult.paths) {
3528
+ purgedPaths.push(physicalPath(instance.prefix, purged));
3309
3529
  }
3310
- callCachePurger2([...purgedPaths]);
3311
- return deleted;
3530
+ const deleted = result.deleted || sharedResult.invalidated;
3531
+ emitPathInvalidation(instance, path, deleted, purgedPaths);
3532
+ return { deleted, purgedPaths };
3312
3533
  }
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));
3534
+ async function revalidatePath(path, type) {
3535
+ const instances = allInstances();
3536
+ const results = await Promise.all(instances.map((instance) => invalidateInstancePath(instance, path, type)));
3537
+ callCachePurger2(new Map(instances.map((instance, index) => [instance, results[index]?.purgedPaths ?? []])));
3538
+ return results.some((result) => result.deleted);
3539
+ }
3540
+ function revalidatePathForInstance(instance, path, type, emitPathEvent) {
3541
+ requestPendingInvalidations()?.add(encodeInvalidationEntry(path, type));
3542
+ let deleted = false;
3543
+ const purgedPaths = [];
3544
+ withInstance(instance, () => {
3545
+ for (const invalidator of getCacheInvalidators(instance)) {
3546
+ const result = invalidator.invalidatePath(path, type);
3547
+ deleted = result.deleted || deleted;
3548
+ purgedPaths.push(...result.purgedPaths);
3318
3549
  }
3319
- if (rule.tags && rule.tags.length > 0) {
3320
- pending.push(revalidateTag(rule.tags));
3550
+ if (emitPathEvent !== false) {
3551
+ emitPathInvalidation(instance, path, deleted, purgedPaths);
3321
3552
  }
3322
- return pending;
3323
3553
  });
3324
- return (await Promise.all(operations)).some(Boolean);
3554
+ return { deleted, purgedPaths };
3325
3555
  }
3326
3556
 
3327
- // src/server/sync/plugin.ts
3328
- init_context_logger();
3557
+ // src/server/auto-invalidate/runtime.ts
3558
+ init_instance();
3329
3559
 
3330
- // src/server/sync/atomic.ts
3331
- import { ElysiaStatus as ElysiaStatus2, StatusMap as StatusMap2, Validator } from "elysia";
3332
- init_context_logger();
3560
+ // src/server/sync/response.ts
3561
+ import { ElysiaStatus, StatusMap } from "elysia";
3333
3562
 
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);
3563
+ // src/server/bounded-body.ts
3564
+ async function readBoundedBytes(stream, maxBytes) {
3565
+ const reader = stream.getReader();
3566
+ const chunks = [];
3567
+ let total = 0;
3568
+ try {
3569
+ for (;; ) {
3570
+ const { done, value } = await reader.read();
3571
+ if (done) {
3572
+ break;
3573
+ }
3574
+ total += value.byteLength;
3575
+ if (total > maxBytes) {
3576
+ await reader.cancel().catch(() => {
3577
+ return;
3578
+ });
3579
+ return;
3355
3580
  }
3581
+ chunks.push(value);
3356
3582
  }
3583
+ } finally {
3584
+ reader.releaseLock();
3357
3585
  }
3358
- if (queries.length > 0) {
3359
- context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
3360
- context.set.headers["x-furin-sync"] = "1";
3586
+ const bytes = new Uint8Array(total);
3587
+ let offset = 0;
3588
+ for (const chunk of chunks) {
3589
+ bytes.set(chunk, offset);
3590
+ offset += chunk.byteLength;
3361
3591
  }
3592
+ return bytes;
3362
3593
  }
3363
3594
 
3364
3595
  // src/server/sync/response.ts
3365
- import { ElysiaStatus, StatusMap } from "elysia";
3366
3596
  var NON_REPLAYABLE_HEADERS = new Set([
3367
3597
  "authorization",
3368
3598
  "connection",
@@ -3377,7 +3607,7 @@ var NON_REPLAYABLE_HEADERS = new Set([
3377
3607
  var MAX_SYNC_REPLAY_RESPONSE_BYTES = 1024 * 1024;
3378
3608
  var UNREPLAYABLE_SYNC_RESPONSE_BODY = new TextEncoder().encode(JSON.stringify({
3379
3609
  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."
3610
+ message: "This mutation response cannot be replayed safely. Return a small bounded response or set idempotent: false on the route."
3381
3611
  }));
3382
3612
  function statusCode(status) {
3383
3613
  if (typeof status === "number") {
@@ -3385,11 +3615,24 @@ function statusCode(status) {
3385
3615
  }
3386
3616
  return status === undefined ? 200 : StatusMap[status];
3387
3617
  }
3388
- function unwrapStatusResponse(value) {
3389
- if (!(value instanceof ElysiaStatus)) {
3390
- return;
3618
+ function effectiveResponseStatus(value, set) {
3619
+ if (value instanceof ElysiaStatus || value instanceof Response && value.status !== 200) {
3620
+ return value.status;
3621
+ }
3622
+ const status = statusCode(set.status);
3623
+ return value instanceof Error && status === 200 ? 500 : status;
3624
+ }
3625
+ function effectiveResponseHeaders(value, set) {
3626
+ const entries = Object.entries(set.headers);
3627
+ if (value instanceof Response) {
3628
+ entries.push(...value.headers);
3629
+ } else if (value instanceof ElysiaStatus) {
3630
+ entries.push(...Object.entries(value.headers ?? {}));
3391
3631
  }
3392
- return { status: value.status, value: value.response };
3632
+ return Object.fromEntries(entries.map(([name, header]) => [name.toLowerCase(), header]));
3633
+ }
3634
+ function replayableHeaders(entries) {
3635
+ return new Headers(Array.from(entries, ([name, value]) => [name, value]).filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
3393
3636
  }
3394
3637
  function responseHeaders(headers) {
3395
3638
  const result = new Headers;
@@ -3431,32 +3674,7 @@ async function readBoundedResponseBody(response) {
3431
3674
  if (contentLength === undefined || contentLength > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
3432
3675
  return;
3433
3676
  }
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();
3452
- }
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;
3458
- }
3459
- return body;
3677
+ return await readBoundedBytes(response.body, MAX_SYNC_REPLAY_RESPONSE_BYTES);
3460
3678
  }
3461
3679
  function unreplayable() {
3462
3680
  return {
@@ -3469,13 +3687,7 @@ function unreplayable() {
3469
3687
  };
3470
3688
  }
3471
3689
  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);
3690
+ const merged = replayableHeaders(storedResponse.headers);
3479
3691
  for (const [name, value] of Object.entries(headers)) {
3480
3692
  if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
3481
3693
  merged.delete(name);
@@ -3496,8 +3708,8 @@ async function storeResponse(responseValue, set) {
3496
3708
  if (body === undefined) {
3497
3709
  return unreplayable();
3498
3710
  }
3499
- const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
3500
- return storedResponseResult(headers, body, clone.status);
3711
+ const headers = replayableHeaders(clone.headers);
3712
+ return storedResponseResult(headers, body, effectiveResponseStatus(responseValue, set));
3501
3713
  }
3502
3714
  return storeResponseSync(responseValue, set);
3503
3715
  }
@@ -3506,39 +3718,136 @@ function storeResponseSync(responseValue, set) {
3506
3718
  if (responseValue.body !== null) {
3507
3719
  return unreplayable();
3508
3720
  }
3509
- return storedResponseResult(new Headers([...responseValue.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))), new Uint8Array, responseValue.status);
3721
+ return storedResponseResult(replayableHeaders(responseValue.headers), new Uint8Array, effectiveResponseStatus(responseValue, set));
3510
3722
  }
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);
3723
+ const headers = responseHeaders(effectiveResponseHeaders(responseValue, set));
3724
+ const value = responseValue instanceof ElysiaStatus ? responseValue.response : responseValue;
3725
+ const responseStatus = responseValue instanceof ElysiaStatus ? responseValue.status : statusCode(set.status);
3515
3726
  let body;
3516
3727
  if (value === undefined || value === null) {
3517
3728
  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);
3729
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3730
+ const contentType = new Response(String(value)).headers.get("content-type");
3731
+ if (!headers.has("content-type") && contentType !== null) {
3732
+ headers.set("content-type", contentType);
3733
+ }
3734
+ body = new TextEncoder().encode(String(value));
3521
3735
  } else {
3522
- headers.set("content-type", headers.get("content-type") ?? "application/json");
3736
+ headers.set("content-type", headers.get("content-type") ?? "application/json;charset=utf-8");
3523
3737
  body = new TextEncoder().encode(JSON.stringify(value));
3524
3738
  }
3525
3739
  return storedResponseResult(headers, body, responseStatus);
3526
3740
  }
3527
3741
  function replayResponse(stored) {
3528
3742
  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
3743
  return new Response(body, {
3536
- headers: new Headers(headerEntries),
3744
+ headers: replayableHeaders(stored.headers),
3537
3745
  status: stored.status
3538
3746
  });
3539
3747
  }
3540
3748
 
3749
+ // src/server/auto-invalidate/runtime.ts
3750
+ function toRules(input) {
3751
+ return Array.isArray(input) ? input : [input];
3752
+ }
3753
+ function isSuccessfulMutationResponse(ctx) {
3754
+ const status = effectiveResponseStatus(ctx.responseValue ?? ctx.response, ctx.set);
3755
+ return status >= 200 && status < 400;
3756
+ }
3757
+ function appendPendingInvalidationHeader(set) {
3758
+ const pending = consumePendingInvalidations();
3759
+ if (pending.length === 0) {
3760
+ return [];
3761
+ }
3762
+ const headerName = "x-furin-revalidate";
3763
+ const existing = set.headers[headerName];
3764
+ set.headers[headerName] = typeof existing === "string" && existing.length > 0 ? `${existing},${serializeInvalidationPaths(pending)}` : serializeInvalidationPaths(pending);
3765
+ return pending;
3766
+ }
3767
+ async function invalidateTagsForInstance(instance, tagList) {
3768
+ let deleted = false;
3769
+ const purgedPaths = new Set;
3770
+ const logicalPurgedPaths = new Set;
3771
+ const sharedInvalidations = [];
3772
+ const pageCache = getPageCacheAdapter(instance);
3773
+ const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
3774
+ kind: "tags",
3775
+ scope: instance.prefix,
3776
+ tags: tagList
3777
+ });
3778
+ if (sharedResult !== undefined) {
3779
+ deleted = sharedResult.invalidated;
3780
+ }
3781
+ const taggedPaths = new Set([
3782
+ ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
3783
+ ...sharedResult?.paths ?? []
3784
+ ]);
3785
+ const tags = new Set(tagList);
3786
+ for (const path of taggedPaths) {
3787
+ const logicalPath = pathWithoutSearch(path);
3788
+ const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
3789
+ const result = revalidatePathForInstance(instance, logicalPath, "page", false);
3790
+ if (pageCache !== undefined && registered) {
3791
+ sharedInvalidations.push(pageCache.invalidate({
3792
+ kind: "path",
3793
+ scope: instance.prefix,
3794
+ path: logicalPath,
3795
+ type: "page"
3796
+ }));
3797
+ }
3798
+ deleted = result.deleted || deleted;
3799
+ purgedPaths.add(physicalPath(instance.prefix, logicalPath));
3800
+ logicalPurgedPaths.add(logicalPath);
3801
+ for (const purged of result.purgedPaths) {
3802
+ purgedPaths.add(physicalPath(instance.prefix, purged));
3803
+ logicalPurgedPaths.add(purged);
3804
+ }
3805
+ }
3806
+ const pathResults = await Promise.all(sharedInvalidations);
3807
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
3808
+ if (instance.development) {
3809
+ withInstance(instance, () => {
3810
+ const request = currentInstrumentationRequest();
3811
+ const operationId = request === undefined ? null : request.operationId;
3812
+ const requestId = request === undefined ? null : request.requestId;
3813
+ emitCacheInvalidated({
3814
+ deleted,
3815
+ operationId,
3816
+ purgedPaths: logicalPurgedPaths.size,
3817
+ reason: "tag",
3818
+ requestId,
3819
+ target: tagList.join(",")
3820
+ });
3821
+ });
3822
+ }
3823
+ return { deleted, purgedPaths: [...purgedPaths] };
3824
+ }
3825
+ async function revalidateTag(tags) {
3826
+ const tagList = typeof tags === "string" ? [tags] : [...tags];
3827
+ const instances = allInstances();
3828
+ callCacheTagPurger(instances, tagList);
3829
+ const results = await Promise.all(instances.map((instance) => invalidateTagsForInstance(instance, tagList)));
3830
+ callCachePurger2(new Map(instances.map((instance, index) => [instance, results[index]?.purgedPaths ?? []])));
3831
+ return results.some((result) => result.deleted);
3832
+ }
3833
+ async function runInvalidationRules(input) {
3834
+ const operations = toRules(input).flatMap((rule) => {
3835
+ const pending = [];
3836
+ if ("path" in rule && rule.path) {
3837
+ pending.push(revalidatePath(rule.path, rule.type));
3838
+ }
3839
+ if (rule.tags && rule.tags.length > 0) {
3840
+ pending.push(revalidateTag(rule.tags));
3841
+ }
3842
+ return pending;
3843
+ });
3844
+ return (await Promise.all(operations)).some(Boolean);
3845
+ }
3541
3846
  // src/server/sync/atomic.ts
3847
+ init_invalidation_header();
3848
+ import { ElysiaStatus as ElysiaStatus2, Validator } from "elysia";
3849
+ init_context_logger();
3850
+ init_queries();
3542
3851
  var TRAILING_SLASH_PATTERN = /\/$/;
3543
3852
 
3544
3853
  class RejectedMutation {
@@ -3547,18 +3856,6 @@ class RejectedMutation {
3547
3856
  this.value = value;
3548
3857
  }
3549
3858
  }
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
3859
  function withStatus(original, value) {
3563
3860
  return original instanceof ElysiaStatus2 ? new ElysiaStatus2(original.status, value, original.headers) : value;
3564
3861
  }
@@ -3588,7 +3885,7 @@ function validateResult(execution, value) {
3588
3885
  sanitize: app["~config"]?.sanitize,
3589
3886
  schemas: route?.hooks.schemas?.flatMap((schema) => schema.response ? [schema.response] : [])
3590
3887
  });
3591
- const validator = validators?.[responseStatus(context, value)];
3888
+ const validator = validators?.get(effectiveResponseStatus(value, context.set));
3592
3889
  if (!validator) {
3593
3890
  return value;
3594
3891
  }
@@ -3605,11 +3902,11 @@ function validateResult(execution, value) {
3605
3902
  }
3606
3903
  function prepare(execution, value, original) {
3607
3904
  const { context } = execution;
3608
- const status = responseStatus(context, value);
3905
+ const status = effectiveResponseStatus(value, context.set);
3609
3906
  if (status < 200 || status >= 400) {
3610
3907
  throw new RejectedMutation(original);
3611
3908
  }
3612
- const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
3909
+ const invalidate = resolveSyncInvalidations(context);
3613
3910
  execution.resolvedInvalidate = invalidate;
3614
3911
  appendQueryInvalidations(invalidate, context);
3615
3912
  const invalidations = [
@@ -3619,20 +3916,15 @@ function prepare(execution, value, original) {
3619
3916
  if (invalidations.length > 0) {
3620
3917
  context.set.headers["x-furin-sync"] = "1";
3621
3918
  }
3622
- const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => entry.type === "layout" ? `${entry.path}:layout` : entry.path);
3919
+ const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => encodeInvalidationEntry(entry.path, entry.type));
3623
3920
  if (paths.length > 0) {
3624
- context.set.headers["x-furin-revalidate"] = paths.join(",");
3921
+ context.set.headers["x-furin-revalidate"] = serializeInvalidationPaths(paths);
3625
3922
  }
3626
3923
  const finish = (stored) => {
3627
3924
  if (stored.kind === "unreplayable") {
3628
3925
  throw new Error("[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses.");
3629
3926
  }
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
- }
3927
+ const headers = effectiveResponseHeaders(value, context.set);
3636
3928
  return {
3637
3929
  invalidations,
3638
3930
  response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
@@ -3726,9 +4018,22 @@ function normalizedInvalidations(input) {
3726
4018
  return invalidations;
3727
4019
  }
3728
4020
  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" });
4021
+ return entries.map((entry) => ({ kind: "path", ...decodeInvalidationEntry(entry) }));
3730
4022
  }
3731
4023
 
4024
+ // src/server/sync/invalidate-sync.ts
4025
+ init_runtime();
4026
+ async function invalidateSync(sync, target, params) {
4027
+ const runtime = resolveSyncRuntime(sync, IS_DEV);
4028
+ const rule = typeof target === "string" ? { tags: [queryTag({ id: target, scope: params ?? {} })] } : target;
4029
+ await runInvalidationRules(rule);
4030
+ publishCursor(runtime, await runtime.adapter.appendInvalidations(normalizedInvalidations(rule)));
4031
+ }
4032
+ // src/server/sync/plugin.ts
4033
+ import { Elysia as Elysia5, ElysiaStatus as ElysiaStatus3 } from "elysia";
4034
+ init_context_logger();
4035
+ init_instance();
4036
+
3732
4037
  // src/server/sync/execution-error.ts
3733
4038
  class MutationLeaseLost extends Error {
3734
4039
  }
@@ -3816,9 +4121,16 @@ function installMutationHandlers(app) {
3816
4121
  };
3817
4122
  return compileHandler(index, immediate, [method, path, wrapped, owner, hooks, chain, inherited, macroScope], aliases, table);
3818
4123
  };
4124
+ const dispatch = app["~dispatch"].bind(app);
4125
+ app["~dispatch"] = (index, context) => {
4126
+ app.handler(index, false, undefined, undefined, app["~routeTable"]);
4127
+ return dispatch(index, context);
4128
+ };
3819
4129
  }
3820
4130
 
3821
4131
  // src/server/sync/plugin.ts
4132
+ init_principal_journal();
4133
+ init_queries();
3822
4134
  init_runtime();
3823
4135
 
3824
4136
  // src/server/sync/validation.ts
@@ -3836,7 +4148,7 @@ function bindSyncValidation(app) {
3836
4148
  applications.set(createContext2(app), app);
3837
4149
  return fetch;
3838
4150
  });
3839
- app.setup((root) => {
4151
+ app.onStart((root) => {
3840
4152
  applications.set(createContext2(root), root);
3841
4153
  });
3842
4154
  }
@@ -3849,24 +4161,26 @@ function syncValidationApp(context) {
3849
4161
  }
3850
4162
 
3851
4163
  // src/server/sync/plugin.ts
3852
- var routeMetadata = new WeakMap;
4164
+ var nonIdempotent = new WeakSet;
3853
4165
  var activeMutations = new WeakMap;
3854
4166
  var atomicCalls = new WeakSet;
3855
4167
  var atomicResponses = new WeakMap;
4168
+ var syncOwners = new WeakMap;
4169
+ var requestOwners = new WeakMap;
4170
+ var ownerId = 0;
3856
4171
  function hideTransportResponse(hook) {
3857
4172
  return hook;
3858
4173
  }
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";
4174
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
4175
+ var PRINTABLE_ASCII = /^[\x20-\x7e]+$/;
4176
+ function invalidIdempotencyKeyResponse() {
4177
+ return Response.json({
4178
+ code: "FURIN_INVALID_IDEMPOTENCY_KEY",
4179
+ detail: `Idempotency-Key must be 1-${MAX_IDEMPOTENCY_KEY_LENGTH} printable ASCII characters.`,
4180
+ status: 400,
4181
+ title: "Bad Request",
4182
+ type: "about:blank"
4183
+ }, { headers: { "content-type": "application/problem+json" }, status: 400 });
3870
4184
  }
3871
4185
  function getIdempotencyKey(ctx) {
3872
4186
  const fromCtxHeaders = ctx.headers["idempotency-key"];
@@ -3887,8 +4201,15 @@ function leaseLostResponse() {
3887
4201
  message: "The mutation lease was lost before its response could be committed."
3888
4202
  }, { status: 503 });
3889
4203
  }
3890
- function createSyncPlugin(options) {
3891
- const runtime = resolveSyncRuntime(options);
4204
+ function idempotentRouteMacro(_idempotent) {
4205
+ return {
4206
+ transform({ request }) {
4207
+ nonIdempotent.add(request);
4208
+ }
4209
+ };
4210
+ }
4211
+ function createSyncPlugin(options, owner) {
4212
+ const runtime = resolveSyncRuntime(options, IS_DEV);
3892
4213
  const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
3893
4214
  function mutationFor(ctx) {
3894
4215
  const mutation = async (callback) => {
@@ -3906,11 +4227,11 @@ function createSyncPlugin(options) {
3906
4227
  app: syncValidationApp(ctx),
3907
4228
  context: ctx,
3908
4229
  lease: active.lease,
3909
- invalidate: routeMetadata.get(ctx.request)?.invalidate,
3910
4230
  runtime,
3911
4231
  onCommit: (result) => atomicResponses.set(ctx.request, result)
3912
4232
  }, callback);
3913
4233
  } finally {
4234
+ sealInvalidations(ctx.request);
3914
4235
  if (atomicResponses.has(ctx.request)) {
3915
4236
  releaseMutation(ctx.request);
3916
4237
  } else {
@@ -3924,20 +4245,14 @@ function createSyncPlugin(options) {
3924
4245
  return mutation;
3925
4246
  }
3926
4247
  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
- });
4248
+ const idempotencyKey = getIdempotencyKey(ctx) ?? crypto.randomUUID();
4249
+ if (idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH || !PRINTABLE_ASCII.test(idempotencyKey)) {
4250
+ return invalidIdempotencyKeyResponse();
3936
4251
  }
3937
4252
  if (!supportsReplayBody(ctx.request)) {
3938
4253
  return Response.json({
3939
4254
  code: "FURIN_UNSUPPORTED_SYNC_BODY",
3940
- message: "This request body cannot be replayed. Set sync: false on the route."
4255
+ message: "This request body cannot be replayed. Set idempotent: false on the route."
3941
4256
  }, { status: 415 });
3942
4257
  }
3943
4258
  const url = new URL(ctx.request.url);
@@ -3984,32 +4299,27 @@ function createSyncPlugin(options) {
3984
4299
  await runtime.adapter.abortMutation(active.lease);
3985
4300
  }
3986
4301
  }
3987
- async function persistMutation(ctx, active) {
3988
- const result = await storeResponse(ctx.responseValue, ctx.set);
4302
+ async function applyInvalidations(ctx) {
3989
4303
  const manualPending = peekPendingInvalidations();
3990
- const invalidate = resolveSyncInvalidations(routeMetadata.get(ctx.request)?.invalidate, ctx, ctx.responseValue);
4304
+ const invalidate = resolveSyncInvalidations(ctx);
3991
4305
  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";
4306
+ try {
4307
+ await runInvalidationRules(invalidate);
4308
+ } catch {
4309
+ getLogger().warn("Sync cache invalidation failed after mutation; preserving its result");
4003
4310
  }
4004
- const response = mergeStoredResponseHeaders(result.response, ctx.set.headers);
4311
+ appendPendingInvalidationHeader(ctx.set);
4312
+ ctx.set.headers["x-furin-sync"] = "1";
4005
4313
  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
- }
4314
+ return [
4315
+ ...semanticInvalidations,
4316
+ ...pendingPathInvalidations(manualPending).filter((manual) => !semanticInvalidations.some((semantic) => semantic.kind === "path" && semantic.path === manual.path && semantic.type === manual.type))
4317
+ ];
4318
+ }
4319
+ async function persistMutation(ctx, active) {
4320
+ const result = await storeResponse(ctx.responseValue, ctx.set);
4321
+ const invalidations = await applyInvalidations(ctx);
4322
+ const response = mergeStoredResponseHeaders(result.response, result.kind === "unreplayable" ? ctx.set.headers : effectiveResponseHeaders(ctx.responseValue, ctx.set));
4013
4323
  const completion = await runtime.adapter.completeMutation({
4014
4324
  invalidations,
4015
4325
  lease: active.lease,
@@ -4018,16 +4328,24 @@ function createSyncPlugin(options) {
4018
4328
  if (completion.kind === "lost") {
4019
4329
  return leaseLostResponse();
4020
4330
  }
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
- });
4331
+ if (completion.cursor !== undefined) {
4332
+ publishCursor(runtime, completion.cursor);
4026
4333
  }
4027
4334
  if (result.kind === "unreplayable") {
4028
4335
  return replayResponse(response);
4029
4336
  }
4030
4337
  }
4338
+ async function journalMutation(ctx) {
4339
+ if (!(isMutationMethod(ctx.request.method) && isSuccessfulMutationResponse(ctx))) {
4340
+ return;
4341
+ }
4342
+ const invalidations = await applyInvalidations(ctx);
4343
+ try {
4344
+ publishCursor(runtime, await runtime.adapter.appendInvalidations(invalidations));
4345
+ } catch {
4346
+ getLogger().warn("Sync journal append failed after a non-idempotent mutation");
4347
+ }
4348
+ }
4031
4349
  async function finishMutation(ctx) {
4032
4350
  const atomic = atomicResponses.get(ctx.request);
4033
4351
  atomicResponses.delete(ctx.request);
@@ -4064,16 +4382,26 @@ function createSyncPlugin(options) {
4064
4382
  }
4065
4383
  }
4066
4384
  }
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) {
4385
+ owner.mutationFor = mutationFor;
4386
+ const plugin = new Elysia5({ name: `furin-sync:${owner.id}` }).wrap((fetch) => (request, ...rest) => ensureRequestScope(() => fetch(request, ...rest))).derive("global", (ctx) => ({
4387
+ mutation: (requestOwners.get(ctx.request) ?? owner).mutationFor(ctx),
4388
+ invalidate: requestInvalidate(ctx.request)
4389
+ })).onBeforeHandle("global", (context) => {
4390
+ if (requestOwners.get(context.request) === owner && isMutationMethod(context.request.method) && !nonIdempotent.has(context.request)) {
4070
4391
  prepareMutationHandler(context, () => beginMutation(context));
4071
4392
  }
4072
- }).afterHandle("global", finishMutationHook).afterHandle("global", async (ctx) => {
4073
- const read = routeMetadata.get(ctx.request)?.read;
4074
- if (ctx.request.method !== "GET" || !read || !isSuccessfulMutationResponse({
4393
+ }).onAfterHandle("global", hideTransportResponse((context) => {
4394
+ if (requestOwners.get(context.request) !== owner) {
4395
+ return Promise.resolve(undefined);
4396
+ }
4397
+ return nonIdempotent.has(context.request) ? journalMutation(context) : finishMutation(context);
4398
+ })).onAfterHandle("global", async (ctx) => {
4399
+ if (requestOwners.get(ctx.request) !== owner) {
4400
+ return;
4401
+ }
4402
+ if (ctx.request.method !== "GET" || isInternalRead(ctx.request) || ctx.responseValue instanceof Response || !isSuccessfulMutationResponse({
4075
4403
  set: ctx.set,
4076
- responseValue: ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
4404
+ responseValue: ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
4077
4405
  })) {
4078
4406
  return;
4079
4407
  }
@@ -4082,38 +4410,39 @@ function createSyncPlugin(options) {
4082
4410
  throw new Error("[furin] Sync principal must not be empty.");
4083
4411
  }
4084
4412
  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")
4413
+ ...urlIdentity(ctx),
4414
+ session: principalHash(options.adapter, principal)
4088
4415
  };
4089
- queryTag(identity);
4090
4416
  ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
4091
- }).error("global", MutationLeaseLost, hideTransportResponse(() => Promise.resolve(leaseLostResponse()))).error("global", hideTransportResponse(async ({ request }) => {
4417
+ }).onError("global", MutationLeaseLost, hideTransportResponse(({ request }) => Promise.resolve(requestOwners.get(request) === owner ? leaseLostResponse() : undefined))).onError("global", hideTransportResponse(async ({ request }) => {
4418
+ if (requestOwners.get(request) !== owner) {
4419
+ return;
4420
+ }
4092
4421
  atomicResponses.delete(request);
4093
4422
  atomicCalls.delete(request);
4094
4423
  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
- });
4424
+ })).macro({ idempotent: idempotentRouteMacro });
4108
4425
  return plugin;
4109
4426
  }
4110
4427
  function furinSync(options) {
4111
4428
  return (app) => {
4429
+ let owner = syncOwners.get(options);
4430
+ if (!owner) {
4431
+ ownerId += 1;
4432
+ owner = { id: ownerId, mutationFor: () => {
4433
+ return;
4434
+ } };
4435
+ syncOwners.set(options, owner);
4436
+ }
4437
+ const routeOwner = owner;
4438
+ app.onTransform(({ request }) => {
4439
+ requestOwners.set(request, routeOwner);
4440
+ });
4112
4441
  installMutationHandlers(app);
4113
4442
  if ("executeMutation" in options.adapter) {
4114
4443
  bindSyncValidation(app);
4115
4444
  }
4116
- return app.use(createSyncPlugin(options));
4445
+ return app.use(createSyncPlugin(options, owner));
4117
4446
  };
4118
4447
  }
4119
4448
 
@@ -4121,15 +4450,11 @@ function furinSync(options) {
4121
4450
  init_stream();
4122
4451
  var createSyncChangesPlugin2 = createSyncChangesPlugin;
4123
4452
  var furinSync2 = furinSync;
4124
- var getSyncPath2 = getSyncPath;
4453
+ var invalidateSync2 = invalidateSync;
4125
4454
  var PollingSyncNotifier2 = PollingSyncNotifier;
4126
- var resolveSyncPath2 = resolveSyncPath;
4127
- var runWithSyncPath2 = runWithSyncPath;
4128
4455
  export {
4129
4456
  PollingSyncNotifier2 as PollingSyncNotifier,
4130
4457
  createSyncChangesPlugin2 as createSyncChangesPlugin,
4131
4458
  furinSync2 as furinSync,
4132
- getSyncPath2 as getSyncPath,
4133
- resolveSyncPath2 as resolveSyncPath,
4134
- runWithSyncPath2 as runWithSyncPath
4459
+ invalidateSync2 as invalidateSync
4135
4460
  };