@teyik0/furin 0.2.0-alpha.5 → 0.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +1 -1
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/bun-build.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/entry-template.d.ts +6 -0
  7. package/dist/build/entry-template.ts +20 -3
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.d.ts +1 -1
  10. package/dist/build/index.js +9363 -5827
  11. package/dist/build/production-instrumentation.d.ts +1 -0
  12. package/dist/build/route-types.d.ts +3 -23
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +1 -1
  15. package/dist/build/types.d.ts +2 -1
  16. package/dist/cli/index.js +9467 -5870
  17. package/dist/client/boundaries.d.ts +6 -4
  18. package/dist/client/define-route.d.ts +35 -0
  19. package/dist/client/document.d.ts +26 -0
  20. package/dist/client/hmr.d.ts +10 -0
  21. package/dist/client/internal/runtime-types.d.ts +32 -0
  22. package/dist/client/link.d.ts +2 -1
  23. package/dist/client/link.js +1884 -1227
  24. package/dist/client/router/boundary-tree.d.ts +1 -1
  25. package/dist/client/router/index.d.ts +2 -2
  26. package/dist/client/router/link-utils.d.ts +14 -1
  27. package/dist/client/router/search/index.d.ts +3 -7
  28. package/dist/client/router/sync-catch-up.d.ts +4 -4
  29. package/dist/client/router/types.d.ts +34 -26
  30. package/dist/client-only.d.ts +1 -0
  31. package/dist/client-only.js +1 -0
  32. package/dist/client.d.ts +11 -169
  33. package/dist/client.js +197 -36
  34. package/dist/config.d.ts +8 -8
  35. package/dist/config.js +10 -10
  36. package/dist/define-route.d.ts +1355 -0
  37. package/dist/devtools/devtools-element.d.ts +1 -0
  38. package/dist/devtools/protocol.d.ts +119 -0
  39. package/dist/furin.d.ts +24 -39
  40. package/dist/furin.js +14432 -7929
  41. package/dist/isomorphic.d.ts +18 -0
  42. package/dist/plugin/binding-scope.d.ts +2 -0
  43. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  44. package/dist/plugin/index.js +1708 -489
  45. package/dist/plugin/route-config-autofix.d.ts +31 -0
  46. package/dist/plugin/routes.d.ts +27 -0
  47. package/dist/plugin/transform-client.d.ts +0 -2
  48. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  49. package/dist/routes.d.ts +6 -0
  50. package/dist/routes.js +1 -0
  51. package/dist/rsc/build/environment.d.ts +2 -0
  52. package/dist/rsc/build/index.d.ts +15 -0
  53. package/dist/rsc/client-codec.d.ts +1 -0
  54. package/dist/rsc/codec.d.ts +4 -0
  55. package/dist/rsc/flight-drain.d.ts +11 -0
  56. package/dist/rsc/render-error.d.ts +17 -0
  57. package/dist/rsc/server-codec.d.ts +2 -0
  58. package/dist/rsc/server-codec.js +24 -0
  59. package/dist/rsc/shared.d.ts +30 -0
  60. package/dist/rsc/symbols.d.ts +2 -0
  61. package/dist/rsc/transport-benchmark.d.ts +13 -0
  62. package/dist/rsc/version.d.ts +7 -0
  63. package/dist/rsc-client.d.ts +4 -0
  64. package/dist/rsc-client.js +166 -0
  65. package/dist/rsc-server.d.ts +11 -0
  66. package/dist/rsc.d.ts +11 -0
  67. package/dist/rsc.js +353 -0
  68. package/dist/server/cache/index.d.ts +2 -2
  69. package/dist/server/cache/invalidation.d.ts +2 -3
  70. package/dist/server/cache/isr-ssg.d.ts +5 -1
  71. package/dist/server/cache/isr.d.ts +9 -0
  72. package/dist/server/cache/route-cache.d.ts +10 -8
  73. package/dist/server/cache/store-view.d.ts +7 -7
  74. package/dist/server/dev-page-plugin.d.ts +11 -5
  75. package/dist/server/devtools/hub.d.ts +11 -0
  76. package/dist/server/devtools/instrumentation.d.ts +22 -0
  77. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  78. package/dist/server/devtools/plugin.d.ts +3 -0
  79. package/dist/server/devtools/request-context.d.ts +6 -0
  80. package/dist/server/internal.d.ts +5 -0
  81. package/dist/server/internal.js +3 -3
  82. package/dist/server/lang-detect.d.ts +1 -0
  83. package/dist/server/logger.d.ts +4 -0
  84. package/dist/server/render/assemble.d.ts +4 -9
  85. package/dist/server/render/document.d.ts +4 -0
  86. package/dist/server/render/element.d.ts +3 -2
  87. package/dist/server/render/index.d.ts +2 -2
  88. package/dist/server/render/index.ts +6 -3
  89. package/dist/server/render/isr.d.ts +1 -1
  90. package/dist/server/render/loaders.d.ts +9 -1
  91. package/dist/server/render/not-found.d.ts +2 -2
  92. package/dist/server/render/ppr-route.d.ts +8 -0
  93. package/dist/server/render/route-frame-transport.d.ts +2 -0
  94. package/dist/server/render/shell.ts +0 -1
  95. package/dist/server/render/ssg.d.ts +1 -1
  96. package/dist/server/render/ssr.d.ts +9 -9
  97. package/dist/server/render/template.d.ts +4 -0
  98. package/dist/server/router/defined-route.d.ts +24 -0
  99. package/dist/server/router/discovery.d.ts +1 -1
  100. package/dist/server/router/hmr.d.ts +17 -9
  101. package/dist/server/router/patterns.d.ts +7 -1
  102. package/dist/server/router/plugin.d.ts +8 -10
  103. package/dist/server/router/schema-merge.d.ts +3 -0
  104. package/dist/server/router/schemas.d.ts +14 -9
  105. package/dist/server/router/source-version.d.ts +2 -0
  106. package/dist/server/router/types.d.ts +2 -1
  107. package/dist/server/runtime-env.js +2 -2
  108. package/dist/server/sync/adapter.d.ts +45 -26
  109. package/dist/server/sync/config.d.ts +5 -9
  110. package/dist/server/sync/fingerprint.d.ts +2 -1
  111. package/dist/server/sync/index.d.ts +15 -4
  112. package/dist/server/sync/index.js +3023 -0
  113. package/dist/server/sync/notifier.d.ts +18 -0
  114. package/dist/server/sync/plugin.d.ts +53 -54
  115. package/dist/server/sync/postgres/index.d.ts +19 -0
  116. package/dist/server/sync/postgres/index.js +252 -0
  117. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  118. package/dist/server/sync/postgres/migrate.js +17 -0
  119. package/dist/server/sync/postgres/migration.sql +66 -0
  120. package/dist/server/sync/redis/index.d.ts +30 -0
  121. package/dist/server/sync/redis/index.js +336 -0
  122. package/dist/server/sync/redis/scripts.d.ts +4 -0
  123. package/dist/server/sync/response.d.ts +10 -1
  124. package/dist/server/sync/runtime.d.ts +6 -0
  125. package/dist/server/sync/sqlite/index.d.ts +20 -0
  126. package/dist/server/sync/sqlite/index.js +250 -0
  127. package/dist/server/sync/stream.d.ts +12 -11
  128. package/dist/server-only.d.ts +1 -0
  129. package/dist/server-only.js +1 -0
  130. package/dist/shared/await.d.ts +6 -7
  131. package/dist/shared/elysia-contract.d.ts +41 -0
  132. package/dist/shared/parser.d.ts +2 -0
  133. package/dist/shared/route-frame.d.ts +49 -0
  134. package/dist/shared/route-map.d.ts +5 -0
  135. package/dist/shared/utils/index.d.ts +1 -3
  136. package/package.json +86 -41
  137. package/src/adapter/bun.ts +113 -36
  138. package/src/adapter/package.ts +23 -15
  139. package/src/adapter/static.ts +97 -50
  140. package/src/build/bun-build.ts +11 -0
  141. package/src/build/client.ts +41 -26
  142. package/src/build/entry-template.ts +20 -3
  143. package/src/build/hydrate.ts +128 -33
  144. package/src/build/index.ts +14 -2
  145. package/src/build/production-instrumentation.ts +14 -0
  146. package/src/build/route-types.ts +20 -116
  147. package/src/build/scan-server.ts +3 -2
  148. package/src/build/shared.ts +1 -1
  149. package/src/build/ssg-cache.ts +4 -2
  150. package/src/build/types.ts +2 -1
  151. package/src/cli/config.ts +3 -3
  152. package/src/cli/index.ts +58 -27
  153. package/src/client/boundaries.tsx +51 -19
  154. package/src/client/default-screens.tsx +4 -4
  155. package/src/client/define-route.ts +48 -0
  156. package/src/client/document.tsx +165 -0
  157. package/src/client/hmr.ts +40 -0
  158. package/src/client/internal/runtime-types.ts +33 -0
  159. package/src/client/link.tsx +51 -38
  160. package/src/client/router/boundary-tree.tsx +2 -2
  161. package/src/client/router/context.ts +13 -9
  162. package/src/client/router/index.ts +4 -0
  163. package/src/client/router/link-utils.ts +92 -3
  164. package/src/client/router/navigation.ts +9 -15
  165. package/src/client/router/provider.tsx +98 -53
  166. package/src/client/router/search/index.ts +9 -19
  167. package/src/client/router/search-store.ts +5 -1
  168. package/src/client/router/spa-response.ts +3 -4
  169. package/src/client/router/sync-catch-up.ts +9 -8
  170. package/src/client/router/types.ts +52 -26
  171. package/src/client/sync.ts +3 -2
  172. package/src/client-only.ts +1 -0
  173. package/src/client.ts +28 -283
  174. package/src/config.ts +10 -10
  175. package/src/define-route.ts +959 -0
  176. package/src/devtools/devtools-element.js +885 -0
  177. package/src/devtools/protocol.ts +139 -0
  178. package/src/furin.ts +475 -136
  179. package/src/isomorphic.ts +66 -0
  180. package/src/plugin/binding-scope.ts +158 -0
  181. package/src/plugin/dead-code-elimination.ts +202 -0
  182. package/src/plugin/index.ts +14 -18
  183. package/src/plugin/route-config-autofix.ts +1140 -0
  184. package/src/plugin/routes.ts +891 -0
  185. package/src/plugin/transform-client.ts +160 -330
  186. package/src/plugin/transform-isomorphic.ts +464 -0
  187. package/src/routes.ts +6 -0
  188. package/src/rsc/build/environment.ts +30 -0
  189. package/src/rsc/build/index.ts +94 -0
  190. package/src/rsc/client-codec.ts +11 -0
  191. package/src/rsc/codec.ts +85 -0
  192. package/src/rsc/flight-drain.ts +68 -0
  193. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  194. package/src/rsc/render-error.ts +120 -0
  195. package/src/rsc/server-codec.ts +25 -0
  196. package/src/rsc/shared.tsx +113 -0
  197. package/src/rsc/symbols.ts +2 -0
  198. package/src/rsc/transport-benchmark.ts +73 -0
  199. package/src/rsc/version.ts +57 -0
  200. package/src/rsc-client.ts +12 -0
  201. package/src/rsc-server.tsx +91 -0
  202. package/src/rsc.tsx +75 -0
  203. package/src/server/auto-invalidate/registry.ts +2 -2
  204. package/src/server/auto-invalidate/runtime.ts +32 -6
  205. package/src/server/cache/dev-loader.ts +70 -10
  206. package/src/server/cache/index.ts +7 -3
  207. package/src/server/cache/invalidation.ts +33 -15
  208. package/src/server/cache/isr-ssg.ts +12 -3
  209. package/src/server/cache/isr.ts +84 -9
  210. package/src/server/cache/route-cache.ts +49 -36
  211. package/src/server/cache/store-view.ts +7 -7
  212. package/src/server/context-logger.ts +7 -7
  213. package/src/server/dev-page-plugin.ts +38 -17
  214. package/src/server/devtools/hub.ts +64 -0
  215. package/src/server/devtools/instrumentation.production.ts +80 -0
  216. package/src/server/devtools/instrumentation.ts +72 -0
  217. package/src/server/devtools/plugin.ts +269 -0
  218. package/src/server/devtools/request-context.ts +76 -0
  219. package/src/server/instance.ts +4 -4
  220. package/src/server/internal.ts +5 -0
  221. package/src/server/lang-detect.ts +14 -10
  222. package/src/server/logger.ts +21 -0
  223. package/src/server/render/assemble.ts +58 -36
  224. package/src/server/render/document.tsx +25 -0
  225. package/src/server/render/element.tsx +24 -9
  226. package/src/server/render/index.ts +6 -3
  227. package/src/server/render/isr.ts +182 -117
  228. package/src/server/render/loaders.ts +289 -50
  229. package/src/server/render/not-found.ts +57 -38
  230. package/src/server/render/ppr-route.ts +146 -0
  231. package/src/server/render/route-frame-transport.ts +62 -0
  232. package/src/server/render/shell.ts +0 -1
  233. package/src/server/render/ssg.ts +7 -6
  234. package/src/server/render/ssr.ts +412 -166
  235. package/src/server/render/template.ts +93 -2
  236. package/src/server/router/defined-route.ts +110 -0
  237. package/src/server/router/discovery.ts +165 -48
  238. package/src/server/router/hmr.ts +126 -53
  239. package/src/server/router/patterns.ts +56 -27
  240. package/src/server/router/plugin.ts +210 -200
  241. package/src/server/router/schema-merge.ts +42 -0
  242. package/src/server/router/schemas.ts +61 -76
  243. package/src/server/router/source-version.ts +16 -0
  244. package/src/server/router/types.ts +3 -1
  245. package/src/server/sync/adapter.ts +44 -28
  246. package/src/server/sync/config.ts +9 -27
  247. package/src/server/sync/fingerprint.ts +8 -3
  248. package/src/server/sync/index.ts +37 -13
  249. package/src/server/sync/notifier.ts +109 -0
  250. package/src/server/sync/plugin.ts +184 -89
  251. package/src/server/sync/postgres/index.ts +301 -0
  252. package/src/server/sync/postgres/migrate.ts +16 -0
  253. package/src/server/sync/postgres/migration.sql +66 -0
  254. package/src/server/sync/redis/index.ts +342 -0
  255. package/src/server/sync/redis/scripts.ts +74 -0
  256. package/src/server/sync/response.ts +145 -16
  257. package/src/server/sync/runtime.ts +27 -0
  258. package/src/server/sync/sql.d.ts +4 -0
  259. package/src/server/sync/sqlite/index.ts +337 -0
  260. package/src/server/sync/sqlite/migration.sql +70 -0
  261. package/src/server/sync/stream.ts +137 -81
  262. package/src/server-only.ts +1 -0
  263. package/src/shared/await.tsx +10 -11
  264. package/src/shared/deferred-ndjson.ts +34 -6
  265. package/src/shared/digest.ts +2 -2
  266. package/src/shared/elysia-contract.ts +63 -0
  267. package/src/shared/parser.ts +5 -0
  268. package/src/shared/route-frame.ts +429 -0
  269. package/src/shared/route-map.ts +37 -0
  270. package/src/shared/search-params.ts +7 -7
  271. package/src/shared/utils/index.ts +6 -22
  272. package/dist/build/server-routes-entry.d.ts +0 -13
  273. package/dist/build/server-routes-entry.ts +0 -30
  274. package/dist/server/dev-inspector.d.ts +0 -89
  275. package/dist/server/router/index.d.ts +0 -6
  276. package/dist/server/router/index.js +0 -27
  277. package/dist/server/router/index.ts +0 -28
  278. package/dist/server/sync/memory-adapter.d.ts +0 -17
  279. package/src/build/server-routes-entry.ts +0 -30
  280. package/src/server/dev-inspector.ts +0 -60
  281. package/src/server/router/index.ts +0 -28
  282. package/src/server/sync/memory-adapter.ts +0 -196
