@skalpgg/sdk 1.11.0 → 1.13.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
@@ -42,7 +42,7 @@ Create the key on the API keys page of your dashboard. Each key is bound to one
42
42
  | Method | Scope |
43
43
  | --- | --- |
44
44
  | `me()` | none |
45
- | `checkout.create({ productId, quantity?, customerEmail?, metadata?, couponCode?, returnUrl?, customFields?, player? })` | `checkout:write` |
45
+ | `checkout.create({ productId, quantity?, customerEmail?, metadata?, couponCode?, returnUrl?, customFields?, player?, ads? })` | `checkout:write` |
46
46
  | `checkout.get(id)` | `checkout:read` |
47
47
  | `orders.list({ status?, productId?, email?, identifier?, createdAfter?, createdBefore?, updatedSince?, limit?, offset? })` | `orders:read` |
48
48
  | `orders.get(id)` | `orders:read` |
@@ -76,15 +76,22 @@ Create the key on the API keys page of your dashboard. Each key is bound to one
76
76
  | `queries.reply(id, { message })` / `queries.close(id)` / `queries.reopen(id)` | `queries:write` |
77
77
  | `blacklist.list({ type? })` / `blacklist.add({ type, value, note? })` / `blacklist.remove(id)` | `blacklist:read` / `blacklist:write` |
78
78
  | `whitelist.list({ type? })` / `whitelist.add({ type, value, note? })` / `whitelist.remove(id)` | `whitelist:read` / `whitelist:write` |
79
- | `subscriptions.createCheckout({ productId \| productSlug, externalRef?, customerEmail?, currency?, ... })` | `checkout:write` |
79
+ | `subscriptions.createCheckout({ productId \| productSlug, externalCustomerId?, customerEmail?, currency?, ads?, ... })` | `checkout:write` |
80
80
  | `subscriptions.getCheckout(id)` | `checkout:read` |
81
- | `subscriptions.list({ externalRef?, status?, updatedSince?, limit?, offset? })` | `subscriptions:read` |
81
+ | `subscriptions.list({ externalCustomerId?, status?, updatedSince?, limit?, offset? })` | `subscriptions:read` |
82
82
  | `subscriptions.get(id)` | `subscriptions:read` |
83
83
  | `subscriptions.changePlan(id, { productId \| productSlug })` | `subscriptions:write` |
84
- | `subscriptions.update(id, { externalRef })` | `subscriptions:write` |
84
+ | `subscriptions.update(id, { externalCustomerId })` | `subscriptions:write` |
85
85
  | `subscriptions.cancel(id)` | `subscriptions:write` |
86
86
  | `subscriptions.createUsageCharge(id, { amount, currency, description, idempotencyKey, periodStart, periodEnd })` | `subscriptions:write` |
87
87
  | `subscriptions.listInvoices(id)` | `subscriptions:read` |
88
+ | `usage.ingest(event \| events[])` | `usage:write` |
89
+ | `usage.summary({ meter, customer?, from?, to?, interval? })` | `usage:read` |
90
+ | `credits.get({ customerId \| externalCustomerId \| customerEmail })` | `usage:read` |
91
+ | `credits.transactions({ customer, meter?, limit?, offset? })` | `usage:read` |
92
+ | `credits.grant({ meter, customer, amount, idempotencyKey, expiresAt?, note? })` | `usage:write` |
93
+ | `meters.list()` | `usage:read` |
94
+ | `meters.create({ name, unit?, key? })` | `usage:write` |
88
95
  | `coins.createCheckout({ steamHex, coins, idempotencyKey?, returnUrl? })` | `coins:purchase` |
89
96
  | `coins.getCheckoutStatus(reference)` | `coins:read` |
90
97
  | `licenses.validate({ key, productId?, hardwareId? })` | `licenses:validate` |
@@ -98,6 +105,22 @@ Create the key on the API keys page of your dashboard. Each key is bound to one
98
105
 
99
106
  `products:write` does not include `products:read`: a key that manages the catalog usually needs both. Every catalog call counts against the key's rate limit.
100
107
 
108
+ ### Ad conversions
109
+
110
+ If the store connected Meta, TikTok or Google Analytics under Integrations, pass `ads` and the purchase reaches them once it is paid. `consent` is what the buyer allowed in your cookie banner: `ads` for Meta and TikTok, `analytics` for Google Analytics. `cookies` are the buyer's `_fbp`, `_fbc`, `_ttp`, `_ga` and `_ga_<stream>` cookies from your site, copied as they are. Without consent nothing is sent.
111
+
112
+ ```ts
113
+ const session = await skalp.checkout.create({
114
+ productId: 'prod_xxx',
115
+ ads: {
116
+ consent: { ads: true, analytics: true },
117
+ cookies: { _fbp: req.cookies._fbp, _ga: req.cookies._ga },
118
+ fbclid: req.query.fbclid,
119
+ pageUrl: 'https://example.com/pricing',
120
+ },
121
+ })
122
+ ```
123
+
101
124
  ## Catalog
102
125
 
