@shware/purchase 6.0.0 → 7.1.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/README.md CHANGED
@@ -12,18 +12,18 @@ signatures and calling store APIs stays in your app, with the official SDKs.
12
12
  ```sh
13
13
  pnpm add @shware/purchase zod
14
14
  # optional peers, only for the subpaths you use
15
- pnpm add stripe # @shware/purchase/stripe (^22.6.2 || ^23.0.0)
15
+ pnpm add stripe # @shware/purchase/stripe (^23.0.0)
16
16
  pnpm add @apple/app-store-server-library # @shware/purchase/app-store (^3.1.0)
17
17
  ```
18
18
 
19
19
  ## Entry points
20
20
 
21
- | Import path | Contents |
22
- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
23
- | `@shware/purchase` | Subscription model (`PLATFORMS`, `SUBSCRIPTION_STATUSES`, `AVAILABLE_STATUSES`, cancellation types) and the three configs |
24
- | `@shware/purchase/stripe` | `StripeEventHandler`, Stripe mappers, checkout schemas, `METADATA_KEYS`, analytics helpers, browser pending-checkout helpers |
25
- | `@shware/purchase/app-store` | `AppStoreNotificationHandler` for App Store Server Notifications V2, `mapCancellationDetails` |
26
- | `@shware/purchase/google-play` | Real-time developer notification (RTDN) types and enums, subscription state and cancellation mappers |
21
+ | Import path | Contents |
22
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
23
+ | `@shware/purchase` | Subscription model (`PLATFORMS`, `SUBSCRIPTION_STATUSES`, `AVAILABLE_STATUSES`, cancellation types) and the three configs |
24
+ | `@shware/purchase/stripe` | `StripeThinEventHandler`, `StripeEventHandler`, Stripe mappers, checkout schemas, `METADATA_KEYS`, analytics helpers, browser pending-checkout helpers |
25
+ | `@shware/purchase/app-store` | `AppStoreNotificationHandler` for App Store Server Notifications V2, `mapCancellationDetails` |
26
+ | `@shware/purchase/google-play` | Real-time developer notification (RTDN) types and enums, subscription state and cancellation mappers |
27
27
 
28
28
  ## Subscription model
29
29
 
@@ -131,14 +131,38 @@ so existing subscribers keep resolving.
131
131
 
132
132
  ### Webhooks
133
133
 
