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
@@ -1,46 +1,17 @@
1
- import { D as AppError } from "./index-ToddX0m3.js";
2
- //#region src/application/messages.d.ts
3
- /**
4
- * The identity of a command or event. Receipts and the outbox are keyed by it.
5
- *
6
- * Internal messages use UUID v7, so receipts sort by creation. External messages use the
7
- * provider's own key, `stripe:event:evt_123`, so a redelivered webhook is a duplicate by
8
- * construction. The app parses and generates ids; this package only carries them.
9
- */
10
- type MessageId = string;
11
- /** An action to perform. One handler, returns a value. The product adds its payload. */
12
- type Command<Name extends string = string> = {
13
- readonly type: 'command';
14
- readonly name: Name;
15
- readonly id: MessageId;
16
- };
17
- /** A request for data. One handler, returns a value. No id: nothing claims a read. */
18
- type Query<Name extends string = string> = {
19
- readonly type: 'query';
20
- readonly name: Name;
21
- };
22
- /** A fact that happened. Zero or more subscribers, returns nothing. The product adds its payload. */
23
- type Event<Name extends string = string> = {
24
- readonly type: 'event';
25
- readonly name: Name;
26
- readonly id: MessageId;
27
- };
28
- /** The routing fields the bus reads. `type` selects the table, `name` selects the slot. */
29
- type Message = Command | Event | Query;
30
- //#endregion
1
+ import { F as DomainQuery, I as MessageId, M as DomainCommand, N as DomainEvent, P as DomainMessage, vt as AppError } from "./index-BStnggQO.js";
31
2
  //#region src/application/handlers.d.ts
32
3
  /**
33
4
  * Handles one command with the dependency container and returns the caller's value.
34
5
  * A handler that writes inside a transaction opens the unit of work itself. Failures throw.
35
6
  */
36
- type CommandHandler<TCommand extends Command, Deps, Value> = (command: TCommand, deps: Deps) => Promise<Value>;
7
+ type CommandHandler<TCommand extends DomainCommand, Deps, Value> = (command: TCommand, deps: Deps) => Promise<Value>;
37
8
  /**
38
9
  * Handles one query with the read-only view of the container.
39
10
  * The view is a type over the same object, so a query cannot name a write capability.
40
11
  */
41
- type QueryHandler<TQuery extends Query, QueryDeps, Value> = (query: TQuery, deps: QueryDeps) => Promise<Value>;
12
+ type QueryHandler<TQuery extends DomainQuery, QueryDeps, Value> = (query: TQuery, deps: QueryDeps) => Promise<Value>;
42
13
  /** Completes one subscriber's work for an event. Failures throw. */
43
- type EventHandler<TEvent extends Event, Deps> = (event: TEvent, deps: Deps) => Promise<void>;
14
+ type EventHandler<TEvent extends DomainEvent, Deps> = (event: TEvent, deps: Deps) => Promise<void>;
44
15
  //#endregion
45
16
  //#region src/application/message-store.d.ts
46
17
  /**
@@ -51,34 +22,34 @@ interface IMessageStore {
51
22
  /** Record this message in the transaction; reject an existing record with `MessageAlreadyProcessedError`. */
52
23
  claim(messageId: MessageId): Promise<void>;
53
24
  /** Write the events to the outbox, inside the same boundary as the state change. */
54
- persistEvents(events: ReadonlyArray<Event>): Promise<void>;
25
+ persistEvents(events: ReadonlyArray<DomainEvent>): Promise<void>;
55
26
  }
56
27
  //#endregion
57
28
  //#region src/application/registry.d.ts
58
29
  /** One slot per command. `unknown` keeps the slot covariant; `MessageResult` recovers the value. */
59
- type CommandRegistry<TCommand extends Command, Deps> = { readonly [M in TCommand as M['name']]: CommandHandler<M, Deps, unknown>; };
30
+ type CommandRegistry<TCommand extends DomainCommand, Deps> = { readonly [M in TCommand as M['name']]: CommandHandler<M, Deps, unknown>; };
60
31
  /** One slot per query, typed with the read-only view of the container. */
61
- type QueryRegistry<TQuery extends Query, QueryDeps> = { readonly [M in TQuery as M['name']]: QueryHandler<M, QueryDeps, unknown>; };
32
+ type QueryRegistry<TQuery extends DomainQuery, QueryDeps> = { readonly [M in TQuery as M['name']]: QueryHandler<M, QueryDeps, unknown>; };
62
33
  /**
63
34
  * Zero or more subscribers per event. Annotate the object with this type rather than
64
35
  * `satisfies`, so an event with no subscribers is still a message the bus accepts.
65
36
  */
66
- type EventRegistry<TEvent extends Event, Deps> = { readonly [M in TEvent as M['name']]?: ReadonlyArray<EventHandler<M, Deps>>; };
37
+ type EventRegistry<TEvent extends DomainEvent, Deps> = { readonly [M in TEvent as M['name']]?: ReadonlyArray<EventHandler<M, Deps>>; };
67
38
  /**
68
39
  * The app's three tables. `satisfies MessageRegistry<AppMessage, AppDeps, AppQueryDeps>`
69
40
  * makes a missing handler a compile error. `Deps extends QueryDeps` is checked here, the one
70
41
  * place both types meet: the read view must be a subset of the container.
71
42
  */