103
126
  ```ts
@@ -136,7 +159,7 @@ const { replacements } = await skalp.orders.replace(order.id, { reason: 'Key doe
136
159
 
137
160
  `cancel` works only on a `PENDING` order and returns it as `CANCELED`. `replace` swaps the delivered keys of a completed order: with no `serialIds` it replaces every key, and with no `values` it draws the new ones from stock (`values` is required for keys that come from your server). The replacement keys come back in `replacements[].value`. `orders.get` also returns `serialsReplaced`, the `replacements` history and `serials`: the id, status, `deliveredAt` and `replacedById` of every delivered or replaced key (never its value), which are the ids `serialIds` expects.
138
161
 
139
- `identifier` keeps the orders of one player (up to 10 values of up to 200 characters; a longer list or value is a 400). A value is a game identity: `steam:<hex>`, a SteamID64, any `kind:value` such as `discord:123456789012345678` or `license:abc...`, or a bare value. It matches orders whose buyer or gift recipient signed in with that Steam account, or where a checkout custom field answer equals the value (case and a leading `kind:` prefix on either side are ignored). It combines with the other filters.
162
+ `identifier` keeps the orders of one player (up to 10 values of up to 200 characters; a longer list or value is a 400). A value is a game identity: `steam:<hex>`, a SteamID64, any `kind:value` such as `discord:123456789012345678` or `license:abc...`, or a bare value. It matches orders whose buyer or gift recipient connected that Steam account, or where a checkout custom field answer equals the value (case and a leading `kind:` prefix on either side are ignored). It combines with the other filters.
140
163
 
141
164
  `redeliver` takes the order's id or its number (`SKP-XXXX-XXXX-XXXX`) and sends a completed order that was not delivered again: a `FAILED` delivery goes back to `PENDING` and the `order.paid` and `purchase.completed` webhooks are sent again to the store's game server, which delivers it as a normal purchase. It returns the order as `orders.get` does. It answers 400 when the order is not `COMPLETED`, is already `DELIVERED`, is a gift nobody has claimed yet, or never had a licence issued, and 404 when the order is not in the key's store.
142
165
 
@@ -183,6 +206,25 @@ await skalp.blacklist.add({ type: 'EMAIL', value: 'chargeback@example.com', note
183
206
 
184
207
  `type` is `EMAIL`, `IP`, `COUNTRY`, `ISP`, `ASN` or `HOST`. `blacklist.list` and `whitelist.list` return every rule as one array, not a page.
185
208
 
209
+ ## Credits and usage
210
+
211
+ Create a meter in the dashboard (or with `meters.create`), add credits to a product, then report usage as it happens:
212
+
213
+ ```ts
214
+ const { balance, access } = await skalp.usage.ingest({
215
+ meter: 'tokens',
216
+ externalCustomerId: user.id,
217
+ quantity: 1250,
218
+ idempotencyKey: requestId,
219
+ })
220
+
221
+ if (!access) return showTopUp()
222
+ ```
223
+
224
+ Pass your own user ID as `externalCustomerId` to `checkout.create` or `subscriptions.createCheckout` and the credits from that purchase land on that customer. `subscriptions.list` and `subscriptions.update` take it too, and `externalRef` still works as its older name. The first event for a new ID also needs `customerEmail`.
225
+
226
+ The same `idempotencyKey` is recorded once and comes back with `duplicate: true`. Send up to 1000 events as an array, and each one gets its own result or `error`. With `requireCredits: true` an event that would go below zero is refused with a 402 `INSUFFICIENT_CREDITS` and nothing is written. `credits.granted` and `credits.depleted` webhooks tell you when a balance changes hands.
227
+
186
228
  ## Usage charges
187
229
 
188
230
  ```ts
@@ -1,6 +1,6 @@
1
- import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
1
+ import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateMeterParams, CreditBalances, CreditGrantResult, CreditTransactionList, CustomerRef, GrantCreditsParams, ListCreditTransactionsParams, Meter, UsageError, UsageEvent, UsageResult, UsageSummary, UsageSummaryParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
2
2
  export type * from './types.js';
3
- export declare const VERSION = "1.11.0";
3
+ export declare const VERSION = "1.13.0";
4
4
  export interface SkalpOptions {
5
5
  apiKey?: string;
6
6
  webhookSecret?: string;
@@ -33,7 +33,7 @@ export declare class Skalp {
33
33
  constructor(options?: string | SkalpOptions);
34
34
  readonly me: () => Promise<Me>;
35
35
  readonly checkout: {
36
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player }: CreateCheckoutParams) => Promise<CheckoutSession>;
36
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
37
  get: (id: string) => Promise<CheckoutSessionStatus>;
38
38
  };