134
- Verify the signature with the Stripe SDK, then dispatch with `StripeEventHandler`. `on` is typed
135
- per event, so each handler receives the right `event.data.object`; `process` throws for an event
136
- type with no handler.
134
+ Two dispatchers, one per Stripe [event format](https://docs.stripe.com/events/how-events-work#event-formats).
135
+ Both are typed per event type, run every handler registered for a type, and throw from `process`
136
+ for a type with no handler.
137
+
138
+ | Handler | Event format | Verify with | Handlers receive |
139
+ | ------------------------ | ------------ | ------------------------------------------ | ---------------------------------------- |
140
+ | `StripeThinEventHandler` | thin | `stripe.parseEventNotificationAsync(...)` | the typed notification (`v1.*` types) |
141
+ | `StripeEventHandler` | snapshot | `stripe.webhooks.constructEventAsync(...)` | `event.data.object` for the event's type |
142
+
143
+ Which to use: Stripe recommends thin events for new integrations, and so do we. Use snapshot
144
+ events when you need the full payload as it was when the event fired, or
145
+ `data.previous_attributes`.
146
+
147
+ #### Thin events (recommended)
148
+
149
+ A thin event only says which object changed (`type`, `id`, `created`, `reason`, `related_object`),
150
+ so each handler reads current state from Stripe with `notification.fetchRelatedObject()` (or the
151
+ full event with `fetchEvent()`). The SDK never pre-fetches: some handlers only need
152
+ `related_object.id`. `on` is keyed by thin event type (`v1.customer.subscription.updated`, ...),
153
+ so `fetchRelatedObject()` resolves to the right Stripe object. Delivery order carries no meaning:
154
+ re-read state instead of applying payloads in order, and dedupe one-off facts (credits, payments,
155
+ refunds) with idempotency keys. `StripeThinEventNotificationOf<T>` types a handler shared across
156
+ several types.
157
+
158
+ Create the event destination with the thin payload style and the `v1.*` types you handle. A
159
+ Cloudflare Workers route with Hono (`parseEventNotificationAsync` uses Web Crypto there):
137
160
 
138
161
  ```ts
139
162
  import {
140
163
  METADATA_KEYS,
141
- StripeEventHandler,
164
+ StripeThinEventHandler,
165
+ type StripeThinEventNotificationOf,
142
166
  mapCancellationDetails,
143
167
  mapSubscriptionStatus,
144
168
  mapTime,
@@ -147,23 +171,31 @@ import Stripe from 'stripe';
147
171
 
148
172
  const stripe = new Stripe(env.STRIPE_SECRET_KEY);
149
173
 
150
- export async function processStripeEvent(signature: string, body: string) {
151
- const event = await stripe.webhooks.constructEventAsync(
152
- body,
153
- signature,
174
+ const handler = StripeThinEventHandler.create()
175
+ .on('v1.checkout.session.completed', handleCheckoutSessionCompleted)
176
+ .on('v1.invoice.paid', handleInvoicePaid)
177
+ .on('v1.customer.subscription.created', handleSubscriptionEvent)
178
+ .on('v1.customer.subscription.updated', handleSubscriptionEvent)
179
+ .on('v1.customer.subscription.deleted', handleSubscriptionEvent);
180
+
181
+ app.post('/webhooks/stripe', async (c) => {
182
+ const notification = await stripe.parseEventNotificationAsync(
183
+ await c.req.text(),
184
+ c.req.header('stripe-signature') ?? '',
154
185
  env.STRIPE_WEBHOOK_SECRET
155
186
  );
156
-
157
- await StripeEventHandler.create()
158
- .on('checkout.session.completed', handleCheckoutSessionCompleted)
159
- .on('invoice.payment_succeeded', handleInvoicePaymentSucceeded)
160
- .on('customer.subscription.created', handleSubscriptionEvent)
161
- .on('customer.subscription.updated', handleSubscriptionEvent)
162
- .on('customer.subscription.deleted', handleSubscriptionEvent)
163
- .process(event);
164
- }
165
-
166
- async function handleSubscriptionEvent(sub: Stripe.Subscription) {
187
+ await handler.process(notification);
188
+ return c.body(null, 204);
189
+ });
190
+
191
+ async function handleSubscriptionEvent(
192
+ notification: StripeThinEventNotificationOf<
193
+ | 'v1.customer.subscription.created'
194
+ | 'v1.customer.subscription.updated'
195
+ | 'v1.customer.subscription.deleted'
196
+ >
197
+ ) {
198
+ const sub = await notification.fetchRelatedObject(); // Stripe.Subscription, current state
167
199
  const userId = sub.metadata[METADATA_KEYS.USER_ID];
168
200
  const productId = sub.metadata[METADATA_KEYS.PRODUCT_ID];
169
201
  await saveSubscription({
@@ -178,6 +210,41 @@ async function handleSubscriptionEvent(sub: Stripe.Subscription) {
178
210
  }
179
211
  ```
180
212
 
213
+ #### Snapshot events
214
+
215
+ `on` is keyed by snapshot event type (`customer.subscription.updated`, ...) and each handler
216
+ receives that event's `data.object`, typed.
217
+
218
+ ```ts
219
+ import { StripeEventHandler } from '@shware/purchase/stripe';
220
+
221
+ export async function processStripeEvent(signature: string, body: string) {
222
+ const event = await stripe.webhooks.constructEventAsync(
223
+ body,
224
+ signature,
225
+ env.STRIPE_WEBHOOK_SECRET
226
+ );
227
+
228
+ await StripeEventHandler.create()
229
+ .on('invoice.payment_succeeded', handleInvoicePaymentSucceeded) // (invoice: Stripe.Invoice)
230
+ .on('customer.subscription.updated', handleSubscription) // (sub: Stripe.Subscription)
231
+ .process(event);
232
+ }
233
+ ```
234
+
235
+ #### Moving from snapshot to thin events
236
+
237
+ - Switch the event destination to the thin payload style; `parseEventNotificationAsync` rejects
238
+ snapshot payloads.
239
+ - Replace `constructEventAsync` with `parseEventNotificationAsync` and `StripeEventHandler` with
240
+ `StripeThinEventHandler`.
241
+ - Prefix every `on` type with `v1.` (`invoice.paid` becomes `v1.invoice.paid`).
242
+ - Handlers receive the notification instead of `event.data.object`: call
243
+ `await notification.fetchRelatedObject()`, or use `notification.related_object.id` when the id
244
+ is enough. The fetched object is current state, so handlers must not depend on delivery order.
245
+ - The mappers (`mapSubscriptionStatus`, `mapInvoice`, `mapCancellationDetails`, ...) take the
246
+ fetched objects unchanged.
247
+
181
248
  ### Checkout
182
249
 
183
250
  `createCheckoutSessionSchema(productIds)` is a `zod/mini` schema for the create-checkout request
@@ -0,0 +1,16 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/stripe/expandable.ts
3
+ function idOf(ref) {
4
+ if (!ref) return null;
5
+ return typeof ref === "string" ? ref : ref.id;
6
+ }
7
+ function expanded(ref, what) {
8
+ if (!ref) return null;
9
+ if (typeof ref === "string") throw new Error(`${what} ${ref} was retrieved without expanding it`);
10
+ return ref;
11
+ }
12
+ //#endregion
13
+ exports.expanded = expanded;
14
+ exports.idOf = idOf;
15
+
16
+ //# sourceMappingURL=expandable.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expandable.cjs","names":[],"sources":["../../src/stripe/expandable.ts"],"sourcesContent":["/**\n * Helpers for Stripe's expandable fields: a reference Stripe returns as a bare id, or as the whole\n * object when the request asked for it with `expand`.\n */\n\ntype Ref<T extends { id: string }> = string | T | null | undefined;\n\n/** The id behind an expandable field, whether it came back expanded or not. */\nexport function idOf<T extends { id: string }>(ref: string | T): string;\nexport function idOf<T extends { id: string }>(ref: Ref<T>): string | null;\nexport function idOf<T extends { id: string }>(ref: Ref<T>): string | null {\n if (!ref) return null;\n return typeof ref === 'string' ? ref : ref.id;\n}\n\n/**\n * The object behind an expandable field the caller retrieved with `expand`. A bare id means the\n * request forgot the expansion, a bug in the caller rather than anything Stripe can fix on a retry,\n * so it throws; an absent reference stays null. `what` names the field for the error message.\n */\nexport function expanded<T extends { id: string }>(ref: string | T, what: string): T;\nexport function expanded<T extends { id: string }>(ref: Ref<T>, what: string): T | null;\nexport function expanded<T extends { id: string }>(ref: Ref<T>, what: string): T | null {\n if (!ref) return null;\n if (typeof ref === 'string') throw new Error(`${what} ${ref} was retrieved without expanding it`);\n return ref;\n}\n"],"mappings":";;AAUA,SAAgB,KAA+B,KAA4B;CACzE,IAAI,CAAC,KAAK,OAAO;CACjB,OAAO,OAAO,QAAQ,WAAW,MAAM,IAAI;AAC7C;AASA,SAAgB,SAAmC,KAAa,MAAwB;CACtF,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,OAAO,QAAQ,UAAU,MAAM,IAAI,MAAM,GAAG,KAAK,GAAG,IAAI,oCAAoC;CAChG,OAAO;AACT"}
@@ -0,0 +1,29 @@
1
+ //#region src/stripe/expandable.d.ts
2
+ /**
3
+ * Helpers for Stripe's expandable fields: a reference Stripe returns as a bare id, or as the whole
4
+ * object when the request asked for it with `expand`.
5
+ */
6
+ type Ref<T extends {
7
+ id: string;
8
+ }> = string | T | null | undefined;
9
+ /** The id behind an expandable field, whether it came back expanded or not. */
10
+ export declare function idOf<T extends {
11
+ id: string;
12
+ }>(ref: string | T): string;
13
+ export declare function idOf<T extends {
14
+ id: string;
15
+ }>(ref: Ref<T>): string | null;
16
+ /**
17
+ * The object behind an expandable field the caller retrieved with `expand`. A bare id means the
18
+ * request forgot the expansion, a bug in the caller rather than anything Stripe can fix on a retry,
19
+ * so it throws; an absent reference stays null. `what` names the field for the error message.
20
+ */
21
+ export declare function expanded<T extends {
22
+ id: string;
23
+ }>(ref: string | T, what: string): T;
24
+ export declare function expanded<T extends {
25
+ id: string;
26
+ }>(ref: Ref<T>, what: string): T | null;
27
+ //#endregion
28
+ export {};
29
+ //# sourceMappingURL=expandable.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expandable.d.cts","names":[],"sources":["../../src/stripe/expandable.ts"],"mappings":";;;;;KAKK,IAAI;EAAY;cAAyB;;wBAG9B,KAAK;EAAY;GAAc,cAAc;wBAC7C,KAAK;EAAY;GAAc,KAAK,IAAI;;;;;;wBAWxC,SAAS;EAAY;GAAc,cAAc,GAAG,eAAe;wBACnE,SAAS;EAAY;GAAc,KAAK,IAAI,IAAI,eAAe"}
@@ -0,0 +1,29 @@
1
+ //#region src/stripe/expandable.d.ts
2
+ /**
3
+ * Helpers for Stripe's expandable fields: a reference Stripe returns as a bare id, or as the whole
4
+ * object when the request asked for it with `expand`.
5
+ */
6
+ type Ref<T extends {
7
+ id: string;
8
+ }> = string | T | null | undefined;
9
+ /** The id behind an expandable field, whether it came back expanded or not. */
10
+ export declare function idOf<T extends {
11
+ id: string;
12
+ }>(ref: string | T): string;
13
+ export declare function idOf<T extends {
14
+ id: string;
15
+ }>(ref: Ref<T>): string | null;
16
+ /**
17
+ * The object behind an expandable field the caller retrieved with `expand`. A bare id means the
18
+ * request forgot the expansion, a bug in the caller rather than anything Stripe can fix on a retry,
19
+ * so it throws; an absent reference stays null. `what` names the field for the error message.
20
+ */
21
+ export declare function expanded<T extends {
22
+ id: string;
23
+ }>(ref: string | T, what: string): T;
24
+ export declare function expanded<T extends {
25
+ id: string;
26
+ }>(ref: Ref<T>, what: string): T | null;
27
+ //#endregion
28
+ export {};
29
+ //# sourceMappingURL=expandable.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expandable.d.mts","names":[],"sources":["../../src/stripe/expandable.ts"],"mappings":";;;;;KAKK,IAAI;EAAY;cAAyB;;wBAG9B,KAAK;EAAY;GAAc,cAAc;wBAC7C,KAAK;EAAY;GAAc,KAAK,IAAI;;;;;;wBAWxC,SAAS;EAAY;GAAc,cAAc,GAAG,eAAe;wBACnE,SAAS;EAAY;GAAc,KAAK,IAAI,IAAI,eAAe"}
@@ -0,0 +1,14 @@
1
+ //#region src/stripe/expandable.ts
2
+ function idOf(ref) {
3
+ if (!ref) return null;
4
+ return typeof ref === "string" ? ref : ref.id;
5
+ }
6
+ function expanded(ref, what) {
7
+ if (!ref) return null;
8
+ if (typeof ref === "string") throw new Error(`${what} ${ref} was retrieved without expanding it`);
9
+ return ref;
10
+ }
11
+ //#endregion
12
+ export { expanded, idOf };
13
+
14
+ //# sourceMappingURL=expandable.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expandable.mjs","names":[],"sources":["../../src/stripe/expandable.ts"],"sourcesContent":["/**\n * Helpers for Stripe's expandable fields: a reference Stripe returns as a bare id, or as the whole\n * object when the request asked for it with `expand`.\n */\n\ntype Ref<T extends { id: string }> = string | T | null | undefined;\n\n/** The id behind an expandable field, whether it came back expanded or not. */\nexport function idOf<T extends { id: string }>(ref: string | T): string;\nexport function idOf<T extends { id: string }>(ref: Ref<T>): string | null;\nexport function idOf<T extends { id: string }>(ref: Ref<T>): string | null {\n if (!ref) return null;\n return typeof ref === 'string' ? ref : ref.id;\n}\n\n/**\n * The object behind an expandable field the caller retrieved with `expand`. A bare id means the\n * request forgot the expansion, a bug in the caller rather than anything Stripe can fix on a retry,\n * so it throws; an absent reference stays null. `what` names the field for the error message.\n */\nexport function expanded<T extends { id: string }>(ref: string | T, what: string): T;\nexport function expanded<T extends { id: string }>(ref: Ref<T>, what: string): T | null;\nexport function expanded<T extends { id: string }>(ref: Ref<T>, what: string): T | null {\n if (!ref) return null;\n if (typeof ref === 'string') throw new Error(`${what} ${ref} was retrieved without expanding it`);\n return ref;\n}\n"],"mappings":";AAUA,SAAgB,KAA+B,KAA4B;CACzE,IAAI,CAAC,KAAK,OAAO;CACjB,OAAO,OAAO,QAAQ,WAAW,MAAM,IAAI;AAC7C;AASA,SAAgB,SAAmC,KAAa,MAAwB;CACtF,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,OAAO,QAAQ,UAAU,MAAM,IAAI,MAAM,GAAG,KAAK,GAAG,IAAI,oCAAoC;CAChG,OAAO;AACT"}
@@ -1,19 +1,24 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_stripe_config = require("./config.cjs");
3
+ const require_stripe_expandable = require("./expandable.cjs");
3
4
  const require_stripe_handler = require("./handler.cjs");
4
5
  const require_stripe_mapper = require("./mapper.cjs");
6
+ const require_stripe_thin_handler = require("./thin-handler.cjs");
5
7
  const require_stripe_schema = require("./schema.cjs");
6
8
  const require_stripe_metadata = require("./metadata.cjs");
7
9
  const require_stripe_pending_checkout = require("./pending-checkout.cjs");
8
10
  exports.METADATA_KEYS = require_stripe_metadata.METADATA_KEYS;
9
11
  exports.StripeConfig = require_stripe_config.StripeConfig;
10
12
  exports.StripeEventHandler = require_stripe_handler.StripeEventHandler;
13
+ exports.StripeThinEventHandler = require_stripe_thin_handler.StripeThinEventHandler;
11
14
  exports.addPendingCheckout = require_stripe_pending_checkout.addPendingCheckout;
12
15
  exports.cancellationDetailsSchema = require_stripe_schema.cancellationDetailsSchema;
13
16
  exports.createCheckoutSessionSchema = require_stripe_schema.createCheckoutSessionSchema;
17
+ exports.expanded = require_stripe_expandable.expanded;
14
18
  exports.getBeginCheckoutProperties = require_stripe_mapper.getBeginCheckoutProperties;
15
19
  exports.getPendingCheckouts = require_stripe_pending_checkout.getPendingCheckouts;
16
20
  exports.getPurchaseProperties = require_stripe_mapper.getPurchaseProperties;
21
+ exports.idOf = require_stripe_expandable.idOf;
17
22
  exports.mapCancellationDetails = require_stripe_mapper.mapCancellationDetails;
18
23
  exports.mapCharge = require_stripe_mapper.mapCharge;
19
24
  exports.mapCheckoutSession = require_stripe_mapper.mapCheckoutSession;
@@ -24,6 +29,7 @@ exports.mapPrice = require_stripe_mapper.mapPrice;
24
29
  exports.mapSubscriptionStatus = require_stripe_mapper.mapSubscriptionStatus;
25
30
  exports.mapTime = require_stripe_mapper.mapTime;
26
31
  exports.minorUnits = require_stripe_mapper.minorUnits;
32
+ exports.money = require_stripe_mapper.money;
27
33
  exports.price = require_stripe_mapper.price;
28
34
  exports.removePendingCheckout = require_stripe_pending_checkout.removePendingCheckout;
29
35
  exports.returnUrlSchema = require_stripe_schema.returnUrlSchema;
@@ -1,9 +1,11 @@
1
1
  import { CancellationDetails } from "../subscription/index.cjs";
2
2
  import { PriceId, StripeConfig, StripeMode } from "./config.cjs";
3
+ import { expanded, idOf } from "./expandable.cjs";
3
4
  import { StripeEventHandler } from "./handler.cjs";
4
- import { BeginCheckoutProperties, CheckoutSession, LineItem, PaymentStatus, Price, ProductPrice, PurchaseProperties, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price } from "./mapper.cjs";
5
+ import { BeginCheckoutProperties, CheckoutSession, LineItem, Money, PaymentStatus, Price, ProductPrice, PurchaseProperties, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price } from "./mapper.cjs";
6
+ import { StripeThinEventHandler, StripeThinEventNotificationOf, StripeThinEventType } from "./thin-handler.cjs";
5
7
  import { AllowedOrigins, CreateCheckoutSessionDTO, CreateCheckoutSessionSchemaOptions, cancellationDetailsSchema, createCheckoutSessionSchema, returnUrlSchema } from "./schema.cjs";
6
8
  import { METADATA_KEYS } from "./metadata.cjs";
7
9
  import { addPendingCheckout, getPendingCheckouts, removePendingCheckout } from "./pending-checkout.cjs";
8
10
  import { Stripe } from "stripe";
9
- export { type AllowedOrigins, type BeginCheckoutProperties, type CancellationDetails, type CheckoutSession, type CreateCheckoutSessionDTO, type CreateCheckoutSessionSchemaOptions, type LineItem, METADATA_KEYS, type PaymentStatus, type Price, type PriceId, type ProductPrice, type PurchaseProperties, type Stripe, StripeConfig, StripeEventHandler, type StripeMode, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price, removePendingCheckout, returnUrlSchema };
11
+ export { type AllowedOrigins, type BeginCheckoutProperties, type CancellationDetails, type CheckoutSession, type CreateCheckoutSessionDTO, type CreateCheckoutSessionSchemaOptions, type LineItem, METADATA_KEYS, type Money, type PaymentStatus, type Price, type PriceId, type ProductPrice, type PurchaseProperties, type Stripe, StripeConfig, StripeEventHandler, type StripeMode, StripeThinEventHandler, type StripeThinEventNotificationOf, type StripeThinEventType, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, expanded, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, idOf, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price, removePendingCheckout, returnUrlSchema };
@@ -1,9 +1,11 @@
1
1
  import { CancellationDetails } from "../subscription/index.mjs";
2
2
  import { PriceId, StripeConfig, StripeMode } from "./config.mjs";
3
+ import { expanded, idOf } from "./expandable.mjs";
3
4
  import { StripeEventHandler } from "./handler.mjs";
4
- import { BeginCheckoutProperties, CheckoutSession, LineItem, PaymentStatus, Price, ProductPrice, PurchaseProperties, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price } from "./mapper.mjs";
5
+ import { BeginCheckoutProperties, CheckoutSession, LineItem, Money, PaymentStatus, Price, ProductPrice, PurchaseProperties, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price } from "./mapper.mjs";
6
+ import { StripeThinEventHandler, StripeThinEventNotificationOf, StripeThinEventType } from "./thin-handler.mjs";
5
7
  import { AllowedOrigins, CreateCheckoutSessionDTO, CreateCheckoutSessionSchemaOptions, cancellationDetailsSchema, createCheckoutSessionSchema, returnUrlSchema } from "./schema.mjs";
6
8
  import { METADATA_KEYS } from "./metadata.mjs";
7
9
  import { addPendingCheckout, getPendingCheckouts, removePendingCheckout } from "./pending-checkout.mjs";
8
10
  import { Stripe } from "stripe";
9
- export { type AllowedOrigins, type BeginCheckoutProperties, type CancellationDetails, type CheckoutSession, type CreateCheckoutSessionDTO, type CreateCheckoutSessionSchemaOptions, type LineItem, METADATA_KEYS, type PaymentStatus, type Price, type PriceId, type ProductPrice, type PurchaseProperties, type Stripe, StripeConfig, StripeEventHandler, type StripeMode, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price, removePendingCheckout, returnUrlSchema };
11
+ export { type AllowedOrigins, type BeginCheckoutProperties, type CancellationDetails, type CheckoutSession, type CreateCheckoutSessionDTO, type CreateCheckoutSessionSchemaOptions, type LineItem, METADATA_KEYS, type Money, type PaymentStatus, type Price, type PriceId, type ProductPrice, type PurchaseProperties, type Stripe, StripeConfig, StripeEventHandler, type StripeMode, StripeThinEventHandler, type StripeThinEventNotificationOf, type StripeThinEventType, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, expanded, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, idOf, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price, removePendingCheckout, returnUrlSchema };
@@ -1,7 +1,9 @@
1
1
  import { StripeConfig } from "./config.mjs";
2
+ import { expanded, idOf } from "./expandable.mjs";
2
3
  import { StripeEventHandler } from "./handler.mjs";
3
- import { getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price } from "./mapper.mjs";
4
+ import { getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price } from "./mapper.mjs";
5
+ import { StripeThinEventHandler } from "./thin-handler.mjs";
4
6
  import { cancellationDetailsSchema, createCheckoutSessionSchema, returnUrlSchema } from "./schema.mjs";
5
7
  import { METADATA_KEYS } from "./metadata.mjs";
6
8
  import { addPendingCheckout, getPendingCheckouts, removePendingCheckout } from "./pending-checkout.mjs";
7
- export { METADATA_KEYS, StripeConfig, StripeEventHandler, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price, removePendingCheckout, returnUrlSchema };
9
+ export { METADATA_KEYS, StripeConfig, StripeEventHandler, StripeThinEventHandler, addPendingCheckout, cancellationDetailsSchema, createCheckoutSessionSchema, expanded, getBeginCheckoutProperties, getPendingCheckouts, getPurchaseProperties, idOf, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price, removePendingCheckout, returnUrlSchema };
@@ -122,6 +122,13 @@ function minorUnits(currency) {
122
122
  function price(value, currency) {
123
123
  return value / minorUnits(currency);
124
124
  }
125
+ /** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */
126
+ function money(value, currency) {
127
+ return {
128
+ amount: price(value, currency),
129
+ currency
130
+ };
131
+ }
125
132
  const GOOGLE_ADS_TRANSACTION_ID_MAX = 64;
126
133
  /**
127
134
  * GA4 purchase events feed Google Ads conversions, whose transaction IDs are
@@ -218,6 +225,7 @@ exports.mapPrice = mapPrice;
218
225
  exports.mapSubscriptionStatus = mapSubscriptionStatus;
219
226
  exports.mapTime = mapTime;
220
227
  exports.minorUnits = minorUnits;
228
+ exports.money = money;
221
229
  exports.price = price;
222
230
 
223
231
  //# sourceMappingURL=mapper.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"mapper.cjs","names":["stripeMinorUnits","CANCELLATION_FEEDBACKS"],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n comment: details.comment ?? null,\n };\n}\n"],"mappings":";;;;AASA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,UAAU,MAAM;EAChB,aAAa,MAAM;EACnB,qBAAqB,MAAM,qBAAqB,SAAS,KAAK;EAC9D,WAAW,MAAM;CACnB;AACF;AAcA,SAAgB,YAAY,MAAiC;CAC3D,OAAO;EACL,IAAI,KAAK,QACL,OAAO,KAAK,MAAM,YAAY,WAC5B,KAAK,MAAM,UACX,KAAK,MAAM,QAAQ,KACrB,KAAK;EACT,UAAU,KAAK;EACf,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,cAAc,KAAK;EACnB,iBAAiB,KAAK;EACtB,iBAAiB,KAAK;EACtB,OAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,IAAI;CAC7C;AACF;AAsBA,SAAgB,mBAAmB,SAAmD;CACpF,IAAI,SAA6B,KAAA;CACjC,IAAI,MAAM,QAAQ,QAAQ,SAAS,KAAK,QAAQ,UAAU,WAAW,GAAG;EACtE,MAAM,WAAW,QAAQ,UAAU;EACnC,IAAI,SAAS,UAAU,OAAO,SAAS,WAAW,UAChD,SAAS,SAAS,OAAO;OACpB,IAAI,OAAO,SAAS,WAAW,UACpC,SAAS,SAAS;OAElB,SAAS,KAAA;CAEb;CAEA,OAAO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A,SAAgB,2BAA2B,GAA0C;CACnF,OAAO;EACL,UAAU,EAAE,SAAS,YAAY;EACjC,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACtC,OAAO,CACL;GACE,SAAS,EAAE,QAAQ;GACnB,WAAW,EAAE,QAAQ;GACrB,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACxC,CACF;CACF;AACF;;;;;;;AAQA,SAAgB,uBACd,cAC4B;CAC5B,MAAM,UAAU,aAAa;CAC7B,IAAI,CAAC,WAAY,CAAC,QAAQ,UAAU,CAAC,QAAQ,YAAY,CAAC,QAAQ,SAAU,OAAO;CACnF,OAAO;EACL,WACE,QAAQ,WAAW,oBAAoB,QAAQ,WAAW,qBACtD,WACA;EACN,QAAQ,QAAQ,UAAU;EAE1B,UAAU,QAAQ,WACbC,2BAAAA,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,SAAS,QAAQ,WAAW;CAC9B;AACF"}
1
+ {"version":3,"file":"mapper.cjs","names":["stripeMinorUnits","CANCELLATION_FEEDBACKS"],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport type Money = { amount: number; currency: string };\n\n/** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */\nexport function money(value: number, currency: string): Money {\n return { amount: price(value, currency), currency };\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n comment: details.comment ?? null,\n };\n}\n"],"mappings":";;;;AASA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,UAAU,MAAM;EAChB,aAAa,MAAM;EACnB,qBAAqB,MAAM,qBAAqB,SAAS,KAAK;EAC9D,WAAW,MAAM;CACnB;AACF;AAcA,SAAgB,YAAY,MAAiC;CAC3D,OAAO;EACL,IAAI,KAAK,QACL,OAAO,KAAK,MAAM,YAAY,WAC5B,KAAK,MAAM,UACX,KAAK,MAAM,QAAQ,KACrB,KAAK;EACT,UAAU,KAAK;EACf,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,cAAc,KAAK;EACnB,iBAAiB,KAAK;EACtB,iBAAiB,KAAK;EACtB,OAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,IAAI;CAC7C;AACF;AAsBA,SAAgB,mBAAmB,SAAmD;CACpF,IAAI,SAA6B,KAAA;CACjC,IAAI,MAAM,QAAQ,QAAQ,SAAS,KAAK,QAAQ,UAAU,WAAW,GAAG;EACtE,MAAM,WAAW,QAAQ,UAAU;EACnC,IAAI,SAAS,UAAU,OAAO,SAAS,WAAW,UAChD,SAAS,SAAS,OAAO;OACpB,IAAI,OAAO,SAAS,WAAW,UACpC,SAAS,SAAS;OA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MAAM,KAAK,cAAc,KAAK,QAAQ;GAC7C,UAAU,KAAK,YAAY;GAC3B,UAAU,MAAM,KAAK,iBAAiB,KAAK,QAAQ;EACrD,EAAE;CACJ;AACF;AAEA,SAAgB,2BAA2B,GAA0C;CACnF,OAAO;EACL,UAAU,EAAE,SAAS,YAAY;EACjC,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACtC,OAAO,CACL;GACE,SAAS,EAAE,QAAQ;GACnB,WAAW,EAAE,QAAQ;GACrB,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACxC,CACF;CACF;AACF;;;;;;;AAQA,SAAgB,uBACd,cAC4B;CAC5B,MAAM,UAAU,aAAa;CAC7B,IAAI,CAAC,WAAY,CAAC,QAAQ,UAAU,CAAC,QAAQ,YAAY,CAAC,QAAQ,SAAU,OAAO;CACnF,OAAO;EACL,WACE,QAAQ,WAAW,oBAAoB,QAAQ,WAAW,qBACtD,WACA;EACN,QAAQ,QAAQ,UAAU;EAE1B,UAAU,QAAQ,WACbC,2BAAAA,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,SAAS,QAAQ,WAAW;CAC9B;AACF"}
@@ -108,6 +108,12 @@ export declare function mapSubscriptionStatus(status: Stripe.Subscription.Status
108
108
  /** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */
109
109
  export declare function minorUnits(currency: string): 1 | 100 | 1000;
110
110
  export declare function price(value: number, currency: string): number;
111
+ export type Money = {
112
+ amount: number;
113
+ currency: string;
114
+ };
115
+ /** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */
116
+ export declare function money(value: number, currency: string): Money;
111
117
  export interface Item {
112
118
  item_id: string;
113
119
  item_name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"mapper.d.cts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;wBASgB,QAAQ,yBACtB,wBAAwB,IACvB;YAKS;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,gBAAgB,OAAO,MAAM;EAC7B,UAAU,OAAO;EACjB;EACA;EACA,WAAW,OAAO,MAAM;;wBAGV,SAAS,OAAO,OAAO,QAAQ;iBAa9B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;;wBAGO,YAAY,MAAM,OAAO,WAAW;YAoBxC,gBAAgB,OAAO,SAAS,QAAQ;iBAMnC;EACf;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA,YAAY;;wBAGE,mBAAmB,SAAS,OAAO,SAAS,UAAU;wBA0BtD,WAAW,GAAG,OAAO;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAc,OAAA,QAAA;EACd;EACA;EACA;EACA,QAAM,OAAA,QAAA;EACN;EACA;EACA;;wBAIY,iBAAiB,QAAQ,OAAO;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,cAAA;EACN;;wBAIY,UAAU,QAAQ,OAAO;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,OAAA;EACN;EACA;;;;;;;;;;;;YAOQ;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,UAAU,OAAO;EACjB;IACE,IAAI,OAAO;IACX,MAAM,OAAO;IACb,aAAa,OAAO;IACpB,UAAU,OAAO;;;wBAIL,sBAAsB,QAAQ,OAAO,aAAa,SAAS;;wBA4B3D,WAAW;wBAIX,MAAM,eAAe;iBAIpB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;iBAGO;EACf;EACA;EACA;EACA,OAAO;;wBAqCO,sBAAsB,SAAS,kBAAkB;wBA2BjD,2BAA2B,GAAG,eAAe;;;;;;;wBAoB7C,uBACd,cAAc,KAAK,OAAO,wCACzB"}
1
+ {"version":3,"file":"mapper.d.cts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;wBASgB,QAAQ,yBACtB,wBAAwB,IACvB;YAKS;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,gBAAgB,OAAO,MAAM;EAC7B,UAAU,OAAO;EACjB;EACA;EACA,WAAW,OAAO,MAAM;;wBAGV,SAAS,OAAO,OAAO,QAAQ;iBAa9B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;;wBAGO,YAAY,MAAM,OAAO,WAAW;YAoBxC,gBAAgB,OAAO,SAAS,QAAQ;iBAMnC;EACf;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA,YAAY;;wBAGE,mBAAmB,SAAS,OAAO,SAAS,UAAU;wBA0BtD,WAAW,GAAG,OAAO;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAc,OAAA,QAAA;EACd;EACA;EACA;EACA,QAAM,OAAA,QAAA;EACN;EACA;EACA;;wBAIY,iBAAiB,QAAQ,OAAO;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,cAAA;EACN;;wBAIY,UAAU,QAAQ,OAAO;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,OAAA;EACN;EACA;;;;;;;;;;;;YAOQ;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,UAAU,OAAO;EACjB;IACE,IAAI,OAAO;IACX,MAAM,OAAO;IACb,aAAa,OAAO;IACpB,UAAU,OAAO;;;wBAIL,sBAAsB,QAAQ,OAAO,aAAa,SAAS;;wBA4B3D,WAAW;wBAIX,MAAM,eAAe;YAIzB;EAAU;EAAgB;;;wBAGtB,MAAM,eAAe,mBAAmB;iBAIvC;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;iBAGO;EACf;EACA;EACA;EACA,OAAO;;wBAqCO,sBAAsB,SAAS,kBAAkB;wBA2BjD,2BAA2B,GAAG,eAAe;;;;;;;wBAoB7C,uBACd,cAAc,KAAK,OAAO,wCACzB"}
@@ -108,6 +108,12 @@ export declare function mapSubscriptionStatus(status: Stripe.Subscription.Status
108
108
  /** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */
109
109
  export declare function minorUnits(currency: string): 1 | 100 | 1000;
110
110
  export declare function price(value: number, currency: string): number;
111
+ export type Money = {
112
+ amount: number;
113
+ currency: string;
114
+ };
115
+ /** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */
116
+ export declare function money(value: number, currency: string): Money;
111
117
  export interface Item {
112
118
  item_id: string;
113
119
  item_name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"mapper.d.mts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;wBASgB,QAAQ,yBACtB,wBAAwB,IACvB;YAKS;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,gBAAgB,OAAO,MAAM;EAC7B,UAAU,OAAO;EACjB;EACA;EACA,WAAW,OAAO,MAAM;;wBAGV,SAAS,OAAO,OAAO,QAAQ;iBAa9B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;;wBAGO,YAAY,MAAM,OAAO,WAAW;YAoBxC,gBAAgB,OAAO,SAAS,QAAQ;iBAMnC;EACf;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA,YAAY;;wBAGE,mBAAmB,SAAS,OAAO,SAAS,UAAU;wBA0BtD,WAAW,GAAG,OAAO;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAc,OAAA,QAAA;EACd;EACA;EACA;EACA,QAAM,OAAA,QAAA;EACN;EACA;EACA;;wBAIY,iBAAiB,QAAQ,OAAO;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,cAAA;EACN;;wBAIY,UAAU,QAAQ,OAAO;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,OAAA;EACN;EACA;;;;;;;;;;;;YAOQ;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,UAAU,OAAO;EACjB;IACE,IAAI,OAAO;IACX,MAAM,OAAO;IACb,aAAa,OAAO;IACpB,UAAU,OAAO;;;wBAIL,sBAAsB,QAAQ,OAAO,aAAa,SAAS;;wBA4B3D,WAAW;wBAIX,MAAM,eAAe;iBAIpB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;iBAGO;EACf;EACA;EACA;EACA,OAAO;;wBAqCO,sBAAsB,SAAS,kBAAkB;wBA2BjD,2BAA2B,GAAG,eAAe;;;;;;;wBAoB7C,uBACd,cAAc,KAAK,OAAO,wCACzB"}
1
+ {"version":3,"file":"mapper.d.mts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;wBASgB,QAAQ,yBACtB,wBAAwB,IACvB;YAKS;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,gBAAgB,OAAO,MAAM;EAC7B,UAAU,OAAO;EACjB;EACA;EACA,WAAW,OAAO,MAAM;;wBAGV,SAAS,OAAO,OAAO,QAAQ;iBAa9B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;;wBAGO,YAAY,MAAM,OAAO,WAAW;YAoBxC,gBAAgB,OAAO,SAAS,QAAQ;iBAMnC;EACf;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA,YAAY;;wBAGE,mBAAmB,SAAS,OAAO,SAAS,UAAU;wBA0BtD,WAAW,GAAG,OAAO;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAc,OAAA,QAAA;EACd;EACA;EACA;EACA,QAAM,OAAA,QAAA;EACN;EACA;EACA;;wBAIY,iBAAiB,QAAQ,OAAO;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,cAAA;EACN;;wBAIY,UAAU,QAAQ,OAAO;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,OAAA;EACN;EACA;;;;;;;;;;;;YAOQ;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,UAAU,OAAO;EACjB;IACE,IAAI,OAAO;IACX,MAAM,OAAO;IACb,aAAa,OAAO;IACpB,UAAU,OAAO;;;wBAIL,sBAAsB,QAAQ,OAAO,aAAa,SAAS;;wBA4B3D,WAAW;wBAIX,MAAM,eAAe;YAIzB;EAAU;EAAgB;;;wBAGtB,MAAM,eAAe,mBAAmB;iBAIvC;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;iBAGO;EACf;EACA;EACA;EACA,OAAO;;wBAqCO,sBAAsB,SAAS,kBAAkB;wBA2BjD,2BAA2B,GAAG,eAAe;;;;;;;wBAoB7C,uBACd,cAAc,KAAK,OAAO,wCACzB"}
@@ -121,6 +121,13 @@ function minorUnits(currency) {
121
121
  function price(value, currency) {
122
122
  return value / minorUnits(currency);
123
123
  }
124
+ /** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */
125
+ function money(value, currency) {
126
+ return {
127
+ amount: price(value, currency),
128
+ currency
129
+ };
130
+ }
124
131
  const GOOGLE_ADS_TRANSACTION_ID_MAX = 64;
125
132
  /**
126
133
  * GA4 purchase events feed Google Ads conversions, whose transaction IDs are
@@ -199,6 +206,6 @@ function mapCancellationDetails(subscription) {
199
206
  };
200
207
  }
201
208
  //#endregion
202
- export { ZERO_DECIMAL_CURRENCIES, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, price };
209
+ export { ZERO_DECIMAL_CURRENCIES, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price };
203
210
 
204
211
  //# sourceMappingURL=mapper.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"mapper.mjs","names":[],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n comment: details.comment ?? null,\n };\n}\n"],"mappings":";;;AASA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;E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,UAAU;EAE1B,UAAU,QAAQ,WACb,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,SAAS,QAAQ,WAAW;CAC9B;AACF"}
1
+ {"version":3,"file":"mapper.mjs","names":[],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport type Money = { amount: number; currency: string };\n\n/** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */\nexport function money(value: number, currency: string): Money {\n return { amount: price(value, currency), currency };\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n comment: details.comment ?? null,\n };\n}\n"],"mappings":";;;AASA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,gBAAgB,M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QAAQ,WAAW,oBAAoB,QAAQ,WAAW,qBACtD,WACA;EACN,QAAQ,QAAQ,UAAU;EAE1B,UAAU,QAAQ,WACb,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,SAAS,QAAQ,WAAW;CAC9B;AACF"}
@@ -0,0 +1,40 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/stripe/thin-handler.ts
3
+ /**
4
+ * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The
5
+ * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes
6
+ * the notification in. A thin event only says which object changed, so each handler reads current
7
+ * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched
8
+ * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API
9
+ * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read
10
+ * state instead of applying a payload, and dedupe one-off facts with idempotency keys.
11
+ *
12
+ * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event
13
+ * types and `parseEventNotificationAsync` need stripe-node 23+.
14
+ */
15
+ var StripeThinEventHandler = class StripeThinEventHandler {
16
+ handlers;
17
+ constructor() {
18
+ this.handlers = /* @__PURE__ */ new Map();
19
+ }
20
+ static create() {
21
+ return new StripeThinEventHandler();
22
+ }
23
+ on = (type, handler) => {
24
+ if (!this.handlers.has(type)) this.handlers.set(type, []);
25
+ this.handlers.get(type)?.push(handler);
26
+ return this;
27
+ };
28
+ process = async (notification) => {
29
+ const eventHandlers = this.handlers.get(notification.type);
30
+ if (eventHandlers) await Promise.all(eventHandlers.map((handler) => handler(notification)));
31
+ else {
32
+ console.error(`No stripe event handler found for event type: ${notification.type}`);
33
+ throw new Error(`No stripe event handler found for event type: ${notification.type}`);
34
+ }
35
+ };
36
+ };
37
+ //#endregion
38
+ exports.StripeThinEventHandler = StripeThinEventHandler;
39
+
40
+ //# sourceMappingURL=thin-handler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thin-handler.cjs","names":[],"sources":["../../src/stripe/thin-handler.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\n\ntype StripeEventNotification = Stripe.V2.Core.EventNotification;\n\nexport type StripeThinEventType = StripeEventNotification['type'];\n\nexport type StripeThinEventNotificationOf<T extends StripeThinEventType> = Extract<\n StripeEventNotification,\n { type: T }\n>;\n\ntype EventHandlerFn<T extends StripeThinEventType = StripeThinEventType> = (\n notification: StripeThinEventNotificationOf<T>\n) => Promise<void>;\n\n/**\n * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The\n * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes\n * the notification in. A thin event only says which object changed, so each handler reads current\n * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched\n * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API\n * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read\n * state instead of applying a payload, and dedupe one-off facts with idempotency keys.\n *\n * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event\n * types and `parseEventNotificationAsync` need stripe-node 23+.\n */\nexport class StripeThinEventHandler {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly handlers: Map<StripeThinEventType, Array<EventHandlerFn<any>>>;\n\n private constructor() {\n this.handlers = new Map();\n }\n\n static create() {\n return new StripeThinEventHandler();\n }\n\n on = <T extends StripeThinEventType>(type: T, handler: EventHandlerFn<T>) => {\n if (!this.handlers.has(type)) {\n this.handlers.set(type, []);\n }\n\n this.handlers.get(type)?.push(handler);\n return this;\n };\n\n process = async (notification: StripeEventNotification): Promise<void> => {\n const eventHandlers = this.handlers.get(notification.type);\n if (eventHandlers) {\n await Promise.all(eventHandlers.map((handler) => handler(notification)));\n } else {\n console.error(`No stripe event handler found for event type: ${notification.type}`);\n throw new Error(`No stripe event handler found for event type: ${notification.type}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA2BA,IAAa,yBAAb,MAAa,uBAAuB;CAElC;CAEA,cAAsB;EACpB,KAAK,2BAAW,IAAI,IAAI;CAC1B;CAEA,OAAO,SAAS;EACd,OAAO,IAAI,uBAAuB;CACpC;CAEA,MAAqC,MAAS,YAA+B;EAC3E,IAAI,CAAC,KAAK,SAAS,IAAI,IAAI,GACzB,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC;EAG5B,KAAK,SAAS,IAAI,IAAI,CAAC,EAAE,KAAK,OAAO;EACrC,OAAO;CACT;CAEA,UAAU,OAAO,iBAAyD;EACxE,MAAM,gBAAgB,KAAK,SAAS,IAAI,aAAa,IAAI;EACzD,IAAI,eACF,MAAM,QAAQ,IAAI,cAAc,KAAK,YAAY,QAAQ,YAAY,CAAC,CAAC;OAClE;GACL,QAAQ,MAAM,iDAAiD,aAAa,MAAM;GAClF,MAAM,IAAI,MAAM,iDAAiD,aAAa,MAAM;EACtF;CACF;AACF"}
@@ -0,0 +1,30 @@
1
+ import { Stripe } from "stripe";
2
+ //#region src/stripe/thin-handler.d.ts
3
+ type StripeEventNotification = Stripe.V2.Core.EventNotification;
4
+ export type StripeThinEventType = StripeEventNotification['type'];
5
+ export type StripeThinEventNotificationOf<T extends StripeThinEventType> = Extract<StripeEventNotification, {
6
+ type: T;
7
+ }>;
8
+ type EventHandlerFn<T extends StripeThinEventType = StripeThinEventType> = (notification: StripeThinEventNotificationOf<T>) => Promise<void>;
9
+ /**
10
+ * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The
11
+ * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes
12
+ * the notification in. A thin event only says which object changed, so each handler reads current
13
+ * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched
14
+ * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API
15
+ * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read
16
+ * state instead of applying a payload, and dedupe one-off facts with idempotency keys.
17
+ *
18
+ * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event
19
+ * types and `parseEventNotificationAsync` need stripe-node 23+.
20
+ */
21
+ export declare class StripeThinEventHandler {
22
+ private readonly handlers;
23
+ private constructor();
24
+ static create(): StripeThinEventHandler;
25
+ on: <T extends StripeThinEventType>(type: T, handler: EventHandlerFn<T>) => this;
26
+ process: (notification: StripeEventNotification) => Promise<void>;
27
+ }
28
+ //#endregion
29
+ export {};
30
+ //# sourceMappingURL=thin-handler.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thin-handler.d.cts","names":[],"sources":["../../src/stripe/thin-handler.ts"],"mappings":";;KAEK,0BAA0B,OAAO,GAAG,KAAK;YAElC,sBAAsB;YAEtB,8BAA8B,UAAU,uBAAuB,QACzE;EACE,MAAM;;KAGL,eAAe,UAAU,sBAAsB,wBAClD,cAAc,8BAA8B,OACzC;;;;;;;;;;;;;qBAcQ;mBAEM;UAEV;SAIA,UAAM;EAIb,KAAM,UAAU,qBAAmB,MAAQ,GAAC,SAAW,eAAe;EAStE,UAAO,cAAwB,4BAA0B"}
@@ -0,0 +1,30 @@
1
+ import { Stripe } from "stripe";
2
+ //#region src/stripe/thin-handler.d.ts
3
+ type StripeEventNotification = Stripe.V2.Core.EventNotification;
4
+ export type StripeThinEventType = StripeEventNotification['type'];
5
+ export type StripeThinEventNotificationOf<T extends StripeThinEventType> = Extract<StripeEventNotification, {
6
+ type: T;
7
+ }>;
8
+ type EventHandlerFn<T extends StripeThinEventType = StripeThinEventType> = (notification: StripeThinEventNotificationOf<T>) => Promise<void>;
9
+ /**
10
+ * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The
11
+ * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes
12
+ * the notification in. A thin event only says which object changed, so each handler reads current
13
+ * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched
14
+ * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API
15
+ * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read
16
+ * state instead of applying a payload, and dedupe one-off facts with idempotency keys.
17
+ *
18
+ * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event
19
+ * types and `parseEventNotificationAsync` need stripe-node 23+.
20
+ */
21
+ export declare class StripeThinEventHandler {
22
+ private readonly handlers;
23
+ private constructor();
24
+ static create(): StripeThinEventHandler;
25
+ on: <T extends StripeThinEventType>(type: T, handler: EventHandlerFn<T>) => this;
26
+ process: (notification: StripeEventNotification) => Promise<void>;
27
+ }
28
+ //#endregion
29
+ export {};
30
+ //# sourceMappingURL=thin-handler.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thin-handler.d.mts","names":[],"sources":["../../src/stripe/thin-handler.ts"],"mappings":";;KAEK,0BAA0B,OAAO,GAAG,KAAK;YAElC,sBAAsB;YAEtB,8BAA8B,UAAU,uBAAuB,QACzE;EACE,MAAM;;KAGL,eAAe,UAAU,sBAAsB,wBAClD,cAAc,8BAA8B,OACzC;;;;;;;;;;;;;qBAcQ;mBAEM;UAEV;SAIA,UAAM;EAIb,KAAM,UAAU,qBAAmB,MAAQ,GAAC,SAAW,eAAe;EAStE,UAAO,cAAwB,4BAA0B"}
@@ -0,0 +1,39 @@
1
+ //#region src/stripe/thin-handler.ts
2
+ /**
3
+ * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The
4
+ * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes
5
+ * the notification in. A thin event only says which object changed, so each handler reads current
6
+ * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched
7
+ * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API
8
+ * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read
9
+ * state instead of applying a payload, and dedupe one-off facts with idempotency keys.
10
+ *
11
+ * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event
12
+ * types and `parseEventNotificationAsync` need stripe-node 23+.
13
+ */
14
+ var StripeThinEventHandler = class StripeThinEventHandler {
15
+ handlers;
16
+ constructor() {
17
+ this.handlers = /* @__PURE__ */ new Map();
18
+ }
19
+ static create() {
20
+ return new StripeThinEventHandler();
21
+ }
22
+ on = (type, handler) => {
23
+ if (!this.handlers.has(type)) this.handlers.set(type, []);
24
+ this.handlers.get(type)?.push(handler);
25
+ return this;
26
+ };
27
+ process = async (notification) => {
28
+ const eventHandlers = this.handlers.get(notification.type);
29
+ if (eventHandlers) await Promise.all(eventHandlers.map((handler) => handler(notification)));
30
+ else {
31
+ console.error(`No stripe event handler found for event type: ${notification.type}`);
32
+ throw new Error(`No stripe event handler found for event type: ${notification.type}`);
33
+ }
34
+ };
35
+ };
36
+ //#endregion
37
+ export { StripeThinEventHandler };
38
+
39
+ //# sourceMappingURL=thin-handler.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thin-handler.mjs","names":[],"sources":["../../src/stripe/thin-handler.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\n\ntype StripeEventNotification = Stripe.V2.Core.EventNotification;\n\nexport type StripeThinEventType = StripeEventNotification['type'];\n\nexport type StripeThinEventNotificationOf<T extends StripeThinEventType> = Extract<\n StripeEventNotification,\n { type: T }\n>;\n\ntype EventHandlerFn<T extends StripeThinEventType = StripeThinEventType> = (\n notification: StripeThinEventNotificationOf<T>\n) => Promise<void>;\n\n/**\n * Stripe thin event dispatcher keyed by event type (`v1.customer.subscription.updated`, ...). The\n * caller verifies and parses the payload with `stripe.parseEventNotificationAsync` first and passes\n * the notification in. A thin event only says which object changed, so each handler reads current\n * state itself with `notification.fetchRelatedObject()` (or `fetchEvent()`). Nothing is pre-fetched\n * here: some handlers only need `related_object.id`, and fetching inside the handler keeps the API\n * call next to the code that uses its result. Delivery order carries no meaning: handlers re-read\n * state instead of applying a payload, and dedupe one-off facts with idempotency keys.\n *\n * The thin-event counterpart of StripeEventHandler, which dispatches snapshot events. Thin event\n * types and `parseEventNotificationAsync` need stripe-node 23+.\n */\nexport class StripeThinEventHandler {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly handlers: Map<StripeThinEventType, Array<EventHandlerFn<any>>>;\n\n private constructor() {\n this.handlers = new Map();\n }\n\n static create() {\n return new StripeThinEventHandler();\n }\n\n on = <T extends StripeThinEventType>(type: T, handler: EventHandlerFn<T>) => {\n if (!this.handlers.has(type)) {\n this.handlers.set(type, []);\n }\n\n this.handlers.get(type)?.push(handler);\n return this;\n };\n\n process = async (notification: StripeEventNotification): Promise<void> => {\n const eventHandlers = this.handlers.get(notification.type);\n if (eventHandlers) {\n await Promise.all(eventHandlers.map((handler) => handler(notification)));\n } else {\n console.error(`No stripe event handler found for event type: ${notification.type}`);\n throw new Error(`No stripe event handler found for event type: ${notification.type}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,IAAa,yBAAb,MAAa,uBAAuB;CAElC;CAEA,cAAsB;EACpB,KAAK,2BAAW,IAAI,IAAI;CAC1B;CAEA,OAAO,SAAS;EACd,OAAO,IAAI,uBAAuB;CACpC;CAEA,MAAqC,MAAS,YAA+B;EAC3E,IAAI,CAAC,KAAK,SAAS,IAAI,IAAI,GACzB,KAAK,SAAS,IAAI,MAAM,CAAC,CAAC;EAG5B,KAAK,SAAS,IAAI,IAAI,CAAC,EAAE,KAAK,OAAO;EACrC,OAAO;CACT;CAEA,UAAU,OAAO,iBAAyD;EACxE,MAAM,gBAAgB,KAAK,SAAS,IAAI,aAAa,IAAI;EACzD,IAAI,eACF,MAAM,QAAQ,IAAI,cAAc,KAAK,YAAY,QAAQ,YAAY,CAAC,CAAC;OAClE;GACL,QAAQ,MAAM,iDAAiD,aAAa,MAAM;GAClF,MAAM,IAAI,MAAM,iDAAiD,aAAa,MAAM;EACtF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/purchase",
3
- "version": "6.0.0",
3
+ "version": "7.1.0",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",
@@ -70,7 +70,7 @@
70
70
  },
71
71
  "peerDependencies": {
72
72
  "@apple/app-store-server-library": "^3.1.0",
73
- "stripe": "^22.6.2 || ^23.0.0",
73
+ "stripe": "^23.0.0",
74
74
  "zod": "^4.6.5"
75
75
  },
76
76
  "peerDependenciesMeta": {