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