39
39
  readonly orders: {
@@ -82,6 +82,22 @@ export declare class Skalp {
82
82
  update: (id: string, { name, note }: UpdateCustomerParams) => Promise<Customer>;
83
83
  delete: (id: string) => Promise<Deleted>;
84
84
  };
85
+ readonly usage: {
86
+ ingest: {
87
+ (event: UsageEvent): Promise<UsageResult>;
88
+ (events: Array<UsageEvent>): Promise<Array<UsageResult | UsageError>>;
89
+ };
90
+ summary: ({ meter, from, to, interval, ...customer }: UsageSummaryParams) => Promise<UsageSummary>;
91
+ };
92
+ readonly credits: {
93
+ get: (customer: CustomerRef) => Promise<CreditBalances>;
94
+ transactions: ({ meter, limit, offset, ...customer }: ListCreditTransactionsParams) => Promise<CreditTransactionList>;
95
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }: GrantCreditsParams) => Promise<CreditGrantResult>;
96
+ };
97
+ readonly meters: {
98
+ list: () => Promise<Meter[]>;
99
+ create: ({ name, unit, key }: CreateMeterParams) => Promise<Meter>;
100
+ };
85
101
  readonly levels: {
86
102
  get: () => Promise<StoreLevels>;
87
103
  customer: (email: string) => Promise<CustomerLevel>;
@@ -116,12 +132,12 @@ export declare class Skalp {
116
132
  getCheckoutStatus: (reference: string) => Promise<CoinCheckoutStatus>;
117
133
  };
118
134
  readonly subscriptions: {
119
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
135
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
120
136
  getCheckout: (id: string) => Promise<SubscriptionCheckoutStatus>;
121
- list: ({ externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
137
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
122
138
  get: (id: string) => Promise<Subscription>;
123
139
  changePlan: (id: string, { productId, productSlug }: ChangeSubscriptionPlanParams) => Promise<Subscription>;
124
- update: (id: string, { externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
140
+ update: (id: string, { externalCustomerId, externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
125
141
  cancel: (id: string) => Promise<Subscription>;
126
142
  createUsageCharge: (id: string, { amount, currency, description, idempotencyKey, periodStart, periodEnd }: CreateUsageChargeParams) => Promise<UsageCharge>;
127
143
  listInvoices: (id: string) => Promise<Invoice[]>;
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Skalp = exports.SkalpSignatureError = exports.SkalpConnectionError = exports.SkalpError = exports.VERSION = void 0;
4
- exports.VERSION = '1.11.0';
4
+ exports.VERSION = '1.13.0';
5
5
  const SIGNATURE_HEADER = 'skalp-signature';
6
6
  const SIGNATURE_TOLERANCE_SECONDS = 300;
7
7
  const PRODUCT_PAGE = 100;
@@ -137,8 +137,8 @@ class Skalp {
137
137
  }
138
138
  me = () => this.#request('GET', '/v1/me');
139
139
  checkout = {
140
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player }) => this.#request('POST', '/v1/checkout/sessions', {
141
- body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player },
140
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }) => this.#request('POST', '/v1/checkout/sessions', {
141
+ body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId },
142
142
  }),
143
143
  get: (id) => this.#request('GET', `/v1/checkout/sessions/${segment(id)}`),
144
144
  };
@@ -236,6 +236,33 @@ class Skalp {
236
236
  update: (id, { name, note }) => this.#request('PATCH', `/v1/customers/${segment(id)}`, { body: { name, note } }),
237
237
  delete: (id) => this.#request('DELETE', `/v1/customers/${segment(id)}`),
238
238
  };
239
+ usage = {
240
+ ingest: (async (events) => {
241
+ if (!Array.isArray(events)) {
242
+ return this.#request('POST', '/v1/usage/events', { body: usageEvent(events) });
243
+ }
244
+ const { data } = await this.#request('POST', '/v1/usage/events', {
245
+ body: { events: events.map(usageEvent) },
246
+ });
247
+ return data;
248
+ }),
249
+ summary: ({ meter, from, to, interval, ...customer }) => this.#request('GET', '/v1/usage', {
250
+ query: { meter, from: optionalDate(from), to: optionalDate(to), interval, ...customerQuery(customer) },
251
+ }),
252
+ };
253
+ credits = {
254
+ get: (customer) => this.#request('GET', '/v1/credits', { query: customerQuery(customer) }),
255
+ transactions: ({ meter, limit, offset, ...customer }) => this.#request('GET', '/v1/credits/transactions', {
256
+ query: { meter, limit, offset, ...customerQuery(customer) },
257
+ }),
258
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }) => this.#request('POST', '/v1/credits/grants', {
259
+ body: { meter, amount, idempotencyKey, expiresAt: optionalDate(expiresAt), note, metadata, ...customerQuery(customer) },
260
+ }),
261
+ };
262
+ meters = {
263
+ list: async () => (await this.#request('GET', '/v1/meters')).data,
264
+ create: ({ name, unit, key }) => this.#request('POST', '/v1/meters', { body: { name, unit, key } }),
265
+ };
239
266
  levels = {
240
267
  get: () => this.#request('GET', '/v1/levels'),
241
268
  customer: (email) => this.#request('GET', `/v1/levels/customers/${segment(email)}`),
@@ -271,12 +298,13 @@ class Skalp {
271
298
  getCheckoutStatus: (reference) => this.#request('GET', `/coins/checkout/${segment(reference)}/status`),
272
299
  };
273
300
  subscriptions = {
274
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, }) => this.#request('POST', '/v1/subscriptions/checkout', {
275
- body: { productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl },
301
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
302
+ body: { productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads },
276
303
  }),
277
304
  getCheckout: (id) => this.#request('GET', `/v1/subscriptions/checkout/${segment(id)}`),