@@ -0,0 +1,3023 @@
1
+ // @bun
2
+ // src/server/sync/config.ts
3
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4
+
5
+ // src/server/instance.ts
6
+ import { AsyncLocalStorage } from "async_hooks";
7
+ var _requestScope = new AsyncLocalStorage;
8
+ var _instances = new Map;
9
+ var _defaultInstance = null;
10
+ function createInstance(prefix, pagesDir) {
11
+ return {
12
+ buildId: "",
13
+ pagesDir,
14
+ prefix,
15
+ registrationEpoch: 0,
16
+ state: new Map,
17
+ syncStreamPath: undefined
18
+ };
19
+ }
20
+ function defaultInstance() {
21
+ if (!_defaultInstance) {
22
+ _defaultInstance = createInstance("", "");
23
+ }
24
+ return _defaultInstance;
25
+ }
26
+ function currentInstance() {
27
+ const scope = _requestScope.getStore();
28
+ if (scope) {
29
+ return scope.instance;
30
+ }
31
+ if (_instances.size === 1) {
32
+ const only = _instances.values().next().value;
33
+ if (only) {
34
+ return only;
35
+ }
36
+ }
37
+ return defaultInstance();
38
+ }
39
+ function allInstances() {
40
+ if (_instances.size === 0) {
41
+ return [defaultInstance()];
42
+ }
43
+ return [..._instances.values()];
44
+ }
45
+ function requestPendingInvalidations() {
46
+ return _requestScope.getStore()?.pending;
47
+ }
48
+ function runWithInstanceScope(instance, fn) {
49
+ return _requestScope.run({ instance, pending: new Set }, fn);
50
+ }
51
+ function withInstance(instance, fn) {
52
+ return runWithInstanceScope(instance, fn);
53
+ }
54
+ function instanceSlot(init) {
55
+ const key = Symbol("furin-instance-slot");
56
+ return (instance) => {
57
+ const target = instance ?? currentInstance();
58
+ if (target.state.has(key)) {
59
+ return target.state.get(key);
60
+ }
61
+ const value = init(target);
62
+ target.state.set(key, value);
63
+ return value;
64
+ };
65
+ }
66
+
67
+ // src/server/sync/config.ts
68
+ var SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
69
+ var requestSyncStreamPath = new AsyncLocalStorage2;
70
+ function resolveSyncStreamPath(sync) {
71
+ if (!sync) {
72
+ return;
73
+ }
74
+ return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
75
+ }
76
+ function getSyncStreamPath() {
77
+ const override = requestSyncStreamPath.getStore();
78
+ if (override !== undefined) {
79
+ return override;
80
+ }
81
+ return currentInstance().syncStreamPath;
82
+ }
83
+ function runWithSyncStreamPath(path, fn) {
84
+ return requestSyncStreamPath.run(path, fn);
85
+ }
86
+ function syncRuntimeOptions(sync) {
87
+ return { adapter: sync.adapter, notifier: sync.notifier, principal: sync.principal };
88
+ }
89
+
90
+ // src/server/sync/notifier.ts
91
+ class PollingSyncNotifier {
92
+ adapter;
93
+ intervalMs;
94
+ listeners = new Set;
95
+ cursor;
96
+ initialization;
97
+ polling;
98
+ revision = 0;
99
+ timer;
100
+ constructor(adapter, intervalMs) {
101
+ this.adapter = adapter;
102
+ this.intervalMs = intervalMs;
103
+ }
104
+ publish(cursor) {
105
+ this.revision += 1;
106
+ this.emit(cursor);
107
+ return Promise.resolve();
108
+ }
109
+ async subscribe(listener) {
110
+ const subscription = { listener };
111
+ this.listeners.add(subscription);
112
+ try {
113
+ await this.start();
114
+ } catch (error) {
115
+ this.listeners.delete(subscription);
116
+ throw error;
117
+ }
118
+ return {
119
+ unsubscribe: () => {
120
+ this.listeners.delete(subscription);
121
+ if (this.listeners.size === 0 && this.timer) {
122
+ clearTimeout(this.timer);
123
+ this.timer = undefined;
124
+ }
125
+ return Promise.resolve();
126
+ }
127
+ };
128
+ }
129
+ emit(cursor) {
130
+ if (cursor === this.cursor) {
131
+ return;
132
+ }
133
+ this.cursor = cursor;
134
+ for (const subscription of [...this.listeners]) {
135
+ try {
136
+ subscription.listener(cursor);
137
+ } catch {}
138
+ }
139
+ }
140
+ async poll() {
141
+ const { revision } = this;
142
+ try {
143
+ const cursor = await this.adapter.currentCursor();
144
+ if (revision === this.revision && this.listeners.size > 0) {
145
+ this.emit(cursor);
146
+ }
147
+ } catch {}
148
+ }
149
+ async start() {
150
+ if (this.timer || this.polling) {
151
+ return;
152
+ }
153
+ if (!this.initialization) {
154
+ const { revision } = this;
155
+ this.initialization = this.adapter.currentCursor().then((cursor) => {
156
+ if (revision === this.revision) {
157
+ this.cursor = cursor;
158
+ }
159
+ }).finally(() => {
160
+ this.initialization = undefined;
161
+ });
162
+ }
163
+ await this.initialization;
164
+ this.schedulePoll();
165
+ }
166
+ schedulePoll() {
167
+ if (this.listeners.size === 0 || this.timer || this.polling) {
168
+ return;
169
+ }
170
+ this.timer = setTimeout(() => {
171
+ this.timer = undefined;
172
+ this.polling = this.poll().finally(() => {
173
+ this.polling = undefined;
174
+ this.schedulePoll();
175
+ });
176
+ }, this.intervalMs);
177
+ this.timer.unref?.();
178
+ }
179
+ }
180
+
181
+ // src/server/sync/plugin.ts
182
+ import { Elysia } from "elysia";
183
+
184
+ // src/server/context-logger.ts
185
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
186
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/utils.mjs
187
+ function elapsedMs(startTime) {
188
+ return Math.max(0, Date.now() - startTime);
189
+ }
190
+ function formatDuration(ms) {
191
+ if (ms < 1000)
192
+ return `${Math.round(ms)}ms`;
193
+ return `${(ms / 1000).toFixed(2)}s`;
194
+ }
195
+ function isServer() {
196
+ return typeof window === "undefined";
197
+ }
198
+ function isBrowser() {
199
+ if (typeof window === "undefined")
200
+ return false;
201
+ if (typeof document === "undefined")
202
+ return false;
203
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
204
+ return false;
205
+ return true;
206
+ }
207
+ function isDev() {
208
+ if (typeof process !== "undefined")
209
+ return true;
210
+ if (typeof window !== "undefined")
211
+ return true;
212
+ return false;
213
+ }
214
+ function detectEnvironment() {
215
+ const env = typeof process !== "undefined" ? process.env : {};
216
+ const defaultEnvironment = isDev() ? "development" : "production";
217
+ return {
218
+ environment: env.NODE_ENV || defaultEnvironment,
219
+ service: env.SERVICE_NAME || "app",
220
+ version: env.APP_VERSION,
221
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
222
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
223
+ };
224
+ }
225
+ var LEVEL_ORDER = {
226
+ debug: 0,
227
+ info: 1,
228
+ warn: 2,
229
+ error: 3
230
+ };
231
+ function isLevelEnabled(level, minLevel) {
232
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
233
+ }
234
+ function getConsoleMethod(level) {
235
+ return level;
236
+ }
237
+ var colors = {
238
+ reset: "\x1B[0m",
239
+ bold: "\x1B[1m",
240
+ dim: "\x1B[2m",
241
+ red: "\x1B[31m",
242
+ green: "\x1B[32m",
243
+ yellow: "\x1B[33m",
244
+ blue: "\x1B[34m",
245
+ magenta: "\x1B[35m",
246
+ cyan: "\x1B[36m",
247
+ white: "\x1B[37m",
248
+ gray: "\x1B[90m"
249
+ };
250
+ var levelColorMap = {
251
+ error: colors.red,
252
+ warn: colors.yellow,
253
+ info: colors.cyan,
254
+ debug: colors.gray
255
+ };
256
+ function getLevelColor(level) {
257
+ return levelColorMap[level] ?? colors.white;
258
+ }
259
+ var cssColors = {
260
+ dim: "color: #6b7280",
261
+ red: "color: #ef4444; font-weight: bold",
262
+ green: "color: #22c55e",
263
+ yellow: "color: #f59e0b; font-weight: bold",
264
+ cyan: "color: #06b6d4; font-weight: bold",
265
+ gray: "color: #6b7280; font-weight: bold",
266
+ reset: "color: inherit; font-weight: normal"
267
+ };
268
+ var cssLevelColorMap = {
269
+ error: cssColors.red,
270
+ warn: cssColors.yellow,
271
+ info: cssColors.cyan,
272
+ debug: cssColors.gray
273
+ };
274
+ function getCssLevelColor(level) {
275
+ return cssLevelColorMap[level] ?? cssColors.reset;
276
+ }
277
+ function escapeFormatString(str) {
278
+ return str.replace(/%/g, "%%");
279
+ }
280
+ var SENSITIVE_HEADERS = [
281
+ "authorization",
282
+ "cookie",
283
+ "set-cookie",
284
+ "x-api-key",
285
+ "x-auth-token",
286
+ "proxy-authorization"
287
+ ];
288
+ var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
289
+ var patternCache = /* @__PURE__ */ new Map;
290
+ function globToRegExp(pattern, separator = "/") {
291
+ const cacheKey = `${separator}:${pattern}`;
292
+ let regex = patternCache.get(cacheKey);
293
+ if (!regex) {
294
+ const segment = separator === "/" ? "[^/]*" : "[^.]*";
295
+ const char = separator === "/" ? "[^/]" : "[^.]";
296
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
297
+ regex = new RegExp(`^${regexPattern}$`);
298
+ patternCache.set(cacheKey, regex);
299
+ }
300
+ return regex;
301
+ }
302
+ function matchesPattern(path, pattern) {
303
+ return globToRegExp(pattern, "/").test(path);
304
+ }
305
+ var _isoDate = /* @__PURE__ */ new Date;
306
+ var _isoCachedSecond = -1;
307
+ var _isoCachedPrefix = "";
308
+ function isoNow() {
309
+ const now = Date.now();
310
+ const sec = Math.floor(now / 1000);
311
+ if (sec !== _isoCachedSecond) {
312
+ _isoCachedSecond = sec;
313
+ _isoDate.setTime(now);
314
+ _isoCachedPrefix = _isoDate.toISOString().slice(0, 19);
315
+ }
316
+ return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
317
+ }
318
+
319
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/redact-C7FmdhwI.mjs
320
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
321
+ function normalizeRedactPathPattern(pattern) {
322
+ if (!pattern.includes("*") && !pattern.includes("."))
323
+ return `**.${pattern}`;
324
+ return pattern;
325
+ }
326
+ function compileRedactPathMatchers(patterns) {
327
+ if (!patterns?.length)
328
+ return;
329
+ const exactPaths = /* @__PURE__ */ new Set;
330
+ const pathGlobs = [];
331
+ const keyGlobs = [];
332
+ const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
333
+ for (const raw of patterns) {
334
+ if (!raw.includes("*")) {
335
+ if (raw.includes("."))
336
+ exactPaths.add(raw);
337
+ else
338
+ addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
339
+ continue;
340
+ }
341
+ if (!raw.includes("."))
342
+ keyGlobs.push(globToRegExp(raw, "."));
343
+ else
344
+ addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
345
+ }
346
+ if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
347
+ return;
348
+ return {
349
+ exactPaths,
350
+ pathGlobs,
351
+ keyGlobs,
352
+ caseInsensitiveLeaves
353
+ };
354
+ }
355
+ function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
356
+ pathGlobs.push(globToRegExp(pattern, "."));
357
+ const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
358
+ if (leaf) {
359
+ exactPaths.add(leaf[1]);
360
+ caseInsensitiveLeaves.add(leaf[1].toLowerCase());
361
+ }
362
+ }
363
+ function matchesRedactPath(fullPath, leafKey, matchers) {
364
+ if (matchers.exactPaths.has(fullPath))
365
+ return true;
366
+ if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
367
+ return true;
368
+ for (const glob of matchers.pathGlobs) {
369
+ glob.lastIndex = 0;
370
+ if (glob.test(fullPath))
371
+ return true;
372
+ }
373
+ for (const glob of matchers.keyGlobs) {
374
+ glob.lastIndex = 0;
375
+ if (glob.test(leafKey))
376
+ return true;
377
+ }
378
+ return false;
379
+ }
380
+ function resolveReplacement(replacement, matched, ctx) {
381
+ if (typeof replacement === "string")
382
+ return replacement;
383
+ try {
384
+ const result = replacement(matched, ctx);
385
+ if (typeof result !== "string") {
386
+ console.error(`[evlog] redact replacement returned ${typeof result} for "${ctx.path}", expected string \u2014 using ${DEFAULT_REPLACEMENT}`);
387
+ return DEFAULT_REPLACEMENT;
388
+ }
389
+ return result;
390
+ } catch (err) {
391
+ console.error(`[evlog] redact replacement failed for "${ctx.path}":`, err);
392
+ return DEFAULT_REPLACEMENT;
393
+ }
394
+ }
395
+ function redactPathsInTree(obj, matchers, replacement, prefix = "") {
396
+ if (obj === null || obj === undefined)
397
+ return;
398
+ if (Array.isArray(obj)) {
399
+ for (let i = 0;i < obj.length; i++) {
400
+ const segment = String(i);
401
+ const fullPath = prefix ? `${prefix}.${segment}` : segment;
402
+ redactPathsInTree(obj[i], matchers, replacement, fullPath);
403
+ }
404
+ return;
405
+ }
406
+ if (typeof obj === "object") {
407
+ const record = obj;
408
+ for (const key of redactableKeys(record)) {
409
+ const fullPath = prefix ? `${prefix}.${key}` : key;
410
+ if (matchesRedactPath(fullPath, key, matchers))
411
+ setRedacted(record, key, resolveReplacement(replacement, record[key], {
412
+ path: fullPath,
413
+ key
414
+ }), fullPath);
415
+ else
416
+ redactPathsInTree(record[key], matchers, replacement, fullPath);
417
+ }
418
+ }
419
+ }
420
+ function redactableKeys(record) {
421
+ return Object.keys(record);
422
+ }
423
+ function setRedacted(record, key, value, path) {
424
+ if (Reflect.set(record, key, value))
425
+ return;
426
+ const desc = Object.getOwnPropertyDescriptor(record, key);
427
+ if (desc && "value" in desc && desc.configurable) {
428
+ Object.defineProperty(record, key, {
429
+ ...desc,
430
+ value
431
+ });
432
+ return;
433
+ }
434
+ console.warn(`[evlog] redact could not rewrite read-only field "${path}" \u2014 value left as-is`);
435
+ }
436
+ var builtinPatterns = {
437
+ creditCard: {
438
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
439
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
440
+ },
441
+ email: {
442
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
443
+ mask: (m) => {
444
+ if (m.indexOf("@") < 1)
445
+ return "***@***";
446
+ const tld = m.slice(m.lastIndexOf("."));
447
+ return `${m[0]}***@***${tld}`;
448
+ }
449
+ },
450
+ ipv4: {
451
+ 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,
452
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
453
+ },
454
+ phone: {
455
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
456
+ mask: (m) => {
457
+ const digits = m.replace(/[^\d]/g, "");
458
+ if (m.startsWith("+") && digits.length > 4) {
459
+ const ccMatch = m.match(/^\+\d{1,3}/);
460
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
461
+ }
462
+ if (digits.length > 2)
463
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
464
+ return "***";
465
+ }
466
+ },
467
+ jwt: {
468
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
469
+ mask: () => "eyJ***.***"
470
+ },
471
+ bearer: {
472
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
473
+ mask: () => "Bearer ***"
474
+ },
475
+ iban: {
476
+ 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,
477
+ mask: (m) => {
478
+ const clean = m.replace(/[\s-]/g, "");
479
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
480
+ }
481
+ }
482
+ };
483
+ function resolveRedactConfig(input) {
484
+ if (input === undefined || input === false)
485
+ return;
486
+ if (input === true)
487
+ return { _maskers: allBuiltinMaskers() };
488
+ if (input.builtins === false)
489
+ return {
490
+ ...input,
491
+ _pathMatchers: compileRedactPathMatchers(input.paths)
492
+ };
493
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
494
+ return {
495
+ ...input,
496
+ _maskers: maskers,
497
+ _pathMatchers: compileRedactPathMatchers(input.paths)
498
+ };
499
+ }
500
+ function allBuiltinMaskers() {
501
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
502
+ }
503
+ function cloneRegex(re) {
504
+ return new RegExp(re.source, re.flags);
505
+ }
506
+ var globallyRedacted = Symbol.for("evlog.globallyRedacted");
507
+ function markGloballyRedacted(event) {
508
+ Object.defineProperty(event, globallyRedacted, {
509
+ value: true,
510
+ enumerable: false,
511
+ configurable: true
512
+ });
513
+ }
514
+ function cloneForRedaction(event) {
515
+ try {
516
+ return structuredClone(event);
517
+ } catch {
518
+ try {
519
+ return JSON.parse(JSON.stringify(event));
520
+ } catch {
521
+ console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
522
+ return { ...event };
523
+ }
524
+ }
525
+ }
526
+ function redactEvent(event, config) {
527
+ const clone = cloneForRedaction(event);
528
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
529
+ if (config.transform)
530
+ try {
531
+ config.transform(clone);
532
+ } catch (err) {
533
+ console.error("[evlog] redact transform failed:", err);
534
+ }
535
+ const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
536
+ if (pathMatchers)
537
+ redactPathsInTree(clone, pathMatchers, replacement);
538
+ if (config._maskers?.length)
539
+ applyMaskersToTree(clone, config._maskers);
540
+ if (config.patterns?.length)
541
+ redactPatterns(clone, config.patterns, replacement);
542
+ return clone;
543
+ }
544
+ function redactPatterns(obj, patterns, replacement, prefix = "") {
545
+ if (obj === null || obj === undefined)
546
+ return;
547
+ if (Array.isArray(obj)) {
548
+ for (let i = 0;i < obj.length; i++) {
549
+ const key = String(i);
550
+ const fullPath = prefix ? `${prefix}.${key}` : key;
551
+ if (typeof obj[i] === "string")
552
+ obj[i] = applyPatterns(obj[i], patterns, replacement, fullPath, key);
553
+ else if (typeof obj[i] === "object")
554
+ redactPatterns(obj[i], patterns, replacement, fullPath);
555
+ }
556
+ return;
557
+ }
558
+ if (typeof obj === "object") {
559
+ const record = obj;
560
+ for (const key of redactableKeys(record)) {
561
+ const val = record[key];
562
+ const fullPath = prefix ? `${prefix}.${key}` : key;
563
+ if (typeof val === "string")
564
+ setRedacted(record, key, applyPatterns(val, patterns, replacement, fullPath, key), fullPath);
565
+ else if (typeof val === "object")
566
+ redactPatterns(val, patterns, replacement, fullPath);
567
+ }
568
+ }
569
+ }
570
+ function applyPatterns(value, patterns, replacement, path, key) {
571
+ let result = value;
572
+ for (const pattern of patterns) {
573
+ if (typeof replacement === "string") {
574
+ result = result.replace(pattern, replacement);
575
+ continue;
576
+ }
577
+ result = result.replace(pattern, (...args) => {
578
+ const match = args[0];
579
+ return resolveReplacement(replacement, match, {
580
+ path,
581
+ key,
582
+ groups: captureGroups(args)
583
+ });
584
+ });
585
+ }
586
+ return result;
587
+ }
588
+ function captureGroups(args) {
589
+ const last = args.at(-1);
590
+ const trailing = typeof last === "object" && last !== null ? 3 : 2;
591
+ return args.slice(1, Math.max(1, args.length - trailing));
592
+ }
593
+ function applyMaskersToTree(obj, maskers) {
594
+ if (obj === null || obj === undefined)
595
+ return;
596
+ if (Array.isArray(obj)) {
597
+ for (let i = 0;i < obj.length; i++)
598
+ if (typeof obj[i] === "string")
599
+ obj[i] = applyMaskers(obj[i], maskers);
600
+ else if (typeof obj[i] === "object")
601
+ applyMaskersToTree(obj[i], maskers);
602
+ return;
603
+ }
604
+ if (typeof obj === "object") {
605
+ const record = obj;
606
+ for (const key of redactableKeys(record)) {
607
+ const val = record[key];
608
+ if (typeof val === "string")
609
+ setRedacted(record, key, applyMaskers(val, maskers), key);
610
+ else if (typeof val === "object")
611
+ applyMaskersToTree(val, maskers);
612
+ }
613
+ }
614
+ }
615
+ function applyMaskers(value, maskers) {
616
+ let result = value;
617
+ for (const [pattern, mask] of maskers)
618
+ result = result.replace(pattern, mask);
619
+ return result;
620
+ }
621
+
622
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
623
+ function logPluginError(name, hook, err) {
624
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
625
+ }
626
+ function createPluginRunner(plugins = []) {
627
+ const byName = /* @__PURE__ */ new Map;
628
+ for (const plugin of plugins)
629
+ byName.set(plugin.name, plugin);
630
+ const list = Array.from(byName.values());
631
+ return {
632
+ plugins: list,
633
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
634
+ hasDrain: list.some((p) => typeof p.drain === "function"),
635
+ hasKeep: list.some((p) => typeof p.keep === "function"),
636
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
637
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
638
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
639
+ applyExtendLogger(logger) {
640
+ for (const plugin of list) {
641
+ if (!plugin.extendLogger)
642
+ continue;
643
+ try {
644
+ plugin.extendLogger(logger);
645
+ } catch (err) {
646
+ logPluginError(plugin.name, "extendLogger", err);
647
+ }
648
+ }
649
+ },
650
+ runOnRequestStart(ctx) {
651
+ for (const plugin of list) {
652
+ if (!plugin.onRequestStart)
653
+ continue;
654
+ try {
655
+ plugin.onRequestStart(ctx);
656
+ } catch (err) {
657
+ logPluginError(plugin.name, "onRequestStart", err);
658
+ }
659
+ }
660
+ },
661
+ runOnRequestFinish(ctx) {
662
+ for (const plugin of list) {
663
+ if (!plugin.onRequestFinish)
664
+ continue;
665
+ try {
666
+ plugin.onRequestFinish(ctx);
667
+ } catch (err) {
668
+ logPluginError(plugin.name, "onRequestFinish", err);
669
+ }
670
+ }
671
+ },
672
+ async runEnrich(ctx) {
673
+ for (const plugin of list) {
674
+ if (!plugin.enrich)
675
+ continue;
676
+ try {
677
+ await plugin.enrich(ctx);
678
+ } catch (err) {
679
+ logPluginError(plugin.name, "enrich", err);
680
+ }
681
+ }
682
+ },
683
+ async runDrain(ctx) {
684
+ const drains = list.filter((p) => typeof p.drain === "function");
685
+ if (drains.length === 0)
686
+ return;
687
+ await Promise.allSettled(drains.map(async (plugin) => {
688
+ try {
689
+ await plugin.drain(ctx);
690
+ } catch (err) {
691
+ logPluginError(plugin.name, "drain", err);
692
+ }
693
+ }));
694
+ },
695
+ async runKeep(ctx) {
696
+ for (const plugin of list) {
697
+ if (!plugin.keep)
698
+ continue;
699
+ try {
700
+ await plugin.keep(ctx);
701
+ } catch (err) {
702
+ logPluginError(plugin.name, "keep", err);
703
+ }
704
+ }
705
+ },
706
+ runOnClientLog(ctx) {
707
+ for (const plugin of list) {
708
+ if (!plugin.onClientLog)
709
+ continue;
710
+ try {
711
+ plugin.onClientLog(ctx);
712
+ } catch (err) {
713
+ logPluginError(plugin.name, "onClientLog", err);
714
+ }
715
+ }
716
+ },
717
+ async runSetup(ctx) {
718
+ for (const plugin of list) {
719
+ if (!plugin.setup)
720
+ continue;
721
+ try {
722
+ await plugin.setup(ctx);
723
+ } catch (err) {
724
+ logPluginError(plugin.name, "setup", err);
725
+ }
726
+ }
727
+ }
728
+ };
729
+ }
730
+ var emptyRunner = createPluginRunner([]);
731
+ function getEmptyPluginRunner() {
732
+ return emptyRunner;
733
+ }
734
+ var EVLOG_MAJOR = 2;
735
+ var REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
736
+ var MAJORS_KEY = Symbol.for("evlog.majors");
737
+ function createConfig() {
738
+ return {
739
+ env: {
740
+ service: "app",
741
+ environment: "development"
742
+ },
743
+ pretty: isDev(),
744
+ prettyError: {
745
+ snippet: isDev(),
746
+ stackDepth: 2,
747
+ compact: isDev(),
748
+ detail: "full"
749
+ },
750
+ sampling: {},
751
+ stringify: true,
752
+ drain: undefined,
753
+ redact: undefined,
754
+ enabled: true,
755
+ silent: false,
756
+ minLevel: "debug",
757
+ locked: false,
758
+ initialized: false,
759
+ pluginRunner: getEmptyPluginRunner()
760
+ };
761
+ }
762
+ function warnOnMultiMajor(host) {
763
+ const majors = host[MAJORS_KEY] ??= /* @__PURE__ */ new Set;
764
+ if (majors.has(EVLOG_MAJOR))
765
+ return;
766
+ majors.add(EVLOG_MAJOR);
767
+ if (majors.size > 1)
768
+ console.warn(`[evlog] Multiple major versions of evlog are loaded in this process (${[...majors].map((m) => `${m}.x`).join(", ")}). They cannot share request scope or logger configuration: events emitted through the other copy will be undrained and unredacted, and useLogger() may throw. Deduplicate evlog to a single major.`);
769
+ }
770
+ function getRegistry() {
771
+ const host = globalThis;
772
+ warnOnMultiMajor(host);
773
+ return host[REGISTRY_KEY] ??= {
774
+ config: createConfig(),
775
+ storages: /* @__PURE__ */ new Map
776
+ };
777
+ }
778
+ var globalConfig = getRegistry().config;
779
+
780
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/pretty-error-DTIHxnBN.mjs
781
+ var snippetReader = null;
782
+ var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
783
+ function pushTreeSpacer(children) {
784
+ children.push(PRETTY_ERROR_TREE_SPACER);
785
+ }
786
+ var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
787
+ var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
788
+ var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
789
+ function isPlainObject(val) {
790
+ return val !== null && typeof val === "object" && !Array.isArray(val);
791
+ }
792
+ function pickString(obj, key) {
793
+ const val = obj[key];
794
+ return typeof val === "string" && val.length > 0 ? val : undefined;
795
+ }
796
+ function pickNumber(obj, key) {
797
+ const val = obj[key];
798
+ return typeof val === "number" ? val : undefined;
799
+ }
800
+ function extractGuidance(data) {
801
+ return {
802
+ code: pickString(data, "code"),
803
+ why: pickString(data, "why"),
804
+ fix: pickString(data, "fix"),
805
+ link: pickString(data, "link")
806
+ };
807
+ }
808
+ function normalizeErrorContext(error) {
809
+ if (error === null || error === undefined)
810
+ return null;
811
+ if (typeof error === "string")
812
+ return { message: error };
813
+ if (!isPlainObject(error))
814
+ return { message: String(error) };
815
+ const result = {
816
+ message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
817
+ name: pickString(error, "name"),
818
+ code: pickString(error, "code"),
819
+ why: pickString(error, "why"),
820
+ fix: pickString(error, "fix"),
821
+ link: pickString(error, "link"),
822
+ status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
823
+ stack: pickString(error, "stack")
824
+ };
825
+ const { data, cause } = error;
826
+ if (isPlainObject(data)) {
827
+ const guidance = extractGuidance(data);
828
+ if (!result.code)
829
+ result.code = guidance.code;
830
+ if (!result.why)
831
+ result.why = guidance.why;
832
+ if (!result.fix)
833
+ result.fix = guidance.fix;
834
+ if (!result.link)
835
+ result.link = guidance.link;
836
+ }
837
+ if (cause instanceof Error)
838
+ result.cause = cause.message;
839
+ else if (isPlainObject(cause) && pickString(cause, "message"))
840
+ result.cause = pickString(cause, "message");
841
+ return result;
842
+ }
843
+ function decodeFileUrl(file) {
844
+ if (file.startsWith("file://"))
845
+ try {
846
+ return decodeURIComponent(new URL(file).pathname);
847
+ } catch {
848
+ return file.slice(7);
849
+ }
850
+ return file;
851
+ }
852
+ function isAppPath(file) {
853
+ const normalized = decodeFileUrl(file).replace(/\\/g, "/");
854
+ if (normalized.startsWith("node:"))
855
+ return false;
856
+ if (SKIP_PATH_RE.test(normalized))
857
+ return false;
858
+ if (normalized.includes("/node_modules/"))
859
+ return false;
860
+ if (isFrameworkRuntimePath(normalized))
861
+ return false;
862
+ return true;
863
+ }
864
+ function formatDisplayPath(file, cwd) {
865
+ const decoded = decodeFileUrl(file).replace(/\\/g, "/");
866
+ const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
867
+ if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
868
+ const rel = decoded.slice(cwdNorm.length + 1);
869
+ return rel.startsWith("./") ? rel.slice(2) : rel;
870
+ }
871
+ const serverIdx = decoded.indexOf("/server/");
872
+ if (serverIdx >= 0)
873
+ return decoded.slice(serverIdx + 1);
874
+ const srcIdx = decoded.indexOf("/src/");
875
+ if (srcIdx >= 0)
876
+ return decoded.slice(srcIdx + 1);
877
+ return decoded;
878
+ }
879
+ function compactStackForStorage(stack, maxFrames = 5) {
880
+ if (!stack)
881
+ return;
882
+ const head = stack.split(`
883
+ `)[0] ?? "";
884
+ const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
885
+ if (useful.length === 0)
886
+ return stack;
887
+ return [head, ...useful.map((f) => f.raw)].join(`
888
+ `);
889
+ }
890
+ function parseStackFrames(stack) {
891
+ if (!stack)
892
+ return [];
893
+ const lines = stack.split(`
894
+ `);
895
+ const frames = [];
896
+ for (const line of lines) {
897
+ const trimmed = line.trim();
898
+ if (!trimmed.startsWith("at "))
899
+ continue;
900
+ const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
901
+ if (withFn) {
902
+ const [, fn, file, lineStr, colStr] = withFn;
903
+ frames.push({
904
+ raw: trimmed,
905
+ fn,
906
+ file,
907
+ line: Number(lineStr),
908
+ column: Number(colStr),
909
+ isApp: isAppPath(file)
910
+ });
911
+ continue;
912
+ }
913
+ const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
914
+ if (withoutFn) {
915
+ const [, file, lineStr, colStr] = withoutFn;
916
+ frames.push({
917
+ raw: trimmed,
918
+ file,
919
+ line: Number(lineStr),
920
+ column: Number(colStr),
921
+ isApp: isAppPath(file)
922
+ });
923
+ continue;
924
+ }
925
+ const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
926
+ if (asyncFn) {
927
+ const [, fn, file, lineStr, colStr] = asyncFn;
928
+ frames.push({
929
+ raw: trimmed,
930
+ fn: `async ${fn}`,
931
+ file,
932
+ line: Number(lineStr),
933
+ column: Number(colStr),
934
+ isApp: isAppPath(file)
935
+ });
936
+ }
937
+ }
938
+ return frames;
939
+ }
940
+ function isFrameworkRuntimePath(path) {
941
+ const normalized = path.replace(/\\/g, "/");
942
+ return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
943
+ }
944
+ function isFrameworkRuntimeFrame(frame) {
945
+ if (!frame.file)
946
+ return false;
947
+ return isFrameworkRuntimePath(decodeFileUrl(frame.file));
948
+ }
949
+ function isInternalErrorFrame(frame) {
950
+ if (isFrameworkRuntimeFrame(frame))
951
+ return true;
952
+ if (frame.fn) {
953
+ const fn = frame.fn.replace(/^async /, "");
954
+ if (SKIP_FRAME_FN_RE.test(fn))
955
+ return true;
956
+ }
957
+ if (!frame.file)
958
+ return true;
959
+ const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
960
+ if (SKIP_FRAME_PATH_RE.test(path))
961
+ return true;
962
+ if (path.includes(".nuxt/"))
963
+ return true;
964
+ if (path.includes(".next/"))
965
+ return true;
966
+ return false;
967
+ }
968
+ function pickPrimaryFrame(frames) {
969
+ for (const frame of frames)
970
+ if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
971
+ return frame;
972
+ }
973
+ function readCodeSnippet(file, line, contextLines = 2) {
974
+ if (!isDev() || isBrowser() || !snippetReader)
975
+ return null;
976
+ const path = decodeFileUrl(file).replace(/\\/g, "/");
977
+ if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
978
+ return null;
979
+ return snippetReader(file, line, contextLines);
980
+ }
981
+ function formatSnippetLines(snippet) {
982
+ const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
983
+ return snippet.map(({ line, content, isErrorLine }) => {
984
+ const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
985
+ const numColor = isErrorLine ? colors.red : colors.gray;
986
+ const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
987
+ return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
988
+ });
989
+ }
990
+ function formatFrameLocation(frame, cwd) {
991
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
992
+ const loc = frame.line ? `${file}:${frame.line}` : file;
993
+ const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
994
+ return fn ? `at ${fn} (${loc})` : `at ${loc}`;
995
+ }
996
+ function formatCollapsedFrame(frame, cwd) {
997
+ const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
998
+ const loc = frame.line ? `${file}:${frame.line}` : file;
999
+ const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
1000
+ const fn = frame.fn?.replace(/^async /, "");
1001
+ if (fn && fn !== "<unknown>" && fn !== loc)
1002
+ return `${prefix}${fn} (${loc})`;
1003
+ return `${prefix}${loc}`;
1004
+ }
1005
+ var GUIDANCE_WRAP_WIDTH = 76;
1006
+ var GUIDANCE_CONTINUATION = " ";
1007
+ function formatGuidanceLine(label, text, labelColor) {
1008
+ const prefix = `${labelColor}${label}:${colors.reset} `;
1009
+ const lines = [];
1010
+ let remaining = text.trim();
1011
+ let first = true;
1012
+ while (remaining.length > 0) {
1013
+ const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
1014
+ if (remaining.length <= budget) {
1015
+ lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
1016
+ break;
1017
+ }
1018
+ let split = remaining.lastIndexOf(" ", budget);
1019
+ if (split <= 0)
1020
+ split = budget;
1021
+ const chunk = remaining.slice(0, split).trimEnd();
1022
+ lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
1023
+ remaining = remaining.slice(split).trimStart();
1024
+ first = false;
1025
+ }
1026
+ return lines;
1027
+ }
1028
+ function buildErrorEntries(error, options = {}) {
1029
+ const normalized = normalizeErrorContext(error);
1030
+ if (!normalized)
1031
+ return [];
1032
+ const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
1033
+ const compact = options.compact ?? isDev();
1034
+ const guidanceOnly = (options.detail ?? "full") === "guidance";
1035
+ const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
1036
+ const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
1037
+ const snippetContextLines = compact ? 1 : 2;
1038
+ const children = [];
1039
+ const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
1040
+ const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
1041
+ if (!guidanceOnly && primary?.file && primary.line) {
1042
+ pushTreeSpacer(children);
1043
+ if (showFrames) {
1044
+ const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
1045
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1046
+ if (snippet)
1047
+ children.push(...formatSnippetLines(snippet));
1048
+ } else
1049
+ children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
1050
+ }
1051
+ if (normalized.code)
1052
+ children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
1053
+ if (Boolean(normalized.why || normalized.fix || normalized.link))
1054
+ pushTreeSpacer(children);
1055
+ if (normalized.why)
1056
+ children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
1057
+ if (normalized.fix)
1058
+ children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
1059
+ if (normalized.link)
1060
+ children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
1061
+ if (normalized.cause && normalized.cause !== normalized.message)
1062
+ children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
1063
+ const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
1064
+ const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
1065
+ if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
1066
+ pushTreeSpacer(children);
1067
+ if (hiddenCount > 0)
1068
+ children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
1069
+ else
1070
+ children.push(`${colors.gray}stack${colors.reset}`);
1071
+ for (const frame of tailFrames)
1072
+ children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
1073
+ }
1074
+ return [{
1075
+ key: "error",
1076
+ value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
1077
+ children: children.length > 0 ? children : undefined
1078
+ }];
1079
+ }
1080
+
1081
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1082
+ var DEV_PRESETS = {
1083
+ evlog: {
1084
+ frameworkOverlay: false,
1085
+ detail: "full"
1086
+ },
1087
+ nitro: {
1088
+ frameworkOverlay: true,
1089
+ detail: "guidance"
1090
+ },
1091
+ both: {
1092
+ frameworkOverlay: true,
1093
+ detail: "full"
1094
+ }
1095
+ };
1096
+ function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1097
+ const compact = partial.compact ?? (inDev && pretty);
1098
+ const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
1099
+ const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
1100
+ return {
1101
+ snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
1102
+ stackDepth,
1103
+ compact,
1104
+ detail
1105
+ };
1106
+ }
1107
+ function resolveDevTerminal(input = {}) {
1108
+ const pretty = input.pretty ?? isDev();
1109
+ const inDev = isDev();
1110
+ let frameworkOverlay;
1111
+ let prettyError = {};
1112
+ if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
1113
+ const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
1114
+ frameworkOverlay = presetOverlay;
1115
+ prettyError = { detail };
1116
+ } else if (input.dev && typeof input.dev === "object") {
1117
+ const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
1118
+ frameworkOverlay = devOverlay;
1119
+ if (devPrettyError)
1120
+ prettyError = devPrettyError;
1121
+ }
1122
+ if (frameworkOverlay === undefined)
1123
+ frameworkOverlay = !(pretty && inDev);
1124
+ return {
1125
+ frameworkOverlay,
1126
+ prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
1127
+ };
1128
+ }
1129
+
1130
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1131
+ var publisher = null;
1132
+ function publishWideEvent(event) {
1133
+ if (!publisher)
1134
+ return;
1135
+ try {
1136
+ publisher(event);
1137
+ } catch (err) {
1138
+ console.error("[evlog] diagnostics channel publish failed:", err);
1139
+ }
1140
+ }
1141
+
1142
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1143
+ var evlogErrorBrand = Symbol.for("evlog.error.brand");
1144
+ function isEvlogError(error) {
1145
+ return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1146
+ }
1147
+
1148
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/error.mjs
1149
+ var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
1150
+ var evlogErrorDataKey = Symbol.for("evlog.error.data");
1151
+ var EvlogError = class EvlogError extends Error {
1152
+ static isEvlogError(error) {
1153
+ return isEvlogError(error);
1154
+ }
1155
+ code;
1156
+ status;
1157
+ why;
1158
+ fix;
1159
+ link;
1160
+ get internal() {
1161
+ return this[evlogErrorInternalKey];
1162
+ }
1163
+ constructor(options) {
1164
+ const opts = typeof options === "string" ? { message: options } : options;
1165
+ super(opts.message, { cause: opts.cause });
1166
+ this.name = "EvlogError";
1167
+ this.code = opts.code;
1168
+ this.status = opts.status ?? 500;
1169
+ this.why = opts.why;
1170
+ this.fix = opts.fix;
1171
+ this.link = opts.link;
1172
+ if (opts.internal !== undefined)
1173
+ Object.defineProperty(this, evlogErrorInternalKey, {
1174
+ value: opts.internal,
1175
+ enumerable: false,
1176
+ writable: false,
1177
+ configurable: true
1178
+ });
1179
+ if (opts.data !== undefined)
1180
+ Object.defineProperty(this, evlogErrorDataKey, {
1181
+ value: opts.data,
1182
+ enumerable: false,
1183
+ writable: false,
1184
+ configurable: true
1185
+ });
1186
+ if (Error.captureStackTrace)
1187
+ Error.captureStackTrace(this, EvlogError);
1188
+ }
1189
+ get statusText() {
1190
+ return this.message;
1191
+ }
1192
+ get statusCode() {
1193
+ return this.status;
1194
+ }
1195
+ get statusMessage() {
1196
+ return this.message;
1197
+ }
1198
+ get data() {
1199
+ const extra = this[evlogErrorDataKey];
1200
+ if (!extra && !this.code && !this.why && !this.fix && !this.link)
1201
+ return;
1202
+ return {
1203
+ ...extra,
1204
+ ...this.code !== undefined && { code: this.code },
1205
+ ...this.why !== undefined && { why: this.why },
1206
+ ...this.fix !== undefined && { fix: this.fix },
1207
+ ...this.link !== undefined && { link: this.link }
1208
+ };
1209
+ }
1210
+ toString() {
1211
+ const useColors = isServer();
1212
+ const red = useColors ? colors.red : "";
1213
+ const yellow = useColors ? colors.yellow : "";
1214
+ const cyan = useColors ? colors.cyan : "";
1215
+ const dim = useColors ? colors.dim : "";
1216
+ const reset = useColors ? colors.reset : "";
1217
+ const bold = useColors ? colors.bold : "";
1218
+ const lines = [];
1219
+ lines.push(`${red}${bold}Error:${reset} ${this.message}`);
1220
+ if (this.code)
1221
+ lines.push(`${dim}Code:${reset} ${this.code}`);
1222
+ if (this.why)
1223
+ lines.push(`${yellow}Why:${reset} ${this.why}`);
1224
+ if (this.fix)
1225
+ lines.push(`${cyan}Fix:${reset} ${this.fix}`);
1226
+ if (this.link)
1227
+ lines.push(`${dim}More info:${reset} ${this.link}`);
1228
+ if (this.cause)
1229
+ lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
1230
+ return lines.join(`
1231
+ `);
1232
+ }
1233
+ toJSON() {
1234
+ const { data } = this;
1235
+ return {
1236
+ name: this.name,
1237
+ message: this.message,
1238
+ status: this.status,
1239
+ ...data && { data },
1240
+ ...this.cause instanceof Error && { cause: {
1241
+ name: this.cause.name,
1242
+ message: this.cause.message
1243
+ } }
1244
+ };
1245
+ }
1246
+ };
1247
+ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
1248
+ value: true,
1249
+ enumerable: false
1250
+ });
1251
+
1252
+ // ../../node_modules/.bun/evlog@2.28.1+4cac44d0f5802a4d/node_modules/evlog/dist/audit-CW8wdQDm.mjs
1253
+ var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
1254
+ function writePrettyStdout(text) {
1255
+ (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1256
+ }
1257
+ function isPlainObject$1(val) {
1258
+ return val !== null && typeof val === "object" && !Array.isArray(val);
1259
+ }
1260
+ var 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).";
1261
+ function warnPostEmit(method, detail) {
1262
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
1263
+ }
1264
+ function mergeInto(target, source) {
1265
+ for (const key in source) {
1266
+ const sourceVal = source[key];
1267
+ if (sourceVal === undefined || sourceVal === null)
1268
+ continue;
1269
+ const targetVal = target[key];
1270
+ if (sourceVal === targetVal)
1271
+ continue;
1272
+ if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
1273
+ mergeInto(targetVal, sourceVal);
1274
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
1275
+ target[key] = [...targetVal, ...sourceVal];
1276
+ else
1277
+ Reflect.set(target, key, sourceVal);
1278
+ }
1279
+ }
1280
+ var pendingDrainState = /* @__PURE__ */ new WeakMap;
1281
+ function isAiOnlyFieldUpdate(data) {
1282
+ const keys = Object.keys(data);
1283
+ return keys.length === 1 && keys[0] === "ai";
1284
+ }
1285
+ var state = globalConfig;
1286
+ function initLogger(config = {}) {
1287
+ state.enabled = config.enabled ?? true;
1288
+ const detected = detectEnvironment();
1289
+ state.env = {
1290
+ service: config.env?.service ?? detected.service ?? "app",
1291
+ environment: config.env?.environment ?? detected.environment ?? "development",
1292
+ version: config.env?.version ?? detected.version,
1293
+ commitHash: config.env?.commitHash ?? detected.commitHash,
1294
+ region: config.env?.region ?? detected.region
1295
+ };
1296
+ state.pretty = config.pretty ?? isDev();
1297
+ state.prettyError = resolveDevTerminal(config).prettyError;
1298
+ state.sampling = config.sampling ?? {};
1299
+ state.stringify = config.stringify ?? true;
1300
+ state.drain = config.drain;
1301
+ state.redact = resolveRedactConfig(config.redact ?? !isDev());
1302
+ state.silent = config.silent ?? false;
1303
+ state.minLevel = config.minLevel ?? "debug";
1304
+ state.pluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1305
+ if (state.pluginRunner.plugins.length > 0)
1306
+ state.pluginRunner.runSetup({ env: { ...state.env } });
1307
+ const hasAnyDrain = !!state.drain || state.pluginRunner.hasDrain;
1308
+ if (state.silent && !hasAnyDrain && !config._suppressDrainWarning)
1309
+ console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
1310
+ state.initialized = true;
1311
+ }
1312
+ function shouldSample(level) {
1313
+ const { rates } = state.sampling;
1314
+ if (!rates)
1315
+ return true;
1316
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
1317
+ if (percentage <= 0)
1318
+ return false;
1319
+ if (percentage >= 100)
1320
+ return true;
1321
+ return Math.random() * 100 < percentage;
1322
+ }
1323
+ function shouldKeep(ctx) {
1324
+ const { keep } = state.sampling;
1325
+ if (!keep?.length)
1326
+ return false;
1327
+ return keep.some((condition) => {
1328
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
1329
+ return true;
1330
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
1331
+ return true;
1332
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
1333
+ return true;
1334
+ return false;
1335
+ });
1336
+ }
1337
+ function emitWideEvent(level, event, options = {}) {
1338
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
1339
+ if (!state.enabled)
1340
+ return null;
1341
+ if (!ownsEvent) {
1342
+ if (!isLevelEnabled(level, state.minLevel))
1343
+ return null;
1344
+ if (!shouldSample(level))
1345
+ return null;
1346
+ }
1347
+ let formatted;
1348
+ if (ownsEvent) {
1349
+ event.timestamp = isoNow();
1350
+ event.level = level;
1351
+ if (event.service === undefined)
1352
+ event.service = state.env.service;
1353
+ if (event.environment === undefined)
1354
+ event.environment = state.env.environment;
1355
+ if (state.env.version !== undefined && event.version === undefined)
1356
+ event.version = state.env.version;
1357
+ if (state.env.commitHash !== undefined && event.commitHash === undefined)
1358
+ event.commitHash = state.env.commitHash;
1359
+ if (state.env.region !== undefined && event.region === undefined)
1360
+ event.region = state.env.region;
1361
+ formatted = event;
1362
+ } else
1363
+ formatted = {
1364
+ timestamp: isoNow(),
1365
+ level,
1366
+ ...state.env,
1367
+ ...event
1368
+ };
1369
+ finalizeAudit(formatted);
1370
+ if (state.redact) {
1371
+ formatted = redactEvent(formatted, state.redact);
1372
+ markGloballyRedacted(formatted);
1373
+ }
1374
+ if (!state.silent)
1375
+ if (state.pretty)
1376
+ prettyPrintWideEvent(formatted);
1377
+ else if (state.stringify)
1378
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
1379
+ else
1380
+ console[getConsoleMethod(level)](formatted);
1381
+ if (!deferDrain) {
1382
+ publishWideEvent(formatted);
1383
+ const drainPromises = [];
1384
+ if (state.drain)
1385
+ drainPromises.push((async () => {
1386
+ try {
1387
+ await state.drain({ event: formatted });
1388
+ } catch (err) {
1389
+ console.error("[evlog] drain failed:", err);
1390
+ }
1391
+ })());
1392
+ if (state.pluginRunner.hasDrain)
1393
+ drainPromises.push(state.pluginRunner.runDrain({ event: formatted }));
1394
+ if (drainPromises.length > 0 && waitUntil)
1395
+ waitUntil(Promise.all(drainPromises));
1396
+ }
1397
+ return formatted;
1398
+ }
1399
+ function emitTaggedLog(level, tag, message) {
1400
+ if (!state.enabled)
1401
+ return;
1402
+ if (state.pretty && !state.silent) {
1403
+ if (!isLevelEnabled(level, state.minLevel))
1404
+ return;
1405
+ if (!shouldSample(level))
1406
+ return;
1407
+ if (isBrowser()) {
1408
+ const levelColor = getCssLevelColor(level);
1409
+ const timestamp = isoNow().slice(11, 23);
1410
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
1411
+ } else {
1412
+ const color = getLevelColor(level);
1413
+ const timestamp = isoNow().slice(11, 23);
1414
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
1415
+ }
1416
+ return;
1417
+ }
1418
+ emitWideEvent(level, {
1419
+ tag,
1420
+ message
1421
+ });
1422
+ }
1423
+ function formatValue(value) {
1424
+ if (value === null || value === undefined)
1425
+ return String(value);
1426
+ if (Array.isArray(value))
1427
+ return JSON.stringify(value);
1428
+ if (isPlainObject$1(value)) {
1429
+ const pairs = [];
1430
+ for (const [k, v] of Object.entries(value))
1431
+ if (v !== undefined && v !== null)
1432
+ if (typeof v === "object")
1433
+ pairs.push(`${k}=${JSON.stringify(v)}`);
1434
+ else
1435
+ pairs.push(`${k}=${v}`);
1436
+ return pairs.join(" ");
1437
+ }
1438
+ return String(value);
1439
+ }
1440
+ function formatCost(cost) {
1441
+ if (cost < 0.01)
1442
+ return `$${cost.toFixed(6)}`;
1443
+ if (cost < 1)
1444
+ return `$${cost.toFixed(4)}`;
1445
+ return `$${cost.toFixed(2)}`;
1446
+ }
1447
+ function asNumber(value) {
1448
+ return typeof value === "number" ? value : undefined;
1449
+ }
1450
+ function asStringArray(value) {
1451
+ if (!Array.isArray(value))
1452
+ return;
1453
+ return value.every((item) => typeof item === "string") ? value : undefined;
1454
+ }
1455
+ function isToolUsageEntry(value) {
1456
+ return isPlainObject$1(value) && typeof value.name === "string" && typeof value.durationMs === "number" && typeof value.success === "boolean";
1457
+ }
1458
+ function asToolUsageArray(value) {
1459
+ if (!Array.isArray(value))
1460
+ return;
1461
+ return value.every(isToolUsageEntry) ? value : undefined;
1462
+ }
1463
+ function serializeToolInput(input) {
1464
+ if (typeof input === "string")
1465
+ return input;
1466
+ const seen = /* @__PURE__ */ new WeakSet;
1467
+ try {
1468
+ return JSON.stringify(input, (_key, value) => {
1469
+ if (typeof value === "bigint")
1470
+ return value.toString();
1471
+ if (typeof value === "object" && value !== null) {
1472
+ if (seen.has(value))
1473
+ return "[Circular]";
1474
+ seen.add(value);
1475
+ }
1476
+ return value;
1477
+ }) ?? "";
1478
+ } catch {
1479
+ return "[unserializable tool input]";
1480
+ }
1481
+ }
1482
+ function isToolCallEntry(value) {
1483
+ return isPlainObject$1(value) && typeof value.name === "string" && "input" in value;
1484
+ }
1485
+ function asToolCallArray(value) {
1486
+ if (!Array.isArray(value))
1487
+ return;
1488
+ return value.every(isToolCallEntry) ? value : undefined;
1489
+ }
1490
+ function buildAIEntries(ai) {
1491
+ const entries = [];
1492
+ const headerParts = [];
1493
+ if (ai.model) {
1494
+ let m = String(ai.model);
1495
+ if (ai.provider)
1496
+ m += ` (${ai.provider})`;
1497
+ headerParts.push(m);
1498
+ }
1499
+ if (ai.calls) {
1500
+ const calls = asNumber(ai.calls);
1501
+ if (calls !== undefined)
1502
+ headerParts.push(`${calls} call${calls > 1 ? "s" : ""}`);
1503
+ }
1504
+ const steps = asNumber(ai.steps);
1505
+ if (steps !== undefined && steps > 1)
1506
+ headerParts.push(`${steps} steps`);
1507
+ entries.push({
1508
+ key: "ai",
1509
+ value: headerParts.join(" \xB7 ")
1510
+ });
1511
+ const inputTokens = asNumber(ai.inputTokens);
1512
+ const outputTokens = asNumber(ai.outputTokens);
1513
+ const totalTokens = asNumber(ai.totalTokens);
1514
+ if (inputTokens !== undefined && outputTokens !== undefined) {
1515
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
1516
+ if (totalTokens)
1517
+ tokLine += ` (${totalTokens} total)`;
1518
+ const extras = [];
1519
+ if (ai.cacheReadTokens)
1520
+ extras.push(`${ai.cacheReadTokens} cache read`);
1521
+ if (ai.cacheWriteTokens)
1522
+ extras.push(`${ai.cacheWriteTokens} cache write`);
1523
+ if (ai.reasoningTokens)
1524
+ extras.push(`${ai.reasoningTokens} reasoning`);
1525
+ if (extras.length)
1526
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
1527
+ entries.push({
1528
+ key: "ai.tokens",
1529
+ value: tokLine
1530
+ });
1531
+ }
1532
+ const msFirst = asNumber(ai.msToFirstChunk);
1533
+ const msFinish = asNumber(ai.msToFinish);
1534
+ const tps = asNumber(ai.tokensPerSecond);
1535
+ if (msFirst !== undefined || msFinish !== undefined) {
1536
+ const parts = [];
1537
+ if (msFirst !== undefined)
1538
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
1539
+ if (msFinish !== undefined)
1540
+ parts.push(`${formatDuration(msFinish)} total`);
1541
+ let streamLine = parts.join(" \u2192 ");
1542
+ if (tps)
1543
+ streamLine += ` \xB7 ${tps} tok/s`;
1544
+ entries.push({
1545
+ key: "ai.streaming",
1546
+ value: streamLine
1547
+ });
1548
+ }
1549
+ const estimatedCost = asNumber(ai.estimatedCost);
1550
+ if (estimatedCost !== undefined)
1551
+ entries.push({
1552
+ key: "ai.cost",
1553
+ value: formatCost(estimatedCost)
1554
+ });
1555
+ const totalDurationMs = asNumber(ai.totalDurationMs);
1556
+ if (totalDurationMs !== undefined)
1557
+ entries.push({
1558
+ key: "ai.totalDuration",
1559
+ value: formatDuration(totalDurationMs)
1560
+ });
1561
+ const toolCalls = Array.isArray(ai.toolCalls) ? ai.toolCalls : undefined;
1562
+ const tools = asToolUsageArray(ai.tools);
1563
+ const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
1564
+ const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
1565
+ if (tools?.length) {
1566
+ const children = tools.map((t, idx) => {
1567
+ const mark = t.success ? "\u2713" : "\u2717";
1568
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
1569
+ if (t.error)
1570
+ line += ` ${t.error}`;
1571
+ if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
1572
+ const tc = toolCallEntries[idx];
1573
+ const inputStr = serializeToolInput(tc.input);
1574
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1575
+ line += ` ${truncated}`;
1576
+ }
1577
+ return line;
1578
+ });
1579
+ entries.push({
1580
+ key: "ai.tools",
1581
+ value: "",
1582
+ children
1583
+ });
1584
+ } else if (toolCalls?.length)
1585
+ if (toolCallEntries?.length) {
1586
+ const children = toolCallEntries.map((tc) => {
1587
+ const inputStr = serializeToolInput(tc.input);
1588
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
1589
+ return `${tc.name}(${truncated})`;
1590
+ });
1591
+ entries.push({
1592
+ key: "ai.tools",
1593
+ value: "",
1594
+ children
1595
+ });
1596
+ } else {
1597
+ const names = asStringArray(toolCalls);
1598
+ if (names?.length)
1599
+ entries.push({
1600
+ key: "ai.tools",
1601
+ value: names.join(", ")
1602
+ });
1603
+ }
1604
+ const stepsUsage = Array.isArray(ai.stepsUsage) ? ai.stepsUsage.filter(isPlainObject$1) : undefined;
1605
+ if (stepsUsage?.length) {
1606
+ const firstModel = stepsUsage[0]?.model;
1607
+ const allSameModel = firstModel !== undefined && stepsUsage.every((s) => s.model === firstModel);
1608
+ const children = stepsUsage.map((s) => {
1609
+ let line = `${allSameModel ? "" : `${String(s.model)} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
1610
+ const stepTools = asStringArray(s.toolCalls);
1611
+ if (stepTools?.length)
1612
+ line += ` [${stepTools.join(", ")}]`;
1613
+ return line;
1614
+ });
1615
+ entries.push({
1616
+ key: "ai.steps",
1617
+ value: "",
1618
+ children
1619
+ });
1620
+ } else if (steps !== undefined && steps > 1)
1621
+ entries.push({
1622
+ key: "ai.steps",
1623
+ value: String(steps)
1624
+ });
1625
+ const embedding = isPlainObject$1(ai.embedding) ? ai.embedding : undefined;
1626
+ if (embedding) {
1627
+ const parts = [];
1628
+ if (embedding.model)
1629
+ parts.push(String(embedding.model));
1630
+ parts.push(`${embedding.tokens} tokens`);
1631
+ if (embedding.dimensions)
1632
+ parts.push(`${embedding.dimensions}d`);
1633
+ if (embedding.count)
1634
+ parts.push(`${embedding.count} items`);
1635
+ entries.push({
1636
+ key: "ai.embedding",
1637
+ value: parts.join(" \xB7 ")
1638
+ });
1639
+ }
1640
+ if (ai.finishReason)
1641
+ entries.push({
1642
+ key: "ai.finishReason",
1643
+ value: String(ai.finishReason)
1644
+ });
1645
+ if (ai.error)
1646
+ entries.push({
1647
+ key: "ai.error",
1648
+ value: String(ai.error)
1649
+ });
1650
+ if (ai.responseId)
1651
+ entries.push({
1652
+ key: "ai.responseId",
1653
+ value: String(ai.responseId)
1654
+ });
1655
+ return entries;
1656
+ }
1657
+ function flushPrettyLines(lines) {
1658
+ if (lines.length === 0)
1659
+ return;
1660
+ const text = `${lines.join(`
1661
+ `)}
1662
+ `;
1663
+ if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
1664
+ writePrettyStdout(text);
1665
+ return;
1666
+ }
1667
+ console.log(lines.join(`
1668
+ `));
1669
+ }
1670
+ function prettyPrintWideEvent(event) {
1671
+ const { timestamp, level, service, environment, version, ...rest } = event;
1672
+ const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
1673
+ const levelLabel = typeof level === "string" ? level : "info";
1674
+ const browser = isBrowser();
1675
+ const lines = [];
1676
+ const writeLine = (...args) => {
1677
+ if (browser) {
1678
+ console.log(...args);
1679
+ return;
1680
+ }
1681
+ const [line] = args;
1682
+ if (typeof line === "string")
1683
+ lines.push(line);
1684
+ };
1685
+ const parts = [];
1686
+ const styles = [];
1687
+ if (browser) {
1688
+ const lc = getCssLevelColor(levelLabel);
1689
+ parts.push(`%c${ts}%c %c${levelLabel.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
1690
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
1691
+ } else {
1692
+ const lc = getLevelColor(levelLabel);
1693
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
1694
+ }
1695
+ if (rest.method && rest.path) {
1696
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
1697
+ delete rest.method;
1698
+ delete rest.path;
1699
+ }
1700
+ if (rest.status) {
1701
+ const statusCode = asNumber(rest.status) ?? Number(rest.status);
1702
+ const sc = browser ? statusCode >= 400 ? cssColors.red : cssColors.green : statusCode >= 400 ? colors.red : colors.green;
1703
+ if (browser) {
1704
+ parts.push(` %c${rest.status}%c`);
1705
+ styles.push(sc, cssColors.reset);
1706
+ } else
1707
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
1708
+ delete rest.status;
1709
+ }
1710
+ if (rest.duration) {
1711
+ if (browser) {
1712
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
1713
+ styles.push(cssColors.dim, cssColors.reset);
1714
+ } else
1715
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
1716
+ delete rest.duration;
1717
+ }
1718
+ delete rest.durationMs;
1719
+ writeLine(parts.join(""), ...styles);
1720
+ const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
1721
+ if (aiData)
1722
+ delete rest.ai;
1723
+ const errorData = rest.error;
1724
+ if (errorData !== undefined)
1725
+ delete rest.error;
1726
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
1727
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
1728
+ const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, state.prettyError) : [];
1729
+ const contextEntries = [...restEntries.map(([key, value]) => ({
1730
+ key,
1731
+ value: formatValue(value)
1732
+ })), ...aiEntries];
1733
+ const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
1734
+ for (let i = 0;i < allEntries.length; i++) {
1735
+ const entry = allEntries[i];
1736
+ if (!entry)
1737
+ continue;
1738
+ const { children } = entry;
1739
+ const hasChildren = children !== undefined && children.length > 0;
1740
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
1741
+ if (browser) {
1742
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
1743
+ writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
1744
+ } else {
1745
+ const val = entry.value ? ` ${entry.value}` : "";
1746
+ writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
1747
+ }
1748
+ if (hasChildren && children) {
1749
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
1750
+ for (let j = 0;j < children.length; j++) {
1751
+ const child = children[j];
1752
+ if (child === undefined)
1753
+ continue;
1754
+ if (child === "__EVLOG_TREE_SPACER__") {
1755
+ writeLine(` ${colors.dim}${connector}${colors.reset}`);
1756
+ continue;
1757
+ }
1758
+ const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
1759
+ if (child === "") {
1760
+ writeLine("");
1761
+ continue;
1762
+ }
1763
+ if (browser)
1764
+ writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
1765
+ else if (child.startsWith(" ") || child.startsWith("\x1B"))
1766
+ writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
1767
+ else
1768
+ writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
1769
+ }
1770
+ }
1771
+ }
1772
+ if (!browser && lines.length > 0)
1773
+ flushPrettyLines(lines);
1774
+ }
1775
+ function createLogMethod(level) {
1776
+ return function logMethod(tagOrEvent, message) {
1777
+ if (typeof tagOrEvent === "string" && message !== undefined)
1778
+ emitTaggedLog(level, tagOrEvent, message);
1779
+ else if (typeof tagOrEvent === "object")
1780
+ emitWideEvent(level, tagOrEvent);
1781
+ else
1782
+ emitTaggedLog(level, "log", String(tagOrEvent));
1783
+ };
1784
+ }
1785
+ var _log = {
1786
+ info: createLogMethod("info"),
1787
+ error: createLogMethod("error"),
1788
+ warn: createLogMethod("warn"),
1789
+ debug: createLogMethod("debug")
1790
+ };
1791
+ var noopLogger = {
1792
+ set() {},
1793
+ setLevel() {},
1794
+ error() {},
1795
+ info() {},
1796
+ warn() {},
1797
+ emit() {
1798
+ return null;
1799
+ },
1800
+ getContext() {
1801
+ return {};
1802
+ },
1803
+ audit: Object.assign(() => {}, { deny: () => {} })
1804
+ };
1805
+ function createLogger(initialContext = {}, internalOptions) {
1806
+ if (!state.enabled)
1807
+ return noopLogger;
1808
+ const deferDrain = internalOptions?._deferDrain ?? false;
1809
+ const waitUntil = internalOptions?.waitUntil;
1810
+ const startTime = Date.now();
1811
+ const context = { ...initialContext };
1812
+ let hasError = false;
1813
+ let hasWarn = false;
1814
+ let manualLevel;
1815
+ let emitted = false;
1816
+ let pendingWideEvent = null;
1817
+ function addLog(level, message) {
1818
+ if (!Array.isArray(context.requestLogs))
1819
+ context.requestLogs = [];
1820
+ context.requestLogs.push({
1821
+ level,
1822
+ message,
1823
+ timestamp: isoNow()
1824
+ });
1825
+ }
1826
+ const auditMethod = function audit(input) {
1827
+ if (emitted) {
1828
+ warnPostEmit("log.audit()", `Audit dropped: action=${input.action}.`);
1829
+ return;
1830
+ }
1831
+ const fields = buildAuditFields(input);
1832
+ if (!isPlainObject$1(context.audit))
1833
+ context.audit = fields;
1834
+ else
1835
+ mergeInto(context.audit, fields);
1836
+ context._auditForceKeep = true;
1837
+ };
1838
+ auditMethod.deny = function deny(reason, input) {
1839
+ auditMethod({
1840
+ ...input,
1841
+ outcome: "denied",
1842
+ reason
1843
+ });
1844
+ };
1845
+ return {
1846
+ audit: auditMethod,
1847
+ set(data) {
1848
+ if (emitted) {
1849
+ const record = data;
1850
+ const pendingState = pendingWideEvent ? pendingDrainState.get(pendingWideEvent) : undefined;
1851
+ if (pendingWideEvent && pendingState && !pendingState.drainStarted && isAiOnlyFieldUpdate(record)) {
1852
+ mergeInto(pendingWideEvent, record);
1853
+ return;
1854
+ }
1855
+ const keys = Object.keys(record);
1856
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
1857
+ return;
1858
+ }
1859
+ mergeInto(context, data);
1860
+ },
1861
+ setLevel(level) {
1862
+ if (emitted) {
1863
+ warnPostEmit("log.setLevel()", `Level dropped: ${level}.`);
1864
+ return;
1865
+ }
1866
+ manualLevel = level;
1867
+ },
1868
+ error(error, errorContext) {
1869
+ if (emitted) {
1870
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
1871
+ return;
1872
+ }
1873
+ hasError = true;
1874
+ const err = typeof error === "string" ? new Error(error) : error;
1875
+ if (errorContext)
1876
+ mergeInto(context, errorContext);
1877
+ const errorObj = {
1878
+ name: err.name,
1879
+ message: err.message,
1880
+ stack: isDev() ? compactStackForStorage(err.stack) : err.stack
1881
+ };
1882
+ const errRecord = err;
1883
+ for (const k of [
1884
+ "code",
1885
+ "status",
1886
+ "statusText",
1887
+ "statusCode",
1888
+ "statusMessage",
1889
+ "data",
1890
+ "cause",
1891
+ "internal"
1892
+ ])
1893
+ if (k in err)
1894
+ errorObj[k] = errRecord[k];
1895
+ if (EvlogError.isEvlogError(err)) {
1896
+ if (err.code)
1897
+ errorObj.code = err.code;
1898
+ if (err.why)
1899
+ errorObj.why = err.why;
1900
+ if (err.fix)
1901
+ errorObj.fix = err.fix;
1902
+ if (err.link)
1903
+ errorObj.link = err.link;
1904
+ if (err.status)
1905
+ errorObj.status = err.status;
1906
+ }
1907
+ if (isPlainObject$1(context.error))
1908
+ mergeInto(context.error, errorObj);
1909
+ else
1910
+ context.error = errorObj;
1911
+ },
1912
+ info(message, infoContext) {
1913
+ if (emitted) {
1914
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
1915
+ return;
1916
+ }
1917
+ addLog("info", message);
1918
+ if (infoContext) {
1919
+ const { requestLogs: _, ...rest } = infoContext;
1920
+ mergeInto(context, rest);
1921
+ }
1922
+ },
1923
+ warn(message, warnContext) {
1924
+ if (emitted) {
1925
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
1926
+ return;
1927
+ }
1928
+ hasWarn = true;
1929
+ addLog("warn", message);
1930
+ if (warnContext) {
1931
+ const { requestLogs: _, ...rest } = warnContext;
1932
+ mergeInto(context, rest);
1933
+ }
1934
+ },
1935
+ emit(overrides) {
1936
+ if (emitted) {
1937
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
1938
+ return null;
1939
+ }
1940
+ const durationMs = elapsedMs(startTime);
1941
+ const level = manualLevel ?? (hasError ? "error" : hasWarn ? "warn" : "info");
1942
+ let forceKeep = false;
1943
+ const auditForceKeep = consumeAuditForceKeep(context);
1944
+ if (overrides?._forceKeep)
1945
+ forceKeep = true;
1946
+ else if (auditForceKeep)
1947
+ forceKeep = true;
1948
+ else if (state.sampling.keep?.length)
1949
+ forceKeep = shouldKeep({
1950
+ status: overrides?.status ?? context.status,
1951
+ duration: durationMs,
1952
+ path: context.path,
1953
+ method: context.method,
1954
+ context
1955
+ });
1956
+ if (!forceKeep && !shouldSample(level)) {
1957
+ emitted = true;
1958
+ pendingWideEvent = null;
1959
+ return null;
1960
+ }
1961
+ if (overrides) {
1962
+ const obj = overrides;
1963
+ for (const key in obj)
1964
+ if (key !== "_forceKeep")
1965
+ context[key] = obj[key];
1966
+ }
1967
+ context.durationMs = durationMs;
1968
+ context.duration = formatDuration(durationMs);
1969
+ const wide = emitWideEvent(level, context, {
1970
+ deferDrain,
1971
+ ownsEvent: true,
1972
+ waitUntil
1973
+ });
1974
+ emitted = true;
1975
+ pendingWideEvent = wide;
1976
+ if (wide)
1977
+ pendingDrainState.set(wide, { drainStarted: !deferDrain });
1978
+ return wide;
1979
+ },
1980
+ getContext() {
1981
+ return { ...context };
1982
+ }
1983
+ };
1984
+ }
1985
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
1986
+ initLogger(__EVLOG_CONFIG__);
1987
+ function isPlainObject2(value) {
1988
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1989
+ return false;
1990
+ if (Object.prototype.toString.call(value) !== "[object Object]")
1991
+ return false;
1992
+ return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
1993
+ }
1994
+ function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
1995
+ if (value === null || typeof value !== "object")
1996
+ return JSON.stringify(value);
1997
+ if (ancestors.has(value))
1998
+ return '"[Circular]"';
1999
+ if (!Array.isArray(value) && !isPlainObject2(value))
2000
+ return JSON.stringify(value);
2001
+ ancestors.add(value);
2002
+ const out = Array.isArray(value) ? `[${value.map((v) => stableStringify(v, ancestors)).join(",")}]` : `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k], ancestors)}`).join(",")}}`;
2003
+ ancestors.delete(value);
2004
+ return out;
2005
+ }
2006
+ function fnv1a32(input, seed) {
2007
+ let h = seed >>> 0;
2008
+ for (let i = 0;i < input.length; i++) {
2009
+ h ^= input.charCodeAt(i) & 255;
2010
+ h = Math.imul(h, 16777619) >>> 0;
2011
+ }
2012
+ return h >>> 0;
2013
+ }
2014
+ function computeIdempotencyKey(audit, timestamp) {
2015
+ const seconds = timestamp.slice(0, 19);
2016
+ const payload = stableStringify({
2017
+ action: audit.action,
2018
+ actor: {
2019
+ type: audit.actor.type,
2020
+ id: audit.actor.id
2021
+ },
2022
+ target: audit.target ? {
2023
+ type: audit.target.type,
2024
+ id: audit.target.id
2025
+ } : undefined,
2026
+ outcome: audit.outcome,
2027
+ timestamp: seconds
2028
+ });
2029
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
2030
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
2031
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
2032
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
2033
+ return a + b + c + d;
2034
+ }
2035
+ function buildAuditFields(input) {
2036
+ return {
2037
+ action: input.action,
2038
+ actor: input.actor,
2039
+ target: input.target,
2040
+ outcome: input.outcome ?? "success",
2041
+ reason: input.reason,
2042
+ changes: input.changes,
2043
+ causationId: input.causationId,
2044
+ correlationId: input.correlationId,
2045
+ version: input.version ?? 1
2046
+ };
2047
+ }
2048
+ var _testCollector = null;
2049
+ function decorateAudit(audit, timestamp) {
2050
+ if (audit.idempotencyKey)
2051
+ return audit;
2052
+ return {
2053
+ ...audit,
2054
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
2055
+ };
2056
+ }
2057
+ function consumeAuditForceKeep(context) {
2058
+ if (context._auditForceKeep) {
2059
+ delete context._auditForceKeep;
2060
+ return true;
2061
+ }
2062
+ if (context.audit)
2063
+ return true;
2064
+ return false;
2065
+ }
2066
+ function isCompleteAuditFields(a) {
2067
+ if (!a || typeof a !== "object")
2068
+ return false;
2069
+ const audit = a;
2070
+ return typeof audit.action === "string" && typeof audit.actor?.type === "string" && typeof audit.actor?.id === "string";
2071
+ }
2072
+ function finalizeAudit(event) {
2073
+ const a = event.audit;
2074
+ if (!isCompleteAuditFields(a))
2075
+ return;
2076
+ const decorated = decorateAudit(a, String(event.timestamp));
2077
+ event.audit = decorated;
2078
+ _testCollector?.(decorated, event);
2079
+ }
2080
+ // src/server/context-logger.ts
2081
+ var syntheticRenderStorage = new AsyncLocalStorage3;
2082
+
2083
+ // src/devtools/protocol.ts
2084
+ var DEVTOOLS_PROTOCOL_VERSION = 1;
2085
+
2086
+ // src/server/devtools/hub.ts
2087
+ var EVENT_LIMIT = 1000;
2088
+ var instanceDevtoolsHub = instanceSlot(() => ({ events: [], listeners: new Set, sequence: 0 }));
2089
+ function devtoolsInstanceId() {
2090
+ const instance = currentInstance();
2091
+ return Bun.hash(`${instance.prefix}\x00${instance.pagesDir}`).toString(16);
2092
+ }
2093
+ function appendDevtoolsEvent(event) {
2094
+ const hub = instanceDevtoolsHub();
2095
+ hub.sequence += 1;
2096
+ const complete = {
2097
+ ...event,
2098
+ id: hub.sequence,
2099
+ instanceId: devtoolsInstanceId(),
2100
+ version: DEVTOOLS_PROTOCOL_VERSION
2101
+ };
2102
+ hub.events.push(complete);
2103
+ if (hub.events.length > EVENT_LIMIT) {
2104
+ hub.events.shift();
2105
+ }
2106
+ for (const listener of hub.listeners) {
2107
+ listener(complete);
2108
+ }
2109
+ return complete;
2110
+ }
2111
+
2112
+ // src/server/auto-invalidate/registry.ts
2113
+ class AutoInvalidateRegistry {
2114
+ pathToTags = new Map;
2115
+ tagToPaths = new Map;
2116
+ registerLoaderTags(urlPath, tags) {
2117
+ if (!tags || tags.length === 0) {
2118
+ this.unregisterPath(urlPath);
2119
+ return;
2120
+ }
2121
+ this.unregisterPath(urlPath);
2122
+ const uniqueTags = new Set(tags);
2123
+ this.pathToTags.set(urlPath, uniqueTags);
2124
+ for (const tag of uniqueTags) {
2125
+ let paths = this.tagToPaths.get(tag);
2126
+ if (!paths) {
2127
+ paths = new Set;
2128
+ this.tagToPaths.set(tag, paths);
2129
+ }
2130
+ paths.add(urlPath);
2131
+ }
2132
+ }
2133
+ pathsForTags(tags) {
2134
+ const paths = new Set;
2135
+ for (const tag of tags) {
2136
+ for (const path of this.tagToPaths.get(tag) ?? []) {
2137
+ paths.add(path);
2138
+ }
2139
+ }
2140
+ return [...paths];
2141
+ }
2142
+ unregisterPath(urlPath) {
2143
+ const tags = this.pathToTags.get(urlPath);
2144
+ if (!tags) {
2145
+ return;
2146
+ }
2147
+ for (const tag of tags) {
2148
+ const paths = this.tagToPaths.get(tag);
2149
+ if (!paths) {
2150
+ continue;
2151
+ }
2152
+ paths.delete(urlPath);
2153
+ if (paths.size === 0) {
2154
+ this.tagToPaths.delete(tag);
2155
+ }
2156
+ }
2157
+ this.pathToTags.delete(urlPath);
2158
+ }
2159
+ reset() {
2160
+ this.pathToTags.clear();
2161
+ this.tagToPaths.clear();
2162
+ }
2163
+ }
2164
+ var instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
2165
+ function getAutoInvalidateRegistry(instance) {
2166
+ return instanceAutoInvalidateRegistry(instance);
2167
+ }
2168
+
2169
+ // src/server/cache/registry.ts
2170
+ var instanceInvalidators = instanceSlot(() => new Map);
2171
+ function getCacheInvalidators(instance) {
2172
+ return instanceInvalidators(instance).values();
2173
+ }
2174
+
2175
+ // src/server/cache/route-cache.ts
2176
+ function pathWithoutSearch(path) {
2177
+ const searchStart = path.indexOf("?");
2178
+ if (searchStart === -1) {
2179
+ return path;
2180
+ }
2181
+ return path.slice(0, searchStart);
2182
+ }
2183
+
2184
+ // src/server/devtools/request-context.ts
2185
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2186
+ var requestContext = new AsyncLocalStorage4;
2187
+ function currentDevtoolsRequest() {
2188
+ return requestContext.getStore();
2189
+ }
2190
+
2191
+ // src/server/devtools/instrumentation.ts
2192
+ function emitCacheInvalidated(event) {
2193
+ appendDevtoolsEvent({ ...event, timestamp: Date.now(), type: "cache.invalidated" });
2194
+ }
2195
+ function currentInstrumentationRequest() {
2196
+ return currentDevtoolsRequest();
2197
+ }
2198
+
2199
+ // src/server/runtime-env.ts
2200
+ var IS_DEV = true;
2201
+
2202
+ // src/server/cache/invalidation.ts
2203
+ var _globalPendingInvalidations = new Set;
2204
+ function _activeInvalidationSet() {
2205
+ return requestPendingInvalidations() ?? _globalPendingInvalidations;
2206
+ }
2207
+ function consumePendingInvalidations() {
2208
+ const set = _activeInvalidationSet();
2209
+ if (set.size === 0) {
2210
+ return [];
2211
+ }
2212
+ const paths = [...set];
2213
+ set.clear();
2214
+ return paths;
2215
+ }
2216
+ function peekPendingInvalidations() {
2217
+ return [..._activeInvalidationSet()];
2218
+ }
2219
+ var _cachePurger = null;
2220
+ function callCachePurger(paths) {
2221
+ if (!_cachePurger || paths.length === 0) {
2222
+ return;
2223
+ }
2224
+ _cachePurger(paths).catch((err) => {
2225
+ const logger = createLogger({});
2226
+ logger.set({
2227
+ furin: {
2228
+ action: "cdn_purge_failed",
2229
+ paths
2230
+ }
2231
+ });
2232
+ logger.error(err instanceof Error ? err : new Error(String(err)));
2233
+ logger.emit();
2234
+ });
2235
+ }
2236
+ function revalidatePath(path, type) {
2237
+ let deleted = false;
2238
+ const purgedPaths = [];
2239
+ for (const instance of allInstances()) {
2240
+ const result = revalidatePathForInstance(instance, path, type);
2241
+ deleted = result.deleted || deleted;
2242
+ purgedPaths.push(`${instance.prefix}${path}`);
2243
+ for (const purged of result.purgedPaths) {
2244
+ purgedPaths.push(`${instance.prefix}${purged}`);
2245
+ }
2246
+ }
2247
+ callCachePurger(dedupePaths(purgedPaths));
2248
+ return deleted;
2249
+ }
2250
+ function revalidatePathForInstance(instance, path, type, emitPathEvent) {
2251
+ _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
2252
+ let deleted = false;
2253
+ const purgedPaths = [];
2254
+ withInstance(instance, () => {
2255
+ for (const invalidator of getCacheInvalidators(instance)) {
2256
+ const result = invalidator.invalidatePath(path, type);
2257
+ deleted = result.deleted || deleted;
2258
+ purgedPaths.push(...result.purgedPaths);
2259
+ }
2260
+ if (IS_DEV && emitPathEvent !== false) {
2261
+ const request = currentInstrumentationRequest();
2262
+ const operationId = request === undefined ? null : request.operationId;
2263
+ const requestId = request === undefined ? null : request.requestId;
2264
+ emitCacheInvalidated({
2265
+ deleted,
2266
+ operationId,
2267
+ purgedPaths: new Set(purgedPaths).size,
2268
+ reason: "path",
2269
+ requestId,
2270
+ target: path
2271
+ });
2272
+ }
2273
+ });
2274
+ return { deleted, purgedPaths };
2275
+ }
2276
+ function dedupePaths(paths) {
2277
+ return [...new Set(paths)];
2278
+ }
2279
+
2280
+ // src/server/auto-invalidate/runtime.ts
2281
+ function toRules(input) {
2282
+ return Array.isArray(input) ? input : [input];
2283
+ }
2284
+ function statusFromResponseValue(responseValue) {
2285
+ if (responseValue instanceof Response) {
2286
+ return responseValue.status;
2287
+ }
2288
+ if (responseValue && typeof responseValue === "object" && "status" in responseValue) {
2289
+ const { status } = responseValue;
2290
+ if (typeof status === "number") {
2291
+ return status;
2292
+ }
2293
+ }
2294
+ if (responseValue && typeof responseValue === "object" && "code" in responseValue) {
2295
+ const { code } = responseValue;
2296
+ if (typeof code === "number") {
2297
+ return code;
2298
+ }
2299
+ }
2300
+ }
2301
+ function isSuccessfulMutationResponse(ctx) {
2302
+ const responseStatus = statusFromResponseValue(ctx.responseValue) ?? statusFromResponseValue(ctx.response);
2303
+ if (responseStatus !== undefined) {
2304
+ return responseStatus >= 200 && responseStatus < 400;
2305
+ }
2306
+ const setStatus = ctx.set.status;
2307
+ if (typeof setStatus === "number") {
2308
+ return setStatus >= 200 && setStatus < 400;
2309
+ }
2310
+ if (typeof setStatus === "string") {
2311
+ const errorStatusTexts = new Set([
2312
+ "Bad Request",
2313
+ "Unauthorized",
2314
+ "Payment Required",
2315
+ "Forbidden",
2316
+ "Not Found",
2317
+ "Method Not Allowed",
2318
+ "Not Acceptable",
2319
+ "Proxy Authentication Required",
2320
+ "Request Timeout",
2321
+ "Conflict",
2322
+ "Gone",
2323
+ "Length Required",
2324
+ "Precondition Failed",
2325
+ "Payload Too Large",
2326
+ "URI Too Long",
2327
+ "Unsupported Media Type",
2328
+ "Range Not Satisfiable",
2329
+ "Expectation Failed",
2330
+ "I'm a teapot",
2331
+ "Misdirected Request",
2332
+ "Unprocessable Content",
2333
+ "Locked",
2334
+ "Failed Dependency",
2335
+ "Too Early",
2336
+ "Upgrade Required",
2337
+ "Precondition Required",
2338
+ "Too Many Requests",
2339
+ "Enhance Your Calm",
2340
+ "Request Header Fields Too Large",
2341
+ "Unavailable For Legal Reasons",
2342
+ "Internal Server Error",
2343
+ "Not Implemented",
2344
+ "Bad Gateway",
2345
+ "Service Unavailable",
2346
+ "Gateway Timeout",
2347
+ "HTTP Version Not Supported",
2348
+ "Variant Also Negotiates",
2349
+ "Insufficient Storage",
2350
+ "Loop Detected",
2351
+ "Not Extended",
2352
+ "Network Authentication Required"
2353
+ ]);
2354
+ return !errorStatusTexts.has(setStatus);
2355
+ }
2356
+ return true;
2357
+ }
2358
+ function appendPendingInvalidationHeader(set) {
2359
+ const pending = consumePendingInvalidations();
2360
+ if (pending.length === 0) {
2361
+ return [];
2362
+ }
2363
+ const headerName = "x-furin-revalidate";
2364
+ const existing = set.headers[headerName];
2365
+ set.headers[headerName] = typeof existing === "string" && existing.length > 0 ? `${existing},${pending.join(",")}` : pending.join(",");
2366
+ return pending;
2367
+ }
2368
+ function revalidateTag(tags) {
2369
+ const tagList = typeof tags === "string" ? [tags] : [...tags];
2370
+ let deleted = false;
2371
+ const purgedPaths = new Set;
2372
+ for (const instance of allInstances()) {
2373
+ let instanceDeleted = false;
2374
+ const instancePurgedPaths = new Set;
2375
+ for (const path of getAutoInvalidateRegistry(instance).pathsForTags(tagList)) {
2376
+ const logicalPath = pathWithoutSearch(path);
2377
+ const result = revalidatePathForInstance(instance, logicalPath, "page", false);
2378
+ deleted = result.deleted || deleted;
2379
+ instanceDeleted = result.deleted || instanceDeleted;
2380
+ purgedPaths.add(`${instance.prefix}${logicalPath}`);
2381
+ instancePurgedPaths.add(logicalPath);
2382
+ for (const purged of result.purgedPaths) {
2383
+ purgedPaths.add(`${instance.prefix}${purged}`);
2384
+ instancePurgedPaths.add(purged);
2385
+ }
2386
+ }
2387
+ if (IS_DEV) {
2388
+ withInstance(instance, () => {
2389
+ const request = currentInstrumentationRequest();
2390
+ const operationId = request === undefined ? null : request.operationId;
2391
+ const requestId = request === undefined ? null : request.requestId;
2392
+ emitCacheInvalidated({
2393
+ deleted: instanceDeleted,
2394
+ operationId,
2395
+ purgedPaths: instancePurgedPaths.size,
2396
+ reason: "tag",
2397
+ requestId,
2398
+ target: tagList.join(",")
2399
+ });
2400
+ });
2401
+ }
2402
+ }
2403
+ callCachePurger([...purgedPaths]);
2404
+ return deleted;
2405
+ }
2406
+ function runInvalidationRules(input) {
2407
+ let deleted = false;
2408
+ for (const rule of toRules(input)) {
2409
+ if ("path" in rule && rule.path) {
2410
+ deleted = revalidatePath(rule.path, rule.type) || deleted;
2411
+ }
2412
+ if (rule.tags && rule.tags.length > 0) {
2413
+ deleted = revalidateTag(rule.tags) || deleted;
2414
+ }
2415
+ }
2416
+ return deleted;
2417
+ }
2418
+
2419
+ // src/server/sync/fingerprint.ts
2420
+ function compareCodePoints(left, right) {
2421
+ if (left === right) {
2422
+ return 0;
2423
+ }
2424
+ return left < right ? -1 : 1;
2425
+ }
2426
+ function canonicalize(value) {
2427
+ if (Array.isArray(value)) {
2428
+ return value.map(canonicalize);
2429
+ }
2430
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
2431
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
2432
+ }
2433
+ return value;
2434
+ }
2435
+ function sha256Hex(source) {
2436
+ const hasher = new Bun.CryptoHasher("sha256");
2437
+ hasher.update(source);
2438
+ return hasher.digest("hex");
2439
+ }
2440
+ function createMutationFingerprint(input) {
2441
+ const url = new URL(input.request.url);
2442
+ const query = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => leftKey === rightKey ? compareCodePoints(leftValue, rightValue) : compareCodePoints(leftKey, rightKey));
2443
+ const source = JSON.stringify({
2444
+ body: canonicalize(input.body) ?? null,
2445
+ contentType: input.request.headers.get("content-type") ?? "",
2446
+ method: input.request.method,
2447
+ pathname: url.pathname,
2448
+ query
2449
+ });
2450
+ return sha256Hex(source);
2451
+ }
2452
+
2453
+ // src/server/sync/response.ts
2454
+ import { ElysiaCustomStatusResponse, StatusMap } from "elysia";
2455
+ var NON_REPLAYABLE_HEADERS = new Set([
2456
+ "authorization",
2457
+ "connection",
2458
+ "keep-alive",
2459
+ "proxy-authenticate",
2460
+ "proxy-authorization",
2461
+ "set-cookie",
2462
+ "transfer-encoding",
2463
+ "upgrade",
2464
+ "www-authenticate"
2465
+ ]);
2466
+ var MAX_SYNC_REPLAY_RESPONSE_BYTES = 1024 * 1024;
2467
+ var UNREPLAYABLE_SYNC_RESPONSE_BODY = new TextEncoder().encode(JSON.stringify({
2468
+ code: "FURIN_UNREPLAYABLE_SYNC_RESPONSE",
2469
+ message: "This mutation response cannot be replayed safely. Return a small bounded response or set sync: false on the route."
2470
+ }));
2471
+ function statusCode(status) {
2472
+ if (typeof status === "number") {
2473
+ return status;
2474
+ }
2475
+ return status === undefined ? 200 : StatusMap[status];
2476
+ }
2477
+ function unwrapStatusResponse(value) {
2478
+ if (!(value instanceof ElysiaCustomStatusResponse)) {
2479
+ return;
2480
+ }
2481
+ return { status: value.code, value: value.response };
2482
+ }
2483
+ function responseHeaders(headers) {
2484
+ const result = new Headers;
2485
+ for (const [name, value] of Object.entries(headers)) {
2486
+ if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2487
+ for (const entry of Array.isArray(value) ? value : [value]) {
2488
+ result.append(name, String(entry));
2489
+ }
2490
+ }
2491
+ }
2492
+ return result;
2493
+ }
2494
+ function storedResponseResult(headers, body, status) {
2495
+ if (body.byteLength > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
2496
+ return unreplayable();
2497
+ }
2498
+ return {
2499
+ kind: "stored",
2500
+ response: {
2501
+ body,
2502
+ headers: [...headers.entries()],
2503
+ status
2504
+ }
2505
+ };
2506
+ }
2507
+ function responseContentLength(response) {
2508
+ const header = response.headers.get("content-length");
2509
+ if (header === null) {
2510
+ return;
2511
+ }
2512
+ const parsed = Number(header);
2513
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;
2514
+ }
2515
+ async function readBoundedResponseBody(response) {
2516
+ if (response.body === null) {
2517
+ return new Uint8Array;
2518
+ }
2519
+ const contentLength = responseContentLength(response);
2520
+ if (contentLength === undefined || contentLength > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
2521
+ return;
2522
+ }
2523
+ const reader = response.body.getReader();
2524
+ const chunks = [];
2525
+ let total = 0;
2526
+ try {
2527
+ for (;; ) {
2528
+ const { done, value } = await reader.read();
2529
+ if (done) {
2530
+ break;
2531
+ }
2532
+ total += value.byteLength;
2533
+ if (total > MAX_SYNC_REPLAY_RESPONSE_BYTES) {
2534
+ await reader.cancel();
2535
+ return;
2536
+ }
2537
+ chunks.push(value);
2538
+ }
2539
+ } finally {
2540
+ reader.releaseLock();
2541
+ }
2542
+ const body = new Uint8Array(total);
2543
+ let offset = 0;
2544
+ for (const chunk of chunks) {
2545
+ body.set(chunk, offset);
2546
+ offset += chunk.byteLength;
2547
+ }
2548
+ return body;
2549
+ }
2550
+ function unreplayable() {
2551
+ return {
2552
+ kind: "unreplayable",
2553
+ response: {
2554
+ body: UNREPLAYABLE_SYNC_RESPONSE_BODY.slice(),
2555
+ headers: [["content-type", "application/json;charset=utf-8"]],
2556
+ status: 500
2557
+ }
2558
+ };
2559
+ }
2560
+ function mergeStoredResponseHeaders(storedResponse, headers) {
2561
+ const headerEntries = [];
2562
+ for (const [name, value] of storedResponse.headers) {
2563
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2564
+ headerEntries.push([name, value]);
2565
+ }
2566
+ }
2567
+ const merged = new Headers(headerEntries);
2568
+ for (const [name, value] of Object.entries(headers)) {
2569
+ if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2570
+ merged.delete(name);
2571
+ for (const entry of Array.isArray(value) ? value : [value]) {
2572
+ merged.append(name, String(entry));
2573
+ }
2574
+ }
2575
+ }
2576
+ return {
2577
+ ...storedResponse,
2578
+ headers: [...merged.entries()]
2579
+ };
2580
+ }
2581
+ async function storeResponse(responseValue, set) {
2582
+ if (responseValue instanceof Response) {
2583
+ const clone = responseValue.clone();
2584
+ const body = await readBoundedResponseBody(clone);
2585
+ if (body === undefined) {
2586
+ return unreplayable();
2587
+ }
2588
+ const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
2589
+ return storedResponseResult(headers, body, clone.status);
2590
+ }
2591
+ const headers = responseHeaders(set.headers);
2592
+ const statusResponse = unwrapStatusResponse(responseValue);
2593
+ const value = statusResponse?.value ?? responseValue;
2594
+ const responseStatus = statusResponse ? statusResponse.status : statusCode(set.status);
2595
+ let body;
2596
+ if (value === undefined || value === null) {
2597
+ body = new Uint8Array;
2598
+ } else if (typeof value === "string") {
2599
+ headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
2600
+ body = new TextEncoder().encode(value);
2601
+ } else {
2602
+ headers.set("content-type", headers.get("content-type") ?? "application/json");
2603
+ body = new TextEncoder().encode(JSON.stringify(value));
2604
+ }
2605
+ return storedResponseResult(headers, body, responseStatus);
2606
+ }
2607
+ function replayResponse(stored) {
2608
+ const body = stored.status === 204 || stored.status === 205 || stored.status === 304 ? null : stored.body.slice();
2609
+ const headerEntries = [];
2610
+ for (const [name, value] of stored.headers) {
2611
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
2612
+ headerEntries.push([name, value]);
2613
+ }
2614
+ }
2615
+ return new Response(body, {
2616
+ headers: new Headers(headerEntries),
2617
+ status: stored.status
2618
+ });
2619
+ }
2620
+
2621
+ // src/server/sync/runtime.ts
2622
+ var POLL_INTERVAL_MS = 250;
2623
+ var pollingNotifiers = new WeakMap;
2624
+ function resolveSyncRuntime(options) {
2625
+ if (!IS_DEV && options.adapter.scope === "process-local") {
2626
+ throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
2627
+ }
2628
+ if (options.notifier) {
2629
+ return { adapter: options.adapter, notifier: options.notifier };
2630
+ }
2631
+ const existing = pollingNotifiers.get(options.adapter);
2632
+ if (existing) {
2633
+ return { adapter: options.adapter, notifier: existing };
2634
+ }
2635
+ const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
2636
+ pollingNotifiers.set(options.adapter, notifier);
2637
+ return { adapter: options.adapter, notifier };
2638
+ }
2639
+
2640
+ // src/server/sync/plugin.ts
2641
+ var routeMetadata = new WeakMap;
2642
+ var activeMutations = new WeakMap;
2643
+ function hideTransportResponse(hook) {
2644
+ return hook;
2645
+ }
2646
+ function invalidationInputFromSync(input) {
2647
+ if (input && typeof input === "object" && "invalidate" in input) {
2648
+ return input.invalidate;
2649
+ }
2650
+ return input;
2651
+ }
2652
+ function isMutationMethod(method) {
2653
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
2654
+ }
2655
+ function getIdempotencyKey(ctx) {
2656
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
2657
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
2658
+ return fromCtxHeaders;
2659
+ }
2660
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
2661
+ return fromRequest || undefined;
2662
+ }
2663
+ function supportsReplayBody(request) {
2664
+ const contentType = request.headers.get("content-type")?.toLowerCase();
2665
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
2666
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
2667
+ }
2668
+ function conflictResponse(reason) {
2669
+ const inProgress = reason === "in-progress";
2670
+ return Response.json({
2671
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
2672
+ message: inProgress ? "A mutation with this Idempotency-Key is still running." : "The Idempotency-Key was already used with a different request."
2673
+ }, {
2674
+ headers: inProgress ? { "retry-after": "1" } : undefined,
2675
+ status: 409
2676
+ });
2677
+ }
2678
+ function leaseLostResponse() {
2679
+ return Response.json({
2680
+ code: "FURIN_SYNC_LEASE_LOST",
2681
+ message: "The mutation lease was lost before its response could be committed."
2682
+ }, { status: 503 });
2683
+ }
2684
+ function normalizedInvalidations(input) {
2685
+ if (!input) {
2686
+ return [];
2687
+ }
2688
+ const rules = Array.isArray(input) ? input : [input];
2689
+ const invalidations = [];
2690
+ for (const rule of rules) {
2691
+ if ("path" in rule && rule.path) {
2692
+ invalidations.push({ kind: "path", path: rule.path, type: rule.type });
2693
+ }
2694
+ if (rule.tags && rule.tags.length > 0) {
2695
+ invalidations.push({ kind: "tags", tags: [...rule.tags] });
2696
+ }
2697
+ }
2698
+ return invalidations;
2699
+ }
2700
+ function pendingPathInvalidations(entries) {
2701
+ return entries.map((entry) => entry.endsWith(":layout") ? { kind: "path", path: entry.slice(0, -":layout".length), type: "layout" } : { kind: "path", path: entry, type: "page" });
2702
+ }
2703
+ function furinSync(options) {
2704
+ const runtime = resolveSyncRuntime(options);
2705
+ async function beginMutation(ctx) {
2706
+ if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
2707
+ return;
2708
+ }
2709
+ const idempotencyKey = getIdempotencyKey(ctx);
2710
+ if (!idempotencyKey) {
2711
+ return new Response("Missing Idempotency-Key header", {
2712
+ headers: { "content-type": "text/plain; charset=utf-8" },
2713
+ status: 428
2714
+ });
2715
+ }
2716
+ if (!supportsReplayBody(ctx.request)) {
2717
+ return Response.json({
2718
+ code: "FURIN_UNSUPPORTED_SYNC_BODY",
2719
+ message: "This request body cannot be replayed. Set sync: false on the route."
2720
+ }, { status: 415 });
2721
+ }
2722
+ const url = new URL(ctx.request.url);
2723
+ const principal = await options.principal(ctx);
2724
+ if (principal.length === 0) {
2725
+ throw new Error("[furin] Sync principal must not be empty.");
2726
+ }
2727
+ const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
2728
+ const fingerprint = createMutationFingerprint({ body: ctx.body, request: ctx.request });
2729
+ const result = await runtime.adapter.beginMutation({ fingerprint, key, principal });
2730
+ if (result.kind === "replay") {
2731
+ return replayResponse(result.response);
2732
+ }
2733
+ if (result.kind === "conflict") {
2734
+ return conflictResponse(result.reason);
2735
+ }
2736
+ const active = { lease: result.lease, renewal: undefined };
2737
+ const renewAfter = Math.max(1000, Math.floor(result.lease.leaseMs / 3));
2738
+ const scheduleRenewal = () => {
2739
+ active.renewal = setTimeout(async () => {
2740
+ if (activeMutations.get(ctx.request) === active) {
2741
+ scheduleRenewal();
2742
+ }
2743
+ await runtime.adapter.renewMutation(result.lease).catch(() => {
2744
+ return;
2745
+ });
2746
+ }, renewAfter);
2747
+ active.renewal.unref?.();
2748
+ };
2749
+ activeMutations.set(ctx.request, active);
2750
+ scheduleRenewal();
2751
+ }
2752
+ async function abortMutation(request) {
2753
+ const active = activeMutations.get(request);
2754
+ if (!active) {
2755
+ return;
2756
+ }
2757
+ activeMutations.delete(request);
2758
+ if (active.renewal) {
2759
+ clearTimeout(active.renewal);
2760
+ }
2761
+ await runtime.adapter.abortMutation(active.lease);
2762
+ }
2763
+ async function persistMutation(ctx, active) {
2764
+ const result = await storeResponse(ctx.responseValue, ctx.set);
2765
+ const manualPending = peekPendingInvalidations();
2766
+ const invalidate = routeMetadata.get(ctx.request)?.invalidate;
2767
+ if (invalidate) {
2768
+ runInvalidationRules(invalidate);
2769
+ }
2770
+ const pending = appendPendingInvalidationHeader(ctx.set);
2771
+ if (pending.length > 0) {
2772
+ ctx.set.headers["x-furin-sync"] = "1";
2773
+ }
2774
+ const response = mergeStoredResponseHeaders(result.response, ctx.set.headers);
2775
+ const semanticInvalidations = normalizedInvalidations(invalidate);
2776
+ const invalidations = [...semanticInvalidations];
2777
+ for (const manual of pendingPathInvalidations(manualPending)) {
2778
+ const duplicated = semanticInvalidations.some((semantic) => semantic.kind === "path" && semantic.path === manual.path && semantic.type === manual.type);
2779
+ if (!duplicated) {
2780
+ invalidations.push(manual);
2781
+ }
2782
+ }
2783
+ const completion = await runtime.adapter.completeMutation({
2784
+ invalidations,
2785
+ lease: active.lease,
2786
+ response
2787
+ });
2788
+ if (completion.kind === "lost") {
2789
+ return leaseLostResponse();
2790
+ }
2791
+ if (completion.cursor !== undefined) {
2792
+ runtime.notifier.publish(completion.cursor).catch(() => {
2793
+ return;
2794
+ });
2795
+ }
2796
+ if (result.kind === "unreplayable") {
2797
+ return replayResponse(response);
2798
+ }
2799
+ }
2800
+ async function finishMutation(ctx) {
2801
+ const active = activeMutations.get(ctx.request);
2802
+ if (!active) {
2803
+ return;
2804
+ }
2805
+ try {
2806
+ if (!isSuccessfulMutationResponse(ctx)) {
2807
+ await runtime.adapter.abortMutation(active.lease);
2808
+ return;
2809
+ }
2810
+ return await persistMutation(ctx, active);
2811
+ } catch (error) {
2812
+ await runtime.adapter.abortMutation(active.lease).catch(() => {
2813
+ return;
2814
+ });
2815
+ throw error;
2816
+ } finally {
2817
+ activeMutations.delete(ctx.request);
2818
+ if (active.renewal) {
2819
+ clearTimeout(active.renewal);
2820
+ }
2821
+ }
2822
+ }
2823
+ const beginMutationHook = hideTransportResponse(beginMutation);
2824
+ const finishMutationHook = hideTransportResponse(finishMutation);
2825
+ return new Elysia({ name: "furin-sync" }).macro({
2826
+ sync(input) {
2827
+ return {
2828
+ transform({ request }) {
2829
+ routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
2830
+ }
2831
+ };
2832
+ }
2833
+ }).onBeforeHandle({ as: "global" }, beginMutationHook).onAfterHandle({ as: "global" }, finishMutationHook).onError({ as: "global" }, ({ request }) => abortMutation(request));
2834
+ }
2835
+
2836
+ // src/server/sync/stream.ts
2837
+ import { Elysia as Elysia2 } from "elysia";
2838
+ var DEFAULT_CHANGE_LIMIT = 100;
2839
+ var MAX_CHANGE_LIMIT = 500;
2840
+ var MAX_STREAM_CLIENTS = 100;
2841
+ var MAX_CURSOR_LENGTH = 128;
2842
+ var SAFETY_POLL_INTERVAL_MS = IS_DEV ? 250 : 15000;
2843
+ var UNSIGNED_INTEGER_PATTERN = /^\d+$/;
2844
+ var defaultStreamPath = "/_furin/sync";
2845
+ var encoder = new TextEncoder;
2846
+ var noOpSubscription = {
2847
+ unsubscribe: () => Promise.resolve()
2848
+ };
2849
+ var streams = new Map;
2850
+ var resolvedStates = new Set;
2851
+ function encodeSseCursor(cursor) {
2852
+ return encoder.encode(`id: ${cursor}
2853
+ event: furin.sync
2854
+ retry: 3000
2855
+ data: ${JSON.stringify({ cursor })}
2856
+
2857
+ `);
2858
+ }
2859
+ function closeClient(state, client) {
2860
+ const heartbeat = state.clients.get(client);
2861
+ state.clients.delete(client);
2862
+ if (heartbeat) {
2863
+ clearInterval(heartbeat);
2864
+ }
2865
+ try {
2866
+ client.close();
2867
+ } catch {}
2868
+ }
2869
+ function notifyState(state, cursor) {
2870
+ if (state.cursor === cursor) {
2871
+ return;
2872
+ }
2873
+ state.cursor = cursor;
2874
+ const chunk = encodeSseCursor(cursor);
2875
+ for (const client of state.clients.keys()) {
2876
+ if (client.desiredSize === null || client.desiredSize <= 0) {
2877
+ closeClient(state, client);
2878
+ continue;
2879
+ }
2880
+ try {
2881
+ client.enqueue(chunk);
2882
+ } catch {
2883
+ closeClient(state, client);
2884
+ }
2885
+ }
2886
+ }
2887
+ async function createStreamState(runtime) {
2888
+ const state = {};
2889
+ state.clients = new Map;
2890
+ state.cursor = await runtime.adapter.currentCursor();
2891
+ state.safetyPoll = setInterval(() => {
2892
+ runtime.adapter.currentCursor().then((cursor) => notifyState(state, cursor)).catch(() => {
2893
+ return;
2894
+ });
2895
+ }, SAFETY_POLL_INTERVAL_MS);
2896
+ state.safetyPoll.unref?.();
2897
+ state.subscription = await runtime.notifier.subscribe((cursor) => notifyState(state, cursor)).catch(() => noOpSubscription);
2898
+ resolvedStates.add(state);
2899
+ return state;
2900
+ }
2901
+ function getStreamState(runtime) {
2902
+ const existing = streams.get(runtime.adapter);
2903
+ if (existing) {
2904
+ return existing;
2905
+ }
2906
+ const state = createStreamState(runtime);
2907
+ streams.set(runtime.adapter, state);
2908
+ state.catch(() => {
2909
+ if (streams.get(runtime.adapter) === state) {
2910
+ streams.delete(runtime.adapter);
2911
+ }
2912
+ });
2913
+ return state;
2914
+ }
2915
+ function parseChangeQuery(request) {
2916
+ const url = new URL(request.url);
2917
+ const after = url.searchParams.get("after") ?? undefined;
2918
+ if (after !== undefined && (after.length === 0 || after.length > MAX_CURSOR_LENGTH)) {
2919
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
2920
+ }
2921
+ const limitValue = url.searchParams.get("limit");
2922
+ if (limitValue !== null && !UNSIGNED_INTEGER_PATTERN.test(limitValue)) {
2923
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2924
+ }
2925
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
2926
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
2927
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
2928
+ }
2929
+ return { after, limit };
2930
+ }
2931
+ function clientInvalidations(change) {
2932
+ const entries = new Set;
2933
+ for (const invalidation of change.invalidations) {
2934
+ if (invalidation.kind === "tags") {
2935
+ entries.add("/:layout");
2936
+ } else {
2937
+ entries.add(invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path);
2938
+ }
2939
+ }
2940
+ return [...entries];
2941
+ }
2942
+ function createSyncStreamPlugin(options) {
2943
+ const streamPath = options.streamPath ?? defaultStreamPath;
2944
+ const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
2945
+ return new Elysia2({ name: `furin-sync-stream-${streamPath}` }).get(`${streamPath}/changes`, async ({ request, set }) => {
2946
+ set.headers["cache-control"] = "no-store";
2947
+ const query = parseChangeQuery(request);
2948
+ if ("error" in query) {
2949
+ return query.error;
2950
+ }
2951
+ const page = await runtime.adapter.readChanges(query);
2952
+ return {
2953
+ ...page,
2954
+ changes: page.changes.map((change) => ({
2955
+ cursor: change.cursor,
2956
+ invalidations: clientInvalidations(change)
2957
+ }))
2958
+ };
2959
+ }).get(streamPath, async () => {
2960
+ const state = await getStreamState(runtime);
2961
+ if (state.clients.size >= MAX_STREAM_CLIENTS) {
2962
+ return Response.json({ code: "FURIN_SYNC_STREAM_CAPACITY" }, { status: 503 });
2963
+ }
2964
+ let controllerRef;
2965
+ let heartbeat;
2966
+ const stream = new ReadableStream({
2967
+ cancel() {
2968
+ if (controllerRef) {
2969
+ closeClient(state, controllerRef);
2970
+ }
2971
+ if (heartbeat) {
2972
+ clearInterval(heartbeat);
2973
+ }
2974
+ },
2975
+ start(controller) {
2976
+ controllerRef = controller;
2977
+ controller.enqueue(encoder.encode(`: connected
2978
+ retry: 3000
2979
+
2980
+ `));
2981
+ state.clients.set(controller, undefined);
2982
+ heartbeat = setInterval(() => {
2983
+ if (controller.desiredSize === null || controller.desiredSize <= 0) {
2984
+ closeClient(state, controller);
2985
+ return;
2986
+ }
2987
+ try {
2988
+ controller.enqueue(encoder.encode(`: heartbeat
2989
+
2990
+ `));
2991
+ } catch {
2992
+ closeClient(state, controller);
2993
+ }
2994
+ }, 15000);
2995
+ heartbeat.unref?.();
2996
+ state.clients.set(controller, heartbeat);
2997
+ }
2998
+ });
2999
+ return new Response(stream, {
3000
+ headers: {
3001
+ "cache-control": "no-cache, no-transform",
3002
+ connection: "keep-alive",
3003
+ "content-type": "text/event-stream; charset=utf-8"
3004
+ }
3005
+ });
3006
+ });
3007
+ }
3008
+
3009
+ // src/server/sync/index.ts
3010
+ var createSyncStreamPlugin2 = createSyncStreamPlugin;
3011
+ var furinSync2 = furinSync;
3012
+ var getSyncStreamPath2 = getSyncStreamPath;
3013
+ var PollingSyncNotifier2 = PollingSyncNotifier;
3014
+ var resolveSyncStreamPath2 = resolveSyncStreamPath;
3015
+ var runWithSyncStreamPath2 = runWithSyncStreamPath;
3016
+ export {
3017
+ PollingSyncNotifier2 as PollingSyncNotifier,
3018
+ createSyncStreamPlugin2 as createSyncStreamPlugin,
3019
+ furinSync2 as furinSync,
3020
+ getSyncStreamPath2 as getSyncStreamPath,
3021
+ resolveSyncStreamPath2 as resolveSyncStreamPath,
3022
+ runWithSyncStreamPath2 as runWithSyncStreamPath
3023
+ };