better-ship 0.16.0 → 0.18.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.
- package/dist/{application-Cf9SER-i.js → application-CNdzHIXk.js} +5 -7
- package/dist/{application-Cf9SER-i.js.map → application-CNdzHIXk.js.map} +1 -1
- package/dist/application.d.ts +2 -2
- package/dist/application.js +1 -1
- package/dist/better-auth/apple-client-secret.d.ts +1 -1
- package/dist/better-auth/apple-client-secret.js +2 -2
- package/dist/better-auth/apple-client-secret.js.map +1 -1
- package/dist/better-auth/auth-client.js +1 -1
- package/dist/better-auth/rate-limit.d.ts +1 -1
- package/dist/better-auth/rate-limit.js +4 -6
- package/dist/better-auth/rate-limit.js.map +1 -1
- package/dist/better-auth.js +1 -1
- package/dist/billing/client.d.ts +86 -0
- package/dist/billing/client.d.ts.map +1 -0
- package/dist/billing/client.js +77 -0
- package/dist/billing/client.js.map +1 -0
- package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
- package/dist/cloudflare/auth-secondary-storage.js +1 -1
- package/dist/cloudflare/durable-object-client.js +1 -1
- package/dist/cloudflare/durable-object-errors.d.ts +1 -1
- package/dist/cloudflare/durable-object-errors.js +1 -1
- package/dist/cloudflare/kv-client.d.ts +31 -0
- package/dist/cloudflare/kv-client.d.ts.map +1 -0
- package/dist/cloudflare/kv-client.js +62 -0
- package/dist/cloudflare/kv-client.js.map +1 -0
- package/dist/cloudflare/kv-errors.d.ts +52 -0
- package/dist/cloudflare/kv-errors.d.ts.map +1 -0
- package/dist/cloudflare/kv-errors.js +144 -0
- package/dist/cloudflare/kv-errors.js.map +1 -0
- package/dist/cloudflare/queue.d.ts +2 -2
- package/dist/cloudflare/queue.d.ts.map +1 -1
- package/dist/cloudflare/queue.js +10 -12
- package/dist/cloudflare/queue.js.map +1 -1
- package/dist/cloudflare/r2-client.d.ts +70 -0
- package/dist/cloudflare/r2-client.d.ts.map +1 -0
- package/dist/cloudflare/r2-client.js +153 -0
- package/dist/cloudflare/r2-client.js.map +1 -0
- package/dist/cloudflare/r2-errors.d.ts +34 -0
- package/dist/cloudflare/r2-errors.d.ts.map +1 -0
- package/dist/cloudflare/r2-errors.js +90 -0
- package/dist/cloudflare/r2-errors.js.map +1 -0
- package/dist/cloudflare/scheduled.d.ts +1 -1
- package/dist/cloudflare/scheduled.js +2 -2
- package/dist/cloudflare/scheduled.js.map +1 -1
- package/dist/cloudflare.d.ts +10 -5
- package/dist/cloudflare.d.ts.map +1 -1
- package/dist/cloudflare.js +21 -10
- package/dist/cloudflare.js.map +1 -1
- package/dist/{core-ClSP5-V9.js → core-UUW2unJd.js} +106 -195
- package/dist/core-UUW2unJd.js.map +1 -0
- package/dist/core.d.ts +2 -2
- package/dist/core.js +2 -2
- package/dist/http.d.ts +2 -2
- package/dist/http.js +3 -3
- package/dist/http.js.map +1 -1
- package/dist/{index-Cchdg2aQ.d.ts → index-CYHXOH08.d.ts} +2 -2
- package/dist/{index-Cchdg2aQ.d.ts.map → index-CYHXOH08.d.ts.map} +1 -1
- package/dist/{index-DvJUcSW1.d.ts → index-DUFS0SJ_.d.ts} +41 -102
- package/dist/index-DUFS0SJ_.d.ts.map +1 -0
- package/dist/{outbox-repository-options-ICOF8g2h.js → outbox-repository-options-CgdqU20T.js} +2 -2
- package/dist/{outbox-repository-options-ICOF8g2h.js.map → outbox-repository-options-CgdqU20T.js.map} +1 -1
- package/dist/{outbox-repository-options-AkihEaik.d.ts → outbox-repository-options-DjBgFhMi.d.ts} +3 -3
- package/dist/{outbox-repository-options-AkihEaik.d.ts.map → outbox-repository-options-DjBgFhMi.d.ts.map} +1 -1
- package/dist/postgres.d.ts +10 -5
- package/dist/postgres.d.ts.map +1 -1
- package/dist/postgres.js +21 -10
- package/dist/postgres.js.map +1 -1
- package/dist/posthog/metrics.d.ts +1 -1
- package/dist/posthog/server.d.ts +2 -2
- package/dist/posthog/server.js +1 -1
- package/dist/resend.d.ts +3 -3
- package/dist/resend.js +2 -2
- package/dist/sentry/client.d.ts +1 -1
- package/dist/sentry/client.d.ts.map +1 -1
- package/dist/sentry/client.js +10 -4
- package/dist/sentry/client.js.map +1 -1
- package/dist/sentry/server.d.ts +2 -2
- package/dist/sentry/server.js +5 -5
- package/dist/sentry/server.js.map +1 -1
- package/dist/stripe/payment-service.d.ts +52 -0
- package/dist/stripe/payment-service.d.ts.map +1 -0
- package/dist/stripe/payment-service.error.d.ts +13 -0
- package/dist/stripe/payment-service.error.d.ts.map +1 -0
- package/dist/stripe/payment-service.error.js +30 -0
- package/dist/stripe/payment-service.error.js.map +1 -0
- package/dist/stripe/payment-service.js +72 -0
- package/dist/stripe/payment-service.js.map +1 -0
- package/dist/stripe/payment-webhook.d.ts +18 -0
- package/dist/stripe/payment-webhook.d.ts.map +1 -0
- package/dist/stripe/payment-webhook.js +47 -0
- package/dist/stripe/payment-webhook.js.map +1 -0
- package/dist/tanstack.d.ts +1 -1
- package/dist/tanstack.js +4 -4
- package/dist/tanstack.js.map +1 -1
- package/dist/testing/outbox-repository.d.ts +2 -2
- package/dist/testing/payment-service.d.ts +10 -0
- package/dist/testing/payment-service.d.ts.map +1 -0
- package/dist/testing/payment-service.js +76 -0
- package/dist/testing/payment-service.js.map +1 -0
- package/dist/{webhook-verification-D6aGQfNi.js → webhook-verification-BBmjkHgI.js} +2 -2
- package/dist/{webhook-verification-D6aGQfNi.js.map → webhook-verification-BBmjkHgI.js.map} +1 -1
- package/dist/{webhook-verification-BcQQG-vY.d.ts → webhook-verification-BuxPzdr4.d.ts} +2 -2
- package/dist/{webhook-verification-BcQQG-vY.d.ts.map → webhook-verification-BuxPzdr4.d.ts.map} +1 -1
- package/package.json +15 -6
- package/src/application/outbox-relay.ts +3 -1
- package/src/core/console-log-sink.ts +65 -0
- package/src/core/index.ts +1 -4
- package/src/core/logger.ts +80 -281
- package/src/infrastructure/better-auth/apple-client-secret.ts +1 -1
- package/src/infrastructure/better-auth/rate-limit.ts +3 -1
- package/src/infrastructure/billing/client.ts +173 -0
- package/src/infrastructure/cloudflare/d1-database-execution.ts +27 -6
- package/src/infrastructure/cloudflare/kv-client.ts +79 -0
- package/src/infrastructure/cloudflare/kv-errors.ts +157 -0
- package/src/infrastructure/cloudflare/queue/queue-consumer.ts +8 -9
- package/src/infrastructure/cloudflare/r2-client.ts +162 -0
- package/src/infrastructure/cloudflare/r2-errors.ts +111 -0
- package/src/infrastructure/cloudflare/scheduled/scheduled-handler.ts +1 -1
- package/src/infrastructure/http/webhook-handler.ts +1 -1
- package/src/infrastructure/postgres/postgres-database-execution.ts +27 -6
- package/src/infrastructure/sentry/client.ts +6 -3
- package/src/infrastructure/sentry/server.ts +4 -4
- package/src/infrastructure/stripe/payment-service.error.ts +42 -0
- package/src/infrastructure/stripe/payment-service.ts +129 -0
- package/src/infrastructure/stripe/payment-webhook.ts +49 -0
- package/src/infrastructure/tanstack/resolve-failure.ts +3 -2
- package/src/infrastructure/testing/payment-service-contract.ts +91 -0
- package/dist/core-ClSP5-V9.js.map +0 -1
- package/dist/index-DvJUcSW1.d.ts.map +0 -1
package/dist/sentry/server.js
CHANGED
|
@@ -20,15 +20,15 @@ function createSentryOptions(options) {
|
|
|
20
20
|
}
|
|
21
21
|
/** Register with setLoggerErrorHook once at startup; an explicit user applies only to this report. */
|
|
22
22
|
function createSentryLoggerErrorHook() {
|
|
23
|
-
return ({ error,
|
|
24
|
-
if (
|
|
23
|
+
return ({ error, userId, attributes }) => {
|
|
24
|
+
if (userId !== void 0) {
|
|
25
25
|
Sentry.captureException(error, {
|
|
26
|
-
extra:
|
|
27
|
-
user: { id:
|
|
26
|
+
extra: attributes,
|
|
27
|
+
user: { id: userId }
|
|
28
28
|
});
|
|
29
29
|
return;
|
|
30
30
|
}
|
|
31
|
-
Sentry.captureException(error, { extra:
|
|
31
|
+
Sentry.captureException(error, { extra: attributes });
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
34
|
/** Identity and scope adapter from Typist and Porte; call inside Sentry's instrumented runtime. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":[],"sources":["../../src/infrastructure/sentry/server.ts"],"sourcesContent":["import * as Sentry from '@sentry/cloudflare'\n\nimport type { ObservabilityScope, ObservabilityService, ObservabilityUser } from '@/application'\nimport type { LoggerErrorHook } from '@/core'\n\n/** Application-owned deployment settings with the full Cloudflare SDK option contract. */\nexport type SentryServerOptions = Sentry.CloudflareOptions & {\n readonly dsn: string\n readonly environment: string\n readonly enabled: boolean\n}\n\n/** Options for Workers, Durable Objects, and Workflows, ported from Typist and Porte. */\nexport function createSentryOptions(options: SentryServerOptions): Sentry.CloudflareOptions {\n return {\n enableLogs: true,\n ...options,\n dataCollection: {\n userInfo: false,\n httpBodies: [],\n ...options.dataCollection,\n genAI: { inputs: false, outputs: false, ...options.dataCollection?.genAI },\n },\n }\n}\n\n/** Register with setLoggerErrorHook once at startup; an explicit user applies only to this report. */\nexport function createSentryLoggerErrorHook(): LoggerErrorHook {\n return ({ error,
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"sources":["../../src/infrastructure/sentry/server.ts"],"sourcesContent":["import * as Sentry from '@sentry/cloudflare'\n\nimport type { ObservabilityScope, ObservabilityService, ObservabilityUser } from '@/application'\nimport type { LoggerErrorHook } from '@/core'\n\n/** Application-owned deployment settings with the full Cloudflare SDK option contract. */\nexport type SentryServerOptions = Sentry.CloudflareOptions & {\n readonly dsn: string\n readonly environment: string\n readonly enabled: boolean\n}\n\n/** Options for Workers, Durable Objects, and Workflows, ported from Typist and Porte. */\nexport function createSentryOptions(options: SentryServerOptions): Sentry.CloudflareOptions {\n return {\n enableLogs: true,\n ...options,\n dataCollection: {\n userInfo: false,\n httpBodies: [],\n ...options.dataCollection,\n genAI: { inputs: false, outputs: false, ...options.dataCollection?.genAI },\n },\n }\n}\n\n/** Register with setLoggerErrorHook once at startup; an explicit user applies only to this report. */\nexport function createSentryLoggerErrorHook(): LoggerErrorHook {\n return ({ error, userId, attributes }) => {\n if (userId !== undefined) {\n Sentry.captureException(error, { extra: attributes, user: { id: userId } })\n return\n }\n Sentry.captureException(error, { extra: attributes })\n }\n}\n\n/** Identity and scope adapter from Typist and Porte; call inside Sentry's instrumented runtime. */\nexport class SentryObservabilityService implements ObservabilityService {\n /** Attribute subsequent reports in the current isolation scope. */\n setUser(user: ObservabilityUser): void {\n Sentry.setUser(user)\n }\n\n /** Await work in a separate scope for each queue message or concurrent operation. */\n async withIsolationScope<T>(callback: (scope: ObservabilityScope) => T | Promise<T>): Promise<T> {\n return await Sentry.withIsolationScope(callback)\n }\n}\n\nexport { Sentry }\n"],"mappings":";;;;AAaA,SAAgB,oBAAoB,SAAwD;CAC1F,OAAO;EACL,YAAY;EACZ,GAAG;EACH,gBAAgB;GACd,UAAU;GACV,YAAY,CAAC;GACb,GAAG,QAAQ;GACX,OAAO;IAAE,QAAQ;IAAO,SAAS;IAAO,GAAG,QAAQ,gBAAgB;GAAM;EAC3E;CACF;AACF;;AAGA,SAAgB,8BAA+C;CAC7D,QAAQ,EAAE,OAAO,QAAQ,iBAAiB;EACxC,IAAI,WAAW,QAAW;GACxB,OAAO,iBAAiB,OAAO;IAAE,OAAO;IAAY,MAAM,EAAE,IAAI,OAAO;GAAE,CAAC;GAC1E;EACF;EACA,OAAO,iBAAiB,OAAO,EAAE,OAAO,WAAW,CAAC;CACtD;AACF;;AAGA,IAAa,6BAAb,MAAwE;;CAEtE,QAAQ,MAA+B;EACrC,OAAO,QAAQ,IAAI;CACrB;;CAGA,MAAM,mBAAsB,UAAqE;EAC/F,OAAO,MAAM,OAAO,mBAAmB,QAAQ;CACjD;AACF"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
//#region src/infrastructure/stripe/payment-service.d.ts
|
|
3
|
+
/** Supply the same key and parameters when repeating one durable payment attempt. */
|
|
4
|
+
export type PaymentRequestOptions = Stripe.RequestOptions & Required<Pick<Stripe.RequestOptions, 'idempotencyKey'>>;
|
|
5
|
+
/** Native Checkout parameters; the service selects payment or setup mode. */
|
|
6
|
+
export type CheckoutInput = Omit<Stripe.Checkout.SessionCreateParams, 'mode'>;
|
|
7
|
+
/** A saved customer method; the service confirms the payment off-session. */
|
|
8
|
+
export type SavedMethodCharge = Omit<Stripe.PaymentIntentCreateParams, 'confirm' | 'off_session'> & Required<Pick<Stripe.PaymentIntentCreateParams, 'customer' | 'payment_method'>>;
|
|
9
|
+
/** Native customer response, including Stripe request metadata. */
|
|
10
|
+
export type CustomerResult = Awaited<ReturnType<Stripe['customers']['create']>>;
|
|
11
|
+
/** Native Checkout response. Its URL can be null; this does not confirm payment. */
|
|
12
|
+
export type CheckoutResult = Awaited<ReturnType<Stripe['checkout']['sessions']['create']>>;
|
|
13
|
+
/** Native PaymentIntent response. Applications decide what each status permits. */
|
|
14
|
+
export type PaymentResult = Awaited<ReturnType<Stripe['paymentIntents']['create']>>;
|
|
15
|
+
/**
|
|
16
|
+
* Stripe payment operations, with native types and stable keys for mutations.
|
|
17
|
+
* Rejects with PaymentServiceError or native StripeCardError; unexpected defects propagate.
|
|
18
|
+
*/
|
|
19
|
+
export interface IPaymentService {
|
|
20
|
+
/** Create a customer; the application owns persistence and reuse of the customer link. */
|
|
21
|
+
createCustomer(input: Stripe.CustomerCreateParams, options: PaymentRequestOptions): Promise<CustomerResult>;
|
|
22
|
+
/** Create one-time payment checkout; application fulfillment requires verified payment confirmation. */
|
|
23
|
+
createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>;
|
|
24
|
+
/** Create checkout in setup mode. The application records consent and verifies the saved method's owner. */
|
|
25
|
+
setupPaymentMethod(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>;
|
|
26
|
+
/** Confirm a saved method off-session. Native card errors can require customer authentication. */
|
|
27
|
+
chargeSavedMethod(input: SavedMethodCharge, options: PaymentRequestOptions): Promise<PaymentResult>;
|
|
28
|
+
/** Retrieve an existing payment without starting another payment attempt. */
|
|
29
|
+
getPayment(paymentId: string, params?: Stripe.PaymentIntentRetrieveParams, options?: Stripe.RequestOptions): Promise<PaymentResult>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Ported from Typist's StripeClient request boundary; the native SDK now owns retries.
|
|
33
|
+
* Each request defaults to two SDK retries. Native request options can override retries and timeout.
|
|
34
|
+
*/
|
|
35
|
+
export declare class StripePaymentService implements IPaymentService {
|
|
36
|
+
private readonly stripe;
|
|
37
|
+
/** Inject a native SDK instance; its transport, credentials, and API version remain caller-owned. */
|
|
38
|
+
constructor(stripe: Stripe);
|
|
39
|
+
/** Create a customer with a stable application key and preserve the native response. */
|
|
40
|
+
createCustomer(input: Stripe.CustomerCreateParams, options: PaymentRequestOptions): Promise<CustomerResult>;
|
|
41
|
+
/** Force payment mode after caller parameters; return the native Checkout Session. */
|
|
42
|
+
createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>;
|
|
43
|
+
/** Force setup mode after caller parameters; this operation does not charge the customer. */
|
|
44
|
+
setupPaymentMethod(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>;
|
|
45
|
+
/** Force confirmation and off-session use; preserve native card failures for application handling. */
|
|
46
|
+
chargeSavedMethod(input: SavedMethodCharge, options: PaymentRequestOptions): Promise<PaymentResult>;
|
|
47
|
+
/** Preserve every native status and response field when reconciling an existing payment. */
|
|
48
|
+
getPayment(paymentId: string, params?: Stripe.PaymentIntentRetrieveParams, options?: Stripe.RequestOptions): Promise<PaymentResult>;
|
|
49
|
+
private request;
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//# sourceMappingURL=payment-service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.d.ts","names":[],"sources":["../../src/infrastructure/stripe/payment-service.ts"],"mappings":";;;YAKY,wBAAwB,OAAO,iBACzC,SAAS,KAAK,OAAO;;YAGX,gBAAgB,KAAK,OAAO,SAAS;;YAGrC,oBAAoB,KAAK,OAAO,wDAC1C,SAAS,KAAK,OAAO;;YAGX,iBAAiB,QAAQ,WAAW;;YAGpC,iBAAiB,QAAQ,WAAW;;YAGpC,gBAAgB,QAAQ,WAAW;;;;;iBAM9B;;EAEf,eACE,OAAO,OAAO,sBACd,SAAS,wBACR,QAAQ;;EAEX,eAAe,OAAO,eAAe,SAAS,wBAAwB,QAAQ;;EAE9E,mBAAmB,OAAO,eAAe,SAAS,wBAAwB,QAAQ;;EAElF,kBACE,OAAO,mBACP,SAAS,wBACR,QAAQ;;EAEX,WACE,mBACA,SAAS,OAAO,6BAChB,UAAU,OAAO,iBAChB,QAAQ;;;;;;qBAOA,gCAAgC;mBAEd;;EAA7B,YAA6B,QAAQ;;EAGrC,eACE,OAAO,OAAO,sBACd,SAAS,wBACR,QAAQ;;EAOX,eAAe,OAAO,eAAe,SAAS,wBAAwB,QAAQ;;EAU9E,mBACE,OAAO,eACP,SAAS,wBACR,QAAQ;;EAUX,kBACE,OAAO,mBACP,SAAS,wBACR,QAAQ;;EAUX,WACE,mBACA,SAAS,OAAO,6BAChB,UAAU,OAAO,iBAChB,QAAQ;UAMG"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Xt as AppError, Zt as FailureClassification } from "../index-DUFS0SJ_.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
//#region src/infrastructure/stripe/payment-service.error.d.ts
|
|
4
|
+
/** A final Stripe request failure. The caller logs once; native details remain in cause. */
|
|
5
|
+
export declare class PaymentServiceError extends AppError {
|
|
6
|
+
readonly operation: string;
|
|
7
|
+
readonly _tag = "PaymentServiceError";
|
|
8
|
+
readonly classification: FailureClassification;
|
|
9
|
+
/** Classify the final SDK error without scheduling another payment attempt. */
|
|
10
|
+
constructor(operation: string, cause: Stripe.errors.StripeError);
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//# sourceMappingURL=payment-service.error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.error.d.ts","names":[],"sources":["../../src/infrastructure/stripe/payment-service.error.ts"],"mappings":";;;;qBAKa,4BAA4B;WAM5B;WALF;WACA,gBAAgB;;EAGzB,YACW,mBACT,OAAO,OAAO,OAAO"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { nt as AppError } from "../core-UUW2unJd.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
|
|
4
|
+
//#region src/infrastructure/stripe/payment-service.error.ts
|
|
5
|
+
/** A final Stripe request failure. The caller logs once; native details remain in cause. */
|
|
6
|
+
var PaymentServiceError = class extends AppError {
|
|
7
|
+
operation;
|
|
8
|
+
_tag = "PaymentServiceError";
|
|
9
|
+
classification;
|
|
10
|
+
/** Classify the final SDK error without scheduling another payment attempt. */
|
|
11
|
+
constructor(operation, cause) {
|
|
12
|
+
super(`Stripe request failed: ${operation}`, { cause });
|
|
13
|
+
this.operation = operation;
|
|
14
|
+
this.classification = classifyStripeError(cause);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function classifyStripeError(error) {
|
|
18
|
+
if (error.headers?.["stripe-should-retry"] === "false") return "terminal";
|
|
19
|
+
const status = error.statusCode;
|
|
20
|
+
if (status !== void 0 && status >= 400 && status < 500 && status !== 409 && status !== 429) return "terminal";
|
|
21
|
+
if (error instanceof Stripe.errors.StripeAuthenticationError || error instanceof Stripe.errors.StripePermissionError || error instanceof Stripe.errors.StripeInvalidRequestError || error instanceof Stripe.errors.StripeIdempotencyError) return "terminal";
|
|
22
|
+
if (error.headers?.["stripe-should-retry"] === "true") return "transient";
|
|
23
|
+
if (status === 409 || status === 429 || status !== void 0 && status >= 500) return "transient";
|
|
24
|
+
if (error instanceof Stripe.errors.StripeConnectionError || error instanceof Stripe.errors.StripeAPIError || error instanceof Stripe.errors.StripeRateLimitError) return "transient";
|
|
25
|
+
return "unknown";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
export { PaymentServiceError };
|
|
30
|
+
//# sourceMappingURL=payment-service.error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.error.js","names":[],"sources":["../../src/infrastructure/stripe/payment-service.error.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport { AppError, type FailureClassification } from '@/core'\n\n/** A final Stripe request failure. The caller logs once; native details remain in cause. */\nexport class PaymentServiceError extends AppError {\n readonly _tag = 'PaymentServiceError'\n readonly classification: FailureClassification\n\n /** Classify the final SDK error without scheduling another payment attempt. */\n constructor(\n readonly operation: string,\n cause: Stripe.errors.StripeError,\n ) {\n super(`Stripe request failed: ${operation}`, { cause })\n this.classification = classifyStripeError(cause)\n }\n}\n\nfunction classifyStripeError(error: Stripe.errors.StripeError): FailureClassification {\n if (error.headers?.['stripe-should-retry'] === 'false') return 'terminal'\n const status = error.statusCode\n if (status !== undefined && status >= 400 && status < 500 && status !== 409 && status !== 429)\n return 'terminal'\n if (\n error instanceof Stripe.errors.StripeAuthenticationError ||\n error instanceof Stripe.errors.StripePermissionError ||\n error instanceof Stripe.errors.StripeInvalidRequestError ||\n error instanceof Stripe.errors.StripeIdempotencyError\n )\n return 'terminal'\n if (error.headers?.['stripe-should-retry'] === 'true') return 'transient'\n if (status === 409 || status === 429 || (status !== undefined && status >= 500))\n return 'transient'\n if (\n error instanceof Stripe.errors.StripeConnectionError ||\n error instanceof Stripe.errors.StripeAPIError ||\n error instanceof Stripe.errors.StripeRateLimitError\n )\n return 'transient'\n return 'unknown'\n}\n"],"mappings":";;;;;AAKA,IAAa,sBAAb,cAAyC,SAAS;CAMrC;CALX,AAAS,OAAO;CAChB,AAAS;;CAGT,YACE,AAAS,WACT,OACA;EACA,MAAM,0BAA0B,aAAa,EAAE,MAAM,CAAC;EAH7C;EAIT,KAAK,iBAAiB,oBAAoB,KAAK;CACjD;AACF;AAEA,SAAS,oBAAoB,OAAyD;CACpF,IAAI,MAAM,UAAU,2BAA2B,SAAS,OAAO;CAC/D,MAAM,SAAS,MAAM;CACrB,IAAI,WAAW,UAAa,UAAU,OAAO,SAAS,OAAO,WAAW,OAAO,WAAW,KACxF,OAAO;CACT,IACE,iBAAiB,OAAO,OAAO,6BAC/B,iBAAiB,OAAO,OAAO,yBAC/B,iBAAiB,OAAO,OAAO,6BAC/B,iBAAiB,OAAO,OAAO,wBAE/B,OAAO;CACT,IAAI,MAAM,UAAU,2BAA2B,QAAQ,OAAO;CAC9D,IAAI,WAAW,OAAO,WAAW,OAAQ,WAAW,UAAa,UAAU,KACzE,OAAO;CACT,IACE,iBAAiB,OAAO,OAAO,yBAC/B,iBAAiB,OAAO,OAAO,kBAC/B,iBAAiB,OAAO,OAAO,sBAE/B,OAAO;CACT,OAAO;AACT"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { PaymentServiceError } from "./payment-service.error.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
|
|
4
|
+
//#region src/infrastructure/stripe/payment-service.ts
|
|
5
|
+
/**
|
|
6
|
+
* Ported from Typist's StripeClient request boundary; the native SDK now owns retries.
|
|
7
|
+
* Each request defaults to two SDK retries. Native request options can override retries and timeout.
|
|
8
|
+
*/
|
|
9
|
+
var StripePaymentService = class {
|
|
10
|
+
stripe;
|
|
11
|
+
/** Inject a native SDK instance; its transport, credentials, and API version remain caller-owned. */
|
|
12
|
+
constructor(stripe) {
|
|
13
|
+
this.stripe = stripe;
|
|
14
|
+
}
|
|
15
|
+
/** Create a customer with a stable application key and preserve the native response. */
|
|
16
|
+
createCustomer(input, options) {
|
|
17
|
+
return this.request("customers.create", () => this.stripe.customers.create(input, {
|
|
18
|
+
maxNetworkRetries: 2,
|
|
19
|
+
...options
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
/** Force payment mode after caller parameters; return the native Checkout Session. */
|
|
23
|
+
createCheckout(input, options) {
|
|
24
|
+
return this.request("checkout.sessions.create", () => this.stripe.checkout.sessions.create({
|
|
25
|
+
...input,
|
|
26
|
+
mode: "payment"
|
|
27
|
+
}, {
|
|
28
|
+
maxNetworkRetries: 2,
|
|
29
|
+
...options
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
/** Force setup mode after caller parameters; this operation does not charge the customer. */
|
|
33
|
+
setupPaymentMethod(input, options) {
|
|
34
|
+
return this.request("checkout.sessions.create", () => this.stripe.checkout.sessions.create({
|
|
35
|
+
...input,
|
|
36
|
+
mode: "setup"
|
|
37
|
+
}, {
|
|
38
|
+
maxNetworkRetries: 2,
|
|
39
|
+
...options
|
|
40
|
+
}));
|
|
41
|
+
}
|
|
42
|
+
/** Force confirmation and off-session use; preserve native card failures for application handling. */
|
|
43
|
+
chargeSavedMethod(input, options) {
|
|
44
|
+
return this.request("paymentIntents.create", () => this.stripe.paymentIntents.create({
|
|
45
|
+
...input,
|
|
46
|
+
confirm: true,
|
|
47
|
+
off_session: true
|
|
48
|
+
}, {
|
|
49
|
+
maxNetworkRetries: 2,
|
|
50
|
+
...options
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
/** Preserve every native status and response field when reconciling an existing payment. */
|
|
54
|
+
getPayment(paymentId, params, options) {
|
|
55
|
+
return this.request("paymentIntents.retrieve", () => this.stripe.paymentIntents.retrieve(paymentId, params, {
|
|
56
|
+
maxNetworkRetries: 2,
|
|
57
|
+
...options
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
async request(operation, work) {
|
|
61
|
+
try {
|
|
62
|
+
return await work();
|
|
63
|
+
} catch (cause) {
|
|
64
|
+
if (!(cause instanceof Stripe.errors.StripeError) || cause instanceof Stripe.errors.StripeCardError) throw cause;
|
|
65
|
+
throw new PaymentServiceError(operation, cause);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
//#endregion
|
|
71
|
+
export { StripePaymentService };
|
|
72
|
+
//# sourceMappingURL=payment-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.js","names":[],"sources":["../../src/infrastructure/stripe/payment-service.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport { PaymentServiceError } from './payment-service.error.ts'\n\n/** Supply the same key and parameters when repeating one durable payment attempt. */\nexport type PaymentRequestOptions = Stripe.RequestOptions &\n Required<Pick<Stripe.RequestOptions, 'idempotencyKey'>>\n\n/** Native Checkout parameters; the service selects payment or setup mode. */\nexport type CheckoutInput = Omit<Stripe.Checkout.SessionCreateParams, 'mode'>\n\n/** A saved customer method; the service confirms the payment off-session. */\nexport type SavedMethodCharge = Omit<Stripe.PaymentIntentCreateParams, 'confirm' | 'off_session'> &\n Required<Pick<Stripe.PaymentIntentCreateParams, 'customer' | 'payment_method'>>\n\n/** Native customer response, including Stripe request metadata. */\nexport type CustomerResult = Awaited<ReturnType<Stripe['customers']['create']>>\n\n/** Native Checkout response. Its URL can be null; this does not confirm payment. */\nexport type CheckoutResult = Awaited<ReturnType<Stripe['checkout']['sessions']['create']>>\n\n/** Native PaymentIntent response. Applications decide what each status permits. */\nexport type PaymentResult = Awaited<ReturnType<Stripe['paymentIntents']['create']>>\n\n/**\n * Stripe payment operations, with native types and stable keys for mutations.\n * Rejects with PaymentServiceError or native StripeCardError; unexpected defects propagate.\n */\nexport interface IPaymentService {\n /** Create a customer; the application owns persistence and reuse of the customer link. */\n createCustomer(\n input: Stripe.CustomerCreateParams,\n options: PaymentRequestOptions,\n ): Promise<CustomerResult>\n /** Create one-time payment checkout; application fulfillment requires verified payment confirmation. */\n createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>\n /** Create checkout in setup mode. The application records consent and verifies the saved method's owner. */\n setupPaymentMethod(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult>\n /** Confirm a saved method off-session. Native card errors can require customer authentication. */\n chargeSavedMethod(\n input: SavedMethodCharge,\n options: PaymentRequestOptions,\n ): Promise<PaymentResult>\n /** Retrieve an existing payment without starting another payment attempt. */\n getPayment(\n paymentId: string,\n params?: Stripe.PaymentIntentRetrieveParams,\n options?: Stripe.RequestOptions,\n ): Promise<PaymentResult>\n}\n\n/**\n * Ported from Typist's StripeClient request boundary; the native SDK now owns retries.\n * Each request defaults to two SDK retries. Native request options can override retries and timeout.\n */\nexport class StripePaymentService implements IPaymentService {\n /** Inject a native SDK instance; its transport, credentials, and API version remain caller-owned. */\n constructor(private readonly stripe: Stripe) {}\n\n /** Create a customer with a stable application key and preserve the native response. */\n createCustomer(\n input: Stripe.CustomerCreateParams,\n options: PaymentRequestOptions,\n ): Promise<CustomerResult> {\n return this.request('customers.create', () =>\n this.stripe.customers.create(input, { maxNetworkRetries: 2, ...options }),\n )\n }\n\n /** Force payment mode after caller parameters; return the native Checkout Session. */\n createCheckout(input: CheckoutInput, options: PaymentRequestOptions): Promise<CheckoutResult> {\n return this.request('checkout.sessions.create', () =>\n this.stripe.checkout.sessions.create(\n { ...input, mode: 'payment' },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Force setup mode after caller parameters; this operation does not charge the customer. */\n setupPaymentMethod(\n input: CheckoutInput,\n options: PaymentRequestOptions,\n ): Promise<CheckoutResult> {\n return this.request('checkout.sessions.create', () =>\n this.stripe.checkout.sessions.create(\n { ...input, mode: 'setup' },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Force confirmation and off-session use; preserve native card failures for application handling. */\n chargeSavedMethod(\n input: SavedMethodCharge,\n options: PaymentRequestOptions,\n ): Promise<PaymentResult> {\n return this.request('paymentIntents.create', () =>\n this.stripe.paymentIntents.create(\n { ...input, confirm: true, off_session: true },\n { maxNetworkRetries: 2, ...options },\n ),\n )\n }\n\n /** Preserve every native status and response field when reconciling an existing payment. */\n getPayment(\n paymentId: string,\n params?: Stripe.PaymentIntentRetrieveParams,\n options?: Stripe.RequestOptions,\n ): Promise<PaymentResult> {\n return this.request('paymentIntents.retrieve', () =>\n this.stripe.paymentIntents.retrieve(paymentId, params, { maxNetworkRetries: 2, ...options }),\n )\n }\n\n private async request<T>(operation: string, work: () => Promise<T>): Promise<T> {\n try {\n return await work()\n } catch (cause) {\n if (\n !(cause instanceof Stripe.errors.StripeError) ||\n cause instanceof Stripe.errors.StripeCardError\n )\n throw cause\n throw new PaymentServiceError(operation, cause)\n }\n }\n}\n"],"mappings":";;;;;;;;AAuDA,IAAa,uBAAb,MAA6D;CAE9B;;CAA7B,YAAY,AAAiB,QAAgB;EAAhB;CAAiB;;CAG9C,eACE,OACA,SACyB;EACzB,OAAO,KAAK,QAAQ,0BAClB,KAAK,OAAO,UAAU,OAAO,OAAO;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CAAC,CAC1E;CACF;;CAGA,eAAe,OAAsB,SAAyD;EAC5F,OAAO,KAAK,QAAQ,kCAClB,KAAK,OAAO,SAAS,SAAS,OAC5B;GAAE,GAAG;GAAO,MAAM;EAAU,GAC5B;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,mBACE,OACA,SACyB;EACzB,OAAO,KAAK,QAAQ,kCAClB,KAAK,OAAO,SAAS,SAAS,OAC5B;GAAE,GAAG;GAAO,MAAM;EAAQ,GAC1B;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,kBACE,OACA,SACwB;EACxB,OAAO,KAAK,QAAQ,+BAClB,KAAK,OAAO,eAAe,OACzB;GAAE,GAAG;GAAO,SAAS;GAAM,aAAa;EAAK,GAC7C;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CACrC,CACF;CACF;;CAGA,WACE,WACA,QACA,SACwB;EACxB,OAAO,KAAK,QAAQ,iCAClB,KAAK,OAAO,eAAe,SAAS,WAAW,QAAQ;GAAE,mBAAmB;GAAG,GAAG;EAAQ,CAAC,CAC7F;CACF;CAEA,MAAc,QAAW,WAAmB,MAAoC;EAC9E,IAAI;GACF,OAAO,MAAM,KAAK;EACpB,SAAS,OAAO;GACd,IACE,EAAE,iBAAiB,OAAO,OAAO,gBACjC,iBAAiB,OAAO,OAAO,iBAE/B,MAAM;GACR,MAAM,IAAI,oBAAoB,WAAW,KAAK;EAChD;CACF;AACF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { r as WebhookVerifier, t as WebhookVerification } from "../webhook-verification-BuxPzdr4.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
//#region src/infrastructure/stripe/payment-webhook.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.
|
|
6
|
+
* Returns native events; application conversion owns event selection and payload validation.
|
|
7
|
+
*/
|
|
8
|
+
export declare class StripeWebhookVerifier implements WebhookVerifier<Stripe.Event> {
|
|
9
|
+
private readonly stripe;
|
|
10
|
+
private readonly signingSecret;
|
|
11
|
+
private readonly tolerance?;
|
|
12
|
+
/** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */
|
|
13
|
+
constructor(stripe: Stripe, signingSecret: string, tolerance?: number | undefined);
|
|
14
|
+
/** Reject signature and JSON failures. Operational failures propagate without logging. */
|
|
15
|
+
verify(body: string, headers: Headers): Promise<WebhookVerification<Stripe.Event>>;
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
//# sourceMappingURL=payment-webhook.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-webhook.d.ts","names":[],"sources":["../../src/infrastructure/stripe/payment-webhook.ts"],"mappings":";;;;;;;qBAYa,iCAAiC,gBAAgB,OAAO;mBAGhD;mBACA;mBACA;;EAHnB,YACmB,QAAQ,QACR,uBACA;;EAIb,OAAO,cAAc,SAAS,UAAU,QAAQ,oBAAoB,OAAO"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { t as WebhookVerificationError } from "../webhook-verification-BBmjkHgI.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
|
|
4
|
+
//#region src/infrastructure/stripe/payment-webhook.ts
|
|
5
|
+
/**
|
|
6
|
+
* Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.
|
|
7
|
+
* Returns native events; application conversion owns event selection and payload validation.
|
|
8
|
+
*/
|
|
9
|
+
var StripeWebhookVerifier = class {
|
|
10
|
+
stripe;
|
|
11
|
+
signingSecret;
|
|
12
|
+
tolerance;
|
|
13
|
+
/** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */
|
|
14
|
+
constructor(stripe, signingSecret, tolerance) {
|
|
15
|
+
this.stripe = stripe;
|
|
16
|
+
this.signingSecret = signingSecret;
|
|
17
|
+
this.tolerance = tolerance;
|
|
18
|
+
}
|
|
19
|
+
/** Reject signature and JSON failures. Operational failures propagate without logging. */
|
|
20
|
+
async verify(body, headers) {
|
|
21
|
+
const signature = headers.get("stripe-signature");
|
|
22
|
+
if (!signature) return {
|
|
23
|
+
outcome: "rejected",
|
|
24
|
+
error: new WebhookVerificationError("missing_headers")
|
|
25
|
+
};
|
|
26
|
+
try {
|
|
27
|
+
return {
|
|
28
|
+
outcome: "event",
|
|
29
|
+
event: await this.stripe.webhooks.constructEventAsync(body, signature, this.signingSecret, this.tolerance, Stripe.createSubtleCryptoProvider())
|
|
30
|
+
};
|
|
31
|
+
} catch (cause) {
|
|
32
|
+
if (cause instanceof Stripe.errors.StripeSignatureVerificationError) return {
|
|
33
|
+
outcome: "rejected",
|
|
34
|
+
error: new WebhookVerificationError("invalid_signature", cause)
|
|
35
|
+
};
|
|
36
|
+
if (cause instanceof SyntaxError) return {
|
|
37
|
+
outcome: "rejected",
|
|
38
|
+
error: new WebhookVerificationError("invalid_payload", cause)
|
|
39
|
+
};
|
|
40
|
+
throw cause;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { StripeWebhookVerifier };
|
|
47
|
+
//# sourceMappingURL=payment-webhook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-webhook.js","names":[],"sources":["../../src/infrastructure/stripe/payment-webhook.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport {\n WebhookVerificationError,\n type WebhookVerification,\n type WebhookVerifier,\n} from '../http/webhook-verification.ts'\n\n/**\n * Authenticate raw Stripe webhook bodies with the SDK's timestamp tolerance and Web Crypto.\n * Returns native events; application conversion owns event selection and payload validation.\n */\nexport class StripeWebhookVerifier implements WebhookVerifier<Stripe.Event> {\n /** Supply the endpoint's signing secret. Tolerance defaults to Stripe's five-minute window. */\n constructor(\n private readonly stripe: Stripe,\n private readonly signingSecret: string,\n private readonly tolerance?: number,\n ) {}\n\n /** Reject signature and JSON failures. Operational failures propagate without logging. */\n async verify(body: string, headers: Headers): Promise<WebhookVerification<Stripe.Event>> {\n const signature = headers.get('stripe-signature')\n if (!signature)\n return { outcome: 'rejected', error: new WebhookVerificationError('missing_headers') }\n try {\n const event = await this.stripe.webhooks.constructEventAsync(\n body,\n signature,\n this.signingSecret,\n this.tolerance,\n Stripe.createSubtleCryptoProvider(),\n )\n return { outcome: 'event', event }\n } catch (cause) {\n if (cause instanceof Stripe.errors.StripeSignatureVerificationError)\n return {\n outcome: 'rejected',\n error: new WebhookVerificationError('invalid_signature', cause),\n }\n if (cause instanceof SyntaxError)\n return {\n outcome: 'rejected',\n error: new WebhookVerificationError('invalid_payload', cause),\n }\n throw cause\n }\n }\n}\n"],"mappings":";;;;;;;;AAYA,IAAa,wBAAb,MAA4E;CAGvD;CACA;CACA;;CAHnB,YACE,AAAiB,QACjB,AAAiB,eACjB,AAAiB,WACjB;EAHiB;EACA;EACA;CAChB;;CAGH,MAAM,OAAO,MAAc,SAA8D;EACvF,MAAM,YAAY,QAAQ,IAAI,kBAAkB;EAChD,IAAI,CAAC,WACH,OAAO;GAAE,SAAS;GAAY,OAAO,IAAI,yBAAyB,iBAAiB;EAAE;EACvF,IAAI;GAQF,OAAO;IAAE,SAAS;IAAS,aAPP,KAAK,OAAO,SAAS,oBACvC,MACA,WACA,KAAK,eACL,KAAK,WACL,OAAO,2BAA2B,CACpC;GACiC;EACnC,SAAS,OAAO;GACd,IAAI,iBAAiB,OAAO,OAAO,kCACjC,OAAO;IACL,SAAS;IACT,OAAO,IAAI,yBAAyB,qBAAqB,KAAK;GAChE;GACF,IAAI,iBAAiB,aACnB,OAAO;IACL,SAAS;IACT,OAAO,IAAI,yBAAyB,mBAAmB,KAAK;GAC9D;GACF,MAAM;EACR;CACF;AACF"}
|
package/dist/tanstack.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ot as ErrorTable } from "./index-DUFS0SJ_.js";
|
|
2
2
|
import { Register } from "@tanstack/react-start";
|
|
3
3
|
import { BetterAuthCookies } from "better-auth";
|
|
4
4
|
//#region src/infrastructure/tanstack/request-context.d.ts
|
package/dist/tanstack.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { H as StaleSessionError, R as ValidationError, W as AuthenticationError, nt as AppError, r as createLogger } from "./core-UUW2unJd.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { getReasonPhrase } from "http-status-codes";
|
|
4
4
|
import { isNotFound, isRedirect, redirect } from "@tanstack/react-router";
|
|
@@ -71,16 +71,16 @@ const logger = createLogger("error-boundary");
|
|
|
71
71
|
function resolveFailure(table, cause) {
|
|
72
72
|
const resolved = table.resolve(cause);
|
|
73
73
|
if (resolved !== null) {
|
|
74
|
-
logger.warn("handled_error", {
|
|
74
|
+
logger.warn("handled_error", {
|
|
75
75
|
tag: resolved.payload._tag,
|
|
76
76
|
status: resolved.status
|
|
77
|
-
}
|
|
77
|
+
});
|
|
78
78
|
return resolved;
|
|
79
79
|
}
|
|
80
80
|
const classification = cause instanceof AppError ? cause.classification : "unknown";
|
|
81
81
|
logger.error("unexpected_error", {
|
|
82
82
|
error: cause,
|
|
83
|
-
|
|
83
|
+
classification
|
|
84
84
|
});
|
|
85
85
|
return table.fallback(cause);
|
|
86
86
|
}
|
package/dist/tanstack.js.map
CHANGED
|
@@ -1 +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"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport type { RequestContext } from './request-context.ts'\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: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\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 const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\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: RequestContext,\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, await requestHeaders())\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 type { deleteCookie } 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 async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.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 server.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, redirect } from '@tanstack/react-router'\nimport { createMiddleware } 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 type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\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 /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\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 await 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 redirect({ href: 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"],"mappings":";;;;;;;;AAOA,MAAMA,WAAS,aAAa,iBAAiB;AAgC7C,MAAM,iBAAiB,YAAY;CACjC,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO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AwC;EAClE,MAAM,EAAE,gBAAgB,MAAM,QAAQ,QAAQ,OAAO,CAAC,CAAC;EACvD,MAAM,yBAAyB,WAAW;CAC5C;CAEA,eAAe,oBAAoB,OAAgB,SAAyC;EAE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB;GACtC,MAAM,aAAa,OAAO;GAE1B,MAAM,SAAS,EAAE,MAAM,QAAQ,OAAO,CAAC;EACzC;EAEA,MAAM,eAAe,KAAK;CAC5B;CAGA,eAAe,iBAAiB,OAAgB,SAA4C;EAE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB,MAAM,aAAa,OAAO;EAClE,OAAO,oBAAoB,KAAK;CAClC;CAsBA,OAAO;EAAE,yBApBuB,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACrE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,oBAAoB,OAAO,OAAO;GAC3C;EACF,CAa6B;EAAG,sBAVL,iBAAiB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OACjE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,iBAAiB,OAAO,OAAO;GACxC;EACF,CAGmD;EAAG;EAAgB;CAAoB;AAC9F"}
|
|
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"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { getSessionCookie } from 'better-auth/cookies'\n\nimport { AuthenticationError, StaleSessionError, createLogger } from '@/core'\n\nimport type { RequestContext } from './request-context.ts'\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: RequestContext) => {\n readonly api: {\n readonly getSession: (options: { headers: Headers }) => Promise<Session | null>\n }\n }\n}\n\n// The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily inside `.server()`.\nconst requestHeaders = async () => {\n const { getRequestHeaders } = await import('@tanstack/react-start/server')\n return getRequestHeaders()\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 const headers = await requestHeaders()\n resolved = await options.getAuth(context).api.getSession({ headers })\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: RequestContext,\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, await requestHeaders())\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 tag: resolved.payload._tag,\n status: resolved.status,\n })\n return resolved\n }\n const classification = cause instanceof AppError ? cause.classification : 'unknown'\n logger.error('unexpected_error', { error: cause, 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 type { deleteCookie } 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 async function clearStaleSessionCookies(cookies: BetterAuthCookies): Promise<void> {\n // The server entry loads react-dom/server; the browser evaluates this module, so it loads lazily here.\n const server = await import('@tanstack/react-start/server')\n const present = [...parseCookies(server.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 server.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, redirect } from '@tanstack/react-router'\nimport { createMiddleware } 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 type { RequestContext } from './request-context.ts'\nimport { clearStaleSessionCookies } from './session-cookies.ts'\nimport { createErrorPayloadConverter } from './to-error-payload.ts'\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 /** The path a server function redirects to for a stale session, with any search string. */\n readonly signIn: string\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 await 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 redirect({ href: 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"],"mappings":";;;;;;;;AAOA,MAAMA,WAAS,aAAa,iBAAiB;AAgC7C,MAAM,iBAAiB,YAAY;CACjC,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAC3C,OAAO,kBAAkB;AAC3B;;;;;AAMA,SAAgB,qBACd,SACA;CACA,MAAM,cAAc,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACzD,OAAO,EAAE,MAAM,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,MAAM,UAAU,MAAM,eAAe;GACrC,WAAW,MAAM,QAAQ,QAAQ,OAAO,CAAC,CAAC,IAAI,WAAW,EAAE,QAAQ,CAAC;EACtE,SAAS,OAAO;GACd,SAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC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AE1F,IAAI,WAAW,KAAK,KAAK,WAAW,KAAK,GAAG,MAAM;EAClD,IAAI,iBAAiB,mBAAmB,MAAM,aAAa,OAAO;EAClE,OAAO,oBAAoB,KAAK;CAClC;CAsBA,OAAO;EAAE,yBApBuB,iBAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,OACrE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,oBAAoB,OAAO,OAAO;GAC3C;EACF,CAa6B;EAAG,sBAVL,iBAAiB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OACjE,OAAO,EAAE,MAAM,cAAc;GAC3B,IAAI;IACF,OAAO,MAAM,KAAK;GACpB,SAAS,OAAO;IACd,OAAO,iBAAiB,OAAO,OAAO;GACxC;EACF,CAGmD;EAAG;EAAgB;CAAoB;AAC9F"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { A as IOutboxRepository } from "../index-
|
|
1
|
+
import { W as DomainEvent } from "../index-DUFS0SJ_.js";
|
|
2
|
+
import { A as IOutboxRepository } from "../index-CYHXOH08.js";
|
|
3
3
|
//#region src/infrastructure/testing/outbox-repository-contract.d.ts
|
|
4
4
|
/** Stored fields observed by the adapter contract, independent of a database library. */
|
|
5
5
|
export type OutboxContractRow = {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { IPaymentService } from "../stripe/payment-service.js";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
//#region src/infrastructure/testing/payment-service-contract.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Test a Stripe payment adapter through native fetch injection without live payments.
|
|
6
|
+
* Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.
|
|
7
|
+
*/
|
|
8
|
+
export declare function paymentServiceContract(test: (name: string, run: () => Promise<void>) => void, create: (stripe: Stripe) => IPaymentService): void;
|
|
9
|
+
//#endregion
|
|
10
|
+
//# sourceMappingURL=payment-service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.d.ts","names":[],"sources":["../../src/infrastructure/testing/payment-service-contract.ts"],"mappings":";;;;;;;wBAUgB,uBACd,OAAO,cAAc,WAAW,wBAChC,SAAS,QAAQ,WAAW"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { deepStrictEqual, equal, rejects } from "node:assert/strict";
|
|
3
|
+
|
|
4
|
+
//#region src/infrastructure/testing/payment-service-contract.ts
|
|
5
|
+
/**
|
|
6
|
+
* Test a Stripe payment adapter through native fetch injection without live payments.
|
|
7
|
+
* Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.
|
|
8
|
+
*/
|
|
9
|
+
function paymentServiceContract(test, create) {
|
|
10
|
+
test("payment checkout selects payment mode and retains the supplied key", async () => {
|
|
11
|
+
const fixture = paymentFixture(create);
|
|
12
|
+
await fixture.service.createCheckout({ customer: "cus_contract" }, { idempotencyKey: "checkout:contract" });
|
|
13
|
+
equal(fixture.requests[0]?.body.get("mode"), "payment");
|
|
14
|
+
equal(fixture.requests[0]?.headers.get("idempotency-key"), "checkout:contract");
|
|
15
|
+
});
|
|
16
|
+
test("payment method setup selects setup mode", async () => {
|
|
17
|
+
const fixture = paymentFixture(create);
|
|
18
|
+
await fixture.service.setupPaymentMethod({ customer: "cus_contract" }, { idempotencyKey: "setup:contract" });
|
|
19
|
+
equal(fixture.requests[0]?.body.get("mode"), "setup");
|
|
20
|
+
});
|
|
21
|
+
test("saved method payments confirm off-session", async () => {
|
|
22
|
+
const fixture = paymentFixture(create);
|
|
23
|
+
await fixture.service.chargeSavedMethod({
|
|
24
|
+
amount: 1e3,
|
|
25
|
+
currency: "usd",
|
|
26
|
+
customer: "cus_contract",
|
|
27
|
+
payment_method: "pm_contract"
|
|
28
|
+
}, { idempotencyKey: "charge:contract" });
|
|
29
|
+
equal(fixture.requests[0]?.body.get("confirm"), "true");
|
|
30
|
+
equal(fixture.requests[0]?.body.get("off_session"), "true");
|
|
31
|
+
});
|
|
32
|
+
test("payment reads preserve native statuses and response fields", async () => {
|
|
33
|
+
const payment = await paymentFixture(create).service.getPayment("pi_contract");
|
|
34
|
+
deepStrictEqual({
|
|
35
|
+
id: payment.id,
|
|
36
|
+
status: payment.status
|
|
37
|
+
}, {
|
|
38
|
+
id: "pi_contract",
|
|
39
|
+
status: "requires_capture"
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
test("card failures retain the native error contract", async () => {
|
|
43
|
+
const fixture = paymentFixture(create, Response.json({ error: {
|
|
44
|
+
type: "card_error",
|
|
45
|
+
code: "authentication_required",
|
|
46
|
+
message: "Authentication required"
|
|
47
|
+
} }, { status: 402 }));
|
|
48
|
+
await rejects(fixture.service.chargeSavedMethod({
|
|
49
|
+
amount: 1e3,
|
|
50
|
+
currency: "usd",
|
|
51
|
+
customer: "cus_contract",
|
|
52
|
+
payment_method: "pm_contract"
|
|
53
|
+
}, { idempotencyKey: "charge:contract" }), Stripe.errors.StripeCardError);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function paymentFixture(create, response = Response.json({
|
|
57
|
+
id: "pi_contract",
|
|
58
|
+
status: "requires_capture"
|
|
59
|
+
})) {
|
|
60
|
+
const requests = [];
|
|
61
|
+
return {
|
|
62
|
+
service: create(new Stripe("sk_test_contract", { httpClient: Stripe.createFetchHttpClient(async (input, init) => {
|
|
63
|
+
const request = new Request(input, init);
|
|
64
|
+
requests.push({
|
|
65
|
+
headers: request.headers,
|
|
66
|
+
body: new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer()))
|
|
67
|
+
});
|
|
68
|
+
return response.clone();
|
|
69
|
+
}) })),
|
|
70
|
+
requests
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
//#endregion
|
|
75
|
+
export { paymentServiceContract };
|
|
76
|
+
//# sourceMappingURL=payment-service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-service.js","names":[],"sources":["../../src/infrastructure/testing/payment-service-contract.ts"],"sourcesContent":["import { deepStrictEqual, equal, rejects } from 'node:assert/strict'\n\nimport Stripe from 'stripe'\n\nimport type { IPaymentService } from '../stripe/payment-service.ts'\n\n/**\n * Test a Stripe payment adapter through native fetch injection without live payments.\n * Each case constructs a fresh SDK instance and adapter; no Vitest dependency is required.\n */\nexport function paymentServiceContract(\n test: (name: string, run: () => Promise<void>) => void,\n create: (stripe: Stripe) => IPaymentService,\n): void {\n test('payment checkout selects payment mode and retains the supplied key', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.createCheckout(\n { customer: 'cus_contract' },\n { idempotencyKey: 'checkout:contract' },\n )\n equal(fixture.requests[0]?.body.get('mode'), 'payment')\n equal(fixture.requests[0]?.headers.get('idempotency-key'), 'checkout:contract')\n })\n\n test('payment method setup selects setup mode', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.setupPaymentMethod(\n { customer: 'cus_contract' },\n { idempotencyKey: 'setup:contract' },\n )\n equal(fixture.requests[0]?.body.get('mode'), 'setup')\n })\n\n test('saved method payments confirm off-session', async () => {\n const fixture = paymentFixture(create)\n await fixture.service.chargeSavedMethod(\n { amount: 1000, currency: 'usd', customer: 'cus_contract', payment_method: 'pm_contract' },\n { idempotencyKey: 'charge:contract' },\n )\n equal(fixture.requests[0]?.body.get('confirm'), 'true')\n equal(fixture.requests[0]?.body.get('off_session'), 'true')\n })\n\n test('payment reads preserve native statuses and response fields', async () => {\n const fixture = paymentFixture(create)\n const payment = await fixture.service.getPayment('pi_contract')\n deepStrictEqual(\n { id: payment.id, status: payment.status },\n { id: 'pi_contract', status: 'requires_capture' },\n )\n })\n\n test('card failures retain the native error contract', async () => {\n const response = Response.json(\n {\n error: {\n type: 'card_error',\n code: 'authentication_required',\n message: 'Authentication required',\n },\n },\n { status: 402 },\n )\n const fixture = paymentFixture(create, response)\n await rejects(\n fixture.service.chargeSavedMethod(\n { amount: 1000, currency: 'usd', customer: 'cus_contract', payment_method: 'pm_contract' },\n { idempotencyKey: 'charge:contract' },\n ),\n Stripe.errors.StripeCardError,\n )\n })\n}\n\nfunction paymentFixture(\n create: (stripe: Stripe) => IPaymentService,\n response = Response.json({ id: 'pi_contract', status: 'requires_capture' }),\n) {\n const requests: { headers: Headers; body: URLSearchParams }[] = []\n const stripe = new Stripe('sk_test_contract', {\n httpClient: Stripe.createFetchHttpClient(async (input, init) => {\n const request = new Request(input, init)\n requests.push({\n headers: request.headers,\n body: new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer())),\n })\n return response.clone()\n }),\n })\n return { service: create(stripe), requests }\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,uBACd,MACA,QACM;CACN,KAAK,sEAAsE,YAAY;EACrF,MAAM,UAAU,eAAe,MAAM;EACrC,MAAM,QAAQ,QAAQ,eACpB,EAAE,UAAU,eAAe,GAC3B,EAAE,gBAAgB,oBAAoB,CACxC;EACA,MAAM,QAAQ,SAAS,EAAE,EAAE,KAAK,IAAI,MAAM,GAAG,SAAS;EACtD,MAAM,QAAQ,SAAS,EAAE,EAAE,QAAQ,IAAI,iBAAiB,GAAG,mBAAmB;CAChF,CAAC;CAED,KAAK,2CAA2C,YAAY;EAC1D,MAAM,UAAU,eAAe,MAAM;EACrC,MAAM,QAAQ,QAAQ,mBACpB,EAAE,UAAU,eAAe,GAC3B,EAAE,gBAAgB,iBAAiB,CACrC;EACA,MAAM,QAAQ,SAAS,EAAE,EAAE,KAAK,IAAI,MAAM,GAAG,OAAO;CACtD,CAAC;CAED,KAAK,6CAA6C,YAAY;EAC5D,MAAM,UAAU,eAAe,MAAM;EACrC,MAAM,QAAQ,QAAQ,kBACpB;GAAE,QAAQ;GAAM,UAAU;GAAO,UAAU;GAAgB,gBAAgB;EAAc,GACzF,EAAE,gBAAgB,kBAAkB,CACtC;EACA,MAAM,QAAQ,SAAS,EAAE,EAAE,KAAK,IAAI,SAAS,GAAG,MA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/** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */
|
|
@@ -15,4 +15,4 @@ var WebhookVerificationError = class extends AppError {
|
|
|
15
15
|
|
|
16
16
|
//#endregion
|
|
17
17
|
export { WebhookVerificationError as t };
|
|
18
|
-
//# sourceMappingURL=webhook-verification-
|
|
18
|
+
//# sourceMappingURL=webhook-verification-BBmjkHgI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-verification-
|
|
1
|
+
{"version":3,"file":"webhook-verification-BBmjkHgI.js","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"sourcesContent":["import { AppError } from '@/core'\n\n/** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */\nexport class WebhookVerificationError extends AppError {\n readonly _tag = 'WebhookVerificationError'\n readonly classification = 'terminal'\n\n /** Keep secrets and payload details out of the public message. */\n constructor(\n readonly reason: 'missing_headers' | 'invalid_signature' | 'invalid_payload',\n cause?: unknown,\n ) {\n super(`Webhook rejected: ${reason}`, { cause })\n }\n}\n\n/** A verified event, an ignored event, or an invalid request. */\nexport type WebhookVerification<Event> =\n | { readonly outcome: 'event'; readonly event: Event }\n | { readonly outcome: 'ignored'; readonly type: string }\n | { readonly outcome: 'rejected'; readonly error: WebhookVerificationError }\n\n/** The provider owns signature verification, timestamp tolerance, and payload parsing. */\nexport interface WebhookVerifier<Event> {\n /** Verify the exact body before parsing it. Return invalid requests; throw operational failures. */\n verify(body: string, headers: Headers): Promise<WebhookVerification<Event>>\n}\n"],"mappings":";;;;AAGA,IAAa,2BAAb,cAA8C,SAAS;CAM1C;CALX,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YACE,AAAS,QACT,OACA;EACA,MAAM,qBAAqB,UAAU,EAAE,MAAM,CAAC;EAHrC;CAIX;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Xt as AppError } from "./index-DUFS0SJ_.js";
|
|
2
2
|
//#region src/infrastructure/http/webhook-verification.d.ts
|
|
3
3
|
/** A webhook cannot be trusted or parsed. The HTTP handler logs the rejection once. */
|
|
4
4
|
declare class WebhookVerificationError extends AppError {
|
|
@@ -26,4 +26,4 @@ interface WebhookVerifier<Event> {
|
|
|
26
26
|
}
|
|
27
27
|
//#endregion
|
|
28
28
|
export { WebhookVerificationError as n, WebhookVerifier as r, WebhookVerification as t };
|
|
29
|
-
//# sourceMappingURL=webhook-verification-
|
|
29
|
+
//# sourceMappingURL=webhook-verification-BuxPzdr4.d.ts.map
|
package/dist/{webhook-verification-BcQQG-vY.d.ts.map → webhook-verification-BuxPzdr4.d.ts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-verification-
|
|
1
|
+
{"version":3,"file":"webhook-verification-BuxPzdr4.d.ts","names":[],"sources":["../src/infrastructure/http/webhook-verification.ts"],"mappings":";;;cAGa,iCAAiC;WAMjC;WALF;WACA;;EAGT,YACW,qEACT;;;KAOQ,oBAAoB;WACjB;WAA2B,OAAO;;WAClC;WAA6B;;WAC7B;WAA8B,OAAO;;;UAGnC,gBAAgB;;EAE/B,OAAO,cAAc,SAAS,UAAU,QAAQ,oBAAoB"}
|