278
- list: ({ externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
305
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
279
306
  query: {
307
+ externalCustomerId,
280
308
  externalRef,
281
309
  status,
282
310
  updatedSince: updatedSince instanceof Date ? updatedSince.toISOString() : updatedSince,
@@ -288,7 +316,7 @@ class Skalp {
288
316
  changePlan: (id, { productId, productSlug }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/plan`, {
289
317
  body: { productId, productSlug },
290
318
  }),
291
- update: (id, { externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalRef } }),
319
+ update: (id, { externalCustomerId, externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalCustomerId, externalRef } }),
292
320
  cancel: (id) => this.#request('DELETE', `/v1/subscriptions/${segment(id)}`),
293
321
  createUsageCharge: (id, { amount, currency, description, idempotencyKey, periodStart, periodEnd }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/usage-charges`, {
294
322
  body: {
@@ -412,6 +440,20 @@ class Skalp {
412
440
  }
413
441
  }
414
442
  exports.Skalp = Skalp;
443
+ function customerQuery({ customerId, externalCustomerId, customerEmail }) {
444
+ return { customerId, externalCustomerId, customerEmail };
445
+ }
446
+ function usageEvent({ meter, quantity, idempotencyKey, timestamp, metadata, requireCredits, ...customer }) {
447
+ return {
448
+ meter,
449
+ quantity,
450
+ idempotencyKey,
451
+ timestamp: optionalDate(timestamp),
452
+ metadata,
453
+ requireCredits,
454
+ ...customerQuery(customer),
455
+ };
456
+ }
415
457
  function readSignature(source) {
416
458
  if (source == null || typeof source === 'string')
417
459
  return source ?? undefined;
@@ -18,6 +18,16 @@ export interface Player {
18
18
  name: string | null;
19
19
  ids: Partial<Record<PlayerIdKey, string>>;
20
20
  }
21
+ export interface AdsInput {
22
+ consent: {
23
+ ads?: boolean;
24
+ analytics?: boolean;
25
+ };
26
+ cookies?: Record<string, string>;
27
+ fbclid?: string;
28
+ ttclid?: string;
29
+ pageUrl?: string;
30
+ }
21
31
  export interface CreateCheckoutParams {
22
32
  productId: string;
23
33
  /** Units to sell, within the product's minQuantity and maxQuantity. Defaults to minQuantity. */
@@ -29,6 +39,8 @@ export interface CreateCheckoutParams {
29
39
  /** Answers you already have, by field key; the buyer adds the rest on the pay page. */
30
40
  customFields?: Record<string, string>;
31
41
  player?: PlayerInput;
42
+ ads?: AdsInput;
43
+ externalCustomerId?: string;
32
44
  }
33
45
  export interface CheckoutSession {
34
46
  id: string;
@@ -756,10 +768,12 @@ export interface CreateSubscriptionCheckoutParams {
756
768
  productId?: string;
757
769
  productSlug?: string;
758
770
  customerEmail?: string;
771
+ externalCustomerId?: string;
759
772
  externalRef?: string;
760
773
  metadata?: Metadata;
761
774
  currency?: 'EUR' | 'USD' | 'PLN' | 'BRL';
762
775
  returnUrl?: string;
776
+ ads?: AdsInput;
763
777
  }
764
778
  export interface SubscriptionCheckout {
765
779
  id: string;
@@ -779,6 +793,7 @@ export interface Subscription {
779
793
  id: string;
780
794
  status: SubscriptionStatus;
781
795
  active: boolean;
796
+ externalCustomerId: string | null;
782
797
  externalRef: string | null;
783
798
  productId: string;
784
799
  productSlug: string;
@@ -801,10 +816,15 @@ export interface ChangeSubscriptionPlanParams {
801
816
  productId?: string;
802
817
  productSlug?: string;
803
818
  }
804
- export interface UpdateSubscriptionParams {
819
+ export type UpdateSubscriptionParams = {
820
+ externalCustomerId: string | null;
821
+ externalRef?: never;
822
+ } | {
805
823
  externalRef: string | null;
806
- }
824
+ externalCustomerId?: never;
825
+ };
807
826
  export interface ListSubscriptionsParams {
827
+ externalCustomerId?: string;
808
828
  externalRef?: string;
809
829
  status?: SubscriptionStatus;
810
830
  updatedSince?: string | Date;
@@ -1133,6 +1153,145 @@ export interface CustomerLevelEventData {
1133
1153
  xp: number;
1134
1154
  tier: LevelTier;
1135
1155
  }
1156
+ export interface CustomerRef {
1157
+ customerId?: string;
1158
+ externalCustomerId?: string;
1159
+ customerEmail?: string;
1160
+ }
1161
+ export interface UsageEvent extends CustomerRef {
1162
+ meter: string;
1163
+ quantity?: number;
1164
+ idempotencyKey?: string;
1165
+ timestamp?: string | Date;
1166
+ metadata?: Record<string, string>;
1167
+ requireCredits?: boolean;
1168
+ }
1169
+ export interface UsageResult {
1170
+ id: string;
1171
+ duplicate: boolean;
1172
+ balance: number;
1173
+ access: boolean;
1174
+ }
1175
+ export interface UsageError {
1176
+ error: {
1177
+ code: string;
1178
+ message: string;
1179
+ };
1180
+ }
1181
+ export interface CreditOverage {
1182
+ price: number;
1183
+ units: number;
1184
+ currency: Currency;
1185
+ }
1186
+ export interface CreditBalance {
1187
+ meter: string;
1188
+ name: string;
1189
+ unit: string;
1190
+ balance: number;
1191
+ granted: number;
1192
+ used: number;
1193
+ expiresNext: {
1194
+ amount: number;
1195
+ at: string;
1196
+ } | null;
1197
+ access: boolean;
1198
+ overage: CreditOverage | null;
1199
+ }
1200
+ export interface CreditBalances {
1201
+ customerId: string | null;
1202
+ data: Array<CreditBalance>;
1203
+ }
1204
+ export type CreditTransactionType = 'grant' | 'usage' | 'adjustment' | 'expiration' | 'revocation' | 'overage' | 'overage_reversal';
1205
+ export interface CreditTransaction {
1206
+ id: string;
1207
+ type: CreditTransactionType;
1208
+ meter: string;
1209
+ amount: number;
1210
+ balanceAfter: number;
1211
+ note: string | null;
1212
+ metadata: Record<string, unknown>;
1213
+ idempotencyKey: string | null;
1214
+ grantId: string | null;
1215
+ orderId: string | null;
1216
+ subscriptionId: string | null;
1217
+ occurredAt: string;
1218
+ createdAt: string;
1219
+ }
1220
+ export interface CreditTransactionList {
1221
+ data: Array<CreditTransaction>;
1222
+ total: number;
1223
+ limit: number;
1224
+ offset: number;
1225
+ }
1226
+ export interface ListCreditTransactionsParams extends CustomerRef {
1227
+ meter?: string;
1228
+ limit?: number;
1229
+ offset?: number;
1230
+ }
1231
+ export interface GrantCreditsParams extends CustomerRef {
1232
+ meter: string;
1233
+ amount: number;
1234
+ idempotencyKey: string;
1235
+ expiresAt?: string | Date;
1236
+ note?: string;
1237
+ metadata?: Record<string, string>;
1238
+ }
1239
+ export interface CreditGrantResult {
1240
+ id: string;
1241
+ grantId: string | null;
1242
+ duplicate: boolean;
1243
+ amount: number;
1244
+ balance: number;
1245
+ access: boolean;
1246
+ }
1247
+ export interface UsageSummaryParams extends Partial<CustomerRef> {
1248
+ meter: string;
1249
+ from?: string | Date;
1250
+ to?: string | Date;
1251
+ interval?: 'hour' | 'day' | 'month';
1252
+ }
1253
+ export interface UsageSummary {
1254
+ meter: string;
1255
+ interval: 'hour' | 'day' | 'month';
1256
+ from: string;
1257
+ to: string;
1258
+ total: number;
1259
+ events: number;
1260
+ data: Array<{
1261
+ start: string;
1262
+ quantity: number;
1263
+ events: number;
1264
+ }>;
1265
+ }
1266
+ export interface Meter {
1267
+ id: string;
1268
+ key: string;
1269
+ name: string;
1270
+ unit: string;
1271
+ archived: boolean;
1272
+ createdAt: string;
1273
+ }
1274
+ export interface CreateMeterParams {
1275
+ name: string;
1276
+ unit?: string;
1277
+ key?: string;
1278
+ }
1279
+ export interface CreditEventCustomer {
1280
+ customerId: string;
1281
+ externalCustomerId: string | null;
1282
+ customerEmail: string | null;
1283
+ meter: string;
1284
+ meterId: string;
1285
+ balance: number;
1286
+ }
1287
+ export interface CreditsGrantedData extends CreditEventCustomer {
1288
+ grantId: string;
1289
+ amount: number;
1290
+ source: 'order' | 'subscription' | 'manual' | 'api';
1291
+ expiresAt: string | null;
1292
+ orderId: string | null;
1293
+ subscriptionId: string | null;
1294
+ }
1136
1295
  export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.canceled', OrderEventData> | Envelope<'order.replaced', OrderReplacedData> | Envelope<'order.paid' | 'purchase.completed', OrderPaidData> | Envelope<'order.refunded', OrderRefundedData> | Envelope<'order.disputed' | 'account.suspend', OrderDisputedData> | Envelope<'account.restore', AccountRestoreData> | Envelope<'subscription.created' | 'subscription.updated' | 'subscription.trial_started' | 'subscription.trial_ended', SubscriptionEventData> | Envelope<'subscription.upcoming', SubscriptionEventData & {
1137
1296
  amountDue: number;
1138
1297
  nextPaymentAttempt: string | null;
@@ -1157,6 +1316,6 @@ export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.can
1157
1316
  disputeId: string;
1158
1317
  disputeStatus: 'open' | 'won' | 'lost';
1159
1318
  disputeReason: string | null;
1160
- }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'webhook.test', WebhookTestData>;
1319
+ }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'credits.granted', CreditsGrantedData> | Envelope<'credits.depleted', CreditEventCustomer> | Envelope<'webhook.test', WebhookTestData>;
1161
1320
  export type SkalpEventType = SkalpEvent['type'];
1162
1321
  export {};
@@ -1,6 +1,6 @@
1
- import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
1
+ import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateMeterParams, CreditBalances, CreditGrantResult, CreditTransactionList, CustomerRef, GrantCreditsParams, ListCreditTransactionsParams, Meter, UsageError, UsageEvent, UsageResult, UsageSummary, UsageSummaryParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
2
2
  export type * from './types.js';
3
- export declare const VERSION = "1.11.0";
3
+ export declare const VERSION = "1.13.0";
4
4
  export interface SkalpOptions {
5
5
  apiKey?: string;
6
6
  webhookSecret?: string;
@@ -33,7 +33,7 @@ export declare class Skalp {
33
33
  constructor(options?: string | SkalpOptions);
34
34
  readonly me: () => Promise<Me>;
35
35
  readonly checkout: {
36
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player }: CreateCheckoutParams) => Promise<CheckoutSession>;
36
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
37
  get: (id: string) => Promise<CheckoutSessionStatus>;
38
38
  };
39
39
  readonly orders: {
@@ -82,6 +82,22 @@ export declare class Skalp {
82
82
  update: (id: string, { name, note }: UpdateCustomerParams) => Promise<Customer>;
83
83
  delete: (id: string) => Promise<Deleted>;
84
84
  };
85
+ readonly usage: {
86
+ ingest: {
87
+ (event: UsageEvent): Promise<UsageResult>;
88
+ (events: Array<UsageEvent>): Promise<Array<UsageResult | UsageError>>;
89
+ };
90
+ summary: ({ meter, from, to, interval, ...customer }: UsageSummaryParams) => Promise<UsageSummary>;
91
+ };
92
+ readonly credits: {
93
+ get: (customer: CustomerRef) => Promise<CreditBalances>;
94
+ transactions: ({ meter, limit, offset, ...customer }: ListCreditTransactionsParams) => Promise<CreditTransactionList>;
95
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }: GrantCreditsParams) => Promise<CreditGrantResult>;
96
+ };
97
+ readonly meters: {
98
+ list: () => Promise<Meter[]>;
99
+ create: ({ name, unit, key }: CreateMeterParams) => Promise<Meter>;
100
+ };
85
101
  readonly levels: {
86
102
  get: () => Promise<StoreLevels>;
87
103
  customer: (email: string) => Promise<CustomerLevel>;
@@ -116,12 +132,12 @@ export declare class Skalp {
116
132
  getCheckoutStatus: (reference: string) => Promise<CoinCheckoutStatus>;
117
133
  };
118
134
  readonly subscriptions: {
119
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
135
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
120
136
  getCheckout: (id: string) => Promise<SubscriptionCheckoutStatus>;
121
- list: ({ externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
137
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
122
138
  get: (id: string) => Promise<Subscription>;
123
139
  changePlan: (id: string, { productId, productSlug }: ChangeSubscriptionPlanParams) => Promise<Subscription>;
124
- update: (id: string, { externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
140
+ update: (id: string, { externalCustomerId, externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
125
141
  cancel: (id: string) => Promise<Subscription>;
126
142
  createUsageCharge: (id: string, { amount, currency, description, idempotencyKey, periodStart, periodEnd }: CreateUsageChargeParams) => Promise<UsageCharge>;
127
143
  listInvoices: (id: string) => Promise<Invoice[]>;
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '1.11.0';
1
+ export const VERSION = '1.13.0';
2
2
  const SIGNATURE_HEADER = 'skalp-signature';
3
3
  const SIGNATURE_TOLERANCE_SECONDS = 300;
4
4
  const PRODUCT_PAGE = 100;
@@ -131,8 +131,8 @@ export class Skalp {
131
131
  }
132
132
  me = () => this.#request('GET', '/v1/me');
133
133
  checkout = {
134
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player }) => this.#request('POST', '/v1/checkout/sessions', {
135
- body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player },
134
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }) => this.#request('POST', '/v1/checkout/sessions', {
135
+ body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId },
136
136
  }),
137
137
  get: (id) => this.#request('GET', `/v1/checkout/sessions/${segment(id)}`),
138
138
  };
@@ -230,6 +230,33 @@ export class Skalp {
230
230
  update: (id, { name, note }) => this.#request('PATCH', `/v1/customers/${segment(id)}`, { body: { name, note } }),
231
231
  delete: (id) => this.#request('DELETE', `/v1/customers/${segment(id)}`),
232
232
  };
233
+ usage = {
234
+ ingest: (async (events) => {
235
+ if (!Array.isArray(events)) {
236
+ return this.#request('POST', '/v1/usage/events', { body: usageEvent(events) });
237
+ }
238
+ const { data } = await this.#request('POST', '/v1/usage/events', {
239
+ body: { events: events.map(usageEvent) },
240
+ });
241
+ return data;
242
+ }),
243
+ summary: ({ meter, from, to, interval, ...customer }) => this.#request('GET', '/v1/usage', {
244
+ query: { meter, from: optionalDate(from), to: optionalDate(to), interval, ...customerQuery(customer) },
245
+ }),
246
+ };
247
+ credits = {
248
+ get: (customer) => this.#request('GET', '/v1/credits', { query: customerQuery(customer) }),
249
+ transactions: ({ meter, limit, offset, ...customer }) => this.#request('GET', '/v1/credits/transactions', {
250
+ query: { meter, limit, offset, ...customerQuery(customer) },
251
+ }),
252
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }) => this.#request('POST', '/v1/credits/grants', {
253
+ body: { meter, amount, idempotencyKey, expiresAt: optionalDate(expiresAt), note, metadata, ...customerQuery(customer) },
254
+ }),
255
+ };
256
+ meters = {
257
+ list: async () => (await this.#request('GET', '/v1/meters')).data,
258
+ create: ({ name, unit, key }) => this.#request('POST', '/v1/meters', { body: { name, unit, key } }),
259
+ };
233
260
  levels = {
234
261
  get: () => this.#request('GET', '/v1/levels'),
235
262
  customer: (email) => this.#request('GET', `/v1/levels/customers/${segment(email)}`),
@@ -265,12 +292,13 @@ export class Skalp {
265
292
  getCheckoutStatus: (reference) => this.#request('GET', `/coins/checkout/${segment(reference)}/status`),
266
293
  };
267
294
  subscriptions = {
268
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, }) => this.#request('POST', '/v1/subscriptions/checkout', {
269
- body: { productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl },
295
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
296
+ body: { productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads },
270
297
  }),
