palbase 0.73.1 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/4DNFXRTX.js +2 -0
  9. package/dist/chunks/{HYPCFC4K.js → 53XWB3UV.js} +1 -1
  10. package/dist/chunks/{W2KD2I4Q.js → 5NLCEWSD.js} +1 -1
  11. package/dist/chunks/{GTKPHG5F.js → 7HDSHHGM.js} +2 -2
  12. package/dist/chunks/{MB7MHOQO.js → AFO74GQQ.js} +1 -1
  13. package/dist/chunks/{IVJOWYRE.js → AKM627JB.js} +2 -2
  14. package/dist/chunks/{5N5GHLUU.js → BBXGUP7G.js} +2 -2
  15. package/dist/chunks/{5N6QKGPA.js → CVBLXV6M.js} +2 -2
  16. package/dist/chunks/{3KCV4F4F.js → DFIAGTHU.js} +2 -2
  17. package/dist/chunks/FKDQMWI7.js +23 -0
  18. package/dist/chunks/{GWWU2FJ7.js → FYZAVXD4.js} +2 -2
  19. package/dist/chunks/{DNSLYLU6.js → IIQ6QEL2.js} +1 -1
  20. package/dist/chunks/{U3H6HER3.js → IJBBBAXY.js} +1 -1
  21. package/dist/chunks/{2TKZTIMD.js → MKKBGO2H.js} +2 -2
  22. package/dist/chunks/OS567PDL.js +2 -0
  23. package/dist/chunks/{VCL3SAQL.js → PF52QMPW.js} +2 -2
  24. package/dist/chunks/{AXANFT2A.js → QJPQVLNV.js} +2 -2
  25. package/dist/chunks/{MFSC4OJV.js → RK4CTF2F.js} +2 -2
  26. package/dist/chunks/{SQNAPFXW.js → SS3YF6MP.js} +2 -2
  27. package/dist/chunks/{4E4ABCSD.js → U5LDOZB5.js} +2 -2
  28. package/dist/chunks/{YU3GFTZV.js → WNPRCDLR.js} +1 -1
  29. package/dist/chunks/{SS2RVI27.js → YDHRQOAN.js} +1 -1
  30. package/dist/chunks/{UOJVMV42.js → YOCX3MXN.js} +2 -2
  31. package/dist/chunks/{HRWVZ4PC.js → ZRNXABQJ.js} +2 -2
  32. package/dist/cli.js +162 -162
  33. package/dist/cloud/index.js +2 -2
  34. package/dist/refuse/ai-sdk.js +1 -1
  35. package/dist/refuse/ai.js +1 -1
  36. package/dist/refuse/backend.js +1 -1
  37. package/dist/refuse/cloud.js +1 -1
  38. package/dist/refuse/server.js +1 -1
  39. package/dist/server/index.js +2 -2
  40. package/dist/server/testing.js +2 -2
  41. package/dist/web/index.js +2 -2
  42. package/dist/web/message.js +2 -2
  43. package/dist/web/palbe.js +2 -2
  44. package/dist/web/payments-ui.js +2 -2
  45. package/dist/web/paywall.js +2 -2
  46. package/dist/web/push-sw.js +1 -1
  47. package/dist/web/ssr.js +2 -2
  48. package/dist/web/vite.js +2 -2
  49. package/package.json +2 -2
  50. package/types/cloud/src/generated/project.d.ts +1 -1
  51. package/types/internal/src/modules/commerce.d.ts +2810 -533
  52. package/types/internal/src/modules/events.d.ts +2 -2
  53. package/types/server/src/commerce.d.ts +172 -3
  54. package/types/server/src/index.d.ts +1 -1
  55. package/types/web/src/commerce.d.ts +460 -20
  56. package/types/web/src/index.d.ts +1 -1
  57. package/types/web/src/session.d.ts +15 -1
  58. package/types/web/src/ssr.d.ts +1 -1
  59. package/dist/chunks/SEICTPQP.js +0 -2
  60. package/dist/chunks/TR2IPX2A.js +0 -23
  61. package/dist/chunks/UXHNXE3J.js +0 -2
@@ -1,7 +1,11 @@
1
1
  import { commerce as commerceModule } from '../../internal/src/modules/index.js';
2
2
  import type { Transport } from '../../internal/src/transport.js';
3
+ import type { Analytics } from './analytics.js';
4
+ import type { Consent } from './consent.js';
5
+ import { type Installation } from './installation.js';
3
6
  import { type SessionManager } from './session.js';
4
7
  type C = typeof commerceModule;
8
+ type CommerceClient = ReturnType<C['client']>;
5
9
  export type Cart = commerceModule.Cart;
6
10
  export type CheckoutResponse = commerceModule.CheckoutResponse;
7
11
  export type Order = commerceModule.Order;
@@ -10,7 +14,9 @@ export type OrderDownloads = commerceModule.OrderDownloads;
10
14
  export type OrderList = commerceModule.OrderList;
11
15
  export type Product = commerceModule.Product;
12
16
  export type ProductDetail = commerceModule.ProductDetail;
13
- export type ProductList = commerceModule.ProductList;
17
+ export type ProductSearchResponse = commerceModule.ProductSearchResponse;
18
+ /** Backwards-compatible alias for `ProductSearchResponse`. */
19
+ export type ProductList = ProductSearchResponse;
14
20
  export type ReturnList = commerceModule.ReturnList;
15
21
  export type ReturnRecord = commerceModule.ReturnRecord;
16
22
  export type Store = commerceModule.Store;
@@ -19,6 +25,262 @@ export type StoreMetrics = commerceModule.StoreMetrics;
19
25
  export type StoreOrder = commerceModule.StoreOrder;
20
26
  export type StoreOrderDetail = commerceModule.StoreOrderDetail;
21
27
  export type StoreOrderList = commerceModule.StoreOrderList;
