better-ship 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/{application-rpZoTfzU.js → application-DjsQtpgw.js} +2 -2
  2. package/dist/application-DjsQtpgw.js.map +1 -0
  3. package/dist/application.d.ts +3 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.d.ts +21 -0
  6. package/dist/better-auth/apple-client-secret.d.ts.map +1 -0
  7. package/dist/better-auth/apple-client-secret.js +44 -0
  8. package/dist/better-auth/apple-client-secret.js.map +1 -0
  9. package/dist/better-auth/auth-client.d.ts +16 -0
  10. package/dist/better-auth/auth-client.d.ts.map +1 -0
  11. package/dist/better-auth/auth-client.js +24 -0
  12. package/dist/better-auth/auth-client.js.map +1 -0
  13. package/dist/better-auth/rate-limit.d.ts +34 -0
  14. package/dist/better-auth/rate-limit.d.ts.map +1 -0
  15. package/dist/better-auth/rate-limit.js +59 -0
  16. package/dist/better-auth/rate-limit.js.map +1 -0
  17. package/dist/better-auth/secondary-storage.d.ts +11 -0
  18. package/dist/better-auth/secondary-storage.d.ts.map +1 -0
  19. package/dist/better-auth/secondary-storage.js +18 -0
  20. package/dist/better-auth/secondary-storage.js.map +1 -0
  21. package/dist/better-auth/stripe.d.ts +9 -0
  22. package/dist/better-auth/stripe.d.ts.map +1 -0
  23. package/dist/better-auth/stripe.js +17 -0
  24. package/dist/better-auth/stripe.js.map +1 -0
  25. package/dist/better-auth.d.ts +100 -0
  26. package/dist/better-auth.d.ts.map +1 -0
  27. package/dist/better-auth.js +112 -0
  28. package/dist/better-auth.js.map +1 -0
  29. package/dist/cloudflare/auth-secondary-storage.d.ts +36 -0
  30. package/dist/cloudflare/auth-secondary-storage.d.ts.map +1 -0
  31. package/dist/cloudflare/auth-secondary-storage.js +98 -0
  32. package/dist/cloudflare/auth-secondary-storage.js.map +1 -0
  33. package/dist/cloudflare.d.ts +7 -7
  34. package/dist/cloudflare.d.ts.map +1 -1
  35. package/dist/cloudflare.js +3 -3
  36. package/dist/cloudflare.js.map +1 -1
  37. package/dist/core-Cx5SeyKV.js +709 -0
  38. package/dist/core-Cx5SeyKV.js.map +1 -0
  39. package/dist/core.d.ts +2 -2
  40. package/dist/core.js +2 -2
  41. package/dist/index-BStnggQO.d.ts +584 -0
  42. package/dist/index-BStnggQO.d.ts.map +1 -0
  43. package/dist/{index-BN_tjxME.d.ts → index-DWIRrJMP.d.ts} +21 -50
  44. package/dist/index-DWIRrJMP.d.ts.map +1 -0
  45. package/dist/postgres.d.ts +7 -7
  46. package/dist/postgres.d.ts.map +1 -1
  47. package/dist/postgres.js +3 -3
  48. package/dist/postgres.js.map +1 -1
  49. package/dist/tanstack.d.ts +88 -1
  50. package/dist/tanstack.d.ts.map +1 -0
  51. package/dist/tanstack.js +225 -0
  52. package/dist/tanstack.js.map +1 -0
  53. package/dist/{unit-of-work-context-CbUJGHlL.d.ts → unit-of-work-context-CPz9rdSS.d.ts} +3 -2
  54. package/dist/unit-of-work-context-CPz9rdSS.d.ts.map +1 -0
  55. package/dist/{unit-of-work-context-BLNj72v0.js → unit-of-work-context-DToDpAkv.js} +2 -2
  56. package/dist/unit-of-work-context-DToDpAkv.js.map +1 -0
  57. package/package.json +57 -12
  58. package/src/application/event-collector.ts +3 -3
  59. package/src/application/handlers.ts +7 -4
  60. package/src/application/index.ts +1 -1
  61. package/src/application/message-already-processed.error.ts +1 -3
  62. package/src/application/message-bus.ts +14 -8
  63. package/src/application/message-store.ts +2 -2
  64. package/src/application/registry.ts +14 -13
  65. package/src/application/unit-of-work.ts +2 -1
  66. package/src/core/authentication.error.ts +11 -0
  67. package/src/core/define-messages.ts +136 -0
  68. package/src/core/entity.ts +33 -0
  69. package/src/core/error-table.ts +188 -0
  70. package/src/core/identity.ts +29 -0
  71. package/src/core/index.ts +50 -0
  72. package/src/core/internal.errors.ts +21 -0
  73. package/src/core/logger.ts +27 -15
  74. package/src/{application → core}/messages.ts +4 -4
  75. package/src/core/not-authorized.error.ts +11 -0
  76. package/src/core/problem-details.ts +57 -0
  77. package/src/core/rate-limit.error.ts +12 -0
  78. package/src/core/request.errors.ts +86 -0
  79. package/src/core/stale-session.error.ts +11 -0
  80. package/src/infrastructure/better-auth/apple-client-secret.ts +54 -0
  81. package/src/infrastructure/better-auth/auth-client.ts +26 -0
  82. package/src/infrastructure/better-auth/options.ts +232 -0
  83. package/src/infrastructure/better-auth/rate-limit.ts +69 -0
  84. package/src/infrastructure/better-auth/secondary-storage.ts +21 -0
  85. package/src/infrastructure/better-auth/stripe.ts +11 -0
  86. package/src/infrastructure/cloudflare/auth-secondary-storage.ts +113 -0
  87. package/src/infrastructure/cloudflare/base-d1-repository.ts +2 -2
  88. package/src/infrastructure/cloudflare/d1-message-store.ts +3 -7
  89. package/src/infrastructure/cloudflare/d1-schema.ts +2 -2
  90. package/src/infrastructure/postgres/base-postgres-repository.ts +2 -2
  91. package/src/infrastructure/postgres/postgres-message-store.ts +3 -7
  92. package/src/infrastructure/postgres/postgres-schema.ts +2 -2
  93. package/src/infrastructure/tanstack/auth.middleware.ts +89 -0
  94. package/src/infrastructure/tanstack/error.middleware.ts +81 -0
  95. package/src/infrastructure/tanstack/http-error-response.ts +30 -0
  96. package/src/infrastructure/tanstack/index.ts +13 -0
  97. package/src/infrastructure/tanstack/last-login-method.ts +13 -0
  98. package/src/infrastructure/tanstack/resolve-failure.ts +24 -0
  99. package/src/infrastructure/tanstack/session-cookies.ts +36 -0
  100. package/src/infrastructure/tanstack/to-error-payload.ts +32 -0
  101. package/src/infrastructure/unit-of-work-context.ts +3 -2
  102. package/dist/application-rpZoTfzU.js.map +0 -1
  103. package/dist/core-MjwyZJ4i.js +0 -302
  104. package/dist/core-MjwyZJ4i.js.map +0 -1
  105. package/dist/index-BN_tjxME.d.ts.map +0 -1
  106. package/dist/index-ToddX0m3.d.ts +0 -213
  107. package/dist/index-ToddX0m3.d.ts.map +0 -1
  108. package/dist/unit-of-work-context-BLNj72v0.js.map +0 -1
  109. package/dist/unit-of-work-context-CbUJGHlL.d.ts.map +0 -1