271
298
  getCheckout: (id) => this.#request('GET', `/v1/subscriptions/checkout/${segment(id)}`),
272
- list: ({ externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
299
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
273
300
  query: {
301
+ externalCustomerId,
274
302
  externalRef,
275
303
  status,
276
304
  updatedSince: updatedSince instanceof Date ? updatedSince.toISOString() : updatedSince,
@@ -282,7 +310,7 @@ export class Skalp {
282
310
  changePlan: (id, { productId, productSlug }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/plan`, {
283
311
  body: { productId, productSlug },
284
312
  }),
285
- update: (id, { externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalRef } }),
313
+ update: (id, { externalCustomerId, externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalCustomerId, externalRef } }),
286
314
  cancel: (id) => this.#request('DELETE', `/v1/subscriptions/${segment(id)}`),
287
315
  createUsageCharge: (id, { amount, currency, description, idempotencyKey, periodStart, periodEnd }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/usage-charges`, {
288
316
  body: {
@@ -405,6 +433,20 @@ export class Skalp {
405
433
  }
406
434
  }
407
435
  }
436
+ function customerQuery({ customerId, externalCustomerId, customerEmail }) {
437
+ return { customerId, externalCustomerId, customerEmail };
438
+ }
439
+ function usageEvent({ meter, quantity, idempotencyKey, timestamp, metadata, requireCredits, ...customer }) {
440
+ return {
441
+ meter,
442
+ quantity,
443
+ idempotencyKey,
444
+ timestamp: optionalDate(timestamp),
445
+ metadata,
446
+ requireCredits,
447
+ ...customerQuery(customer),
448
+ };
449
+ }
408
450
  function readSignature(source) {
409
451
  if (source == null || typeof source === 'string')
410
452
  return source ?? undefined;
@@ -18,6 +18,16 @@ export interface Player {
18
18
  name: string | null;
19
19
  ids: Partial<Record<PlayerIdKey, string>>;
20
20
  }
21
+ export interface AdsInput {
22
+ consent: {
23
+ ads?: boolean;
24
+ analytics?: boolean;
25
+ };
26
+ cookies?: Record<string, string>;
27
+ fbclid?: string;
28
+ ttclid?: string;
29
+ pageUrl?: string;
30
+ }
21
31
  export interface CreateCheckoutParams {
22
32
  productId: string;
23
33
  /** Units to sell, within the product's minQuantity and maxQuantity. Defaults to minQuantity. */
@@ -29,6 +39,8 @@ export interface CreateCheckoutParams {
29
39
  /** Answers you already have, by field key; the buyer adds the rest on the pay page. */
30
40
  customFields?: Record<string, string>;
31
41
  player?: PlayerInput;
42
+ ads?: AdsInput;
43
+ externalCustomerId?: string;
32
44
  }
33
45
  export interface CheckoutSession {
34
46
  id: string;
@@ -756,10 +768,12 @@ export interface CreateSubscriptionCheckoutParams {
756
768
  productId?: string;
757
769
  productSlug?: string;
758
770
  customerEmail?: string;
771
+ externalCustomerId?: string;
759
772
  externalRef?: string;
760
773
  metadata?: Metadata;
761
774
  currency?: 'EUR' | 'USD' | 'PLN' | 'BRL';
762
775
  returnUrl?: string;
776
+ ads?: AdsInput;
763
777
  }
764
778
  export interface SubscriptionCheckout {
765
779
  id: string;
@@ -779,6 +793,7 @@ export interface Subscription {
779
793
  id: string;
780
794
  status: SubscriptionStatus;
781
795
  active: boolean;
796
+ externalCustomerId: string | null;
782
797
  externalRef: string | null;
783
798
  productId: string;
784
799
  productSlug: string;
@@ -801,10 +816,15 @@ export interface ChangeSubscriptionPlanParams {
801
816
  productId?: string;
802
817
  productSlug?: string;
803
818
  }
804
- export interface UpdateSubscriptionParams {
819
+ export type UpdateSubscriptionParams = {
820
+ externalCustomerId: string | null;
821
+ externalRef?: never;
822
+ } | {
805
823
  externalRef: string | null;
806
- }
824
+ externalCustomerId?: never;
825
+ };
807
826
  export interface ListSubscriptionsParams {
827
+ externalCustomerId?: string;
808
828
  externalRef?: string;
809
829
  status?: SubscriptionStatus;
810
830
  updatedSince?: string | Date;
@@ -1133,6 +1153,145 @@ export interface CustomerLevelEventData {
1133
1153
  xp: number;
1134
1154
  tier: LevelTier;
1135
1155
  }
1156
+ export interface CustomerRef {
1157
+ customerId?: string;
1158
+ externalCustomerId?: string;
1159
+ customerEmail?: string;
1160
+ }
1161
+ export interface UsageEvent extends CustomerRef {
1162
+ meter: string;
1163
+ quantity?: number;
1164
+ idempotencyKey?: string;
1165
+ timestamp?: string | Date;
1166
+ metadata?: Record<string, string>;
1167
+ requireCredits?: boolean;
1168
+ }
1169
+ export interface UsageResult {
1170
+ id: string;
1171
+ duplicate: boolean;
1172
+ balance: number;
1173
+ access: boolean;
1174
+ }
1175
+ export interface UsageError {
1176
+ error: {
1177
+ code: string;
1178
+ message: string;
1179
+ };
1180
+ }
1181
+ export interface CreditOverage {
1182
+ price: number;
1183
+ units: number;
1184
+ currency: Currency;
1185
+ }
1186
+ export interface CreditBalance {
1187
+ meter: string;
1188
+ name: string;
1189
+ unit: string;
1190
+ balance: number;
1191
+ granted: number;
1192
+ used: number;
1193
+ expiresNext: {
1194
+ amount: number;
1195
+ at: string;
1196
+ } | null;
1197
+ access: boolean;
1198
+ overage: CreditOverage | null;
1199
+ }
1200
+ export interface CreditBalances {
1201
+ customerId: string | null;
1202
+ data: Array<CreditBalance>;
1203
+ }
1204
+ export type CreditTransactionType = 'grant' | 'usage' | 'adjustment' | 'expiration' | 'revocation' | 'overage' | 'overage_reversal';
1205
+ export interface CreditTransaction {
1206
+ id: string;
1207
+ type: CreditTransactionType;
1208
+ meter: string;
1209
+ amount: number;
1210
+ balanceAfter: number;
1211
+ note: string | null;
1212
+ metadata: Record<string, unknown>;
1213
+ idempotencyKey: string | null;
1214
+ grantId: string | null;
1215
+ orderId: string | null;
1216
+ subscriptionId: string | null;
1217
+ occurredAt: string;
1218
+ createdAt: string;
1219
+ }
1220
+ export interface CreditTransactionList {
1221
+ data: Array<CreditTransaction>;
1222
+ total: number;
1223
+ limit: number;
1224
+ offset: number;
1225
+ }
1226
+ export interface ListCreditTransactionsParams extends CustomerRef {
1227
+ meter?: string;
1228
+ limit?: number;
1229
+ offset?: number;
1230
+ }
1231
+ export interface GrantCreditsParams extends CustomerRef {
1232
+ meter: string;
1233
+ amount: number;
1234
+ idempotencyKey: string;
1235
+ expiresAt?: string | Date;
1236
+ note?: string;
1237
+ metadata?: Record<string, string>;
1238
+ }
1239
+ export interface CreditGrantResult {
1240
+ id: string;
1241
+ grantId: string | null;
1242
+ duplicate: boolean;
1243
+ amount: number;
1244
+ balance: number;
1245
+ access: boolean;
1246
+ }
1247
+ export interface UsageSummaryParams extends Partial<CustomerRef> {
1248
+ meter: string;
1249
+ from?: string | Date;
1250
+ to?: string | Date;
1251
+ interval?: 'hour' | 'day' | 'month';
1252
+ }
1253
+ export interface UsageSummary {
1254
+ meter: string;
1255
+ interval: 'hour' | 'day' | 'month';
1256
+ from: string;
1257
+ to: string;
1258
+ total: number;
1259
+ events: number;
1260
+ data: Array<{
1261
+ start: string;
1262
+ quantity: number;
1263
+ events: number;
1264
+ }>;
1265
+ }
1266
+ export interface Meter {
1267
+ id: string;
1268
+ key: string;
1269
+ name: string;
1270
+ unit: string;
1271
+ archived: boolean;
1272
+ createdAt: string;
1273
+ }
1274
+ export interface CreateMeterParams {
1275
+ name: string;
1276
+ unit?: string;
1277
+ key?: string;
1278
+ }
1279
+ export interface CreditEventCustomer {
1280
+ customerId: string;
1281
+ externalCustomerId: string | null;
1282
+ customerEmail: string | null;
1283
+ meter: string;
1284
+ meterId: string;
1285
+ balance: number;
1286
+ }
1287
+ export interface CreditsGrantedData extends CreditEventCustomer {
1288
+ grantId: string;
1289
+ amount: number;
1290
+ source: 'order' | 'subscription' | 'manual' | 'api';
1291
+ expiresAt: string | null;
1292
+ orderId: string | null;
1293
+ subscriptionId: string | null;
1294
+ }
1136
1295
  export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.canceled', OrderEventData> | Envelope<'order.replaced', OrderReplacedData> | Envelope<'order.paid' | 'purchase.completed', OrderPaidData> | Envelope<'order.refunded', OrderRefundedData> | Envelope<'order.disputed' | 'account.suspend', OrderDisputedData> | Envelope<'account.restore', AccountRestoreData> | Envelope<'subscription.created' | 'subscription.updated' | 'subscription.trial_started' | 'subscription.trial_ended', SubscriptionEventData> | Envelope<'subscription.upcoming', SubscriptionEventData & {
1137
1296
  amountDue: number;
1138
1297
  nextPaymentAttempt: string | null;
@@ -1157,6 +1316,6 @@ export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.can
1157
1316
  disputeId: string;
1158
1317
  disputeStatus: 'open' | 'won' | 'lost';
1159
1318
  disputeReason: string | null;
1160
- }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'webhook.test', WebhookTestData>;
1319
+ }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'credits.granted', CreditsGrantedData> | Envelope<'credits.depleted', CreditEventCustomer> | Envelope<'webhook.test', WebhookTestData>;
1161
1320
  export type SkalpEventType = SkalpEvent['type'];
1162
1321
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skalpgg/sdk",
3
- "version": "1.11.0",
3
+ "version": "1.13.0",
4
4
  "description": "Official Skalp SDK for Node.js and edge runtimes: checkout, subscriptions, catalog and key stock, webhooks and license verification.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://skalp.gg/docs/sdk",