28
+ export type AppliedRuleSummary = commerceModule.AppliedRuleSummary;
29
+ export type AttributeFacetBucketList = commerceModule.AttributeFacetBucketList;
30
+ export type AttributeFacetMap = commerceModule.AttributeFacetMap;
31
+ export type BrandFacetBucket = commerceModule.BrandFacetBucket;
32
+ export type BrandSummary = commerceModule.BrandSummary;
33
+ export type BuyBoxSummary = commerceModule.BuyBoxSummary;
34
+ export type CategoryFacetBucket = commerceModule.CategoryFacetBucket;
35
+ export type CategorySummary = commerceModule.CategorySummary;
36
+ export type ExperimentAssignment = commerceModule.ExperimentAssignment;
37
+ export type PriceRangeFacet = commerceModule.PriceRangeFacet;
38
+ export type PrimaryMedia = commerceModule.PrimaryMedia;
39
+ export type ProductSearchHit = commerceModule.ProductSearchHit;
40
+ export type ProductSearchRequest = commerceModule.ProductSearchRequest;
41
+ export type RatingFacetBucket = commerceModule.RatingFacetBucket;
42
+ export type RecommendRequest = commerceModule.RecommendRequest;
43
+ export type RecommendResponse = commerceModule.RecommendResponse;
44
+ export type SearchFacets = commerceModule.SearchFacets;
45
+ export type SuggestProductHit = commerceModule.SuggestProductHit;
46
+ export type SuggestResponse = commerceModule.SuggestResponse;
47
+ export type TermFacetBucket = commerceModule.TermFacetBucket;
48
+ export type ProductReview = commerceModule.ProductReview;
49
+ export type ProductReviewListResponse = commerceModule.ProductReviewListResponse;
50
+ export type ProductReviewSummary = commerceModule.ProductReviewSummary;
51
+ export type ReviewDeleteResponse = commerceModule.ReviewDeleteResponse;
52
+ export type ReviewMedia = commerceModule.ReviewMedia;
53
+ export type ReviewModerationResponse = commerceModule.ReviewModerationResponse;
54
+ export type ReviewReplyResponse = commerceModule.ReviewReplyResponse;
55
+ export type ReviewUploadURLResponse = commerceModule.ReviewUploadURLResponse;
56
+ export type ReviewVoteResponse = commerceModule.ReviewVoteResponse;
57
+ export type ReviewsBundle = commerceModule.ReviewsBundle;
58
+ export type StoreReview = commerceModule.StoreReview;
59
+ export type StoreReviewListResponse = commerceModule.StoreReviewListResponse;
60
+ export type StoreReviewSummary = commerceModule.StoreReviewSummary;
61
+ export type ProductKind = 'physical' | 'digital' | 'service' | 'bundle' | (string & {});
62
+ export type OfferCondition = 'new' | 'open_box' | 'refurbished' | 'used' | (string & {});
63
+ export type ProductSort = 'relevance' | 'newest' | 'price_asc' | 'price_desc' | 'rating_desc' | 'bestsellers' | 'trending' | (string & {});
64
+ export type DiscoveryStrategyKey = 'relevance' | 'trending' | 'bestsellers' | 'new_arrivals' | 'top_rated' | 'similar' | 'fbt' | 'frequently_bought_together' | 'cart_complementary' | 'personalized' | 'hybrid' | (string & {});
65
+ export type ProductFacetGroup = 'brands' | 'categories' | 'price_range' | 'in_stock' | 'rating' | 'conditions' | 'attributes' | (string & {});
66
+ export interface ProductListQuery {
67
+ limit?: number;
68
+ cursor?: string;
69
+ q?: string;
70
+ category_id?: string;
71
+ category_ids?: string[];
72
+ brand_id?: string;
73
+ brand_ids?: string[];
74
+ store_id?: string;
75
+ collection_id?: string;
76
+ channel?: string;
77
+ region?: string;
78
+ currency?: string;
79
+ kind?: ProductKind;
80
+ condition?: OfferCondition;
81
+ min_price?: number;
82
+ max_price?: number;
83
+ in_stock?: boolean;
84
+ min_rating?: number;
85
+ attributes?: string | Record<string, unknown>;
86
+ sort?: ProductSort;
87
+ strategy?: DiscoveryStrategyKey;
88
+ facets?: ProductFacetGroup[];
89
+ include_facets?: boolean;
90
+ }
91
+ export interface SellerProductListQuery {
92
+ limit?: number;
93
+ cursor?: string;
94
+ q?: string;
95
+ status?: string;
96
+ approval_status?: string;
97
+ category_id?: string;
98
+ brand_id?: string;
99
+ sort?: ProductSort;
100
+ currency?: string;
101
+ region?: string;
102
+ in_stock?: boolean;
103
+ }
104
+ export interface SuggestQuery {
105
+ q?: string;
106
+ limit?: number;
107
+ max_results?: number;
108
+ channel?: string;
109
+ region?: string;
110
+ currency?: string;
111
+ }
112
+ export interface ProductRecommendationsQuery {
113
+ strategy?: DiscoveryStrategyKey;
114
+ limit?: number;
115
+ max_results?: number;
116
+ channel?: string;
117
+ region?: string;
118
+ currency?: string;
119
+ in_stock?: boolean;
120
+ }
121
+ export interface ContextRecommendationOptions {
122
+ category_id?: string;
123
+ brand_id?: string;
124
+ store_id?: string;
125
+ channel?: string;
126
+ region?: string;
127
+ currency?: string;
128
+ limit?: number;
129
+ exclude_product_ids?: string[];
130
+ in_stock?: boolean;
131
+ params?: Record<string, unknown>;
132
+ }
133
+ export interface ProductRecommendationHelperOptions extends ContextRecommendationOptions {
134
+ max_results?: number;
135
+ }
136
+ export interface CartComplementaryOptions extends ContextRecommendationOptions {
137
+ guestToken?: string;
138
+ product_ids?: string[];
139
+ }
140
+ export type RecommendOptions = Omit<RecommendRequest, 'strategy'> & {
141
+ strategy?: DiscoveryStrategyKey;
142
+ guestToken?: string;
143
+ };
144
+ export type ReviewKind = 'product' | 'store';
145
+ export type ReviewSort = 'newest' | 'highest' | 'lowest' | 'most_helpful';
146
+ export interface ProductReviewListQuery {
147
+ rating?: number;
148
+ store_id?: string;
149
+ with_media?: boolean;
150
+ media_kind?: 'image' | 'video';
151
+ verified_only?: boolean;
152
+ sort?: ReviewSort;
153
+ limit?: number;
154
+ cursor?: string;
155
+ }
156
+ export interface StoreReviewListQuery {
157
+ limit?: number;
158
+ cursor?: string;
159
+ }
160
+ export interface ReviewMediaInput {
161
+ media_kind: 'image' | 'video';
162
+ storage_bucket?: string;
163
+ storage_key?: string;
164
+ url?: string;
165
+ thumbnail_url?: string;
166
+ mime_type?: string;
167
+ size_bytes?: number;
168
+ width?: number;
169
+ height?: number;
170
+ duration_ms?: number;
171
+ }
172
+ export interface CreateProductReviewInput {
173
+ rating: number;
174
+ title?: string;
175
+ body?: string;
176
+ author_name?: string;
177
+ anonymous?: boolean;
178
+ store_id?: string;
179
+ order_line_id?: string;
180
+ media?: ReviewMediaInput[];
181
+ metadata?: Record<string, unknown>;
182
+ }
183
+ export interface CreateStoreReviewInput {
184
+ overall_rating: number;
185
+ shipping_rating?: number;
186
+ packaging_rating?: number;
187
+ communication_rating?: number;
188
+ title?: string;
189
+ body?: string;
190
+ author_name?: string;
191
+ anonymous?: boolean;
192
+ store_order_id?: string;
193
+ media?: ReviewMediaInput[];
194
+ metadata?: Record<string, unknown>;
195
+ }
196
+ export interface VoteReviewInput {
197
+ helpful: boolean;
198
+ review_kind?: ReviewKind;
199
+ }
200
+ export interface MintReviewUploadUrlInput {
201
+ content_type: string;
202
+ size_bytes?: number;
203
+ filename?: string;
204
+ }
205
+ export interface SellerReplyReviewInput {
206
+ reply: string;
207
+ review_kind?: ReviewKind;
208
+ }
209
+ /** Canonical discovery telemetry event names aligned with Palbase analytics. */
210
+ export declare const COMMERCE_DISCOVERY_EVENTS: {
211
+ readonly SEARCH_PERFORMED: 'search.performed';
212
+ readonly PRODUCT_CLICKED: 'product.clicked';
213
+ readonly PRODUCT_VIEWED: 'product.viewed';
214
+ readonly CART_ITEM_ADDED: 'cart.item_added';
215
+ readonly RECOMMENDATION_CLICKED: 'recommendation.clicked';
216
+ };
217
+ export type CommerceDiscoveryEvent = (typeof COMMERCE_DISCOVERY_EVENTS)[keyof typeof COMMERCE_DISCOVERY_EVENTS];
218
+ export interface TrackSearchPerformedInput {
219
+ query?: string;
220
+ strategy?: string;
221
+ sort?: string;
222
+ total?: number;
223
+ result_count?: number;
224
+ category_id?: string;
225
+ brand_id?: string;
226
+ store_id?: string;
227
+ experiment_key?: string;
228
+ experiment_variant?: string;
229
+ [key: string]: unknown;
230
+ }
231
+ export interface TrackProductClickedInput {
232
+ product_id: string;
233
+ query?: string;
234
+ strategy?: string;
235
+ position?: number;
236
+ category_id?: string;
237
+ brand_id?: string;
238
+ store_id?: string;
239
+ [key: string]: unknown;
240
+ }
241
+ export interface TrackProductViewedInput {
242
+ product_id: string;
243
+ handle?: string;
244
+ category_id?: string;
245
+ brand_id?: string;
246
+ store_id?: string;
247
+ price_amount?: number;
248
+ currency?: string;
249
+ [key: string]: unknown;
250
+ }
251
+ export interface TrackCartItemAddedInput {
252
+ product_id: string;
253
+ listing_id?: string;
254
+ variant_id?: string;
255
+ cart_id?: string;
256
+ quantity?: number;
257
+ unit_amount?: number;
258
+ currency?: string;
259
+ category_id?: string;
260
+ brand_id?: string;
261
+ store_id?: string;
262
+ [key: string]: unknown;
263
+ }
264
+ export interface TrackRecommendationClickedInput {
265
+ product_id: string;
266
+ strategy: string;
267
+ position?: number;
268
+ anchor_product_id?: string;
269
+ cart_id?: string;
270
+ category_id?: string;
271
+ brand_id?: string;
272
+ store_id?: string;
273
+ personalized?: boolean;
274
+ [key: string]: unknown;
275
+ }
276
+ /** Consent-respecting storefront discovery telemetry helpers (`pb.commerce.track`). */
277
+ export interface CommerceTracker {
278
+ searchPerformed(input: TrackSearchPerformedInput): void;
279
+ productClicked(input: TrackProductClickedInput): void;
280
+ productViewed(input: TrackProductViewedInput): void;
281
+ cartItemAdded(input: TrackCartItemAddedInput): void;
282
+ recommendationClicked(input: TrackRecommendationClickedInput): void;
283
+ }
22
284
  export interface CartAuthOptions {
23
285
  guestToken?: string;
24
286
  signal?: AbortSignal;
@@ -30,13 +292,13 @@ export interface CartAuthOptions {
30
292
  */
31
293
  export declare class SellerPortal {
32
294
  readonly storeId: string;
33
- readonly api: ReturnType<C['client']>;
295
+ readonly api: CommerceClient;
34
296
  constructor(storeId: string, transport: Transport);
35
- listProducts(query?: {
36
- q?: string;
37
- limit?: number;
38
- cursor?: string;
39
- }, signal?: AbortSignal): Promise<ProductList>;
297
+ /**
298
+ * Lists products belonging to this seller store with enriched Buy Box pricing,
299
+ * stock availability, and offer counts.
300
+ */
301
+ listProducts(query?: SellerProductListQuery, signal?: AbortSignal): Promise<ProductSearchResponse>;
40
302
  createQuickProduct(body: Record<string, unknown>, signal?: AbortSignal): Promise<commerceModule.QuickProductResponse>;
41
303
  listListings(signal?: AbortSignal): Promise<commerceModule.ListingList>;
42
304
  createListing(body: Record<string, unknown>, signal?: AbortSignal): Promise<commerceModule.Listing>;
@@ -57,31 +319,209 @@ export declare class SellerPortal {
57
319
  listReturns(signal?: AbortSignal): Promise<ReturnList>;
58
320
  approveReturn(returnId: string, body?: Record<string, unknown>, signal?: AbortSignal): Promise<ReturnRecord>;
59
321
  completeReturn(returnId: string, body?: Record<string, unknown>, signal?: AbortSignal): Promise<ReturnRecord>;
322
+ /**
323
+ * Lists customer product and store reviews attributed to this seller store.
324
+ *
325
+ * @example
326
+ * const seller = pb.commerce.seller(storeId);
327
+ * const bundle = await seller.listReviews({ limit: 25 });
328
+ */
329
+ listReviews(query?: StoreReviewListQuery, signal?: AbortSignal): Promise<ReviewsBundle>;
330
+ /**
331
+ * Publishes or updates an official seller reply on a review attributed to this store.
332
+ *
333
+ * @example
334
+ * const seller = pb.commerce.seller(storeId);
335
+ * await seller.replyReview('rev_123', {
336
+ * review_kind: 'product',
337
+ * reply: 'Thank you for your feedback! We have shared this with our fulfillment team.',
338
+ * });
339
+ */
340
+ replyReview(reviewId: string, body: SellerReplyReviewInput, signal?: AbortSignal): Promise<ReviewReplyResponse>;
60
341
  listSettlements(signal?: AbortSignal): Promise<commerceModule.SettlementList>;
61
342
  metrics(signal?: AbortSignal): Promise<StoreMetrics>;
62
343
  onboardPayouts(body: Record<string, unknown>, signal?: AbortSignal): Promise<commerceModule.SubMerchantAccount>;
63
344
  onboardingLink(body: Record<string, unknown>, signal?: AbortSignal): Promise<commerceModule.OnboardingLink>;
64
345
  }
65
346
  export declare class Commerce {
66
- readonly api: ReturnType<C['client']>;
347
+ readonly api: CommerceClient;
348
+ /** Consent-respecting storefront discovery event trackers (`search.performed`, `product.clicked`, `product.viewed`, `cart.item_added`, `recommendation.clicked`). */
349
+ readonly track: CommerceTracker;
67
350
  private transport;
68
351
  private userTransport;
69
352
  private session;
353
+ private installation;
354
+ private analytics;
355
+ private consent;
70
356
  private guestTokens;
71
- constructor(transport: Transport, userTransport: (user: string) => Transport, session: SessionManager);
357
+ constructor(transport: Transport, userTransport: (user: string) => Transport, session: SessionManager, installation?: Installation, analytics?: Analytics, consent?: Consent);
72
358
  private cartClient;
73
- /** Storefront product discovery with search, category, brand, store, and collection filters. */
74
- listProducts(query?: {
75
- q?: string;
76
- category_id?: string;
77
- brand_id?: string;
78
- store_id?: string;
79
- collection_id?: string;
80
- channel?: string;
81
- limit?: number;
82
- cursor?: string;
83
- }, signal?: AbortSignal): Promise<ProductList>;
359
+ private discoveryHeaders;
360
+ private discoveryClient;
361
+ /**
362
+ * Captures a canonical storefront discovery telemetry event through `pb.analytics`
363
+ * when `analytics` consent is granted.
364
+ *
365
+ * @example
366
+ * pb.commerce.trackDiscoveryEvent('product.viewed', {
367
+ * product_id: 'prod_123',
368
+ * category_id: 'cat_audio',
369
+ * brand_id: 'brand_sound',
370
+ * price_amount: 14900,
371
+ * currency: 'USD',
372
+ * });
373
+ */
374
+ trackDiscoveryEvent(event: CommerceDiscoveryEvent | (string & {}), properties?: Record<string, unknown>): void;
375
+ /**
376
+ * Lists and searches active storefront products with typo-tolerant lexical matching,
377
+ * multi-facet filtering, sorting, dynamic facets, and materialized Buy Box data.
378
+ *
379
+ * @example
380
+ * const res = await pb.commerce.listProducts({
381
+ * q: 'wireless headphones',
382
+ * in_stock: true,
383
+ * attributes: { color: ['black', 'silver'] },
384
+ * sort: 'price_asc',
385
+ * facets: ['brands', 'categories', 'price_range'],
386
+ * limit: 24,
387
+ * });
388
+ */
389
+ listProducts(query?: ProductListQuery, signal?: AbortSignal): Promise<ProductSearchResponse>;
390
+ /**
391
+ * Executes a structured storefront product search with nested/multi-value attribute
392
+ * filters, sorting, composite cursor pagination, and dynamic single-CTE facets.
393
+ *
394
+ * @example
395
+ * const res = await pb.commerce.searchProducts({
396
+ * q: 'wireless headphones',
397
+ * in_stock: true,
398
+ * attributes: { color: ['black', 'silver'], driver_mm: 40 },
399
+ * sort: 'relevance',
400
+ * facets: ['brands', 'categories', 'price_range', 'rating'],
401
+ * limit: 24,
402
+ * });
403
+ */
404
+ searchProducts(request?: ProductSearchRequest, signal?: AbortSignal): Promise<ProductSearchResponse>;
405
+ /**
406
+ * Returns fast prefix and typo-tolerant autocomplete suggestions across query
407
+ * completions, products (with Buy Box price and media), categories, and brands.
408
+ *
409
+ * @example
410
+ * const ac = await pb.commerce.suggest('headph', { limit: 6, currency: 'USD' });
411
+ */
412
+ suggest(query?: string | SuggestQuery, optsOrSignal?: Omit<SuggestQuery, 'q'> | AbortSignal, signal?: AbortSignal): Promise<SuggestResponse>;
413
+ /**
414
+ * Generates storefront product recommendations using built-in algorithmic strategies
415
+ * (`trending`, `bestsellers`, `new_arrivals`, `top_rated`, `similar`, `fbt`,
416
+ * `cart_complementary`, `personalized`) or custom project discovery strategies.
417
+ *
418
+ * @example
419
+ * const recs = await pb.commerce.recommend({
420
+ * strategy: 'personalized',
421
+ * channel: 'web',
422
+ * limit: 12,
423
+ * });
424
+ */
425
+ recommend(request: RecommendOptions, signal?: AbortSignal): Promise<RecommendResponse>;
426
+ /**
427
+ * Returns product recommendations anchored to a product UUID or handle.
428
+ *
429
+ * @example
430
+ * const recs = await pb.commerce.productRecommendations('wireless-headphones', {
431
+ * strategy: 'similar',
432
+ * limit: 8,
433
+ * in_stock: true,
434
+ * });
435
+ */
436
+ productRecommendations(productIdOrHandle: string, opts?: ProductRecommendationsQuery, signal?: AbortSignal): Promise<RecommendResponse>;
437
+ /**
438
+ * Returns products similar to the given product UUID or handle.
439
+ * Uses the lightweight `GET .../recommendations` route when only basic options
440
+ * are passed, or `POST /commerce/catalog/recommend` when exclusions/filters/params
441
+ * or `limit > 50` are supplied.
442
+ */
443
+ similarProducts(productIdOrHandle: string, opts?: ProductRecommendationHelperOptions, signal?: AbortSignal): Promise<RecommendResponse>;
444
+ /**
445
+ * Returns products frequently bought together with the given product UUID or handle.
446
+ */
447
+ frequentlyBoughtTogether(productIdOrHandle: string, opts?: ProductRecommendationHelperOptions, signal?: AbortSignal): Promise<RecommendResponse>;
448
+ private productStrategyRecommend;
449
+ /** Returns trending products ranked by recent engagement velocity. */
450
+ trendingProducts(opts?: ContextRecommendationOptions, signal?: AbortSignal): Promise<RecommendResponse>;
451
+ /** Returns bestselling products ranked by order and revenue velocity. */
452
+ bestsellers(opts?: ContextRecommendationOptions, signal?: AbortSignal): Promise<RecommendResponse>;
453
+ /** Returns newly published catalog products. */
454
+ newArrivals(opts?: ContextRecommendationOptions, signal?: AbortSignal): Promise<RecommendResponse>;
455
+ /** Returns top-rated products ranked with Bayesian rating shrinkage. */
456
+ topRated(opts?: ContextRecommendationOptions, signal?: AbortSignal): Promise<RecommendResponse>;
457
+ /**
458
+ * Returns personalized recommendations gated by `personalization` consent,
459
+ * automatically attaching device installation proof headers when signed out and
460
+ * falling back deterministically when consent is denied or cold-start.
461
+ *
462
+ * @example
463
+ * const picks = await pb.commerce.personalizedProducts({ limit: 8, in_stock: true });
464
+ */
465
+ personalizedProducts(opts?: ContextRecommendationOptions, signal?: AbortSignal): Promise<RecommendResponse>;
466
+ /**
467
+ * Returns complementary product recommendations for a shopping cart, automatically
468
+ * attaching any stored `X-Commerce-Guest-Token` for guest carts.
469
+ *
470
+ * @example
471
+ * const addons = await pb.commerce.cartComplementary(cart.id!, { limit: 6 });
472
+ */
473
+ cartComplementary(cartId: string, opts?: CartComplementaryOptions, signal?: AbortSignal): Promise<RecommendResponse>;
84
474
  getProduct(idOrHandle: string, signal?: AbortSignal): Promise<ProductDetail>;
475
+ /**
476
+ * Lists published reviews for a product along with star histogram and summary stats.
477
+ *
478
+ * @example
479
+ * const reviews = await pb.commerce.listProductReviews('wireless-headphones', {
480
+ * verified_only: true,
481
+ * sort: 'most_helpful',
482
+ * limit: 20,
483
+ * });
484
+ */
485
+ listProductReviews(productIdOrHandle: string, query?: ProductReviewListQuery, signal?: AbortSignal): Promise<ProductReviewListResponse>;
486
+ /**
487
+ * Lists published multi-dimensional reviews for a marketplace store.
488
+ */
489
+ listStoreReviews(storeIdOrSlug: string, query?: StoreReviewListQuery, signal?: AbortSignal): Promise<StoreReviewListResponse>;
490
+ /**
491
+ * Submits a customer review for a product (requires a signed-in user session).
492
+ *
493
+ * @example
494
+ * const review = await pb.commerce.createProductReview('wireless-headphones', {
495
+ * rating: 5,
496
+ * title: 'Crisp audio and long battery life',
497
+ * body: 'Comfortable for all-day calls and commuting.',
498
+ * });
499
+ */
500
+ createProductReview(productIdOrHandle: string, body: CreateProductReviewInput, signal?: AbortSignal): Promise<ProductReview>;
501
+ /**
502
+ * Submits a customer review for a marketplace store with optional shipping,
503
+ * packaging, and communication ratings (requires a signed-in user session).
504
+ */
505
+ createStoreReview(storeIdOrSlug: string, body: CreateStoreReviewInput, signal?: AbortSignal): Promise<StoreReview>;
506
+ /** Lists product and store reviews authored by the signed-in customer. */
507
+ myReviews(signal?: AbortSignal): Promise<ReviewsBundle>;
508
+ /** Deletes a product or store review owned by the signed-in customer. */
509
+ deleteReview(reviewId: string, kindOrOpts?: ReviewKind | {
510
+ kind?: ReviewKind;
511
+ }, signal?: AbortSignal): Promise<ReviewDeleteResponse>;
512
+ /** Records or updates the signed-in customer's helpfulness vote on a review. */
513
+ voteReview(reviewId: string, body: VoteReviewInput, signal?: AbortSignal): Promise<ReviewVoteResponse>;
514
+ /**
515
+ * Mints a short-lived direct-to-Storage PUT URL for uploading a review photo or video.
516
+ *
517
+ * @example
518
+ * const upload = await pb.commerce.mintReviewUploadUrl({
519
+ * content_type: 'image/jpeg',
520
+ * size_bytes: 245760,
521
+ * filename: 'unboxing.jpg',
522
+ * });
523
+ */
524
+ mintReviewUploadUrl(body: MintReviewUploadUrlInput, signal?: AbortSignal): Promise<ReviewUploadURLResponse>;
85
525
  listCategories(signal?: AbortSignal): Promise<commerceModule.CategoryList>;
86
526
  listBrands(signal?: AbortSignal): Promise<commerceModule.BrandList>;
87
527
  listCollections(signal?: AbortSignal): Promise<commerceModule.CollectionList>;
@@ -11,7 +11,7 @@ export { connectVoice, type StartedVoice, type VoiceConnection, type VoiceOption
11
11
  export { ClientTemplates, type TemplateAttachment, type TemplateRunOptions, type TemplateRunResult, type TemplateRunUsage, type TemplateStreamChunk, type TemplateVoiceOptions, type TemplateVoiceResult, type WebAI, } from './templates.js';
12
12
  export { Iap, redemptionToken, type CheckoutSource, type CustomerInfo, type CustomerInfoListener, type GrantInfo, type MergeGrant, type OfferView, type Offerings, type Redeemed, type RedemptionLink, type RefundDataConsent, } from './iap.js';
13
13
  export { Payments, TERMINAL_INTENT_STATUSES, declineMessage, isTerminalIntentStatus, mountEmbedFrame, parseCallbackMessage, type Address, type Buyer, type CancelSubscriptionResponse, type Capabilities, type CapabilitiesResponse, type ConfirmIntentOptions, type InstallmentConfig, type InstallmentOption, type InstallmentTable, type IntentView, type MasterpassAction, type NextAction, type OtpPromptContext, type PaymentCallbackMessage, type PaymentRealtimeEvent, type PaymentRealtimeListener, type PresentIntentOptions, type PresentableIntent, type ProviderOptions, type SavedMethodView, type SpendToken, type SubmitOtpOptions, type SubscriptionListResponse, type SubscriptionSummary, type TopUpWalletOptions, type WaitForIntentOptions, type WalletBalance, type WalletBalancesListener, } from './payments.js';
14
- export { Commerce, SellerPortal, type Cart, type CartAuthOptions, type CheckoutResponse, type Order, type OrderDetail, type OrderDownloads, type OrderList, type Product, type ProductDetail, type ProductList, type ReturnList, type ReturnRecord, type Store, type StoreList, type StoreMetrics, type StoreOrder, type StoreOrderDetail, type StoreOrderList, } from './commerce.js';
14
+ export { COMMERCE_DISCOVERY_EVENTS, Commerce, SellerPortal, type AppliedRuleSummary, type AttributeFacetBucketList, type AttributeFacetMap, type BrandFacetBucket, type BrandSummary, type BuyBoxSummary, type Cart, type CartAuthOptions, type CartComplementaryOptions, type CategoryFacetBucket, type CategorySummary, type CheckoutResponse, type CommerceDiscoveryEvent, type CommerceTracker, type ContextRecommendationOptions, type CreateProductReviewInput, type CreateStoreReviewInput, type DiscoveryStrategyKey, type ExperimentAssignment, type MintReviewUploadUrlInput, type OfferCondition, type Order, type OrderDetail, type OrderDownloads, type OrderList, type PriceRangeFacet, type PrimaryMedia, type Product, type ProductDetail, type ProductFacetGroup, type ProductKind, type ProductList, type ProductListQuery, type ProductRecommendationHelperOptions, type ProductRecommendationsQuery, type ProductReview, type ProductReviewListQuery, type ProductReviewListResponse, type ProductReviewSummary, type ProductSearchHit, type ProductSearchRequest, type ProductSearchResponse, type ProductSort, type RatingFacetBucket, type RecommendOptions, type RecommendRequest, type RecommendResponse, type ReturnList, type ReturnRecord, type ReviewDeleteResponse, type ReviewKind, type ReviewMedia, type ReviewMediaInput, type ReviewModerationResponse, type ReviewReplyResponse, type ReviewSort, type ReviewUploadURLResponse, type ReviewVoteResponse, type ReviewsBundle, type SearchFacets, type SellerProductListQuery, type SellerReplyReviewInput, type Store, type StoreList, type StoreMetrics, type StoreOrder, type StoreOrderDetail, type StoreOrderList, type StoreReview, type StoreReviewListQuery, type StoreReviewListResponse, type StoreReviewSummary, type SuggestProductHit, type SuggestQuery, type SuggestResponse, type TermFacetBucket, type TrackCartItemAddedInput, type TrackProductClickedInput, type TrackProductViewedInput, type TrackRecommendationClickedInput, type TrackSearchPerformedInput, type VoteReviewInput, } from './commerce.js';
15
15
  export { Campaigns, type CampaignAttribution, type OnSiteEventWrite, type OnSiteImpression, type OnSiteImpressionWrite, type OnSiteMessage, type OnSiteMessageList, } from './campaigns.js';
16
16
  export { Notify, WebPush, type PushPermission, type PushSubscribeOptions } from './notify.js';
17
17
  export { Flags, type FlagSource, type FlagsListener } from './flags.js';
@@ -42,8 +42,22 @@ export declare function memoryStore(): SessionStore;
42
42
  * than losing it.
43
43
  */
44
44
  export declare function localStore(key: string): SessionStore;
45
- /** The user an access token is: its sub claim (read, not verified — the server verifies). */
45
+ /** The user an access token is: its sub claim. */
46
46
  export declare function subjectOf(accessToken: string): string;
47
+ /**
48
+ * How long before its end a session is renewed: `most` — or, for an access
49
+ * token that lives less than twice that, half its life (its own exp − iat).
50
+ *
51
+ * A project may give its access tokens a minute (auth's least; a FAPI
52
+ * project's live five). Such a token has "little left" from the moment it is
53
+ * made: renewed a minute ahead, it was renewed behind every call the app
54
+ * made — and renewed five minutes ahead by a server's middleware, before
55
+ * every request — each renewal spending a refresh token.
56
+ *
57
+ * A token that does not say how long it lives (no JWT, a test's) is renewed
58
+ * `most` ahead.
59
+ */
60
+ export declare function renewWithin(accessToken: string, most: number): number;
47
61
  /** A refusal of the refresh token itself (rotated away, revoked, expired): the session is over. */
48
62
  export type IsRejected = (e: unknown) => boolean;
49
63
  /**
@@ -1,6 +1,6 @@
1
1
  import type { User } from './auth.js';
2
2
  import { type ClientOptions, type PalbaseClient } from './client.js';
3
- import type { SessionStore } from './session.js';
3
+ import { type SessionStore } from './session.js';
4
4
  /** A cookie's attributes, as Next.js's cookies().set and the cookie package name them. */
5
5
  export interface CookieOptions {
6
6
  path?: string;
@@ -1,2 +0,0 @@
1
- /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
- import{b as C}from"./MB7MHOQO.js";import{a as pe}from"./U3H6HER3.js";import{a as L,b as B,c as K,d as U,e as I,f as $,g as N,h as D,i as F,j as q,k as V,l as J,m as z,n as Y,o as G,p as X,q as Z,r as Q,s as ee}from"./UXHNXE3J.js";import{a as w,c as re,d as oe,e as ie,f as se,h as ae,i as ce,j as R,k as le,l as de,o as A}from"./YU3GFTZV.js";import{a as te,b as ne}from"./3KCV4F4F.js";import{b as P,d as v}from"./HRWVZ4PC.js";var m=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},We=6e4,He=1e3;function M(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var b=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(r=>setTimeout(r,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},We),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let i of r.keys){let s=oe(i.key);o.set(i.id,{privateKey:s,publicKey:this.keys.get(i.id)?.publicKey??await ie(s)})}this.keys=o,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(M),...[...this.retired].map(M))}async key(e){let n=this.now();for(;M(e)>this.newest()&&this.heldFrom<n;){let i=this.fetchedAt+He-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new m("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new m("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new m("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ae(e.header).kid}catch{throw new m("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=se(this.projectId,e.method,e.path,e.params??[])}catch{throw new m("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new E(n,await ce(e.header,r.privateKey,r.publicKey,o))}catch(i){throw i instanceof re?new m("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):i}}},E=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,i)=>{if(!le(i))throw new m("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,i)}catch{throw new m("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>R(this.key,r,o))}sealField(e,n){return R(this.key,e,n)}};var je=/^pb_[a-z0-9]+_s/;function O(t){if(pe())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof t.secretKey!="string"||!je.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=ne(v({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??te),n=X.client(e);return{ai:L.client(e),analytics:B.client(e),auth:K.client(e),cache:U.client(e),calls:I.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:D.client(e),iap:F.client(e),machines:V.client(e),messaging:J.client(e),notify:z.client(e),payments:Y.client(e),campaigns:$.client(e),commerce:N.client(e),journeys:q.client(e),realtime:G.client(e),secrets:n,storage:Z.client(e),stores:Q.client(e),workspaces:ee.client(e),transit:new b({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Be=300,Ke=/^[0-9]{1,12}$/,Ue=/^[0-9a-f]{64}$/,ue=8,Ie=/^whsec_[0-9A-Za-z]{32,}$/,$e=1024*1024;async function ye(t){if(typeof t.secret!="string"||!Ie.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(fe(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Je(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=fe(t.body),{t:n,v1:r}=me(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",o,Ve(new TextEncoder().encode(`${n}.`),e))),s=!1;for(let l of r)qe(i,Fe(l))&&(s=!0);if(!s)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function me(t){let e=t.toleranceSeconds??Be;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,i=[];for(let s of r.split(",")){let l=s.indexOf("=");if(l<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=s.slice(0,l).trim(),a=s.slice(l+1).trim();if(c==="t"){if(o!==void 0||!Ke.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ue.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ue)throw new u("malformed_signature",`Palbase-Signature carries at most ${ue} v1`);i.push(a)}}if(o===void 0||i.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:i}}async function Ne(t,e,n={}){let r=await De(t,n.maxBytes??$e);return ye({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function De(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),i=[],s=0;for(;;){let{done:a,value:d}=await o.read();if(a)break;if(s+=d.byteLength,s>e)throw await o.cancel().catch(()=>{}),n();i.push(d)}let l=new Uint8Array(s),c=0;for(let a of i)l.set(a,c),c+=a.byteLength;return l}function fe(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Fe(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function qe(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function Ve(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Je(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var ge=60,ze=60,Ye=8*1024,Ge=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function be(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function we(t){let e=be(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ge){this.max=e}spend(e,n){if(n>=e.until)throw new p("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new p("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,n,r){for(let[o,i]of n){if(i>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[i,s]of o)s>e||(o.delete(i),this.held--);o.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Xe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function ke(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function Se(t,e,n,r){let o=Oe=>{throw new p("proof",`the DPoP proof is not taken: ${Oe}`)},i=n.proof;if(!i)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>Ye)return o("it is too long");let s=i.split(".");if(s.length!==3)return o("it is not a JWS of three parts");let l=we(s[0]),c=we(s[1]);if(!l||!c)return o("its header or claims are not base64url JSON");if(l.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(l.alg!=="ES256")return o(`it is signed with ${String(l.alg)}; only ES256 is taken`);let a=l.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Xe(a.x,a.y)!==e)return o("it is signed by a key the token does not name");let d;try{d=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return o("its key is not a P-256 point")}let y=be(s[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,y,new TextEncoder().encode(`${s[0]}.${s[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let h=typeof c.htu=="string"?ke(c.htu):void 0,f=ke(n.url);if(!h||!f||h!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let S=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-S)>ge)return o("it was not made within a minute of now");let Ce=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Ce)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let Me=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Me,until:(c.iat+ge+ze)*1e3+1}}var p=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},Ze=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Qe(t){return async e=>{let n=v({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof P&&r.status===401&&!Ze.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var H={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ve=60,et=16*1024,tt=10*6e4,nt=5e4,Ee=t=>typeof t=="string"&&Object.hasOwn(H,t),j=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new x;constructor(e){let n=new URL(e.issuer);if(n.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=n.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,n){if(typeof e!="string"||e.length===0||e.length>et)throw new p("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new p("malformed","the token is not a JWS of three parts");let o=xe(r[0]),i=xe(r[1]);if(!o||!i)throw new p("malformed","the token header or claims are not base64url JSON");let s=o.alg;if(!Ee(s))throw new p("algorithm",`the token is signed with ${String(s)}; only ES256 and PS256 are taken`);let l=o.kid;if(typeof l!="string"||l==="")throw new p("malformed","the token header names no kid");let c=await this.key(l);if(!c)throw new p("unknown_key",`no key ${l} in the project's key set`);if(c.alg!==s)throw new p("algorithm",`key ${l} is ${c.alg}, the token says ${s}`);let a=_e(r[2]);if(!a)throw new p("malformed","the signature is not base64url");let d=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(H[c.alg].verify,c.key,a,d).catch(()=>!1))throw new p("signature","the signature does not verify");let g=this.check(i),h=i.cnf,f;if(h!==void 0){if(!n)throw new p("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new p("bound","the token is bound to a key it does not name (cnf.jkt)");f=await Se(e,h.jkt,n,this.now())}else if(n)throw new p("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new p("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:ot(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new p("malformed","the Authorization header is not a Bearer or DPoP token");let i=o[1].toLowerCase()==="dpop",s=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],i?{proof:n.get("dpop"),method:e.method,url:Te(n,s)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let i=this.asking.get(n);i||(i=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,i));let s;try{s=await i}catch(c){let a=this.standings.get(n),d=this.now();if(a&&d<a.at+this.standingStaleMs)return a.until=Math.min(d+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new k("a session's standing cannot be read now",{cause:c})}let l=this.now();return this.standings.delete(n),this.standings.set(n,{live:s,at:l,until:l+this.standingTtlMs}),this.standings.size>nt&&this.standings.delete(this.standings.keys().next().value),s}check(e){if(e.iss!==this.issuer)throw new p("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new p("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new p("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ve<=r)throw new p("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ve>r))throw new p("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new p("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new p("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new p("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+tt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!o)throw i}}let r=this.keys.get(e);return!r&&n-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(i){throw this.lastFailure=i,new k("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let s=i.alg;if(typeof i.kid!="string"||!Ee(s))continue;let l=H[s];if(i.kty!==l.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:s,key:await crypto.subtle.importKey("jwk",a,l.import,!1,["verify"])})}catch{}}this.keys=r;let o=it(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function Te(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return rt.test(o)?`${r}://${o}${e.pathname}`:""}var rt=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function ot(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function it(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function _e(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function xe(t){let e=_e(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function st(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var T=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function at(t,e,n,r){let{idempotencyKey:o,amount:i,ttlSeconds:s,metadata:l}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...s!==void 0?{ttl_seconds:s}:{},...l!==void 0?{metadata:l}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new T(a);let d={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:d}).catch(()=>{}),g}return await t.iap.commitSpend({path:d}),y}var ct=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function lt(t){return t!==void 0&&ct.has(t)}function dt(t,e){return{[Pe]:!0,commitAmount:t,value:e}}var Pe=Symbol("palbase.payments.settleWalletHold");function pt(t){return typeof t=="object"&&t!==null&&Pe in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function ut(t,e,n){let{idempotencyKey:r,walletKey:o,amount:i,ttlSeconds:s,reference:l,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(i)||i<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:i,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...s!==void 0?{ttl_seconds:s}:{},...l!==void 0?{reference:l}:{},...c!==void 0?{metadata:c}:{}},d=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(d.status!=="held")throw new _(d);let y;try{y=await n(d)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:d.id}}).catch(()=>{}),g}return pt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:d.id}}):await t.payments.commitWalletHold({path:{hold_id:d.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:d.id}}),y)}function yt(t){return t.type.startsWith("payments.")}function ht(t){return t.type.startsWith("commerce.")}function mt(t){return t.type.startsWith("promotions.")}var ft=300,gt=/^[0-9]{1,12}$/;function wt(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function kt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function St(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Re(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!gt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??ft,i=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(i-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let s=wt(t.body),l=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(l.length+s.length);c.set(l,0),c.set(s,l.length);let a=kt(t.secret),d=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),h=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let S=St(f.slice(3));if(S&&bt(g,S)){h=!0;break}}if(!h)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function vt(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Re({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(s){let l=s instanceof u?s.code:"signature_mismatch",c=s instanceof Error?s.message:"invalid hook signature";return new Response(JSON.stringify({error:l,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let i=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(i),{status:200,headers:{"content-type":"application/json"}})}}function Et(t){return t.type.startsWith("campaigns.")}function xt(t){return t.type.startsWith("journey.")}async function*Tt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var _t=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Pt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ae(t){return!_t.test(t)||Pt.test(t)||/_PROXY$/i.test(t)}var Rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function At(t){return Rt.test(t)}async function Ct(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:s}=await i.secrets.getEnvironmentValues({path:{environment:n}}),l=[],c=[],a=[];for(let[d,y]of Object.entries(s.values)){if(Ae(d)){a.push(d);continue}if(e[d]!==void 0&&e[d]!==""){c.push(d);continue}e[d]=y,l.push(d)}return{set:n,loaded:l.sort(),kept:c.sort(),refused:a.sort()}}export{m as a,b,E as c,O as d,u as e,ye as f,he as g,me as h,Ne as i,p as j,k,Qe as l,j as m,Te as n,st as o,T as p,at as q,lt as r,dt as s,_ as t,ut as u,yt as v,ht as w,mt as x,Re as y,vt as z,Et as A,xt as B,Tt as C,Ae as D,At as E,Ct as F};