72
- type MessageRegistry<TMessage extends Message, Deps extends QueryDeps, QueryDeps> = {
73
- readonly commands: CommandRegistry<Extract<TMessage, Command>, Deps>;
74
- readonly queries: QueryRegistry<Extract<TMessage, Query>, QueryDeps>;
75
- readonly events: EventRegistry<Extract<TMessage, Event>, Deps>;
43
+ type MessageRegistry<TMessage extends DomainMessage, Deps extends QueryDeps, QueryDeps> = {
44
+ readonly commands: CommandRegistry<Extract<TMessage, DomainCommand>, Deps>;
45
+ readonly queries: QueryRegistry<Extract<TMessage, DomainQuery>, QueryDeps>;
46
+ readonly events: EventRegistry<Extract<TMessage, DomainEvent>, Deps>;
76
47
  };
77
48
  type Slot<Deps> = {
78
- handle(message: Message, deps: Deps): Promise<unknown>;
49
+ handle(message: DomainMessage, deps: Deps): Promise<unknown>;
79
50
  }['handle'];
80
51
  type Subscription<Deps> = {
81
- handle(event: Event, deps: Deps): Promise<void>;
52
+ handle(event: DomainEvent, deps: Deps): Promise<void>;
82
53
  }['handle'];
83
54
  /**
84
55
  * The registry as the bus routes it: each table keyed by name. The app's names are unknown
@@ -95,12 +66,12 @@ type SubscriptionMessage<TSlots> = NonNullable<TSlots[keyof TSlots]> extends Rea
95
66
  type RegistryMessage<TRegistry extends Handlers<never>> = SlotMessage<TRegistry['commands']> | SlotMessage<TRegistry['queries']> | SubscriptionMessage<TRegistry['events']>;
96
67
  type SlotValue<TSlots, TName extends string> = TName extends keyof TSlots ? Awaited<ReturnType<Extract<TSlots[TName], Slot<never>>>> : never;
97
68
  /** The value `bus.handle(message)` resolves to: the slot's own return type, or void for an event. */
98
- type MessageResult<TMessage extends Message, TRegistry extends Handlers<never>> = TMessage extends Command ? SlotValue<TRegistry['commands'], TMessage['name']> : TMessage extends Query ? SlotValue<TRegistry['queries'], TMessage['name']> : void;
69
+ type MessageResult<TMessage extends DomainMessage, TRegistry extends Handlers<never>> = TMessage extends DomainCommand ? SlotValue<TRegistry['commands'], TMessage['name']> : TMessage extends DomainQuery ? SlotValue<TRegistry['queries'], TMessage['name']> : void;
99
70
  //#endregion
100
71
  //#region src/application/message-bus.d.ts
101
72
  /** The port an entrypoint dispatches through. `AppDeps` names this as `IMessageBus<typeof registry>`. */
102
73
  interface IMessageBus<TRegistry extends Handlers<never>> {
103
- handle<TMessage extends Message & RegistryMessage<TRegistry>>(message: TMessage): Promise<MessageResult<TMessage, TRegistry>>;
74
+ handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(message: TMessage): Promise<MessageResult<TMessage, TRegistry>>;
104
75
  }
105
76
  /**
106
77
  * Routes one message to its slot. The bus opens no transaction and keeps no outbox:
@@ -111,7 +82,7 @@ declare class MessageBus<Deps, TRegistry extends Handlers<Deps>> implements IMes
111
82
  private readonly registry;
112
83
  constructor(deps: Deps, registry: TRegistry);
113
84
  /** Resolves to the handler's own value for a command or query, and to void for an event. */
114
- handle<TMessage extends Message & RegistryMessage<TRegistry>>(message: TMessage): Promise<MessageResult<TMessage, TRegistry>>;
85
+ handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(message: TMessage): Promise<MessageResult<TMessage, TRegistry>>;
115
86
  private dispatch;
116
87
  private handleCommand;
117
88
  private handleQuery;
@@ -146,8 +117,8 @@ interface ITransaction<Tx> {
146
117
  //#region src/application/event-collector.d.ts
147
118
  /** Records events in the current unit of work; the unit of work collects a snapshot for outbox persistence. */
148
119
  interface IEventCollector {
149
- emit(event: Event): void;
150
- collect(): ReadonlyArray<Event>;
120
+ emit(event: DomainEvent): void;
121
+ collect(): ReadonlyArray<DomainEvent>;
151
122
  }
152
123
  //#endregion
153
124
  //#region src/application/unit-of-work.d.ts
@@ -196,5 +167,5 @@ declare class UnitOfWorkAlreadyActiveError extends AppError {
196
167
  constructor();
197
168
  }
198
169
  //#endregion
199
- export { Event as C, Query as E, Command as S, MessageId as T, RegistryMessage as _, UnitOfWorkDeps as a, EventHandler as b, IOutboxRelay as c, CommandRegistry as d, EventRegistry as f, QueryRegistry as g, MessageResult as h, UnitOfWork as i, IMessageBus as l, MessageRegistry as m, MessageAlreadyProcessedError as n, IEventCollector as o, Handlers as p, IUnitOfWork as r, ITransaction as s, UnitOfWorkAlreadyActiveError as t, MessageBus as u, IMessageStore as v, Message as w, QueryHandler as x, CommandHandler as y };
200
- //# sourceMappingURL=index-BN_tjxME.d.ts.map
170
+ export { RegistryMessage as _, UnitOfWorkDeps as a, EventHandler as b, IOutboxRelay as c, CommandRegistry as d, EventRegistry as f, QueryRegistry as g, MessageResult as h, UnitOfWork as i, IMessageBus as l, MessageRegistry as m, MessageAlreadyProcessedError as n, IEventCollector as o, Handlers as p, IUnitOfWork as r, ITransaction as s, UnitOfWorkAlreadyActiveError as t, MessageBus as u, IMessageStore as v, QueryHandler as x, CommandHandler as y };
171
+ //# sourceMappingURL=index-DWIRrJMP.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-DWIRrJMP.d.ts","names":[],"sources":["../src/application/handlers.ts","../src/application/message-store.ts","../src/application/registry.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/transaction.ts","../src/application/event-collector.ts","../src/application/unit-of-work.ts","../src/application/message-already-processed.error.ts","../src/application/unit-of-work.errors.ts"],"mappings":";;;;;;KAMY,eAAe,iBAAiB,eAAe,MAAM,UAC/D,SAAS,UACT,MAAM,SACH,QAAQ;;;;;KAMD,aAAa,eAAe,aAAa,WAAW,UAC9D,OAAO,QACP,MAAM,cACH,QAAQ;;KAGD,aAAa,eAAe,aAAa,SACnD,OAAO,QACP,MAAM,SACH;;;;;;;UClBY;;EAEf,MAAM,WAAW,YAAY;;EAE7B,cAAc,QAAQ,cAAc,eAAe;;;;;KCLzC,gBAAgB,iBAAiB,eAAe,oBAChD,KAAK,YAAY,YAAY,eAAe,GAAG;;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f;;;;;;;;;UCDe,aAAa;EAC5B,YAAY,GAAG,OAAO,IAAI,OAAO,QAAQ,KAAK,QAAQ;;;;;UCHvC;EACf,KAAK,OAAO;EACZ,WAAW,cAAc;;;;;;;;;UCQV,YAAY;EAC3B,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;KAGhE,eAAe,IAAI;WACpB,aAAa,aAAa;;WAE1B,eAAe,IAAI,OAAO;;WAE1B,qBAAqB,IAAI,OAAO;WAChC,gBAAgB;WAChB,OAAO;;;cAIL,WAAW,IAAI,kBAAkB,YAAY;mBAC3B;EAA7B,YAA6B,MAAM,eAAe,IAAI;EAEhD,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;;;;cC5BrE,qCAAqC;WAKrC,WAAW;WAJb;WACA;EAET,YACW,WAAW,WACpB;aAAqB;;;SAMhB,KAAK,gBAAgB,WAAW,YAAY;;;;;cCZxC,qCAAqC;WACvC;WACA;EAET"}
@@ -1,6 +1,6 @@
1
- import { C as Event, T as MessageId, s as ITransaction, v as IMessageStore } from "./index-BN_tjxME.js";
2
- import { E as DatabaseFailure, T as DatabaseError } from "./index-ToddX0m3.js";
3
- import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-CbUJGHlL.js";
1
+ import { G as DatabaseFailure, I as MessageId, N as DomainEvent, W as DatabaseError } from "./index-BStnggQO.js";
2
+ import { s as ITransaction, v as IMessageStore } from "./index-DWIRrJMP.js";
3
+ import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-CPz9rdSS.js";
4
4
  import { ExtractTablesWithRelations } from "drizzle-orm";
5
5
  import { PostgresJsDatabase, PostgresJsTransaction, drizzle } from "drizzle-orm/postgres-js";
6
6
  //#region src/infrastructure/postgres/postgres-database-types.d.ts
@@ -20,7 +20,7 @@ type PostgresTx<Schema extends DrizzleSchema> = {
20
20
  //#region src/infrastructure/postgres/base-postgres-repository.d.ts
21
21
  /** A domain aggregate that accumulates events for the unit of work to drain. */
22
22
  interface AggregateEvents {
23
- collectEvents(): ReadonlyArray<Event>;
23
+ collectEvents(): ReadonlyArray<DomainEvent>;
24
24
  clearEvents(): void;
25
25
  }
26
26
  /** Shared plumbing for a repository that writes inside a Postgres unit of work. */
@@ -39,7 +39,7 @@ export declare class PostgresMessageStore<Schema extends DrizzleSchema> implemen
39
39
  private readonly db;
40
40
  constructor(db: PostgresDbTransaction<Schema>);
41
41
  claim(messageId: MessageId): Promise<void>;
42
- persistEvents(events: ReadonlyArray<Event>): Promise<void>;
42
+ persistEvents(events: ReadonlyArray<DomainEvent>): Promise<void>;
43
43
  }
44
44
  //#endregion
45
45
  //#region src/infrastructure/postgres/postgres-schema.d.ts
@@ -112,7 +112,7 @@ export declare const messageOutbox: import("drizzle-orm/pg-core").PgTableWithCol
112
112
  tableName: "message_outbox";
113
113
  dataType: "json";
114
114
  columnType: "PgJsonb";
115
- data: Event;
115
+ data: DomainEvent;
116
116
  driverParam: unknown;
117
117
  notNull: true;
118
118
  hasDefault: false;
@@ -124,7 +124,7 @@ export declare const messageOutbox: import("drizzle-orm/pg-core").PgTableWithCol
124
124
  identity: undefined;
125
125
  generated: undefined;
126
126
  }, {}, {
127
- $type: Event;
127
+ $type: DomainEvent;
128
128
  }>;
129
129
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
130
130
  name: "created_at";
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.d.ts","names":[],"sources":["../src/infrastructure/postgres/postgres-database-types.ts","../src/infrastructure/postgres/base-postgres-repository.ts","../src/infrastructure/postgres/postgres-message-store.ts","../src/infrastructure/postgres/postgres-schema.ts","../src/infrastructure/postgres/postgres-transaction.ts","../src/infrastructure/postgres/postgres-database-execution.ts","../src/infrastructure/postgres/classify-postgres-error.ts"],"mappings":";;;;;;;KAMY,qBAAqB,kBAAkB;;KAGvC,WAAW,eAAe,iBAAiB,mBAAmB;;KAG9D,eAAe,eAAe,iBAAiB,KACzD,WAAW;;KAKD,sBAAsB,eAAe,iBAAiB,sBAChE,QACA,2BAA2B;;KAIjB,WAAW,eAAe;WAC3B,IAAI,sBAAsB;;;;;UCjBpB;EACf,iBAAiB,cAAc;EAC/B;;;8BAIoB,uBAAuB,eAAe;qBAC3B,IAAI,sBAAsB;EAAzD,YAA+B,IAAI,sBAAsB;;YAG/C,KAAK,GAAG,mBAAmB,aAAa,YAAY,KAAK,QAAQ;;YAKjE,eAAe,WAAW;;;;;qBCXzB,qBAAqB,eAAe,0BAA0B;mBAC5C;EAA7B,YAA6B,IAAI,sBAAsB;EAEjD,MAAM,WAAW,YAAY;EAU7B,cAAc,QAAQ,cAAc,SAAS;;;;;qBCnBxC,iDAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;YAAjB;;;;;;;;;;;;;;;;qBAMA,6CAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBCDb,oBAAoB,eAAe,0BAA0B,aACxE,WAAW;mBAEkB;EAA7B,YAA6B,IAAI,WAAW;EAE5C,YAAY,GAAG,OAAO,IAAI,WAAW,YAAY,QAAQ,KAAK,QAAQ;;;;;wBCblD,gBAAgB,GACpC,mBACA,YAAY,YAAY,KACvB,QAAQ;;;;wBC2BK,sBACd,gBACA,oBACC"}
1
+ {"version":3,"file":"postgres.d.ts","names":[],"sources":["../src/infrastructure/postgres/postgres-database-types.ts","../src/infrastructure/postgres/base-postgres-repository.ts","../src/infrastructure/postgres/postgres-message-store.ts","../src/infrastructure/postgres/postgres-schema.ts","../src/infrastructure/postgres/postgres-transaction.ts","../src/infrastructure/postgres/postgres-database-execution.ts","../src/infrastructure/postgres/classify-postgres-error.ts"],"mappings":";;;;;;;KAMY,qBAAqB,kBAAkB;;KAGvC,WAAW,eAAe,iBAAiB,mBAAmB;;KAG9D,eAAe,eAAe,iBAAiB,KACzD,WAAW;;KAKD,sBAAsB,eAAe,iBAAiB,sBAChE,QACA,2BAA2B;;KAIjB,WAAW,eAAe;WAC3B,IAAI,sBAAsB;;;;;UCjBpB;EACf,iBAAiB,cAAc;EAC/B;;;8BAIoB,uBAAuB,eAAe;qBAC3B,IAAI,sBAAsB;EAAzD,YAA+B,IAAI,sBAAsB;;YAG/C,KAAK,GAAG,mBAAmB,aAAa,YAAY,KAAK,QAAQ;;YAKjE,eAAe,WAAW;;;;;qBCfzB,qBAAqB,eAAe,0BAA0B;mBAC5C;EAA7B,YAA6B,IAAI,sBAAsB;EAEjD,MAAM,WAAW,YAAY;EAU7B,cAAc,QAAQ,cAAc,eAAe;;;;;qBCf9C,iDAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;YAAjB;;;;;;;;;;;;;;;;qBAMA,6CAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBCDb,oBAAoB,eAAe,0BAA0B,aACxE,WAAW;mBAEkB;EAA7B,YAA6B,IAAI,WAAW;EAE5C,YAAY,GAAG,OAAO,IAAI,WAAW,YAAY,QAAQ,KAAK,QAAQ;;;;;wBCblD,gBAAgB,GACpC,mBACA,YAAY,YAAY,KACvB,QAAQ;;;;wBC2BK,sBACd,gBACA,oBACC"}
package/dist/postgres.js CHANGED
@@ -1,6 +1,6 @@
1
- import { m as AppError, p as DatabaseError } from "./core-MjwyZJ4i.js";
2
- import { i as MessageAlreadyProcessedError } from "./application-rpZoTfzU.js";
3
- import { n as eventCollector, r as runWithUnitOfWorkContext } from "./unit-of-work-context-BLNj72v0.js";
1
+ import { N as AppError, g as DatabaseError } from "./core-Cx5SeyKV.js";
2
+ import { i as MessageAlreadyProcessedError } from "./application-DjsQtpgw.js";
3
+ import { n as eventCollector, r as runWithUnitOfWorkContext } from "./unit-of-work-context-DToDpAkv.js";
4
4
  import { DrizzleQueryError } from "drizzle-orm/errors";
5
5
  import { isNull } from "drizzle-orm";
6
6
  import { index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.js","names":[],"sources":["../src/infrastructure/postgres/classify-postgres-error.ts","../src/infrastructure/postgres/postgres-database-execution.ts","../src/infrastructure/postgres/base-postgres-repository.ts","../src/infrastructure/postgres/postgres-schema.ts","../src/infrastructure/postgres/postgres-message-store.ts","../src/infrastructure/postgres/postgres-transaction.ts"],"sourcesContent":["import { DrizzleQueryError } from 'drizzle-orm/errors'\n\nimport { AppError, DatabaseError, type FailureClassification } from '@/core'\n\nconst TRANSIENT_CODES = new Set([\n '40001',\n '40P01',\n '08000',\n '08001',\n '08003',\n '08006',\n '57P01',\n '57P02',\n '57P03',\n 'CONNECT_TIMEOUT',\n 'CONNECTION_CLOSED',\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n])\nconst TERMINAL_CODES = new Set(['57014', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED', 'ECANCELED'])\nconst DRIVER_CODES = new Set([\n 'CONNECT_TIMEOUT',\n 'CONNECTION_CLOSED',\n 'CONNECTION_ENDED',\n 'CONNECTION_DESTROYED',\n])\nconst TERMINAL_CLASSES = new Set(['0A', '22', '23', '25', '28', '3D', '3F', '42', '54'])\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- Raw driver exceptions have no shared schema; this boundary validates the fields it exposes. */\n/** Read SQLSTATE or driver codes; unknown callback exceptions remain unchanged. */\nexport function classifyPostgresError(\n cause: unknown,\n operation: string,\n): DatabaseError | undefined {\n let error = cause\n const seen = new Set<unknown>()\n while (error instanceof DrizzleQueryError && !seen.has(error)) {\n seen.add(error)\n error = error.cause\n }\n if (error instanceof AppError || (error instanceof Error && error.name === 'AbortError'))\n return undefined\n const code =\n error instanceof Error && 'code' in error && typeof error.code === 'string'\n ? error.code\n : undefined\n const serverError =\n error instanceof Error &&\n error.name === 'PostgresError' &&\n code !== undefined &&\n /^[0-9A-Z]{5}$/.test(code)\n const driverError = code !== undefined && DRIVER_CODES.has(code)\n if (!(cause instanceof DrizzleQueryError) && !serverError && !driverError) return undefined\n\n return new DatabaseError(\n operation,\n classificationOf(code),\n {\n database: 'postgres',\n code,\n table_name:\n error instanceof Error && 'table_name' in error && typeof error.table_name === 'string'\n ? error.table_name\n : undefined,\n column_name:\n error instanceof Error && 'column_name' in error && typeof error.column_name === 'string'\n ? error.column_name\n : undefined,\n constraint_name:\n error instanceof Error &&\n 'constraint_name' in error &&\n typeof error.constraint_name === 'string'\n ? error.constraint_name\n : undefined,\n },\n { cause },\n )\n}\n\n/* oxlint-enable anti-slop/no-runtime-typeof */\n\nfunction classificationOf(code: string | undefined): FailureClassification {\n if (code === undefined) return 'unknown'\n if (TRANSIENT_CODES.has(code)) return 'transient'\n if (TERMINAL_CODES.has(code) || TERMINAL_CLASSES.has(code.slice(0, 2))) return 'terminal'\n return 'unknown'\n}\n","import { classifyPostgresError } from './classify-postgres-error.ts'\n\n/** Execute once without retries; convert recognized Postgres failures and preserve other exceptions unchanged. */\nexport async function executeDatabase<T>(\n operation: string,\n work: () => PromiseLike<T>,\n): Promise<T> {\n try {\n return await work()\n } catch (cause) {\n throw classifyPostgresError(cause, operation) ?? cause\n }\n}\n","import type { Event } from '@/application'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport { eventCollector } from '../unit-of-work-context.ts'\nimport { executeDatabase } from './postgres-database-execution.ts'\nimport type { PostgresDbTransaction } from './postgres-database-types.ts'\n\n/** A domain aggregate that accumulates events for the unit of work to drain. */\nexport interface AggregateEvents {\n collectEvents(): ReadonlyArray<Event>\n clearEvents(): void\n}\n\n/** Shared plumbing for a repository that writes inside a Postgres unit of work. */\nexport abstract class BasePostgresRepository<Schema extends DrizzleSchema> {\n constructor(protected readonly db: PostgresDbTransaction<Schema>) {}\n\n /** Execute one read with database error conversion and no automatic retries. */\n protected read<T>(operation: string, query: () => PromiseLike<T>): Promise<T> {\n return executeDatabase(operation, query)\n }\n\n /** Drain an aggregate's pending events into the active boundary. */\n protected dispatchEvents(aggregate: AggregateEvents): void {\n const events = aggregate.collectEvents()\n if (events.length === 0) return\n for (const event of events) eventCollector.emit(event)\n aggregate.clearEvents()\n }\n}\n","import { isNull } from 'drizzle-orm'\nimport { index, integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'\n\nimport type { Event } from '@/application'\n\n/** One row per committed message. The primary key is the idempotency claim. */\nexport const processedMessages = pgTable('processed_messages', {\n messageId: text('message_id').primaryKey(),\n processedAt: timestamp('processed_at', { withTimezone: true }).notNull().defaultNow(),\n})\n\n/** Events committed with their state change, waiting for the relay to deliver them. */\nexport const messageOutbox = pgTable(\n 'message_outbox',\n {\n id: text('id').primaryKey(),\n payload: jsonb('payload').$type<Event>().notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n availableAt: timestamp('available_at', { withTimezone: true }).notNull().defaultNow(),\n attempts: integer('attempts').notNull().default(0),\n claimToken: text('claim_token'),\n claimExpiresAt: timestamp('claim_expires_at', { withTimezone: true }),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n failedAt: timestamp('failed_at', { withTimezone: true }),\n lastError: text('last_error'),\n },\n (table) => [\n index('idx_message_outbox_due')\n .on(table.availableAt, table.createdAt)\n .where(isNull(table.publishedAt)),\n index('idx_message_outbox_claim_token').on(table.claimToken),\n ],\n)\n","import {\n MessageAlreadyProcessedError,\n type Event,\n type IMessageStore,\n type MessageId,\n} from '@/application'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport type { PostgresDbTransaction } from './postgres-database-types.ts'\nimport { messageOutbox, processedMessages } from './postgres-schema.ts'\n\n/** Processed messages and outbox events share the active Postgres transaction; the insert result establishes the claim. */\nexport class PostgresMessageStore<Schema extends DrizzleSchema> implements IMessageStore {\n constructor(private readonly db: PostgresDbTransaction<Schema>) {}\n\n async claim(messageId: MessageId): Promise<void> {\n const claimed = await this.db\n .insert(processedMessages)\n .values({ messageId })\n .onConflictDoNothing()\n .returning({ messageId: processedMessages.messageId })\n // Thrown inside the transaction, so drizzle rolls back everything written before the claim.\n if (claimed.length === 0) throw new MessageAlreadyProcessedError(messageId)\n }\n\n async persistEvents(events: ReadonlyArray<Event>): Promise<void> {\n if (events.length === 0) return\n await this.db\n .insert(messageOutbox)\n .values(events.map((event) => ({ id: event.id, payload: event })))\n }\n}\n","import type { ITransaction } from '@/application'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport { runWithUnitOfWorkContext } from '../unit-of-work-context.ts'\nimport { executeDatabase } from './postgres-database-execution.ts'\nimport type { PostgresDb, PostgresTx } from './postgres-database-types.ts'\n\n/**\n * The Postgres transaction boundary uses native Drizzle transactions through postgres.js.\n * Drizzle commits when `work` returns and rolls back when it throws.\n */\nexport class PostgresTransaction<Schema extends DrizzleSchema> implements ITransaction<\n PostgresTx<Schema>\n> {\n constructor(private readonly db: PostgresDb<Schema>) {}\n\n transaction<T>(work: (tx: PostgresTx<Schema>) => Promise<T>): Promise<T> {\n return runWithUnitOfWorkContext('postgres', () =>\n executeDatabase('unit of work transaction', () => this.db.transaction((db) => work({ db }))),\n )\n }\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAS;CAAoB;CAAwB;AAAW,CAAC;AACjG,MAAM,+BAAe,IAAI,IAAI;CAC3B;C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AAC,CAC5B,GAAG,MAAM,aAAa,MAAM,SAAS,CAAC,CACtC,MAAM,OAAO,MAAM,WAAW,CAAC,GAClC,MAAM,gCAAgC,CAAC,CAAC,GAAG,MAAM,UAAU,CAC7D,CACF;;;;;ACpBA,IAAa,uBAAb,MAAyF;CAC1D;CAA7B,YAAY,AAAiB,IAAmC;EAAnC;CAAoC;CAEjE,MAAM,MAAM,WAAqC;EAO/C,KAAI,MANkB,KAAK,GACxB,OAAO,iBAAiB,CAAC,CACzB,OAAO,EAAE,UAAU,CAAC,CAAC,CACrB,oBAAoB,CAAC,CACrB,UAAU,EAAE,WAAW,kBAAkB,UAAU,CAAC,EAE5C,CAAC,WAAW,GAAG,MAAM,IAAI,6BAA6B,SAAS;CAC5E;CAEA,MAAM,cAAc,QAA6C;EAC/D,IAAI,OAAO,WAAW,GAAG;EACzB,MAAM,KAAK,GACR,OAAO,aAAa,CAAC,CACrB,OAAO,OAAO,KAAK,WAAW;GAAE,IAAI,MAAM;GAAI,SAAS;EAAM,EAAE,CAAC;CACrE;AACF;;;;;;;;ACpBA,IAAa,sBAAb,MAEE;CAC6B;CAA7B,YAAY,AAAiB,IAAwB;EAAxB;CAAyB;CAEtD,YAAe,MAA0D;EACvE,OAAO,yBAAyB,kBAC9B,gBAAgB,kCAAkC,KAAK,GAAG,aAAa,OAAO,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAC7F;CACF;AACF"}
1
+ {"version":3,"file":"postgres.js","names":[],"sources":["../src/infrastructure/postgres/classify-postgres-error.ts","../src/infrastructure/postgres/postgres-database-execution.ts","../src/infrastructure/postgres/base-postgres-repository.ts","../src/infrastructure/postgres/postgres-schema.ts","../src/infrastructure/postgres/postgres-message-store.ts","../src/infrastructure/postgres/postgres-transaction.ts"],"sourcesContent":["import { DrizzleQueryError } from 'drizzle-orm/errors'\n\nimport { AppError, DatabaseError, type FailureClassification } from '@/core'\n\nconst TRANSIENT_CODES = new Set([\n '40001',\n '40P01',\n '08000',\n '08001',\n '08003',\n '08006',\n '57P01',\n '57P02',\n '57P03',\n 'CONNECT_TIMEOUT',\n 'CONNECTION_CLOSED',\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n])\nconst TERMINAL_CODES = new Set(['57014', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED', 'ECANCELED'])\nconst DRIVER_CODES = new Set([\n 'CONNECT_TIMEOUT',\n 'CONNECTION_CLOSED',\n 'CONNECTION_ENDED',\n 'CONNECTION_DESTROYED',\n])\nconst TERMINAL_CLASSES = new Set(['0A', '22', '23', '25', '28', '3D', '3F', '42', '54'])\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- Raw driver exceptions have no shared schema; this boundary validates the fields it exposes. */\n/** Read SQLSTATE or driver codes; unknown callback exceptions remain unchanged. */\nexport function classifyPostgresError(\n cause: unknown,\n operation: string,\n): DatabaseError | undefined {\n let error = cause\n const seen = new Set<unknown>()\n while (error instanceof DrizzleQueryError && !seen.has(error)) {\n seen.add(error)\n error = error.cause\n }\n if (error instanceof AppError || (error instanceof Error && error.name === 'AbortError'))\n return undefined\n const code =\n error instanceof Error && 'code' in error && typeof error.code === 'string'\n ? error.code\n : undefined\n const serverError =\n error instanceof Error &&\n error.name === 'PostgresError' &&\n code !== undefined &&\n /^[0-9A-Z]{5}$/.test(code)\n const driverError = code !== undefined && DRIVER_CODES.has(code)\n if (!(cause instanceof DrizzleQueryError) && !serverError && !driverError) return undefined\n\n return new DatabaseError(\n operation,\n classificationOf(code),\n {\n database: 'postgres',\n code,\n table_name:\n error instanceof Error && 'table_name' in error && typeof error.table_name === 'string'\n ? error.table_name\n : undefined,\n column_name:\n error instanceof Error && 'column_name' in error && typeof error.column_name === 'string'\n ? error.column_name\n : undefined,\n constraint_name:\n error instanceof Error &&\n 'constraint_name' in error &&\n typeof error.constraint_name === 'string'\n ? error.constraint_name\n : undefined,\n },\n { cause },\n )\n}\n\n/* oxlint-enable anti-slop/no-runtime-typeof */\n\nfunction classificationOf(code: string | undefined): FailureClassification {\n if (code === undefined) return 'unknown'\n if (TRANSIENT_CODES.has(code)) return 'transient'\n if (TERMINAL_CODES.has(code) || TERMINAL_CLASSES.has(code.slice(0, 2))) return 'terminal'\n return 'unknown'\n}\n","import { classifyPostgresError } from './classify-postgres-error.ts'\n\n/** Execute once without retries; convert recognized Postgres failures and preserve other exceptions unchanged. */\nexport async function executeDatabase<T>(\n operation: string,\n work: () => PromiseLike<T>,\n): Promise<T> {\n try {\n return await work()\n } catch (cause) {\n throw classifyPostgresError(cause, operation) ?? cause\n }\n}\n","import type { DomainEvent } from '@/core'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport { eventCollector } from '../unit-of-work-context.ts'\nimport { executeDatabase } from './postgres-database-execution.ts'\nimport type { PostgresDbTransaction } from './postgres-database-types.ts'\n\n/** A domain aggregate that accumulates events for the unit of work to drain. */\nexport interface AggregateEvents {\n collectEvents(): ReadonlyArray<DomainEvent>\n clearEvents(): void\n}\n\n/** Shared plumbing for a repository that writes inside a Postgres unit of work. */\nexport abstract class BasePostgresRepository<Schema extends DrizzleSchema> {\n constructor(protected readonly db: PostgresDbTransaction<Schema>) {}\n\n /** Execute one read with database error conversion and no automatic retries. */\n protected read<T>(operation: string, query: () => PromiseLike<T>): Promise<T> {\n return executeDatabase(operation, query)\n }\n\n /** Drain an aggregate's pending events into the active boundary. */\n protected dispatchEvents(aggregate: AggregateEvents): void {\n const events = aggregate.collectEvents()\n if (events.length === 0) return\n for (const event of events) eventCollector.emit(event)\n aggregate.clearEvents()\n }\n}\n","import { isNull } from 'drizzle-orm'\nimport { index, integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'\n\nimport type { DomainEvent } from '@/core'\n\n/** One row per committed message. The primary key is the idempotency claim. */\nexport const processedMessages = pgTable('processed_messages', {\n messageId: text('message_id').primaryKey(),\n processedAt: timestamp('processed_at', { withTimezone: true }).notNull().defaultNow(),\n})\n\n/** Events committed with their state change, waiting for the relay to deliver them. */\nexport const messageOutbox = pgTable(\n 'message_outbox',\n {\n id: text('id').primaryKey(),\n payload: jsonb('payload').$type<DomainEvent>().notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n availableAt: timestamp('available_at', { withTimezone: true }).notNull().defaultNow(),\n attempts: integer('attempts').notNull().default(0),\n claimToken: text('claim_token'),\n claimExpiresAt: timestamp('claim_expires_at', { withTimezone: true }),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n failedAt: timestamp('failed_at', { withTimezone: true }),\n lastError: text('last_error'),\n },\n (table) => [\n index('idx_message_outbox_due')\n .on(table.availableAt, table.createdAt)\n .where(isNull(table.publishedAt)),\n index('idx_message_outbox_claim_token').on(table.claimToken),\n ],\n)\n","import { MessageAlreadyProcessedError, type IMessageStore, type MessageId } from '@/application'\nimport type { DomainEvent } from '@/core'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport type { PostgresDbTransaction } from './postgres-database-types.ts'\nimport { messageOutbox, processedMessages } from './postgres-schema.ts'\n\n/** Processed messages and outbox events share the active Postgres transaction; the insert result establishes the claim. */\nexport class PostgresMessageStore<Schema extends DrizzleSchema> implements IMessageStore {\n constructor(private readonly db: PostgresDbTransaction<Schema>) {}\n\n async claim(messageId: MessageId): Promise<void> {\n const claimed = await this.db\n .insert(processedMessages)\n .values({ messageId })\n .onConflictDoNothing()\n .returning({ messageId: processedMessages.messageId })\n // Thrown inside the transaction, so drizzle rolls back everything written before the claim.\n if (claimed.length === 0) throw new MessageAlreadyProcessedError(messageId)\n }\n\n async persistEvents(events: ReadonlyArray<DomainEvent>): Promise<void> {\n if (events.length === 0) return\n await this.db\n .insert(messageOutbox)\n .values(events.map((event) => ({ id: event.id, payload: event })))\n }\n}\n","import type { ITransaction } from '@/application'\n\nimport type { DrizzleSchema } from '../drizzle-schema.ts'\nimport { runWithUnitOfWorkContext } from '../unit-of-work-context.ts'\nimport { executeDatabase } from './postgres-database-execution.ts'\nimport type { PostgresDb, PostgresTx } from './postgres-database-types.ts'\n\n/**\n * The Postgres transaction boundary uses native Drizzle transactions through postgres.js.\n * Drizzle commits when `work` returns and rolls back when it throws.\n */\nexport class PostgresTransaction<Schema extends DrizzleSchema> implements ITransaction<\n PostgresTx<Schema>\n> {\n constructor(private readonly db: PostgresDb<Schema>) {}\n\n transaction<T>(work: (tx: PostgresTx<Schema>) => Promise<T>): Promise<T> {\n return runWithUnitOfWorkContext('postgres', () =>\n executeDatabase('unit of work transaction', () => this.db.transaction((db) => work({ db }))),\n )\n }\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAS;CAAoB;CAAwB;AAAW,CAAC;AACjG,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAAI,CAAC;;AAIvF,SAAgB,sBACd,OACA,WAC2B;CAC3B,IAAI,QAAQ;CACZ,MAAM,uBAAO,IAAI,IAAa;CAC9B,OAAO,iBAAiB,qBAAqB,CAAC,KAAK,IAAI,KAAK,GAAG;EAC7D,KAAK,IAAI,KAAK;EACd,QAAQ,MAAM;CAChB;CACA,IAAI,iBAAiB,YAAa,iBAAiB,SAAS,MAAM,SAAS,cACzE,OAAO;CACT,MAAM,OACJ,iBAAiB,SAAS,UAAU,SAAS,OAAO,MAAM,SAAS,WAC/D,MAAM,OACN;CACN,MAAM,cACJ,iBAAiB,SACjB,MAAM,SAAS,mBACf,SAAS,UACT,gBAAgB,KAAK,IAAI;CAC3B,MAAM,cAAc,SAAS,UAAa,aAAa,IAAI,IAAI;CAC/D,IAAI,EAAE,iBAAiB,sB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AAS;EAAM,EAAE,CAAC;CACrE;AACF;;;;;;;;AChBA,IAAa,sBAAb,MAEE;CAC6B;CAA7B,YAAY,AAAiB,IAAwB;EAAxB;CAAyB;CAEtD,YAAe,MAA0D;EACvE,OAAO,yBAAyB,kBAC9B,gBAAgB,kCAAkC,KAAK,GAAG,aAAa,OAAO,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAC7F;CACF;AACF"}
@@ -1 +1,88 @@
1
- export {}
1
+ import { Y as ErrorTable } from "./index-BStnggQO.js";
2
+ import { Register, RequestServerOptions } from "@tanstack/react-start";
3
+ import { AnyRedirect } from "@tanstack/react-router";
4
+ import { BetterAuthCookies } from "better-auth";
5
+ //#region src/infrastructure/tanstack/auth.middleware.d.ts
6
+ /** The fields middleware reads; generic callers retain every additional session and user field. */
7
+ type AuthSession = {
8
+ readonly user: {
9
+ readonly id: string;
10
+ };
11
+ readonly session: {
12
+ readonly id: string;
13
+ };
14
+ };
15
+ /** Authenticated context retains the application's complete user and session types. */
16
+ type RequiredAuthContext<Session extends AuthSession> = {
17
+ readonly user: Session['user'];
18
+ readonly session: Session['session'];
19
+ };
20
+ /** Optional authentication supplies both fields together or neither field. */
21
+ type AuthContext<Session extends AuthSession> = RequiredAuthContext<Session> | {
22
+ readonly user: undefined;
23
+ readonly session: undefined;
24
+ };
25
+ /** Select the current request's Better Auth instance from TanStack's registered context. */
26
+ type AuthMiddlewareOptions<Session extends AuthSession> = {
27
+ readonly getAuth: (context: RequestServerOptions<Register, undefined>['context']) => {
28
+ readonly api: {
29
+ readonly getSession: (options: {
30
+ headers: Headers;
31
+ }) => Promise<Session | null>;
32
+ };
33
+ };
34
+ };
35
+ /**
36
+ * Preserve Porte's function and request middleware contracts with application-owned services.
37
+ * Optional lookup failures log once and continue as guests. Required lookup failures propagate.
38
+ */
39
+ export declare function createAuthMiddleware<Session extends AuthSession>(options: AuthMiddlewareOptions<Session>): {
40
+ extractAuth: import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, AuthContext<Session>, undefined, undefined, undefined>;
41
+ requireAuth: import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, RequiredAuthContext<Session>, undefined, undefined, undefined>;
42
+ requireAuthRequest: import("@tanstack/react-start").RequestMiddlewareAfterServer<{}, undefined, RequiredAuthContext<Session>>;
43
+ };
44
+ //#endregion
45
+ //#region src/infrastructure/tanstack/error.middleware.d.ts
46
+ type RequestContext = RequestServerOptions<Register, undefined>['context'];
47
+ /** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */
48
+ type AuthCookieSource = {
49
+ readonly $context: Promise<{
50
+ readonly authCookies: BetterAuthCookies;
51
+ }>;
52
+ };
53
+ /** The application's error table, its stale-session redirect, and its Better Auth instance. */
54
+ type ErrorMiddlewareOptions<Entries> = {
55
+ readonly errors: ErrorTable<Entries>;
56
+ /** Build the redirect a server function throws for a stale session. */
57
+ readonly signIn: () => AnyRedirect;
58
+ /** Select the request's Better Auth instance; its cookie definitions say what to clear. */
59
+ readonly getAuth: (context: RequestContext) => AuthCookieSource;
60
+ };
61
+ /**
62
+ * Build both transport boundaries from one error table.
63
+ * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.
64
+ */
65
+ export declare function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>): {
66
+ functionErrorMiddleware: import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, undefined, undefined, undefined, undefined>;
67
+ routeErrorMiddleware: import("@tanstack/react-start").RequestMiddlewareAfterServer<{}, undefined, undefined>;
68
+ toErrorPayload: (cause: unknown) => { [Tag in keyof Entries & string]: Entries[Tag] extends (infer T) ? T extends Entries[Tag] ? T extends {
69
+ readonly fields: infer Fields extends import("zod").ZodType;
70
+ } ? {
71
+ readonly _tag: Tag;
72
+ readonly message: string;
73
+ } & import("zod").infer<Fields> : {
74
+ readonly _tag: Tag;
75
+ readonly message: string;
76
+ } : never : never; }[keyof Entries & string];
77
+ toHttpErrorResponse: (cause: unknown) => Response;
78
+ };
79
+ //#endregion
80
+ //#region src/infrastructure/tanstack/last-login-method.d.ts
81
+ /**
82
+ * Read the method this browser last signed in with from the current request, for the sign-in loader on the server.
83
+ * Pass `cookieName` only when `integrations.lastLoginMethod.cookieName` is set. Returns `null` when the cookie is absent.
84
+ */
85
+ export declare function getLastUsedLoginMethod(cookieName?: string): string | null;
86
+ //#endregion
87
+ export type { AuthContext, AuthCookieSource, AuthMiddlewareOptions, AuthSession, ErrorMiddlewareOptions, RequiredAuthContext };
88
+ //# sourceMappingURL=tanstack.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack.d.ts","names":[],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/last-login-method.ts"],"mappings":";;;;;;KASY;WACD;aAAiB;;WACjB;aAAoB;;;;KAInB,oBAAoB,gBAAgB;WACrC,MAAM;WACN,SAAS;;;KAIR,YAAY,gBAAgB,eACpC,oBAAoB;WAET;WACA;;;KAIH,sBAAsB,gBAAgB;WACvC,UAAU,SAAS,qBAAqB;aACtC;eACE,aAAa;QAAW,SAAS;YAAc,QAAQ;;;;;;;;wBAStD,qBAAqB,gBAAgB,aACnD,SAAS,sBAAsB;;;;;;;KChC5B,iBAAiB,qBAAqB;;KAG/B;WACD,UAAU;aAAmB,aAAa;;;;KAIzC,uBAAuB;WACxB,QAAQ,WAAW;;WAEnB,cAAc;;WAEd,UAAU,SAAS,mBAAmB;;;;;;wBAOjC,sBAAsB,SAAS,SAAS,uBAAuB;;;;;;;;;;;;;;;;;;;;wBCpB/D,uBAAuB"}
package/dist/tanstack.js CHANGED
@@ -0,0 +1,225 @@
1
+ import { A as StaleSessionError, E as ValidationError, M as AuthenticationError, N as AppError, a as createLogger } from "./core-Cx5SeyKV.js";
2
+ import { z } from "zod";
3
+ import { createMiddleware } from "@tanstack/react-start";
4
+ import { deleteCookie, getRequestHeaders } from "@tanstack/react-start/server";
5
+ import { getSessionCookie, parseCookies } from "better-auth/cookies";
6
+ import { isNotFound, isRedirect } from "@tanstack/react-router";
7
+ import { getReasonPhrase } from "http-status-codes";
8
+
9
+ //#region src/infrastructure/tanstack/auth.middleware.ts
10
+ const logger$1 = createLogger("auth-middleware");
11
+ /**
12
+ * Preserve Porte's function and request middleware contracts with application-owned services.
13
+ * Optional lookup failures log once and continue as guests. Required lookup failures propagate.
14
+ */
15
+ function createAuthMiddleware(options) {
16
+ const extractAuth = createMiddleware({ type: "function" }).server(async ({ next, context }) => {
17
+ let resolved;
18
+ try {
19
+ resolved = await options.getAuth(context).api.getSession({ headers: getRequestHeaders() });
20
+ } catch (error) {
21
+ logger$1.error("get_session_failed", { error });
22
+ resolved = null;
23
+ }
24
+ if (resolved === null) return next({ context: {
25
+ user: void 0,
26
+ session: void 0
27
+ } });
28
+ return next({ context: {
29
+ user: resolved.user,
30
+ session: resolved.session
31
+ } });
32
+ });
33
+ async function resolveRequiredSession(context, headers) {
34
+ const resolved = await options.getAuth(context).api.getSession({ headers });
35
+ if (resolved === null) {
36
+ if (getSessionCookie(headers)) throw new StaleSessionError();
37
+ throw new AuthenticationError();
38
+ }
39
+ return resolved;
40
+ }
41
+ return {
42
+ extractAuth,
43
+ requireAuth: createMiddleware({ type: "function" }).server(async ({ next, context }) => {
44
+ const resolved = await resolveRequiredSession(context, getRequestHeaders());
45
+ return next({ context: {
46
+ user: resolved.user,
47
+ session: resolved.session
48
+ } });
49
+ }),
50
+ requireAuthRequest: createMiddleware({ type: "request" }).server(async ({ request, next, context }) => {
51
+ const resolved = await resolveRequiredSession(context, request.headers);
52
+ return next({ context: {
53
+ user: resolved.user,
54
+ session: resolved.session
55
+ } });
56
+ })
57
+ };
58
+ }
59
+
60
+ //#endregion
61
+ //#region src/infrastructure/tanstack/resolve-failure.ts
62
+ const logger = createLogger("error-boundary");
63
+ /**
64
+ * Resolve one failure through the table or fall back to the generic replacement, and log it once.
65
+ * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.
66
+ */
67
+ function resolveFailure(table, cause) {
68
+ const resolved = table.resolve(cause);
69
+ if (resolved !== null) {
70
+ logger.warn("handled_error", { details: {
71
+ tag: resolved.payload._tag,
72
+ status: resolved.status
73
+ } });
74
+ return resolved;
75
+ }
76
+ const classification = cause instanceof AppError ? cause.classification : "unknown";
77
+ logger.error("unexpected_error", {
78
+ error: cause,
79
+ details: { classification }
80
+ });
81
+ return table.fallback(cause);
82
+ }
83
+
84
+ //#endregion
85
+ //#region src/infrastructure/tanstack/http-error-response.ts
86
+ const RetryAfterSchema = z.object({ retryAfter: z.number() });
87
+ /**
88
+ * Build the API route converter for one error table.
89
+ * The body is RFC 9457 problem details; public fields become extension members.
90
+ */
91
+ function createHttpErrorResponseConverter(table) {
92
+ return function toHttpErrorResponse(cause) {
93
+ const { status, payload } = resolveFailure(table, cause);
94
+ const { _tag, message, ...fields } = payload;
95
+ const body = {
96
+ type: "about:blank",
97
+ title: getReasonPhrase(status),
98
+ detail: message,
99
+ ...fields
100
+ };
101
+ const headers = new Headers({ "Content-Type": "application/problem+json" });
102
+ const retry = RetryAfterSchema.safeParse(payload);
103
+ if (retry.success) headers.set("Retry-After", String(retry.data.retryAfter));
104
+ return Response.json(body, {
105
+ status,
106
+ headers
107
+ });
108
+ };
109
+ }
110
+
111
+ //#endregion
112
+ //#region src/infrastructure/tanstack/session-cookies.ts
113
+ /**
114
+ * Delete the session, session cache, account cache, and remember-me cookies of one instance.
115
+ * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.
116
+ */
117
+ function clearStaleSessionCookies(cookies) {
118
+ const present = [...parseCookies(getRequestHeaders().get("cookie") ?? "").keys()];
119
+ const definitions = [
120
+ cookies.sessionToken,
121
+ cookies.sessionData,
122
+ cookies.accountData,
123
+ cookies.dontRememberToken
124
+ ];
125
+ for (const cookie of definitions) {
126
+ const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`));
127
+ for (const name of /* @__PURE__ */ new Set([cookie.name, ...chunks])) deleteCookie(name, deletionOf(cookie.attributes));
128
+ }
129
+ }
130
+ function deletionOf(attributes) {
131
+ const options = {
132
+ path: attributes.path ?? "/",
133
+ secure: attributes.secure ?? false
134
+ };
135
+ if (attributes.domain !== void 0) options.domain = attributes.domain;
136
+ return options;
137
+ }
138
+
139
+ //#endregion
140
+ //#region src/infrastructure/tanstack/to-error-payload.ts
141
+ const SerializedIssuesSchema = z.array(z.object({
142
+ message: z.string(),
143
+ path: z.array(z.union([z.string(), z.number()]))
144
+ })).min(1);
145
+ function reconstructValidationError(cause) {
146
+ if (!(cause instanceof Error)) return null;
147
+ let message;
148
+ try {
149
+ message = JSON.parse(cause.message);
150
+ } catch {
151
+ return null;
152
+ }
153
+ const parsed = SerializedIssuesSchema.safeParse(message);
154
+ return parsed.success ? ValidationError.fromIssues(parsed.data) : null;
155
+ }
156
+ /**
157
+ * Build the server-function converter for one error table.
158
+ * The result is a plain object, because only own data survives serialization.
159
+ */
160
+ function createErrorPayloadConverter(table) {
161
+ return function toErrorPayload(cause) {
162
+ return resolveFailure(table, reconstructValidationError(cause) ?? cause).payload;
163
+ };
164
+ }
165
+
166
+ //#endregion
167
+ //#region src/infrastructure/tanstack/error.middleware.ts
168
+ /**
169
+ * Build both transport boundaries from one error table.
170
+ * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.
171
+ */
172
+ function createErrorMiddleware(options) {
173
+ const toErrorPayload = createErrorPayloadConverter(options.errors);
174
+ const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors);
175
+ async function clearSession(context) {
176
+ const { authCookies } = await options.getAuth(context).$context;
177
+ clearStaleSessionCookies(authCookies);
178
+ }
179
+ async function handleFunctionError(cause, context) {
180
+ if (isNotFound(cause) || isRedirect(cause)) throw cause;
181
+ if (cause instanceof StaleSessionError) {
182
+ await clearSession(context);
183
+ throw options.signIn();
184
+ }
185
+ throw toErrorPayload(cause);
186
+ }
187
+ async function handleRouteError(cause, context) {
188
+ if (isNotFound(cause) || isRedirect(cause)) throw cause;
189
+ if (cause instanceof StaleSessionError) await clearSession(context);
190
+ return toHttpErrorResponse(cause);
191
+ }
192
+ return {
193
+ functionErrorMiddleware: createMiddleware({ type: "function" }).server(async ({ next, context }) => {
194
+ try {
195
+ return await next();
196
+ } catch (cause) {
197
+ return handleFunctionError(cause, context);
198
+ }
199
+ }),
200
+ routeErrorMiddleware: createMiddleware({ type: "request" }).server(async ({ next, context }) => {
201
+ try {
202
+ return await next();
203
+ } catch (cause) {
204
+ return handleRouteError(cause, context);
205
+ }
206
+ }),
207
+ toErrorPayload,
208
+ toHttpErrorResponse
209
+ };
210
+ }
211
+
212
+ //#endregion
213
+ //#region src/infrastructure/tanstack/last-login-method.ts
214
+ const DEFAULT_COOKIE_NAME = "better-auth.last_used_login_method";
215
+ /**
216
+ * Read the method this browser last signed in with from the current request, for the sign-in loader on the server.
217
+ * Pass `cookieName` only when `integrations.lastLoginMethod.cookieName` is set. Returns `null` when the cookie is absent.
218
+ */
219
+ function getLastUsedLoginMethod(cookieName = DEFAULT_COOKIE_NAME) {
220
+ return parseCookies(getRequestHeaders().get("cookie") ?? "").get(cookieName) ?? null;
221
+ }
222
+
223
+ //#endregion
224
+ export { createAuthMiddleware, createErrorMiddleware, getLastUsedLoginMethod };
225
+ //# sourceMappingURL=tanstack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack.js","names":["logger"],"sources":["../src/infrastructure/tanstack/auth.middleware.ts","../src/infrastructure/tanstack/resolve-failure.ts","../src/infrastructure/tanstack/http-error-response.ts","../src/infrastructure/tanstack/session-cookies.ts","../src/infrastructure/tanstack/to-error-payload.ts","../src/infrastructure/tanstack/error.middleware.ts","../src/infrastructure/tanstack/last-login-method.ts"],"sourcesContent":["import { createMiddleware, type Register, type RequestServerOptions } from '@tanstack/react-start'\nimport { getRequestHeaders } from '@tanstack/react-start/server'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nconst logger = createLogger('auth-middleware')\n\n/** The fields middleware reads; generic callers retain every additional session and user field. */\nexport type AuthSession = {\n readonly user: { readonly id: string }\n readonly session: { readonly id: string }\n}\n\n/** Authenticated context retains the application's complete user and session types. */\nexport type RequiredAuthContext<Session extends AuthSession> = {\n readonly user: Session['user']\n readonly session: Session['session']\n}\n\n/** Optional authentication supplies both fields together or neither field. */\nexport type AuthContext<Session extends AuthSession> =\n | RequiredAuthContext<Session>\n | {\n readonly user: undefined\n readonly session: undefined\n }\n\n/** Select the current request's Better Auth instance from TanStack's registered context. */\nexport type AuthMiddlewareOptions<Session extends AuthSession> = {\n readonly getAuth: (context: RequestServerOptions<Register, undefined>['context']) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n}\n\n/**\n * Preserve Porte's function and request middleware contracts with application-owned services.\n * Optional lookup failures log once and continue as guests. Required lookup failures propagate.\n */\nexport function createAuthMiddleware<Session extends AuthSession>(\n options: AuthMiddlewareOptions<Session>,\n) {\n const extractAuth = createMiddleware({ type: 'function' }).server<AuthContext<Session>>(\n async ({ next, context }) => {\n let resolved: Session | null\n try {\n resolved = await options.getAuth(context).api.getSession({ headers: getRequestHeaders() })\n } catch (error) {\n logger.error('get_session_failed', { error })\n resolved = null\n }\n if (resolved === null)\n return next<AuthContext<Session>>({ context: { user: undefined, session: undefined } })\n return next<AuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n\n async function resolveRequiredSession(\n context: RequestServerOptions<Register, undefined>['context'],\n headers: Headers,\n ): Promise<Session> {\n const resolved = await options.getAuth(context).api.getSession({ headers })\n if (resolved === null) {\n if (getSessionCookie(headers)) throw new StaleSessionError()\n throw new AuthenticationError()\n }\n return resolved\n }\n\n const requireAuth = createMiddleware({ type: 'function' }).server(async ({ next, context }) => {\n const resolved = await resolveRequiredSession(context, getRequestHeaders())\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n })\n const requireAuthRequest = createMiddleware({ type: 'request' }).server(\n async ({ request, next, context }) => {\n const resolved = await resolveRequiredSession(context, request.headers)\n return next<RequiredAuthContext<Session>>({\n context: { user: resolved.user, session: resolved.session },\n })\n },\n )\n return { extractAuth, requireAuth, requireAuthRequest }\n}\n","import { AppError, createLogger, type ErrorTable, type ResolvedError } from '@/core'\nimport type { ErrorPayloadOf } from '@/core'\n\nconst logger = createLogger('error-boundary')\n\n/**\n * Resolve one failure through the table or fall back to the generic replacement, and log it once.\n * Both transport converters call this, so one rule decides the log level: mapped is a warning, unmapped is an error with the cause.\n */\nexport function resolveFailure<Entries>(\n table: ErrorTable<Entries>,\n cause: unknown,\n): ResolvedError<ErrorPayloadOf<ErrorTable<Entries>>> {\n const resolved = table.resolve(cause)\n if (resolved !== null) {\n logger.warn('handled_error', {\n details: { tag: resolved.payload._tag, status: resolved.status },\n })\n return resolved\n }\n const classification = cause instanceof AppError ? cause.classification : 'unknown'\n logger.error('unexpected_error', { error: cause, details: { classification } })\n return table.fallback(cause)\n}\n","import { getReasonPhrase } from 'http-status-codes'\nimport { z } from 'zod'\n\nimport type { ErrorTable, ProblemDetails } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// A known delay becomes the header; a null delay sends no header.\nconst RetryAfterSchema = z.object({ retryAfter: z.number() })\n\n/**\n * Build the API route converter for one error table.\n * The body is RFC 9457 problem details; public fields become extension members.\n */\nexport function createHttpErrorResponseConverter<Entries>(table: ErrorTable<Entries>) {\n return function toHttpErrorResponse(cause: unknown): Response {\n const { status, payload } = resolveFailure(table, cause)\n const { _tag, message, ...fields } = payload\n const body: ProblemDetails = {\n type: 'about:blank',\n title: getReasonPhrase(status),\n detail: message,\n ...fields,\n }\n const headers = new Headers({ 'Content-Type': 'application/problem+json' })\n const retry = RetryAfterSchema.safeParse(payload)\n if (retry.success) headers.set('Retry-After', String(retry.data.retryAfter))\n return Response.json(body, { status, headers })\n }\n}\n","import { deleteCookie, getRequestHeaders } from '@tanstack/react-start/server'\nimport type { BetterAuthCookies } from 'better-auth'\nimport { parseCookies } from 'better-auth/cookies'\n\ntype AuthCookie = BetterAuthCookies['sessionToken']\ntype DeleteCookieOptions = NonNullable<Parameters<typeof deleteCookie>[1]>\n\n/**\n * Delete the session, session cache, account cache, and remember-me cookies of one instance.\n * Chunks present on the request go too. Names and attributes come from the instance, so custom prefixes and domain cookies clear.\n */\nexport function clearStaleSessionCookies(cookies: BetterAuthCookies): void {\n const present = [...parseCookies(getRequestHeaders().get('cookie') ?? '').keys()]\n const definitions = [\n cookies.sessionToken,\n cookies.sessionData,\n cookies.accountData,\n cookies.dontRememberToken,\n ]\n for (const cookie of definitions) {\n // Better Auth names a chunk `${name}.${index}`, so a missed chunk would resurrect the value.\n const chunks = present.filter((name) => name.startsWith(`${cookie.name}.`))\n for (const name of new Set([cookie.name, ...chunks]))\n deleteCookie(name, deletionOf(cookie.attributes))\n }\n}\n\nfunction deletionOf(attributes: AuthCookie['attributes']): DeleteCookieOptions {\n // Better Auth sets `/` and the secure flag at runtime; the types leave both optional.\n const options: DeleteCookieOptions = {\n path: attributes.path ?? '/',\n secure: attributes.secure ?? false,\n }\n if (attributes.domain !== undefined) options.domain = attributes.domain\n return options\n}\n","import { z } from 'zod'\n\nimport { ValidationError, type ErrorPayloadOf, type ErrorTable } from '@/core'\n\nimport { resolveFailure } from './resolve-failure.ts'\n\n// TanStack serializes a validator's issues into `Error.message` as JSON.\nconst SerializedIssuesSchema = z\n .array(z.object({ message: z.string(), path: z.array(z.union([z.string(), z.number()])) }))\n .min(1)\n\nfunction reconstructValidationError(cause: unknown): ValidationError | null {\n if (!(cause instanceof Error)) return null\n let message: unknown\n try {\n message = JSON.parse(cause.message)\n } catch {\n return null\n }\n const parsed = SerializedIssuesSchema.safeParse(message)\n return parsed.success ? ValidationError.fromIssues(parsed.data) : null\n}\n\n/**\n * Build the server-function converter for one error table.\n * The result is a plain object, because only own data survives serialization.\n */\nexport function createErrorPayloadConverter<Entries>(table: ErrorTable<Entries>) {\n return function toErrorPayload(cause: unknown): ErrorPayloadOf<ErrorTable<Entries>> {\n return resolveFailure(table, reconstructValidationError(cause) ?? cause).payload\n }\n}\n","import { isNotFound, isRedirect, type AnyRedirect } from '@tanstack/react-router'\nimport { createMiddleware, type Register, type RequestServerOptions } from '@tanstack/react-start'\nimport type { BetterAuthCookies } from 'better-auth'\n\nimport { StaleSessionError, type ErrorTable } from '@/core'\n\nimport { createHttpErrorResponseConverter } from './http-error-response.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\n\ntype RequestContext = RequestServerOptions<Register, undefined>['context']\n\n/** The part of a Better Auth instance the boundary reads: its computed cookie definitions. */\nexport type AuthCookieSource = {\n readonly $context: Promise<{ readonly authCookies: BetterAuthCookies }>\n}\n\n/** The application's error table, its stale-session redirect, and its Better Auth instance. */\nexport type ErrorMiddlewareOptions<Entries> = {\n readonly errors: ErrorTable<Entries>\n /** Build the redirect a server function throws for a stale session. */\n readonly signIn: () => AnyRedirect\n /** Select the request's Better Auth instance; its cookie definitions say what to clear. */\n readonly getAuth: (context: RequestContext) => AuthCookieSource\n}\n\n/**\n * Build both transport boundaries from one error table.\n * Register `functionErrorMiddleware` globally. Put `routeErrorMiddleware` first in an API route's `server.middleware`.\n */\nexport function createErrorMiddleware<Entries>(options: ErrorMiddlewareOptions<Entries>) {\n const toErrorPayload = createErrorPayloadConverter(options.errors)\n const toHttpErrorResponse = createHttpErrorResponseConverter(options.errors)\n\n async function clearSession(context: RequestContext): Promise<void> {\n const { authCookies } = await options.getAuth(context).$context\n clearStaleSessionCookies(authCookies)\n }\n\n async function handleFunctionError(cause: unknown, context: RequestContext): Promise<never> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) {\n await clearSession(context)\n // oxlint-disable-next-line typescript/only-throw-error -- Router redirects by throwing this.\n throw options.signIn()\n }\n // oxlint-disable-next-line typescript/only-throw-error -- The client rejects with this and reads its tag.\n throw toErrorPayload(cause)\n }\n\n // A route answers 401 instead of a redirect because fetch would follow it into the HTML shell.\n async function handleRouteError(cause: unknown, context: RequestContext): Promise<Response> {\n // oxlint-disable-next-line typescript/only-throw-error -- TanStack uses throwable control-flow objects.\n if (isNotFound(cause) || isRedirect(cause)) throw cause\n if (cause instanceof StaleSessionError) await clearSession(context)\n return toHttpErrorResponse(cause)\n }\n\n const functionErrorMiddleware = createMiddleware({ type: 'function' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleFunctionError(cause, context)\n }\n },\n )\n\n const routeErrorMiddleware = createMiddleware({ type: 'request' }).server(\n async ({ next, context }) => {\n try {\n return await next()\n } catch (cause) {\n return handleRouteError(cause, context)\n }\n },\n )\n\n return { functionErrorMiddleware, routeErrorMiddleware, toErrorPayload, toHttpErrorResponse }\n}\n","import { getRequestHeaders } from '@tanstack/react-start/server'\nimport { parseCookies } from 'better-auth/cookies'\n\n// Better Auth keeps the plugin default private; this is the value LastLoginMethodOptions.cookieName documents.\nconst DEFAULT_COOKIE_NAME = 'better-auth.last_used_login_method'\n\n/**\n * Read the method this browser last signed in with from the current request, for the sign-in loader on the server.\n * Pass `cookieName` only when `integrations.lastLoginMethod.cookieName` is set. Returns `null` when the cookie is absent.\n */\nexport function getLastUsedLoginMethod(cookieName = DEFAULT_COOKIE_NAME): string | null {\n return parseCookies(getRequestHeaders().get('cookie') ?? '').get(cookieName) ?? null\n}\n"],"mappings":";;;;;;;;;AAMA,MAAMA,WAAS,aAAa,iBAAiB;;;;;AAmC7C,SAAgB,qBACd,SACA;CACA,MAAM,cAAc,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACzD,OAAO,EAAE,MAAM,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,QAAQ,QA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