@@ -0,0 +1,709 @@
1
+ import { z } from "zod";
2
+ import { panic } from "better-result";
3
+ import { v7 } from "uuid";
4
+
5
+ //#region src/core/app-error.ts
6
+ /**
7
+ * The base of every expected failure. A subclass declares its tag and its classification,
8
+ * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from
9
+ * raw throws with `instanceof AppError`; a value that fails it was never judged.
10
+ *
11
+ * A `readonly` field with a literal initializer keeps the literal type, so
12
+ * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.
13
+ */
14
+ var AppError = class extends Error {
15
+ get name() {
16
+ return this._tag;
17
+ }
18
+ };
19
+
20
+ //#endregion
21
+ //#region src/core/authentication.error.ts
22
+ /** A protected operation requires a session that the caller did not provide. */
23
+ var AuthenticationError = class extends AppError {
24
+ _tag = "AuthenticationError";
25
+ classification = "terminal";
26
+ constructor() {
27
+ super("Authentication required");
28
+ }
29
+ };
30
+
31
+ //#endregion
32
+ //#region src/core/rate-limit.error.ts
33
+ /** HTTP 429 with a retry delay in seconds. A null delay means the response supplies no valid duration. */
34
+ var RateLimitError = class extends AppError {
35
+ retryAfter;
36
+ _tag = "RateLimitError";
37
+ classification = "transient";
38
+ status = 429;
39
+ constructor(retryAfter) {
40
+ super("Too many requests");
41
+ this.retryAfter = retryAfter;
42
+ }
43
+ };
44
+
45
+ //#endregion
46
+ //#region src/core/stale-session.error.ts
47
+ /** A presented session cookie no longer resolves; the application owns cleanup and redirect policy. */
48
+ var StaleSessionError = class extends AppError {
49
+ _tag = "StaleSessionError";
50
+ classification = "terminal";
51
+ constructor() {
52
+ super("Session is no longer valid. Sign in again.");
53
+ }
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/core/not-authorized.error.ts
58
+ /** The authenticated caller cannot perform this operation. Ported from Porte's auth.errors.ts. */
59
+ var NotAuthorizedError = class extends AppError {
60
+ _tag = "NotAuthorizedError";
61
+ classification = "terminal";
62
+ constructor() {
63
+ super("Not allowed");
64
+ }
65
+ };
66
+
67
+ //#endregion
68
+ //#region src/core/internal.errors.ts
69
+ /** Safe public replacement for an unknown failure, ported from Porte's internal.errors.ts. */
70
+ var InternalServerError = class extends AppError {
71
+ _tag = "InternalServerError";
72
+ classification = "unknown";
73
+ constructor() {
74
+ super("Something went wrong");
75
+ }
76
+ };
77
+ /** Safe public replacement for a classified transient failure. */
78
+ var ServiceUnavailableError = class extends AppError {
79
+ _tag = "ServiceUnavailableError";
80
+ classification = "transient";
81
+ constructor() {
82
+ super("Try again shortly");
83
+ }
84
+ };
85
+
86
+ //#endregion
87
+ //#region src/core/request.errors.ts
88
+ /** Invalid user input, one entry per invalid value in the RFC 9457 shape. Technical failures use another error. */
89
+ var ValidationError = class ValidationError extends AppError {
90
+ errors;
91
+ _tag = "ValidationError";
92
+ classification = "terminal";
93
+ constructor(errors, message = "The request was not valid") {
94
+ super(message);
95
+ this.errors = errors;
96
+ }
97
+ /** Convert a Zod error. Each issue path becomes a JSON Pointer. */
98
+ static fromZod(error, message) {
99
+ return ValidationError.fromIssues(error.issues, message);
100
+ }
101
+ /** Convert issues from any validator, such as issues TanStack serialized into an error message. */
102
+ static fromIssues(issues, message) {
103
+ return new ValidationError(issues.map((issue) => ({
104
+ detail: issue.message,
105
+ pointer: jsonPointer(issue.path)
106
+ })), message);
107
+ }
108
+ };
109
+ /** The server cannot parse the request syntax. */
110
+ var MalformedRequestError = class extends AppError {
111
+ _tag = "MalformedRequestError";
112
+ classification = "terminal";
113
+ constructor(args) {
114
+ super("The request was malformed", args);
115
+ }
116
+ };
117
+ /** No resource matches the requested HTTP path. */
118
+ var ResourceNotFoundError = class extends AppError {
119
+ _tag = "ResourceNotFoundError";
120
+ classification = "terminal";
121
+ constructor() {
122
+ super("Resource not found");
123
+ }
124
+ };
125
+ /** A WebSocket route received a request without an upgrade. */
126
+ var UpgradeRequiredError = class extends AppError {
127
+ _tag = "UpgradeRequiredError";
128
+ classification = "terminal";
129
+ constructor() {
130
+ super("WebSocket upgrade required");
131
+ }
132
+ };
133
+ /** The requested operation did not answer before its deadline. */
134
+ var RequestTimeoutError = class extends AppError {
135
+ _tag = "RequestTimeoutError";
136
+ classification = "transient";
137
+ constructor() {
138
+ super("The request timed out");
139
+ }
140
+ };
141
+ const readablePathSchema = z.array(z.union([z.string(), z.number()]));
142
+ function jsonPointer(path) {
143
+ const parsed = readablePathSchema.safeParse(path);
144
+ const steps = parsed.success ? parsed.data : [];
145
+ if (steps.length === 0) return "#";
146
+ return `#/${steps.map((step) => String(step).replaceAll("~", "~0").replaceAll("/", "~1")).join("/")}`;
147
+ }
148
+
149
+ //#endregion
150
+ //#region src/core/problem-details.ts
151
+ /**
152
+ * The standard RFC 9457 body for a failed HTTP response.
153
+ * The HTTP response status remains authoritative; extensions may add problem-specific data.
154
+ * @see https://http.dev/problem-details
155
+ */
156
+ const ProblemDetailsSchema = z.looseObject({
157
+ /**
158
+ * Stable URI for the problem type; use `about:blank` when the HTTP status is sufficient.
159
+ * @example "about:blank"
160
+ */
161
+ type: z.string(),
162
+ /**
163
+ * Stable human-readable name for the problem type.
164
+ * @example "Service Unavailable"
165
+ */
166
+ title: z.string(),
167
+ /**
168
+ * Safe human-readable explanation for this occurrence; clients must not parse it.
169
+ * @example "The service is unavailable."
170
+ */
171
+ detail: z.string().optional(),
172
+ /**
173
+ * URI reference for this occurrence; omit it when no correlation resource exists.
174
+ * @example "/problems/occurrences/01K5F6Y7"
175
+ */
176
+ instance: z.string().optional()
177
+ });
178
+ /** One invalid value in a `422` validation problem. */
179
+ const ValidationProblemErrorSchema = z.object({
180
+ /**
181
+ * Safe explanation of why this value is invalid.
182
+ * @example "Must be a positive integer."
183
+ */
184
+ detail: z.string(),
185
+ /**
186
+ * RFC 6901 JSON Pointer fragment for the invalid value.
187
+ * @example "#/age"
188
+ */
189
+ pointer: z.string().regex(/^#(?:\/(?:[^~]|~[01])*)*$/u)
190
+ });
191
+ /** An RFC 9457 validation problem with one or more invalid content values. */
192
+ const ValidationProblemDetailsSchema = ProblemDetailsSchema.extend({ errors: z.array(ValidationProblemErrorSchema).min(1) });
193
+
194
+ //#endregion
195
+ //#region src/core/error-table.ts
196
+ function entriesOf(entries) {
197
+ return entries;
198
+ }
199
+ const ValidationFields = z.object({ errors: z.array(ValidationProblemErrorSchema) });
200
+ const RateLimitFields = z.object({ retryAfter: z.number().nullable() });
201
+ /** The errors every application can throw, with their statuses. `defineErrors` includes them. */
202
+ const sharedErrors = entriesOf({
203
+ MalformedRequestError: {
204
+ error: MalformedRequestError,
205
+ status: 400
206
+ },
207
+ AuthenticationError: {
208
+ error: AuthenticationError,
209
+ status: 401
210
+ },
211
+ StaleSessionError: {
212
+ error: StaleSessionError,
213
+ status: 401
214
+ },
215
+ NotAuthorizedError: {
216
+ error: NotAuthorizedError,
217
+ status: 403
218
+ },
219
+ ResourceNotFoundError: {
220
+ error: ResourceNotFoundError,
221
+ status: 404
222
+ },
223
+ ValidationError: {
224
+ error: ValidationError,
225
+ status: 422,
226
+ fields: ValidationFields
227
+ },
228
+ UpgradeRequiredError: {
229
+ error: UpgradeRequiredError,
230
+ status: 426
231
+ },
232
+ RateLimitError: {
233
+ error: RateLimitError,
234
+ status: 429,
235
+ fields: RateLimitFields
236
+ },
237
+ InternalServerError: {
238
+ error: InternalServerError,
239
+ status: 500
240
+ },
241
+ ServiceUnavailableError: {
242
+ error: ServiceUnavailableError,
243
+ status: 503
244
+ },
245
+ RequestTimeoutError: {
246
+ error: RequestTimeoutError,
247
+ status: 504
248
+ }
249
+ });
250
+ const RemoteErrorSchema = z.object({
251
+ _tag: z.string(),
252
+ message: z.string(),
253
+ remote: z.literal(true)
254
+ });
255
+ function match(byTag, cause) {
256
+ if (cause instanceof AppError) {
257
+ const entry = byTag.get(cause._tag);
258
+ if (entry === void 0 || !(cause instanceof entry.error)) return null;
259
+ return {
260
+ tag: cause._tag,
261
+ entry,
262
+ error: cause
263
+ };
264
+ }
265
+ if (!(cause instanceof Error)) return null;
266
+ const remote = RemoteErrorSchema.safeParse(cause);
267
+ if (!remote.success) return null;
268
+ const entry = byTag.get(remote.data._tag);
269
+ return entry === void 0 ? null : {
270
+ tag: remote.data._tag,
271
+ entry,
272
+ error: cause
273
+ };
274
+ }
275
+ /**
276
+ * Build the application's error table. The shared entries are always included;
277
+ * an entry with the same key replaces the shared one.
278
+ */
279
+ function defineErrors(entries) {
280
+ const merged = {
281
+ ...sharedErrors,
282
+ ...entries
283
+ };
284
+ const byTag = new Map(Object.entries(merged));
285
+ const resolve = (cause) => {
286
+ const found = match(byTag, cause);
287
+ if (found === null) return null;
288
+ const fields = found.entry.fields?.safeParse(found.error);
289
+ if (fields !== void 0 && !fields.success) return null;
290
+ const payload = {
291
+ _tag: found.tag,
292
+ message: found.error.message,
293
+ ...fields?.data
294
+ };
295
+ return {
296
+ status: found.entry.status,
297
+ payload
298
+ };
299
+ };
300
+ const resolveShared = (error) => resolve(error) ?? panic(`Error table cannot resolve shared error ${error._tag}`);
301
+ const generic = resolveShared(new InternalServerError());
302
+ const unavailable = resolveShared(new ServiceUnavailableError());
303
+ const [first, ...rest] = [...byTag].map(([tag, entry]) => z.strictObject({
304
+ _tag: z.literal(tag),
305
+ message: z.string(),
306
+ ...entry.fields?.shape
307
+ }));
308
+ if (first === void 0) return panic("Error table has no entries");
309
+ const payloadSchema = z.discriminatedUnion("_tag", [first, ...rest]).pipe(z.custom());
310
+ const parse = (cause) => {
311
+ const parsed = payloadSchema.safeParse(cause);
312
+ return parsed.success ? parsed.data : null;
313
+ };
314
+ return {
315
+ entries: merged,
316
+ payloadSchema,
317
+ generic: generic.payload,
318
+ parse,
319
+ is(cause, tag) {
320
+ const parsed = parse(cause);
321
+ return parsed !== null && parsed._tag === tag;
322
+ },
323
+ resolve,
324
+ fallback: (cause) => cause instanceof AppError && cause.classification === "transient" ? unavailable : generic
325
+ };
326
+ }
327
+
328
+ //#endregion
329
+ //#region src/core/database.error.ts
330
+ /** Classification describes the failure; callers must separately establish whether repetition is safe. */
331
+ var DatabaseError = class extends AppError {
332
+ operation;
333
+ classification;
334
+ details;
335
+ _tag = "DatabaseError";
336
+ constructor(operation, classification, details, options) {
337
+ super(`Database operation failed: ${operation}`, options);
338
+ this.operation = operation;
339
+ this.classification = classification;
340
+ this.details = details;
341
+ }
342
+ };
343
+
344
+ //#endregion
345
+ //#region src/core/defects.ts
346
+ /**
347
+ * Mark a line the types say cannot run. A union member without a branch stops compilation here.
348
+ *
349
+ * @throws Panic when a value outside the union arrives at runtime.
350
+ */
351
+ function unreachable(value) {
352
+ return panic(`Unreachable: ${String(value)}`);
353
+ }
354
+ /**
355
+ * Mark a body that is not written yet. A defect, not an expected failure.
356
+ *
357
+ * @param what - The behavior the body will provide, such as `invoice export`.
358
+ * @throws Panic always.
359
+ */
360
+ function notImplemented(what) {
361
+ return panic(`Not implemented: ${what}`);
362
+ }
363
+
364
+ //#endregion
365
+ //#region src/core/identity.ts
366
+ /**
367
+ * Define an id kind the application mints: `export const CallId = defineId('CallId')`.
368
+ * An id another system mints, such as a provider's call id, stays a plain branded schema.
369
+ */
370
+ function defineId(brand) {
371
+ return {
372
+ schema: z.uuidv7({ error: `Invalid ${brand}` }).brand(),
373
+ create: () => v7()
374
+ };
375
+ }
376
+
377
+ //#endregion
378
+ //#region src/core/define-messages.ts
379
+ const MessageIdSchema = z.string().min(1);
380
+ /** One full message schema: the routing fields joined to the payload. */
381
+ function messageSchema(type, name, payload) {
382
+ return (type === "query" ? z.object({
383
+ type: z.literal(type),
384
+ name: z.literal(name)
385
+ }) : z.object({
386
+ type: z.literal(type),
387
+ name: z.literal(name),
388
+ id: MessageIdSchema
389
+ })).and(payload);
390
+ }
391
+ /** A union over every message of one kind. Empty when the application has none of that kind. */
392
+ function unionOf(type, schemas) {
393
+ return z.union(Object.entries(schemas).map(([name, payload]) => messageSchema(type, name, payload)));
394
+ }
395
+ /**
396
+ * Define an application's messages once. The key is the name; the factories add the routing
397
+ * fields `type`, `name`, and `id`. A payload that declares one of them is a compile error.
398
+ */
399
+ function defineMessages(definition) {
400
+ const commandSchema = unionOf("command", definition.commands);
401
+ const eventSchema = unionOf("event", definition.events);
402
+ const querySchema = unionOf("query", definition.queries);
403
+ return {
404
+ definition,
405
+ createCommand: (name, payload, id = v7()) => ({
406
+ ...payload,
407
+ type: "command",
408
+ name,
409
+ id
410
+ }),
411
+ createEvent: (name, payload, id = v7()) => ({
412
+ ...payload,
413
+ type: "event",
414
+ name,
415
+ id
416
+ }),
417
+ createQuery: (name, payload) => ({
418
+ ...payload,
419
+ type: "query",
420
+ name
421
+ }),
422
+ commandSchema: commandSchema.pipe(z.custom()),
423
+ eventSchema: eventSchema.pipe(z.custom()),
424
+ querySchema: querySchema.pipe(z.custom()),
425
+ queueSchema: z.union([commandSchema, eventSchema]).pipe(z.custom())
426
+ };
427
+ }
428
+
429
+ //#endregion
430
+ //#region src/core/entity.ts
431
+ /**
432
+ * The base of an aggregate: its identity, the events it raised, and the plain data a repository
433
+ * stores. The subclass keeps its constructor private and declares `static restore(data: Data)`,
434
+ * the one door a repository rebuilds it through. A repository drains the events after `save`.
435
+ */
436
+ var Entity = class {
437
+ events = [];
438
+ /** Record one event with the state change that caused it. The unit of work commits both. */
439
+ addEvent(event) {
440
+ this.events.push(event);
441
+ }
442
+ /** A copy of the events raised since the last `clearEvents`. */
443
+ collectEvents() {
444
+ return [...this.events];
445
+ }
446
+ /** Forget the raised events once the boundary has taken them. */
447
+ clearEvents() {
448
+ this.events = [];
449
+ }
450
+ };
451
+
452
+ //#endregion
453
+ //#region src/core/failure-classification.ts
454
+ /** Decide whether one retry owner may repeat a failed operation. */
455
+ function shouldRetryFailure(args) {
456
+ if (!args.repeatSafe) return false;
457
+ if (args.classification === "transient") return true;
458
+ if (args.classification === "terminal") return false;
459
+ return args.owner === "durable";
460
+ }
461
+
462
+ //#endregion
463
+ //#region src/core/transport-classification.ts
464
+ /**
465
+ * Messages that the platform-neutral transports raise for a failure that may pass.
466
+ *
467
+ * A boundary that knows its own runtime adds its own patterns before these.
468
+ */
469
+ const TRANSIENT_TRANSPORT_PATTERNS = [
470
+ /network/,
471
+ /fetch failed/,
472
+ /timeout/,
473
+ /timed?\s*out/,
474
+ /connection.*(lost|reset|refused|closed|aborted)/,
475
+ /econnreset/,
476
+ /econnrefused/,
477
+ /etimedout/,
478
+ /eai_again/
479
+ ];
480
+ /** Cancellation is a decision, not a failure to repeat. */
481
+ function isAbortError(cause) {
482
+ return cause instanceof Error && cause.name === "AbortError";
483
+ }
484
+ /** Match known transient transport messages while excluding explicit cancellation. */
485
+ function isTransientTransportError(cause) {
486
+ if (!(cause instanceof Error) || isAbortError(cause)) return false;
487
+ const message = cause.message.toLowerCase();
488
+ return TRANSIENT_TRANSPORT_PATTERNS.some((pattern) => pattern.test(message));
489
+ }
490
+
491
+ //#endregion
492
+ //#region src/core/logger.ts
493
+ /**
494
+ * The supported log severity levels, in ascending order.
495
+ *
496
+ * A const object, not an enum, so a parsed environment value typed `'INFO'` is a `LogLevel`.
497
+ */
498
+ const LogLevel = {
499
+ DEBUG: "DEBUG",
500
+ INFO: "INFO",
501
+ WARN: "WARN",
502
+ ERROR: "ERROR"
503
+ };
504
+ const DEFAULT_SETTINGS = {
505
+ level: LogLevel.INFO,
506
+ format: "json"
507
+ };
508
+ let settings = DEFAULT_SETTINGS;
509
+ /**
510
+ * Set application settings, including for existing loggers. Per-logger overrides take priority.
511
+ * Call at startup, never per request. An omitted field resets to INFO and JSON output.
512
+ */
513
+ function configureLogger(config) {
514
+ settings = {
515
+ level: config.level ?? DEFAULT_SETTINGS.level,
516
+ format: config.format ?? DEFAULT_SETTINGS.format
517
+ };
518
+ }
519
+ let errorHook = null;
520
+ /**
521
+ * Register the function that receives each logged error.
522
+ *
523
+ * Set once at the process entry point. A later call replaces the earlier hook.
524
+ */
525
+ function setLoggerErrorHook(fn) {
526
+ errorHook = fn;
527
+ }
528
+ const CONSOLE_METHOD = {
529
+ [LogLevel.DEBUG]: "debug",
530
+ [LogLevel.INFO]: "info",
531
+ [LogLevel.WARN]: "warn",
532
+ [LogLevel.ERROR]: "error"
533
+ };
534
+ const ESC = String.fromCharCode(27);
535
+ const ANSI_RESET = `${ESC}[0m`;
536
+ const ANSI_GRAY = `${ESC}[90m`;
537
+ const ANSI_BLUE = `${ESC}[34m`;
538
+ const LEVEL_ANSI = {
539
+ DEBUG: `${ESC}[2;36m`,
540
+ INFO: ANSI_BLUE,
541
+ WARN: `${ESC}[33m`,
542
+ ERROR: `${ESC}[1;31m`
543
+ };
544
+ function prettyLine(entry) {
545
+ const level = `[${entry.level}]`;
546
+ const module = `[${entry.module}]`;
547
+ if ("window" in globalThis) return `${entry.timestamp} ${level} ${module} ${entry.message}`;
548
+ return `${`${ANSI_GRAY}${entry.timestamp}${ANSI_RESET}`} ${`${LEVEL_ANSI[entry.level]}${level}${ANSI_RESET}`} ${`${ANSI_BLUE}${module}${ANSI_RESET}`} ${entry.message}`;
549
+ }
550
+ /**
551
+ * JSON format writes the entry object. Pretty format writes one line, then the details,
552
+ * the error, and the stack as separate console arguments.
553
+ */
554
+ const consoleSink = (entry) => {
555
+ const write = console[CONSOLE_METHOD[entry.level]];
556
+ if (settings.format === "json") {
557
+ write(entry);
558
+ return;
559
+ }
560
+ const line = prettyLine(entry);
561
+ const fields = entry.userId === void 0 ? entry.details : {
562
+ ...entry.details,
563
+ userId: entry.userId
564
+ };
565
+ const details = Object.keys(fields).length === 0 ? [] : [fields];
566
+ if (entry.error === void 0) {
567
+ write(line, ...details);
568
+ return;
569
+ }
570
+ const { stack, ...error } = entry.error;
571
+ if (stack === void 0) write(line, ...details, error);
572
+ else write(line, ...details, error, `\n${stack}`);
573
+ };
574
+ let logSink = consoleSink;
575
+ /**
576
+ * Send every log entry somewhere other than `console`.
577
+ *
578
+ * Set once at the process entry point, never per module. A logger is created
579
+ * by name and nothing else, so its destination is a fact about the process.
580
+ */
581
+ function setLogSink(fn) {
582
+ logSink = fn;
583
+ }
584
+ const LOG_LEVELS = Object.values(LogLevel);
585
+ const MAX_ERROR_DEPTH = 3;
586
+ /**
587
+ * Diagnostics worth keeping off an error, named one by one.
588
+ *
589
+ * An allowlist rather than every own property: an error raised by a library we
590
+ * do not control may hang a request or a user payload off itself, and a log is
591
+ * the wrong place to discover that. `_tag` and `classification` are what every `AppError`
592
+ * declares. `remote` and the three flags after it are the ones workerd sets itself.
593
+ */
594
+ const KEPT_ERROR_FIELDS = [
595
+ "_tag",
596
+ "classification",
597
+ "code",
598
+ "operation",
599
+ "status",
600
+ "statusCode",
601
+ "remote",
602
+ "retryable",
603
+ "overloaded",
604
+ "durableObjectReset"
605
+ ];
606
+ const serializeError = (error, depth = 0) => {
607
+ if (depth > MAX_ERROR_DEPTH) return {
608
+ name: "Error",
609
+ message: "[error nesting truncated]"
610
+ };
611
+ const carrier = error;
612
+ const kept = KEPT_ERROR_FIELDS.filter((key) => carrier[key] !== void 0);
613
+ const serialized = {
614
+ name: error.name,
615
+ message: error.message
616
+ };
617
+ if (error.stack !== void 0) serialized.stack = error.stack;
618
+ if (kept.length > 0) serialized.fields = Object.fromEntries(kept.map((key) => [key, carrier[key]]));
619
+ if (error.cause instanceof Error) serialized.cause = serializeError(error.cause, depth + 1);
620
+ else if (error.cause !== void 0) serialized.cause = {
621
+ name: "Error",
622
+ message: "[non-error cause]"
623
+ };
624
+ if (error instanceof AggregateError) serialized.errors = error.errors.map((failure) => failure instanceof Error ? serializeError(failure, depth + 1) : {
625
+ name: "NonError",
626
+ message: "[non-error aggregate member]"
627
+ });
628
+ return serialized;
629
+ };
630
+ /** Write module-scoped logs with application defaults and optional overrides. */
631
+ var Logger = class {
632
+ module;
633
+ config;
634
+ /** Create a logger for one module. */
635
+ constructor(module, overrideConfig) {
636
+ this.module = module;
637
+ this.config = { ...overrideConfig };
638
+ }
639
+ log(level, message, details, error, userId) {
640
+ const threshold = this.config.level ?? settings.level;
641
+ if (threshold === "OFF") return;
642
+ if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(threshold)) return;
643
+ let entry = {
644
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
645
+ level,
646
+ module: this.module,
647
+ message,
648
+ details
649
+ };
650
+ if (userId !== void 0) entry = {
651
+ ...entry,
652
+ userId
653
+ };
654
+ logSink(error === void 0 ? entry : {
655
+ ...entry,
656
+ error
657
+ });
658
+ }
659
+ /** Write a debug log. */
660
+ debug(message, details = {}) {
661
+ this.log(LogLevel.DEBUG, message, details);
662
+ }
663
+ /** Write an information log. */
664
+ info(message, details = {}) {
665
+ this.log(LogLevel.INFO, message, details);
666
+ }
667
+ /** Write a warning log. */
668
+ warn(message, details = {}) {
669
+ this.log(LogLevel.WARN, message, details);
670
+ }
671
+ /**
672
+ * Write an error log and send the error to the configured hook.
673
+ *
674
+ * The details say which call this was, and the error says what went wrong
675
+ * inside it. Both the entry and the error hook receive the supplied user ID.
676
+ */
677
+ error(message, context = {}) {
678
+ const details = context.details ?? {};
679
+ const thrown = context.error;
680
+ let error;
681
+ if (thrown instanceof Error) error = serializeError(thrown);
682
+ else if (thrown !== void 0) {
683
+ let json;
684
+ try {
685
+ json = JSON.stringify(thrown);
686
+ } catch {
687
+ json = "[non-serializable error]";
688
+ }
689
+ error = {
690
+ name: "NonError",
691
+ message: json
692
+ };
693
+ }
694
+ this.log(LogLevel.ERROR, message, details, error, context.userId);
695
+ if (errorHook !== null && thrown !== void 0) errorHook({
696
+ error: thrown,
697
+ distinctId: context.userId,
698
+ context: details
699
+ });
700
+ }
701
+ };
702
+ /** Create a logger for one module. */
703
+ function createLogger(module, config) {
704
+ return new Logger(module, config);
705
+ }
706
+
707
+ //#endregion
708
+ export { StaleSessionError as A, RequestTimeoutError as C, InternalServerError as D, ValidationError as E, AuthenticationError as M, AppError as N, ServiceUnavailableError as O, MalformedRequestError as S, UpgradeRequiredError as T, defineErrors as _, createLogger as a, ValidationProblemDetailsSchema as b, isAbortError as c, Entity as d, defineMessages as f, DatabaseError as g, unreachable as h, consoleSink as i, RateLimitError as j, NotAuthorizedError as k, isTransientTransportError as l, notImplemented as m, Logger as n, setLogSink as o, defineId as p, configureLogger as r, setLoggerErrorHook as s, LogLevel as t, shouldRetryFailure as u, sharedErrors as v, ResourceNotFoundError as w, ValidationProblemErrorSchema as x, ProblemDetailsSchema as y };
709
+ //# sourceMappingURL=core-Cx5SeyKV.js.map