@moonbase.sh/storefront-api 0.0.0-next-20260526085904

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1775 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ActivationMethod: () => ActivationMethod,
24
+ ActivationRequestFulfillmentType: () => ActivationRequestFulfillmentType,
25
+ ActivationRequestStatus: () => ActivationRequestStatus,
26
+ ActivationStatus: () => ActivationStatus,
27
+ Architecture: () => Architecture,
28
+ ConnectableAccountProvider: () => ConnectableAccountProvider,
29
+ ConsoleLogger: () => ConsoleLogger,
30
+ CycleLength: () => CycleLength,
31
+ DiscountUtils: () => DiscountUtils,
32
+ InMemoryStore: () => InMemoryStore,
33
+ LicenseStatus: () => LicenseStatus,
34
+ LocalStorageStore: () => LocalStorageStore,
35
+ LogLevel: () => LogLevel,
36
+ MarketingConsentType: () => MarketingConsentType,
37
+ MoneyCollectionUtils: () => MoneyCollectionUtils,
38
+ MoonbaseApi: () => MoonbaseApi,
39
+ MoonbaseClient: () => MoonbaseClient,
40
+ MoonbaseError: () => MoonbaseError,
41
+ NotAuthenticatedError: () => NotAuthenticatedError,
42
+ NotAuthorizedError: () => NotAuthorizedError,
43
+ NotFoundError: () => NotFoundError,
44
+ OfferUtils: () => OfferUtils,
45
+ OrderStatus: () => OrderStatus,
46
+ Platform: () => Platform,
47
+ SubscriptionStatus: () => SubscriptionStatus,
48
+ TokenStore: () => TokenStore,
49
+ objectToQuery: () => objectToQuery,
50
+ parseOffSiteReferrer: () => parseOffSiteReferrer,
51
+ problemDetailsSchema: () => problemDetailsSchema,
52
+ resolveUtm: () => resolveUtm,
53
+ schemas: () => schemas_exports12,
54
+ utmToObject: () => utmToObject
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/activationRequests/endpoints.ts
59
+ var import_zod5 = require("zod");
60
+
61
+ // src/activationRequests/schemas.ts
62
+ var schemas_exports3 = {};
63
+ __export(schemas_exports3, {
64
+ activationRequestSchema: () => activationRequestSchema
65
+ });
66
+ var import_zod4 = require("zod");
67
+
68
+ // src/storefront/schemas.ts
69
+ var schemas_exports2 = {};
70
+ __export(schemas_exports2, {
71
+ offerConditionSchema: () => offerConditionSchema,
72
+ storefrontBundleSchema: () => storefrontBundleSchema,
73
+ storefrontOfferSchema: () => storefrontOfferSchema,
74
+ storefrontProductSchema: () => storefrontProductSchema,
75
+ storefrontSchema: () => storefrontSchema,
76
+ taxEstimateSchema: () => taxEstimateSchema
77
+ });
78
+ var import_zod3 = require("zod");
79
+
80
+ // src/globalSchemas.ts
81
+ var import_zod = require("zod");
82
+
83
+ // src/globalModels.ts
84
+ var CycleLength = /* @__PURE__ */ ((CycleLength2) => {
85
+ CycleLength2["Daily"] = "Daily";
86
+ CycleLength2["Weekly"] = "Weekly";
87
+ CycleLength2["Monthly"] = "Monthly";
88
+ CycleLength2["Quarterly"] = "Quarterly";
89
+ CycleLength2["Yearly"] = "Yearly";
90
+ return CycleLength2;
91
+ })(CycleLength || {});
92
+ var MarketingConsentType = /* @__PURE__ */ ((MarketingConsentType2) => {
93
+ MarketingConsentType2["OptIn"] = "OptIn";
94
+ MarketingConsentType2["OptedInByDefault"] = "OptedInByDefault";
95
+ MarketingConsentType2["OptOut"] = "OptOut";
96
+ return MarketingConsentType2;
97
+ })(MarketingConsentType || {});
98
+ function utmToObject(utm) {
99
+ return Object.entries({
100
+ utm_source: utm == null ? void 0 : utm.source,
101
+ utm_medium: utm == null ? void 0 : utm.medium,
102
+ utm_campaign: utm == null ? void 0 : utm.campaign,
103
+ utm_term: utm == null ? void 0 : utm.term,
104
+ utm_content: utm == null ? void 0 : utm.content,
105
+ utm_referrer: utm == null ? void 0 : utm.referrer
106
+ }).filter(([_, value]) => value !== void 0).reduce((obj, [key, value]) => ({
107
+ ...obj,
108
+ [key]: value
109
+ }), {});
110
+ }
111
+
112
+ // src/globalSchemas.ts
113
+ var priceCollectionSchema = import_zod.z.record(import_zod.z.number());
114
+ var percentageOffDiscountSchema = import_zod.z.object({
115
+ type: import_zod.z.literal("PercentageOffDiscount"),
116
+ name: import_zod.z.string(),
117
+ description: import_zod.z.string().optional(),
118
+ percentage: import_zod.z.number(),
119
+ total: priceCollectionSchema.optional(),
120
+ isExclusive: import_zod.z.boolean(),
121
+ recurringPaymentUseCount: import_zod.z.number().optional()
122
+ });
123
+ var flatAmountOffDiscountSchema = import_zod.z.object({
124
+ type: import_zod.z.literal("FlatAmountOffDiscount"),
125
+ name: import_zod.z.string(),
126
+ description: import_zod.z.string().optional(),
127
+ total: priceCollectionSchema.optional(),
128
+ isExclusive: import_zod.z.boolean(),
129
+ recurringPaymentUseCount: import_zod.z.number().optional()
130
+ });
131
+ var moneySchema = import_zod.z.object({
132
+ currency: import_zod.z.string(),
133
+ amount: import_zod.z.number()
134
+ });
135
+ var discountSchema = import_zod.z.discriminatedUnion("type", [
136
+ percentageOffDiscountSchema,
137
+ flatAmountOffDiscountSchema
138
+ ]);
139
+ var recurrenceSchema = import_zod.z.discriminatedUnion("type", [
140
+ import_zod.z.object({ type: import_zod.z.literal("OneOff") }),
141
+ import_zod.z.object({ type: import_zod.z.literal("Recurring"), cycleLength: import_zod.z.nativeEnum(CycleLength) })
142
+ ]);
143
+ var pricingTierSchema = import_zod.z.object({
144
+ minQuantity: import_zod.z.number(),
145
+ originalPrice: priceCollectionSchema,
146
+ price: priceCollectionSchema
147
+ });
148
+ var pricingVariationSchema = import_zod.z.object({
149
+ id: import_zod.z.string(),
150
+ name: import_zod.z.string(),
151
+ originalPrice: priceCollectionSchema,
152
+ price: priceCollectionSchema,
153
+ hasDiscount: import_zod.z.boolean(),
154
+ discount: discountSchema.optional(),
155
+ recurrence: recurrenceSchema,
156
+ pricingTiers: import_zod.z.array(pricingTierSchema).nullish()
157
+ });
158
+ var rawPropertyValueSchema = import_zod.z.lazy(
159
+ () => import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean(), import_zod.z.record(rawPropertyValueSchema)])
160
+ );
161
+ function paged(itemSchema) {
162
+ return import_zod.z.object({
163
+ items: import_zod.z.array(itemSchema),
164
+ hasMore: import_zod.z.boolean(),
165
+ next: import_zod.z.string().nullable()
166
+ });
167
+ }
168
+ function quantifiable(itemSchema) {
169
+ return import_zod.z.object({
170
+ value: itemSchema,
171
+ quantity: import_zod.z.number()
172
+ });
173
+ }
174
+ function singleOrMultiple(schema) {
175
+ return import_zod.z.union([schema, import_zod.z.array(schema)]);
176
+ }
177
+
178
+ // src/inventory/products/schemas.ts
179
+ var schemas_exports = {};
180
+ __export(schemas_exports, {
181
+ downloadSchema: () => downloadSchema,
182
+ manifestSchema: () => manifestSchema,
183
+ productSummarySchema: () => productSummarySchema
184
+ });
185
+ var import_zod2 = require("zod");
186
+
187
+ // src/inventory/products/models.ts
188
+ var Platform = /* @__PURE__ */ ((Platform2) => {
189
+ Platform2["Universal"] = "Universal";
190
+ Platform2["Windows"] = "Windows";
191
+ Platform2["Linux"] = "Linux";
192
+ Platform2["Mac"] = "Mac";
193
+ Platform2["iOS"] = "iOS";
194
+ Platform2["Android"] = "Android";
195
+ return Platform2;
196
+ })(Platform || {});
197
+ var Architecture = /* @__PURE__ */ ((Architecture2) => {
198
+ Architecture2["Unknown"] = "Unknown";
199
+ Architecture2["Universal"] = "Universal";
200
+ Architecture2["X86"] = "X86";
201
+ Architecture2["X64"] = "X64";
202
+ Architecture2["Arm"] = "Arm";
203
+ Architecture2["Arm64"] = "Arm64";
204
+ return Architecture2;
205
+ })(Architecture || {});
206
+
207
+ // src/inventory/products/schemas.ts
208
+ var manifestSchema = import_zod2.z.object({
209
+ files: import_zod2.z.object({
210
+ name: import_zod2.z.string(),
211
+ path: import_zod2.z.string()
212
+ }).array(),
213
+ licensePath: import_zod2.z.string().nullable()
214
+ });
215
+ var downloadSchema = import_zod2.z.object({
216
+ name: import_zod2.z.string(),
217
+ key: import_zod2.z.string(),
218
+ platform: import_zod2.z.nativeEnum(Platform),
219
+ arch: import_zod2.z.nativeEnum(Architecture).nullish(),
220
+ size: import_zod2.z.number(),
221
+ path: import_zod2.z.string().nullable(),
222
+ manifest: manifestSchema.optional()
223
+ });
224
+ var productSummarySchema = import_zod2.z.object({
225
+ id: import_zod2.z.string(),
226
+ name: import_zod2.z.string(),
227
+ tagline: import_zod2.z.string(),
228
+ description: import_zod2.z.string().nullish(),
229
+ website: import_zod2.z.string().optional(),
230
+ iconUrl: import_zod2.z.string().optional(),
231
+ numberOfLicenses: import_zod2.z.number().optional(),
232
+ numberOfTrials: import_zod2.z.number().optional(),
233
+ currentActivations: import_zod2.z.number().optional(),
234
+ maxActivations: import_zod2.z.number().optional(),
235
+ externalLicenses: import_zod2.z.number().optional(),
236
+ subscriptionLicenses: import_zod2.z.number().optional(),
237
+ currentVersion: import_zod2.z.string().nullable(),
238
+ version: import_zod2.z.string().optional(),
239
+ prerelease: import_zod2.z.boolean().optional(),
240
+ releaseDescription: import_zod2.z.string().optional(),
241
+ downloadsNeedsUser: import_zod2.z.boolean(),
242
+ downloadsNeedsOwnership: import_zod2.z.boolean(),
243
+ downloads: import_zod2.z.array(downloadSchema).optional()
244
+ });
245
+
246
+ // src/storefront/schemas.ts
247
+ var storefrontProductSchema = import_zod3.z.object({
248
+ id: import_zod3.z.string(),
249
+ name: import_zod3.z.string(),
250
+ tagline: import_zod3.z.string(),
251
+ description: import_zod3.z.string(),
252
+ iconUrl: import_zod3.z.string().nullable(),
253
+ website: import_zod3.z.string().nullish(),
254
+ owned: import_zod3.z.boolean(),
255
+ currentVersion: import_zod3.z.string().optional(),
256
+ downloads: downloadSchema.array().optional(),
257
+ defaultVariation: pricingVariationSchema.optional(),
258
+ variations: pricingVariationSchema.array().optional(),
259
+ properties: import_zod3.z.record(rawPropertyValueSchema).nullish(),
260
+ type: import_zod3.z.string().optional().default("Product").pipe(import_zod3.z.literal("Product"))
261
+ });
262
+ var storefrontBundleSchema = import_zod3.z.object({
263
+ id: import_zod3.z.string(),
264
+ name: import_zod3.z.string(),
265
+ tagline: import_zod3.z.string(),
266
+ description: import_zod3.z.string(),
267
+ iconUrl: import_zod3.z.string().nullable(),
268
+ owned: import_zod3.z.boolean(),
269
+ partial: import_zod3.z.boolean(),
270
+ products: storefrontProductSchema.and(import_zod3.z.object({
271
+ included: import_zod3.z.boolean().optional()
272
+ })).array(),
273
+ defaultVariation: pricingVariationSchema.optional(),
274
+ variations: pricingVariationSchema.array().optional(),
275
+ properties: import_zod3.z.record(rawPropertyValueSchema).nullish(),
276
+ type: import_zod3.z.string().optional().default("Bundle").pipe(import_zod3.z.literal("Bundle"))
277
+ });
278
+ var cartContainsItemsConditionSchema = import_zod3.z.object({
279
+ type: import_zod3.z.literal("CartContainsItems"),
280
+ minimumItems: import_zod3.z.number(),
281
+ relevantItemVariations: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string().array())
282
+ });
283
+ var offerConditionSchema = import_zod3.z.discriminatedUnion("type", [cartContainsItemsConditionSchema]);
284
+ var storefrontOfferSchema = import_zod3.z.object({
285
+ id: import_zod3.z.string(),
286
+ target: singleOrMultiple(import_zod3.z.union([storefrontProductSchema, storefrontBundleSchema])),
287
+ targetVariations: import_zod3.z.string().array(),
288
+ condition: offerConditionSchema,
289
+ discount: discountSchema
290
+ });
291
+ var taxEstimateSchema = import_zod3.z.object({
292
+ rate: import_zod3.z.number(),
293
+ mode: import_zod3.z.enum(["Exclusive", "Inclusive"]),
294
+ countryCode: import_zod3.z.string(),
295
+ region: import_zod3.z.string().optional()
296
+ });
297
+ var storefrontSchema = import_zod3.z.object({
298
+ suggestedCurrency: import_zod3.z.string(),
299
+ // Enabled currencies need to be optional since we may still have old, cached representations in browsers
300
+ enabledCurrencies: import_zod3.z.string().array().optional(),
301
+ products: storefrontProductSchema.array(),
302
+ bundles: storefrontBundleSchema.array(),
303
+ // Offers need to be optional since we may still have old, cached representations in browsers
304
+ offers: storefrontOfferSchema.array().optional(),
305
+ // Depending on circumstances, we may have a tax estimate available
306
+ estimatedTax: taxEstimateSchema.optional()
307
+ });
308
+
309
+ // src/activationRequests/models.ts
310
+ var ActivationRequestFulfillmentType = /* @__PURE__ */ ((ActivationRequestFulfillmentType2) => {
311
+ ActivationRequestFulfillmentType2["License"] = "License";
312
+ ActivationRequestFulfillmentType2["Trial"] = "Trial";
313
+ return ActivationRequestFulfillmentType2;
314
+ })(ActivationRequestFulfillmentType || {});
315
+ var ActivationRequestStatus = /* @__PURE__ */ ((ActivationRequestStatus2) => {
316
+ ActivationRequestStatus2["Requested"] = "Requested";
317
+ ActivationRequestStatus2["Fulfilled"] = "Fulfilled";
318
+ ActivationRequestStatus2["Completed"] = "Completed";
319
+ ActivationRequestStatus2["Cancelled"] = "Cancelled";
320
+ return ActivationRequestStatus2;
321
+ })(ActivationRequestStatus || {});
322
+
323
+ // src/activationRequests/schemas.ts
324
+ var activationRequestSchema = import_zod4.z.object({
325
+ id: import_zod4.z.string(),
326
+ status: import_zod4.z.nativeEnum(ActivationRequestStatus),
327
+ product: storefrontProductSchema,
328
+ fulfillmentType: import_zod4.z.nativeEnum(ActivationRequestFulfillmentType).optional(),
329
+ trialEligibility: import_zod4.z.object({
330
+ eligible: import_zod4.z.boolean(),
331
+ existing: import_zod4.z.boolean(),
332
+ requiresAccount: import_zod4.z.boolean(),
333
+ requiresNewsletterOptIn: import_zod4.z.boolean(),
334
+ numberOfDaysPerProduct: import_zod4.z.number(),
335
+ numberOfDaysRemaining: import_zod4.z.number()
336
+ }).optional(),
337
+ licenseEligibility: import_zod4.z.object({
338
+ eligible: import_zod4.z.boolean()
339
+ }).optional()
340
+ });
341
+
342
+ // src/activationRequests/endpoints.ts
343
+ var ActivationRequestEndpoints = class {
344
+ constructor(api) {
345
+ this.api = api;
346
+ }
347
+ async get(requestId) {
348
+ const response = await this.api.fetch(`/api/customer/activations/${requestId}`, activationRequestSchema);
349
+ return response.data;
350
+ }
351
+ async isCompleted(requestId) {
352
+ const response = await this.api.fetch(`/api/customer/activations/${requestId}/completed`, import_zod5.z.boolean());
353
+ return import_zod5.z.boolean().parse(response.data);
354
+ }
355
+ async fulfillLicense(requestId) {
356
+ const response = await this.api.authenticatedFetch(`/api/customer/activations/${requestId}/license`, activationRequestSchema, { method: "POST" });
357
+ return response.data;
358
+ }
359
+ async fulfillTrial(requestId) {
360
+ const response = await this.api.fetch(`/api/customer/activations/${requestId}/trial`, activationRequestSchema, { method: "POST" });
361
+ return response.data;
362
+ }
363
+ async cancel(requestId) {
364
+ const response = await this.api.fetch(`/api/customer/activations/${requestId}/cancel`, activationRequestSchema, { method: "POST" });
365
+ return response.data;
366
+ }
367
+ };
368
+
369
+ // src/communications/schemas.ts
370
+ var schemas_exports4 = {};
371
+ __export(schemas_exports4, {
372
+ communicationPreferencesViewSchema: () => communicationPreferencesViewSchema,
373
+ subscribeResponseSchema: () => subscribeResponseSchema
374
+ });
375
+ var import_zod6 = require("zod");
376
+ var subscribeResponseSchema = import_zod6.z.object({
377
+ status: import_zod6.z.enum(["subscribed", "confirmation_sent"])
378
+ });
379
+ var communicationPreferencesViewSchema = import_zod6.z.object({
380
+ email: import_zod6.z.string(),
381
+ name: import_zod6.z.string().nullish(),
382
+ newsletter: import_zod6.z.boolean(),
383
+ productUpdates: import_zod6.z.boolean()
384
+ });
385
+
386
+ // src/communications/endpoints.ts
387
+ function encodeToken(token) {
388
+ return encodeURIComponent(token.replaceAll(" ", "+"));
389
+ }
390
+ var CommunicationsEndpoints = class {
391
+ constructor(api) {
392
+ this.api = api;
393
+ }
394
+ async subscribe(input) {
395
+ var _a, _b, _c;
396
+ const response = await this.api.fetch("/api/customer/communications/subscribe", subscribeResponseSchema, {
397
+ method: "POST",
398
+ body: {
399
+ email: input.email,
400
+ name: ((_a = input.name) == null ? void 0 : _a.trim()) || null,
401
+ newsletter: (_b = input.newsletter) != null ? _b : true,
402
+ productUpdates: (_c = input.productUpdates) != null ? _c : true
403
+ }
404
+ });
405
+ return response.data;
406
+ }
407
+ async confirm(email, token) {
408
+ await this.api.fetch(
409
+ `/api/customer/communications/confirm?email=${encodeURIComponent(email)}&token=${encodeToken(token)}`,
410
+ null,
411
+ { method: "POST" }
412
+ );
413
+ }
414
+ async getPreferences(email, token) {
415
+ const response = await this.api.fetch(
416
+ `/api/customer/communications/preferences?email=${encodeURIComponent(email)}&token=${encodeToken(token)}`,
417
+ communicationPreferencesViewSchema
418
+ );
419
+ return response.data;
420
+ }
421
+ async updatePreferences(email, token, preferences) {
422
+ const response = await this.api.fetch(
423
+ `/api/customer/communications/preferences?email=${encodeURIComponent(email)}&token=${encodeToken(token)}`,
424
+ communicationPreferencesViewSchema,
425
+ {
426
+ method: "POST",
427
+ body: {
428
+ newsletter: preferences.newsletter,
429
+ productUpdates: preferences.productUpdates
430
+ }
431
+ }
432
+ );
433
+ return response.data;
434
+ }
435
+ async unsubscribe(email, token) {
436
+ await this.api.fetch(
437
+ `/api/customer/communications/unsubscribe?email=${encodeURIComponent(email)}&token=${encodeToken(token)}`,
438
+ null,
439
+ { method: "POST" }
440
+ );
441
+ }
442
+ };
443
+
444
+ // src/utils/errors.ts
445
+ var NotAuthorizedError = class extends Error {
446
+ constructor() {
447
+ super();
448
+ this.name = "NotAuthorizedError";
449
+ this.message = "Not allowed";
450
+ }
451
+ };
452
+ var NotAuthenticatedError = class extends Error {
453
+ constructor() {
454
+ super();
455
+ this.name = "NotAuthenticatedError";
456
+ this.message = "Not authenticated";
457
+ }
458
+ };
459
+ var NotFoundError = class extends Error {
460
+ constructor(message) {
461
+ super();
462
+ this.name = "NotFoundError";
463
+ this.message = message != null ? message : "Not found";
464
+ }
465
+ };
466
+ var MoonbaseError = class extends Error {
467
+ constructor(title, detail, status, errors) {
468
+ super();
469
+ this.title = title;
470
+ this.detail = detail;
471
+ this.status = status;
472
+ this.errors = errors;
473
+ this.name = "MoonbaseError";
474
+ if (errors && Object.values(errors).length === 1) {
475
+ this.message = Object.values(errors)[0];
476
+ } else {
477
+ this.message = detail != null ? detail : title;
478
+ }
479
+ }
480
+ };
481
+
482
+ // src/utils/problemDetails.ts
483
+ var import_zod7 = require("zod");
484
+ var problemDetailsSchema = import_zod7.z.object({
485
+ type: import_zod7.z.string().optional(),
486
+ title: import_zod7.z.string(),
487
+ detail: import_zod7.z.string().optional(),
488
+ status: import_zod7.z.number().optional(),
489
+ instance: import_zod7.z.string().optional(),
490
+ errors: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string().array()).optional()
491
+ });
492
+
493
+ // src/utils/problemHandler.ts
494
+ function camelCase(str) {
495
+ return str.split(".").map((word, index) => {
496
+ let [firstLetter, ...restOfLetters] = word;
497
+ firstLetter = index !== 0 ? firstLetter.toUpperCase() : firstLetter.toLowerCase();
498
+ restOfLetters = [restOfLetters.join("").toLowerCase()];
499
+ return firstLetter + restOfLetters[0];
500
+ }).join("");
501
+ }
502
+ async function handleResponseProblem(response, logger) {
503
+ if (response.status === 404)
504
+ throw new NotFoundError();
505
+ if (response.status === 401) {
506
+ throw new NotAuthenticatedError();
507
+ }
508
+ if (response.status === 403) {
509
+ throw new NotAuthorizedError();
510
+ }
511
+ let problemDetails;
512
+ try {
513
+ const json = await response.json();
514
+ problemDetails = problemDetailsSchema.parse(json);
515
+ } catch (err) {
516
+ logger.warn("Could not handle response", { response, err, content: await response.text() });
517
+ throw new Error("An unknown problem occurred");
518
+ }
519
+ logger.debug("The response indicates a problem", problemDetails);
520
+ throw new MoonbaseError(
521
+ problemDetails.title,
522
+ problemDetails.detail,
523
+ problemDetails.status,
524
+ problemDetails.errors ? Object.fromEntries(Object.entries(problemDetails.errors).map(([field, errors]) => [camelCase(field), errors.join(", ")])) : void 0
525
+ );
526
+ }
527
+
528
+ // src/identity/schemas.ts
529
+ var schemas_exports5 = {};
530
+ __export(schemas_exports5, {
531
+ addressSchema: () => addressSchema,
532
+ communicationPreferencesSchema: () => communicationPreferencesSchema,
533
+ connectedAccountSchema: () => connectedAccountSchema,
534
+ connectionUrlSchema: () => connectionUrlSchema,
535
+ identitySchema: () => identitySchema,
536
+ ilokConnectedAccountSchema: () => ilokConnectedAccountSchema,
537
+ pendingActivationSchema: () => pendingActivationSchema,
538
+ userAccountConfirmedSchema: () => userAccountConfirmedSchema,
539
+ userAccountConfirmedStatusSchema: () => userAccountConfirmedStatusSchema,
540
+ userSchema: () => userSchema
541
+ });
542
+ var import_zod8 = require("zod");
543
+
544
+ // src/identity/models.ts
545
+ var ConnectableAccountProvider = /* @__PURE__ */ ((ConnectableAccountProvider2) => {
546
+ ConnectableAccountProvider2["iLok"] = "iLok";
547
+ return ConnectableAccountProvider2;
548
+ })(ConnectableAccountProvider || {});
549
+
550
+ // src/identity/schemas.ts
551
+ var addressSchema = import_zod8.z.object({
552
+ countryCode: import_zod8.z.string(),
553
+ streetAddress1: import_zod8.z.string(),
554
+ streetAddress2: import_zod8.z.string().nullable(),
555
+ locality: import_zod8.z.string().nullable(),
556
+ region: import_zod8.z.string().nullable(),
557
+ postCode: import_zod8.z.string().nullable()
558
+ });
559
+ var communicationPreferencesSchema = import_zod8.z.object({
560
+ newsletterOptIn: import_zod8.z.boolean(),
561
+ // Default keeps older persisted identities (pre productUpdatesOptIn) parseable
562
+ // during boot. The server-side value is hydrated by updateUser() right after.
563
+ productUpdatesOptIn: import_zod8.z.boolean().default(false)
564
+ });
565
+ var ilokConnectedAccountSchema = import_zod8.z.object({
566
+ provider: import_zod8.z.literal("iLok" /* iLok */),
567
+ isConnected: import_zod8.z.boolean(),
568
+ pendingLicenseFulfillments: import_zod8.z.boolean(),
569
+ accountId: import_zod8.z.string().nullish()
570
+ });
571
+ var connectedAccountSchema = import_zod8.z.discriminatedUnion("provider", [
572
+ ilokConnectedAccountSchema
573
+ ]);
574
+ var connectionUrlSchema = import_zod8.z.object({
575
+ url: import_zod8.z.string()
576
+ });
577
+ var userSchema = import_zod8.z.object({
578
+ id: import_zod8.z.string(),
579
+ email: import_zod8.z.string(),
580
+ name: import_zod8.z.string(),
581
+ tenantId: import_zod8.z.string(),
582
+ address: addressSchema.optional(),
583
+ phone: import_zod8.z.string().optional(),
584
+ communicationPreferences: communicationPreferencesSchema,
585
+ ownedProducts: import_zod8.z.string().array().optional(),
586
+ subscribedProducts: import_zod8.z.string().array().optional(),
587
+ confirmedAccount: import_zod8.z.boolean().optional(),
588
+ hasProducts: import_zod8.z.boolean().nullish(),
589
+ hasSubscriptions: import_zod8.z.boolean().nullish(),
590
+ connectedAccounts: import_zod8.z.array(connectedAccountSchema).default([])
591
+ });
592
+ var identitySchema = userSchema.and(import_zod8.z.object({
593
+ accessToken: import_zod8.z.string(),
594
+ refreshToken: import_zod8.z.string()
595
+ }));
596
+ var userAccountConfirmedStatusSchema = import_zod8.z.enum([
597
+ "PasswordSetupRequired",
598
+ "SignedIn"
599
+ ]);
600
+ var userAccountConfirmedSchema = userSchema.and(import_zod8.z.object({
601
+ status: userAccountConfirmedStatusSchema,
602
+ resetPasswordToken: import_zod8.z.string().nullish(),
603
+ accessToken: import_zod8.z.string().nullish(),
604
+ refreshToken: import_zod8.z.string().nullish()
605
+ }));
606
+ var pendingActivationSchema = import_zod8.z.object({
607
+ status: import_zod8.z.literal("activation_pending"),
608
+ email: import_zod8.z.string()
609
+ });
610
+
611
+ // src/identity/endpoints.ts
612
+ var IdentityEndpoints = class {
613
+ constructor(api, tokenStore, logger) {
614
+ this.api = api;
615
+ this.tokenStore = tokenStore;
616
+ this.logger = logger;
617
+ }
618
+ async get() {
619
+ const response = await this.api.authenticatedFetch("/api/customer/meta/user", userSchema);
620
+ return response.data;
621
+ }
622
+ async signIn(email, password) {
623
+ const response = await fetch(`${this.api.baseUrl}/api/customer/identity/sign-in?email=${encodeURIComponent(email)}&scheme=JWT`, {
624
+ method: "POST",
625
+ headers: {
626
+ "Accept": "application/json",
627
+ "Content-Type": "text/plain",
628
+ "x-mb-cors": "1"
629
+ },
630
+ body: password
631
+ });
632
+ if (response.status === 404)
633
+ throw new NotFoundError("User not found");
634
+ if (response.status >= 400)
635
+ await handleResponseProblem(response, this.logger);
636
+ try {
637
+ const data = await response.json();
638
+ const user = identitySchema.parse(data);
639
+ this.tokenStore.setUser(user);
640
+ return userSchema.parse(user);
641
+ } catch (err) {
642
+ this.logger.warn("Could not sign in user", { email, response, err });
643
+ throw new MoonbaseError("Bad response", "Could not sign in user", response.status);
644
+ }
645
+ }
646
+ async signUp(name, email, password, address, acceptedPrivacyPolicy, acceptedTermsAndConditions, communicationOptIn) {
647
+ const path = `/api/customer/identity/sign-up?scheme=JWT&communicationOptIn=${communicationOptIn ? "true" : "false"}`;
648
+ const response = await fetch(`${this.api.baseUrl}${path}`, {
649
+ method: "POST",
650
+ headers: {
651
+ "Accept": "application/json",
652
+ "Content-Type": "application/json",
653
+ "x-mb-cors": "1"
654
+ },
655
+ body: JSON.stringify({
656
+ name,
657
+ email,
658
+ password,
659
+ address,
660
+ acceptedPrivacyPolicy,
661
+ acceptedTermsAndConditions
662
+ })
663
+ });
664
+ if (response.status >= 400)
665
+ await handleResponseProblem(response, this.logger);
666
+ const data = await response.json();
667
+ if (response.status === 202) {
668
+ const parsed = pendingActivationSchema.parse(data);
669
+ return { status: "activation-pending", email: parsed.email };
670
+ }
671
+ try {
672
+ const identity = identitySchema.parse(data);
673
+ this.tokenStore.setUser(identity);
674
+ return { status: "signed-in", user: userSchema.parse(identity) };
675
+ } catch (err) {
676
+ this.logger.warn("Could not sign up user", { email, response, err });
677
+ throw new MoonbaseError("Bad response", "Could not sign up user", response.status);
678
+ }
679
+ }
680
+ async signOut() {
681
+ this.tokenStore.clear();
682
+ }
683
+ async update(name, email, emailConfirmationToken, communicationPreferences) {
684
+ const response = await this.api.authenticatedFetch("/api/customer/identity", userSchema, {
685
+ method: "PATCH",
686
+ body: {
687
+ name,
688
+ email,
689
+ emailConfirmationToken,
690
+ communicationPreferences
691
+ }
692
+ });
693
+ this.tokenStore.setUser(response.data);
694
+ return {
695
+ needsEmailConfirmationToken: response.status === 201,
696
+ user: response.data
697
+ };
698
+ }
699
+ async setPassword(currentPassword, newPassword) {
700
+ await this.api.authenticatedFetch(`/api/customer/identity/set-password`, null, {
701
+ method: "POST",
702
+ body: {
703
+ currentPassword,
704
+ newPassword
705
+ }
706
+ });
707
+ }
708
+ async forgotPassword(email) {
709
+ await this.api.fetch(`/api/customer/identity/forgot-password?email=${encodeURIComponent(email)}`, null, { method: "POST" });
710
+ }
711
+ async resetPassword(email, newPassword, code) {
712
+ const response = await fetch(`${this.api.baseUrl}/api/customer/identity/reset-password?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code.replaceAll(" ", "+"))}`, {
713
+ method: "POST",
714
+ headers: {
715
+ "Accept": "application/json",
716
+ "Content-Type": "text/plain",
717
+ "x-mb-cors": "1"
718
+ },
719
+ body: newPassword
720
+ });
721
+ if (response.status >= 400)
722
+ await handleResponseProblem(response, this.logger);
723
+ }
724
+ async confirmAccount(email, code) {
725
+ const response = await this.api.fetch(`/api/customer/identity/confirm-account?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code.replaceAll(" ", "+"))}&scheme=JWT`, userAccountConfirmedSchema, { method: "POST" });
726
+ const result = response.data;
727
+ if (result.status === "SignedIn") {
728
+ if (!result.accessToken || !result.refreshToken) {
729
+ this.logger.warn("Confirm-account returned SignedIn without tokens", { email });
730
+ throw new MoonbaseError(
731
+ "Bad response",
732
+ "Confirm-account succeeded but the server did not return auth tokens",
733
+ response.status
734
+ );
735
+ }
736
+ this.tokenStore.setUser({
737
+ ...result,
738
+ accessToken: result.accessToken,
739
+ refreshToken: result.refreshToken
740
+ });
741
+ }
742
+ return result;
743
+ }
744
+ async confirmEmail(email, code) {
745
+ await this.api.fetch(`/api/customer/identity/confirm-email?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code.replaceAll(" ", "+"))}`, null, { method: "POST" });
746
+ }
747
+ async confirmEmailChange(email, code) {
748
+ await this.api.authenticatedFetch(`/api/customer/identity/confirm-email-change?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code.replaceAll(" ", "+"))}`, null, { method: "POST" });
749
+ }
750
+ async getConnectionUrl(provider, redirectUri, loginId) {
751
+ const params = new URLSearchParams({ redirectUri });
752
+ if (loginId)
753
+ params.set("loginId", loginId);
754
+ const response = await this.api.authenticatedFetch(
755
+ `/api/customer/connect/${provider}/authorize?${params.toString()}`,
756
+ connectionUrlSchema
757
+ );
758
+ return response.data.url;
759
+ }
760
+ async disconnectAccount(provider) {
761
+ await this.api.authenticatedFetch(`/api/customer/connect/${provider}`, null, { method: "DELETE" });
762
+ }
763
+ };
764
+
765
+ // src/inventory/activation/endpoints.ts
766
+ var import_zod10 = require("zod");
767
+
768
+ // src/inventory/licenses/schemas.ts
769
+ var schemas_exports6 = {};
770
+ __export(schemas_exports6, {
771
+ activationSchema: () => activationSchema,
772
+ externalLicenseContent: () => externalLicenseContent,
773
+ licenseSchema: () => licenseSchema
774
+ });
775
+ var import_zod9 = require("zod");
776
+
777
+ // src/inventory/licenses/models.ts
778
+ var LicenseStatus = /* @__PURE__ */ ((LicenseStatus2) => {
779
+ LicenseStatus2["Active"] = "Active";
780
+ LicenseStatus2["Pending"] = "Pending";
781
+ LicenseStatus2["Revoked"] = "Revoked";
782
+ return LicenseStatus2;
783
+ })(LicenseStatus || {});
784
+ var ActivationStatus = /* @__PURE__ */ ((ActivationStatus2) => {
785
+ ActivationStatus2["Active"] = "Active";
786
+ ActivationStatus2["Revoked"] = "Revoked";
787
+ return ActivationStatus2;
788
+ })(ActivationStatus || {});
789
+ var ActivationMethod = /* @__PURE__ */ ((ActivationMethod2) => {
790
+ ActivationMethod2["Online"] = "Online";
791
+ ActivationMethod2["Offline"] = "Offline";
792
+ return ActivationMethod2;
793
+ })(ActivationMethod || {});
794
+
795
+ // src/inventory/licenses/schemas.ts
796
+ var externalLicenseFileContent = import_zod9.z.object({
797
+ type: import_zod9.z.literal("file"),
798
+ fileName: import_zod9.z.string(),
799
+ contentType: import_zod9.z.string(),
800
+ data: import_zod9.z.string()
801
+ });
802
+ var externalLicenseILokContent = import_zod9.z.object({
803
+ type: import_zod9.z.literal("iLok")
804
+ });
805
+ var externalLicenseContent = import_zod9.z.union([
806
+ import_zod9.z.string(),
807
+ import_zod9.z.discriminatedUnion("type", [
808
+ externalLicenseFileContent,
809
+ externalLicenseILokContent
810
+ ])
811
+ ]);
812
+ var licenseSchema = import_zod9.z.object({
813
+ id: import_zod9.z.string(),
814
+ status: import_zod9.z.nativeEnum(LicenseStatus),
815
+ product: productSummarySchema,
816
+ activeNumberOfActivations: import_zod9.z.number(),
817
+ maxNumberOfActivations: import_zod9.z.number(),
818
+ externalFulfillment: externalLicenseContent.optional(),
819
+ requiredConnectedAccount: import_zod9.z.nativeEnum(ConnectableAccountProvider).nullish(),
820
+ fulfillmentMessage: import_zod9.z.string().optional(),
821
+ properties: import_zod9.z.record(rawPropertyValueSchema).nullish(),
822
+ expiresAt: import_zod9.z.coerce.date().optional(),
823
+ createdAt: import_zod9.z.coerce.date()
824
+ });
825
+ var activationSchema = import_zod9.z.object({
826
+ id: import_zod9.z.string(),
827
+ licenseId: import_zod9.z.string(),
828
+ name: import_zod9.z.string(),
829
+ status: import_zod9.z.nativeEnum(ActivationStatus),
830
+ activationMethod: import_zod9.z.nativeEnum(ActivationMethod),
831
+ firstValidatedAt: import_zod9.z.coerce.date(),
832
+ lastValidatedAt: import_zod9.z.coerce.date().nullable()
833
+ });
834
+
835
+ // src/inventory/activation/endpoints.ts
836
+ var ActivationEndpoints = class {
837
+ constructor(api, configuration) {
838
+ this.api = api;
839
+ this.configuration = configuration;
840
+ }
841
+ async activate(deviceToken, activationMethod) {
842
+ const response = await this.api.authenticatedFetch(`/api/customer/inventory/activate?method=${activationMethod}${this.configuration.includeManifests ? "&includeManifests=true" : ""}`, licenseSchema, {
843
+ method: "POST",
844
+ body: deviceToken,
845
+ contentType: "text/plain"
846
+ });
847
+ return {
848
+ license: response.data,
849
+ url: import_zod10.z.string().parse(response.headers.location)
850
+ };
851
+ }
852
+ };
853
+
854
+ // src/inventory/licenses/endpoints.ts
855
+ var LicenseEndpoints = class {
856
+ constructor(api, configuration) {
857
+ this.api = api;
858
+ this.configuration = configuration;
859
+ }
860
+ async get(nextUrl) {
861
+ const response = await this.api.authenticatedFetch(nextUrl || `/api/customer/inventory/licenses${this.configuration.includeManifests ? "?includeManifests=true" : ""}`, paged(licenseSchema));
862
+ return response.data;
863
+ }
864
+ async getActivations(licenseId, nextUrl) {
865
+ const response = await this.api.authenticatedFetch(
866
+ nextUrl || `/api/customer/inventory/licenses/${licenseId}/activations`,
867
+ paged(activationSchema)
868
+ );
869
+ return response.data;
870
+ }
871
+ async revokeActivation(licenseId, activationId) {
872
+ await this.api.authenticatedFetch(`/api/customer/inventory/licenses/${licenseId}/activations/${activationId}/revoke`, null, { method: "POST" });
873
+ }
874
+ };
875
+
876
+ // src/inventory/products/endpoints.ts
877
+ var import_zod11 = require("zod");
878
+ var ProductEndpoints = class {
879
+ constructor(api, configuration) {
880
+ this.api = api;
881
+ this.configuration = configuration;
882
+ }
883
+ async get(productId, version) {
884
+ const response = await this.api.fetch(`/api/customer/inventory/products/${productId}${version ? `?version=${version}${this.configuration.includeManifests ? "&includeManifests=true" : ""}` : this.configuration.includeManifests ? "?includeManifests=true" : ""}`, productSummarySchema);
885
+ return response.data;
886
+ }
887
+ async getOwned(nextUrl) {
888
+ const response = await this.api.authenticatedFetch(nextUrl || `/api/customer/inventory/products${this.configuration.includeManifests ? "?includeManifests=true" : ""}`, paged(productSummarySchema));
889
+ return response.data;
890
+ }
891
+ async getLicenses(productId, nextUrl) {
892
+ const response = await this.api.authenticatedFetch(nextUrl || `/api/customer/inventory/products/${productId}/licenses${this.configuration.includeManifests ? "?includeManifests=true" : ""}`, paged(licenseSchema));
893
+ return response.data;
894
+ }
895
+ async getActivations(productId, nextUrl) {
896
+ const response = await this.api.authenticatedFetch(nextUrl || `/api/customer/inventory/products/${productId}/licenses/activations`, paged(activationSchema));
897
+ return response.data;
898
+ }
899
+ async getDownloadUrl(path) {
900
+ const url = new URL(path);
901
+ url.searchParams.append("redirect", "false");
902
+ const response = await this.api.fetch(url.pathname + url.search, import_zod11.z.object({
903
+ location: import_zod11.z.string()
904
+ }));
905
+ return response.data.location;
906
+ }
907
+ };
908
+
909
+ // src/utils/api.ts
910
+ function objectToQuery(obj) {
911
+ return Object.entries(obj != null ? obj : {}).filter(([_, value]) => value !== void 0).map(([key, value]) => `${key}=${encodeURIComponent(value instanceof Date ? value.toISOString() : value)}`).join("&");
912
+ }
913
+ var MoonbaseApi = class {
914
+ constructor(baseUrl, tokenStore, logger) {
915
+ this.baseUrl = baseUrl;
916
+ this.tokenStore = tokenStore;
917
+ this.logger = logger;
918
+ }
919
+ async authenticatedFetch(path, schema, options) {
920
+ if (!this.tokenStore.user)
921
+ throw new NotAuthenticatedError();
922
+ return await this.fetch(path, schema, options);
923
+ }
924
+ async fetch(path, schema, options) {
925
+ var _a;
926
+ const accessToken = await this.tokenStore.getAccessToken();
927
+ const contentType = (_a = options == null ? void 0 : options.contentType) != null ? _a : "application/json";
928
+ this.logger.debug("Making request to Moonbase API...", {
929
+ path,
930
+ body: options == null ? void 0 : options.body
931
+ });
932
+ const startedAt = /* @__PURE__ */ new Date();
933
+ const request = {
934
+ method: (options == null ? void 0 : options.method) || "GET",
935
+ mode: "cors",
936
+ headers: {
937
+ "Accept": "application/json",
938
+ "Content-Type": contentType,
939
+ // While this fetch can be anonymous, we add the token if we have it
940
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
941
+ // Force CORS on all calls
942
+ "x-mb-cors": "1"
943
+ },
944
+ body: (options == null ? void 0 : options.body) ? contentType !== "application/json" ? options.body : JSON.stringify(options.body) : void 0,
945
+ signal: options == null ? void 0 : options.abort,
946
+ redirect: "manual"
947
+ };
948
+ const response = await fetch(this.baseUrl + path, request);
949
+ const finishedAt = /* @__PURE__ */ new Date();
950
+ this.logger.debug("Received response from Moonbase", {
951
+ path,
952
+ status: response.status,
953
+ duration: finishedAt.getTime() - startedAt.getTime()
954
+ });
955
+ if (response.status >= 400) {
956
+ try {
957
+ await handleResponseProblem(response, this.logger);
958
+ } catch (err) {
959
+ this.reportRequestProblem(path, request, response, err);
960
+ throw err;
961
+ }
962
+ }
963
+ let json;
964
+ try {
965
+ json = schema ? await response.json() : null;
966
+ return {
967
+ data: schema ? schema.parse(json) : null,
968
+ headers: Object.fromEntries(response.headers.entries()),
969
+ status: response.status
970
+ };
971
+ } catch (err) {
972
+ this.logger.warn("Could not parse response", {
973
+ status: response.status,
974
+ path,
975
+ content: json || (response.bodyUsed ? "unknown" : await response.text()),
976
+ headers: Object.fromEntries(response.headers.entries()),
977
+ userAgent: window && window.navigator && window.navigator.userAgent,
978
+ err
979
+ });
980
+ this.reportParsingProblem(path, err, json || (response.bodyUsed ? "unknown" : await response.text()));
981
+ throw new MoonbaseError("Bad response", "Could not parse server response", response.status);
982
+ }
983
+ }
984
+ async reportParsingProblem(path, err, body) {
985
+ try {
986
+ await fetch(`${this.baseUrl}/api/customer/insights/error`, {
987
+ mode: "cors",
988
+ method: "POST",
989
+ headers: {
990
+ "Accept": "application/json",
991
+ "Content-Type": "application/json"
992
+ },
993
+ body: JSON.stringify({
994
+ title: "Parse error",
995
+ detail: `Could not parse response body`,
996
+ path,
997
+ origin: window == null ? void 0 : window.location.href,
998
+ userAgent: window && window.navigator && window.navigator.userAgent,
999
+ err,
1000
+ body
1001
+ })
1002
+ });
1003
+ } catch (e) {
1004
+ }
1005
+ }
1006
+ async reportRequestProblem(path, request, response, err) {
1007
+ try {
1008
+ await fetch(`${this.baseUrl}/api/customer/insights/warn`, {
1009
+ mode: "cors",
1010
+ method: "POST",
1011
+ headers: {
1012
+ "Accept": "application/json",
1013
+ "Content-Type": "application/json"
1014
+ },
1015
+ body: JSON.stringify({
1016
+ title: "Request error",
1017
+ detail: `Request failed with status ${response.status}`,
1018
+ status: response.status,
1019
+ request: {
1020
+ ...request,
1021
+ headers: void 0,
1022
+ body: void 0
1023
+ },
1024
+ error: err,
1025
+ path,
1026
+ origin: window == null ? void 0 : window.location.href
1027
+ })
1028
+ });
1029
+ } catch (e) {
1030
+ }
1031
+ }
1032
+ };
1033
+
1034
+ // src/inventory/subscriptions/endpoints.ts
1035
+ var import_zod14 = require("zod");
1036
+
1037
+ // src/inventory/subscriptions/schemas.ts
1038
+ var schemas_exports8 = {};
1039
+ __export(schemas_exports8, {
1040
+ milestoneProgressSchema: () => milestoneProgressSchema,
1041
+ subscriptionSchema: () => subscriptionSchema
1042
+ });
1043
+ var import_zod13 = require("zod");
1044
+
1045
+ // src/inventory/subscriptions/models.ts
1046
+ var SubscriptionStatus = /* @__PURE__ */ ((SubscriptionStatus2) => {
1047
+ SubscriptionStatus2["Active"] = "Active";
1048
+ SubscriptionStatus2["Expired"] = "Expired";
1049
+ SubscriptionStatus2["Cancelled"] = "Cancelled";
1050
+ SubscriptionStatus2["Completed"] = "Completed";
1051
+ return SubscriptionStatus2;
1052
+ })(SubscriptionStatus || {});
1053
+
1054
+ // src/orders/schemas.ts
1055
+ var schemas_exports7 = {};
1056
+ __export(schemas_exports7, {
1057
+ completedOrderSchema: () => completedOrderSchema,
1058
+ openBundleLineItem: () => openBundleLineItem,
1059
+ openOrderLineItem: () => openOrderLineItem,
1060
+ openOrderSchema: () => openOrderSchema,
1061
+ openProductLineItem: () => openProductLineItem,
1062
+ orderSchema: () => orderSchema,
1063
+ orderTotalSchema: () => orderTotalSchema
1064
+ });
1065
+ var import_zod12 = require("zod");
1066
+
1067
+ // src/orders/models.ts
1068
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1069
+ OrderStatus2["Open"] = "Open";
1070
+ OrderStatus2["PaymentProcessing"] = "PaymentProcessing";
1071
+ OrderStatus2["Paid"] = "Paid";
1072
+ OrderStatus2["Completed"] = "Completed";
1073
+ OrderStatus2["Failed"] = "Failed";
1074
+ return OrderStatus2;
1075
+ })(OrderStatus || {});
1076
+
1077
+ // src/orders/schemas.ts
1078
+ var couponSchema = import_zod12.z.object({
1079
+ code: import_zod12.z.string(),
1080
+ name: import_zod12.z.string(),
1081
+ description: import_zod12.z.string()
1082
+ });
1083
+ var lineItemProductSchema = import_zod12.z.object({
1084
+ id: import_zod12.z.string(),
1085
+ name: import_zod12.z.string(),
1086
+ tagline: import_zod12.z.string(),
1087
+ iconUrl: import_zod12.z.string().nullable()
1088
+ });
1089
+ var lineItemTotalSchema = import_zod12.z.object({
1090
+ original: moneySchema,
1091
+ discount: moneySchema,
1092
+ subtotal: moneySchema,
1093
+ due: moneySchema
1094
+ });
1095
+ var openProductLineItem = import_zod12.z.object({
1096
+ id: import_zod12.z.string(),
1097
+ type: import_zod12.z.literal("Product"),
1098
+ productId: import_zod12.z.string(),
1099
+ quantity: import_zod12.z.number(),
1100
+ variationId: import_zod12.z.string(),
1101
+ offerId: import_zod12.z.string().optional(),
1102
+ isDefaultVariation: import_zod12.z.boolean().nullish(),
1103
+ isSubcriptionPayment: import_zod12.z.boolean().nullish(),
1104
+ price: priceCollectionSchema.optional(),
1105
+ variation: pricingVariationSchema.optional(),
1106
+ total: lineItemTotalSchema.nullish(),
1107
+ product: lineItemProductSchema.optional(),
1108
+ appliedDiscount: discountSchema.optional()
1109
+ });
1110
+ var lineItemBundleSchema = import_zod12.z.object({
1111
+ id: import_zod12.z.string(),
1112
+ name: import_zod12.z.string(),
1113
+ tagline: import_zod12.z.string(),
1114
+ iconUrl: import_zod12.z.string().nullable(),
1115
+ products: lineItemProductSchema.and(import_zod12.z.object({
1116
+ included: import_zod12.z.boolean().optional()
1117
+ })).array()
1118
+ });
1119
+ var openBundleLineItem = import_zod12.z.object({
1120
+ id: import_zod12.z.string(),
1121
+ type: import_zod12.z.literal("Bundle"),
1122
+ bundleId: import_zod12.z.string(),
1123
+ quantity: import_zod12.z.number(),
1124
+ variationId: import_zod12.z.string(),
1125
+ offerId: import_zod12.z.string().optional(),
1126
+ partial: import_zod12.z.boolean().optional(),
1127
+ replaced: import_zod12.z.string().array().optional(),
1128
+ isDefaultVariation: import_zod12.z.boolean().nullish(),
1129
+ isSubcriptionPayment: import_zod12.z.boolean().nullish(),
1130
+ price: priceCollectionSchema.optional(),
1131
+ variation: pricingVariationSchema.optional(),
1132
+ total: lineItemTotalSchema.nullish(),
1133
+ bundle: lineItemBundleSchema.optional(),
1134
+ appliedDiscount: discountSchema.optional()
1135
+ });
1136
+ var openOrderLineItem = import_zod12.z.discriminatedUnion("type", [
1137
+ openProductLineItem,
1138
+ openBundleLineItem
1139
+ ]);
1140
+ var orderTotalSchema = import_zod12.z.object({
1141
+ original: moneySchema,
1142
+ discount: moneySchema,
1143
+ subtotal: moneySchema,
1144
+ taxes: moneySchema,
1145
+ due: moneySchema
1146
+ });
1147
+ var openOrderSchema = import_zod12.z.object({
1148
+ id: import_zod12.z.string(),
1149
+ currency: import_zod12.z.string(),
1150
+ total: orderTotalSchema.nullish(),
1151
+ items: openOrderLineItem.array(),
1152
+ couponsApplied: couponSchema.array(),
1153
+ checkoutUrl: import_zod12.z.string().optional(),
1154
+ hostedCheckoutUrl: import_zod12.z.string().optional(),
1155
+ embeddedCheckoutUrl: import_zod12.z.string().optional()
1156
+ });
1157
+ var customerSnapshotSchema = import_zod12.z.object({
1158
+ name: import_zod12.z.string().nullable(),
1159
+ businessName: import_zod12.z.string().nullable(),
1160
+ taxId: import_zod12.z.string().nullable(),
1161
+ email: import_zod12.z.string().nullable(),
1162
+ phone: import_zod12.z.string().nullable(),
1163
+ address: addressSchema.nullable()
1164
+ });
1165
+ var completedOrderSchema = import_zod12.z.object({
1166
+ id: import_zod12.z.string(),
1167
+ status: import_zod12.z.literal("Completed" /* Completed */),
1168
+ currency: import_zod12.z.string(),
1169
+ customer: customerSnapshotSchema,
1170
+ total: orderTotalSchema,
1171
+ items: openOrderLineItem.array(),
1172
+ couponsApplied: couponSchema.array()
1173
+ });
1174
+ var orderSchema = import_zod12.z.discriminatedUnion("status", [
1175
+ openOrderSchema.extend({
1176
+ status: import_zod12.z.literal("Open" /* Open */)
1177
+ }),
1178
+ openOrderSchema.extend({
1179
+ status: import_zod12.z.literal("PaymentProcessing" /* PaymentProcessing */)
1180
+ }),
1181
+ openOrderSchema.extend({
1182
+ status: import_zod12.z.literal("Paid" /* Paid */)
1183
+ }),
1184
+ openOrderSchema.extend({
1185
+ status: import_zod12.z.literal("Failed" /* Failed */)
1186
+ }),
1187
+ completedOrderSchema
1188
+ ]);
1189
+
1190
+ // src/inventory/subscriptions/schemas.ts
1191
+ var baseMilestoneProgressEventSchema = import_zod13.z.object({
1192
+ milestoneId: import_zod13.z.string(),
1193
+ fulfilled: import_zod13.z.boolean(),
1194
+ afterCycleNumber: import_zod13.z.number(),
1195
+ afterNormalizedCycleNumber: import_zod13.z.number(),
1196
+ message: import_zod13.z.string().optional()
1197
+ });
1198
+ var milestoneProgressEventSchema = import_zod13.z.discriminatedUnion("type", [
1199
+ baseMilestoneProgressEventSchema.extend({
1200
+ type: import_zod13.z.literal("CouponCodeMilestone"),
1201
+ code: import_zod13.z.string().optional(),
1202
+ redeemed: import_zod13.z.boolean().optional()
1203
+ }),
1204
+ baseMilestoneProgressEventSchema.extend({
1205
+ type: import_zod13.z.literal("PerpetualLicenseConversionMilestone")
1206
+ })
1207
+ ]);
1208
+ var milestoneProgressSchema = import_zod13.z.object({
1209
+ title: import_zod13.z.string(),
1210
+ description: import_zod13.z.string().nullish(),
1211
+ currentCycleNumber: import_zod13.z.number(),
1212
+ currentNormalizedCycleNumber: import_zod13.z.number(),
1213
+ currentCycleIsCompleted: import_zod13.z.boolean(),
1214
+ fromCycleNumber: import_zod13.z.number(),
1215
+ fromNormalizedCycleNumber: import_zod13.z.number(),
1216
+ toCycleNumber: import_zod13.z.number(),
1217
+ toNormalizedCycleNumber: import_zod13.z.number(),
1218
+ events: import_zod13.z.record(import_zod13.z.coerce.number(), milestoneProgressEventSchema.array())
1219
+ });
1220
+ var subscriptionSchema = import_zod13.z.object({
1221
+ id: import_zod13.z.string(),
1222
+ status: import_zod13.z.nativeEnum(SubscriptionStatus),
1223
+ hasPaymentMethod: import_zod13.z.boolean(),
1224
+ cancellable: import_zod13.z.boolean(),
1225
+ expiresAt: import_zod13.z.coerce.date(),
1226
+ renewedAt: import_zod13.z.coerce.date().nullable(),
1227
+ nextPaymentScheduledAt: import_zod13.z.coerce.date().nullable(),
1228
+ startedAt: import_zod13.z.coerce.date(),
1229
+ total: orderTotalSchema,
1230
+ cycleLength: import_zod13.z.nativeEnum(CycleLength),
1231
+ paymentMethod: import_zod13.z.string().optional(),
1232
+ milestoneProgress: milestoneProgressSchema.nullish(),
1233
+ embeddedUpdatePaymentUrl: import_zod13.z.string().optional(),
1234
+ content: import_zod13.z.discriminatedUnion("type", [
1235
+ import_zod13.z.object({
1236
+ type: import_zod13.z.literal("Product"),
1237
+ quantity: import_zod13.z.number(),
1238
+ product: storefrontProductSchema
1239
+ }),
1240
+ import_zod13.z.object({
1241
+ type: import_zod13.z.literal("Bundle"),
1242
+ quantity: import_zod13.z.number(),
1243
+ bundle: storefrontBundleSchema
1244
+ })
1245
+ ])
1246
+ });
1247
+
1248
+ // src/inventory/subscriptions/endpoints.ts
1249
+ var SubscriptionEndpoints = class {
1250
+ constructor(api, configuration) {
1251
+ this.api = api;
1252
+ this.configuration = configuration;
1253
+ }
1254
+ async get(nextUrl) {
1255
+ const response = await this.api.authenticatedFetch(nextUrl || "/api/customer/inventory/subscriptions", paged(subscriptionSchema));
1256
+ return response.data;
1257
+ }
1258
+ async getById(subscriptionId, options) {
1259
+ const response = await this.api.authenticatedFetch(`/api/customer/inventory/subscriptions/${subscriptionId}?${objectToQuery(options)}`, subscriptionSchema);
1260
+ return response.data;
1261
+ }
1262
+ async cancel(subscriptionId) {
1263
+ const response = await this.api.authenticatedFetch(`/api/customer/inventory/subscriptions/${subscriptionId}/cancel`, subscriptionSchema, { method: "POST" });
1264
+ return response.data;
1265
+ }
1266
+ async renew(subscriptionId, returnUrl, embedded) {
1267
+ const response = await this.api.authenticatedFetch(`/api/customer/inventory/subscriptions/${subscriptionId}/renew?redirect=false&return=${returnUrl}&embedded=${embedded ? "true" : "false"}`, import_zod14.z.object({
1268
+ location: import_zod14.z.string()
1269
+ }), { method: "POST" });
1270
+ return response.data;
1271
+ }
1272
+ };
1273
+
1274
+ // src/inventory/index.ts
1275
+ var InventoryEndpoints = class {
1276
+ constructor(api, configuration) {
1277
+ this.licenses = new LicenseEndpoints(api, configuration);
1278
+ this.products = new ProductEndpoints(api, configuration);
1279
+ this.activation = new ActivationEndpoints(api, configuration);
1280
+ this.subscriptions = new SubscriptionEndpoints(api, configuration);
1281
+ }
1282
+ };
1283
+
1284
+ // src/orders/endpoints.ts
1285
+ var OrderEndpoints = class {
1286
+ constructor(api) {
1287
+ this.api = api;
1288
+ }
1289
+ async get(orderId, options) {
1290
+ const query = new URLSearchParams();
1291
+ if (options == null ? void 0 : options.finalize) {
1292
+ query.append("finalize", "true");
1293
+ }
1294
+ if (options == null ? void 0 : options.checkout) {
1295
+ query.append("checkout", "true");
1296
+ if (options.checkout.returnUrl) {
1297
+ query.append("returnUrl", options.checkout.returnUrl);
1298
+ }
1299
+ }
1300
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}?${query.toString()}`, orderSchema, {
1301
+ abort: options == null ? void 0 : options.abort
1302
+ });
1303
+ return response.data;
1304
+ }
1305
+ async pushContent(order, checkout, utm) {
1306
+ const query = {
1307
+ ...utmToObject(utm)
1308
+ };
1309
+ if (checkout) {
1310
+ query.checkout = "true";
1311
+ if (checkout.returnUrl)
1312
+ query.returnUrl = checkout.returnUrl;
1313
+ }
1314
+ const response = await this.api.fetch(
1315
+ `/api/customer/orders/${order.id}?${new URLSearchParams(query).toString()}`,
1316
+ openOrderSchema,
1317
+ {
1318
+ method: "PATCH",
1319
+ body: {
1320
+ currency: order.currency || void 0,
1321
+ items: order.items
1322
+ }
1323
+ }
1324
+ );
1325
+ return response.data;
1326
+ }
1327
+ async addBillingDetails(orderId, details) {
1328
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}/billing-details`, openOrderSchema, { method: "PATCH", body: details });
1329
+ return response.data;
1330
+ }
1331
+ async removeBillingDetails(orderId) {
1332
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}/billing-details`, openOrderSchema, { method: "DELETE" });
1333
+ return response.data;
1334
+ }
1335
+ async addCouponCode(orderId, code) {
1336
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}/coupon?code=${encodeURIComponent(code)}`, openOrderSchema, { method: "PATCH" });
1337
+ return response.data;
1338
+ }
1339
+ async removeCouponCode(orderId, code) {
1340
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}/coupon?code=${encodeURIComponent(code)}`, openOrderSchema, { method: "DELETE" });
1341
+ return response.data;
1342
+ }
1343
+ async clearCouponCodes(orderId) {
1344
+ const response = await this.api.fetch(`/api/customer/orders/${orderId}/coupons`, openOrderSchema, { method: "DELETE" });
1345
+ return response.data;
1346
+ }
1347
+ };
1348
+
1349
+ // src/storefront/endpoints.ts
1350
+ var StorefrontEndpoints = class {
1351
+ constructor(api, configuration) {
1352
+ this.api = api;
1353
+ this.configuration = configuration;
1354
+ }
1355
+ async get(utm) {
1356
+ const query = new URLSearchParams(this.configuration.includeManifests ? {
1357
+ includeManifests: "true",
1358
+ ...utmToObject(utm)
1359
+ } : utmToObject(utm));
1360
+ const response = await this.api.fetch(`/api/customer/storefront?${query.toString()}`, storefrontSchema);
1361
+ return response.data;
1362
+ }
1363
+ };
1364
+
1365
+ // src/utils/store.ts
1366
+ var LocalStorageStore = class {
1367
+ get(key) {
1368
+ const item = localStorage.getItem(key);
1369
+ if (item) {
1370
+ return JSON.parse(item);
1371
+ }
1372
+ return null;
1373
+ }
1374
+ set(key, item) {
1375
+ localStorage.setItem(key, JSON.stringify(item));
1376
+ }
1377
+ remove(key) {
1378
+ localStorage.removeItem(key);
1379
+ }
1380
+ listen(key, callback) {
1381
+ if (typeof window !== "undefined") {
1382
+ window.addEventListener("storage", (event) => {
1383
+ if (event.key === key) {
1384
+ callback(event.newValue ? JSON.parse(event.newValue) : null);
1385
+ }
1386
+ });
1387
+ }
1388
+ }
1389
+ };
1390
+ var InMemoryStore = class {
1391
+ constructor() {
1392
+ this.store = {};
1393
+ this.listeners = {};
1394
+ }
1395
+ get(key) {
1396
+ var _a;
1397
+ return (_a = this.store[key]) != null ? _a : null;
1398
+ }
1399
+ set(key, item) {
1400
+ this.store[key] = item;
1401
+ for (const listener of this.listeners[key] || []) {
1402
+ listener(item);
1403
+ }
1404
+ }
1405
+ remove(key) {
1406
+ delete this.store[key];
1407
+ for (const listener of this.listeners[key] || []) {
1408
+ listener(null);
1409
+ }
1410
+ }
1411
+ listen(key, callback) {
1412
+ if (!this.listeners[key]) this.listeners[key] = [];
1413
+ this.listeners[key].push(callback);
1414
+ }
1415
+ };
1416
+
1417
+ // src/utils/tokenStore.ts
1418
+ var _TokenStore = class _TokenStore {
1419
+ constructor(configuration) {
1420
+ this.configuration = configuration;
1421
+ this.tokens = null;
1422
+ this.refreshTimeoutId = null;
1423
+ this.refreshPromise = null;
1424
+ var _a;
1425
+ this.store = (_a = configuration.store) != null ? _a : typeof window !== "undefined" && localStorage ? new LocalStorageStore() : new InMemoryStore();
1426
+ const storedToken = this.store.get(_TokenStore.storageKey);
1427
+ if (storedToken) {
1428
+ this.tokens = {
1429
+ ...storedToken,
1430
+ expiresAt: new Date(storedToken.expiresAt)
1431
+ };
1432
+ }
1433
+ this.store.listen(_TokenStore.storageKey, (updatedTokens) => this.handleStorageUpdate(updatedTokens));
1434
+ }
1435
+ get user() {
1436
+ if (this.tokens)
1437
+ return this.tokens;
1438
+ return null;
1439
+ }
1440
+ async getAccessToken() {
1441
+ var _a, _b, _c;
1442
+ if (this.isExpired) {
1443
+ if (this.refreshPromise) {
1444
+ const tokens2 = await this.refreshPromise;
1445
+ return (_a = tokens2 == null ? void 0 : tokens2.accessToken) != null ? _a : null;
1446
+ }
1447
+ this.refreshPromise = this.refreshTokens();
1448
+ const tokens = await this.refreshPromise;
1449
+ return (_b = tokens == null ? void 0 : tokens.accessToken) != null ? _b : null;
1450
+ }
1451
+ return ((_c = this.tokens) == null ? void 0 : _c.accessToken) || null;
1452
+ }
1453
+ setUser(user) {
1454
+ const identity = user;
1455
+ if (!identity.accessToken || !identity.refreshToken) {
1456
+ if (!this.tokens) return null;
1457
+ this.tokens = {
1458
+ ...user,
1459
+ accessToken: this.tokens.accessToken,
1460
+ refreshToken: this.tokens.refreshToken,
1461
+ expiresAt: this.tokens.expiresAt
1462
+ };
1463
+ } else {
1464
+ this.tokens = {
1465
+ ...identity,
1466
+ // Hardcoded 15 minutes now, might want to check the JWT tho
1467
+ expiresAt: new Date((/* @__PURE__ */ new Date()).getTime() + 15 * 60 * 1e3)
1468
+ };
1469
+ }
1470
+ this.store.set(_TokenStore.storageKey, this.tokens);
1471
+ if (typeof window !== "undefined") {
1472
+ if (this.refreshTimeoutId != null)
1473
+ window.clearTimeout(this.refreshTimeoutId);
1474
+ this.refreshTimeoutId = window.setTimeout(() => {
1475
+ this.refreshPromise = this.refreshTokens();
1476
+ }, 10 * 60 * 1e3);
1477
+ }
1478
+ return this.tokens;
1479
+ }
1480
+ clear() {
1481
+ this.tokens = null;
1482
+ this.store.remove(_TokenStore.storageKey);
1483
+ if (this.refreshTimeoutId != null && typeof window !== "undefined")
1484
+ window.clearTimeout(this.refreshTimeoutId);
1485
+ return null;
1486
+ }
1487
+ get isExpired() {
1488
+ return this.tokens != null && this.tokens.expiresAt < /* @__PURE__ */ new Date();
1489
+ }
1490
+ async refreshTokens() {
1491
+ if (!this.tokens)
1492
+ throw new Error("No tokens found to refresh");
1493
+ const response = await fetch(`${this.configuration.endpoint}/api/customer/identity/refresh?token=${this.tokens.refreshToken}`, {
1494
+ method: "POST",
1495
+ headers: {
1496
+ "Accept": "application/json",
1497
+ "Content-Type": "text/plain",
1498
+ "x-mb-cors": "1"
1499
+ },
1500
+ body: this.tokens.accessToken
1501
+ });
1502
+ if (response.status !== 200) {
1503
+ if (response.status === 403 || response.status === 404) {
1504
+ this.clear();
1505
+ return null;
1506
+ }
1507
+ throw new MoonbaseError("Unexpected result", `Could not refresh access token, status code ${response.status}`, response.status);
1508
+ }
1509
+ const result = identitySchema.parse(await response.json());
1510
+ this.setUser(result);
1511
+ return this.tokens;
1512
+ }
1513
+ handleStorageUpdate(updatedTokens) {
1514
+ this.tokens = updatedTokens;
1515
+ if (this.refreshTimeoutId != null)
1516
+ window.clearTimeout(this.refreshTimeoutId);
1517
+ if (this.tokens) {
1518
+ this.tokens.expiresAt = new Date(this.tokens.expiresAt);
1519
+ }
1520
+ }
1521
+ };
1522
+ _TokenStore.storageKey = "moonbase_auth";
1523
+ var TokenStore = _TokenStore;
1524
+
1525
+ // src/vendor/schemas.ts
1526
+ var schemas_exports9 = {};
1527
+ __export(schemas_exports9, {
1528
+ vendorSchema: () => vendorSchema
1529
+ });
1530
+ var import_zod15 = require("zod");
1531
+ var vendorSchema = import_zod15.z.object({
1532
+ id: import_zod15.z.string(),
1533
+ name: import_zod15.z.string(),
1534
+ logoUrl: import_zod15.z.string().nullable()
1535
+ });
1536
+
1537
+ // src/vendor/endpoints.ts
1538
+ var VendorEndpoints = class {
1539
+ constructor(api) {
1540
+ this.api = api;
1541
+ }
1542
+ async get() {
1543
+ const response = await this.api.fetch(`/api/public/vendors/current`, vendorSchema);
1544
+ return response.data;
1545
+ }
1546
+ };
1547
+
1548
+ // src/vouchers/schemas.ts
1549
+ var schemas_exports10 = {};
1550
+ __export(schemas_exports10, {
1551
+ voucherSchema: () => voucherSchema
1552
+ });
1553
+ var import_zod16 = require("zod");
1554
+ var voucherSchema = import_zod16.z.object({
1555
+ id: import_zod16.z.string(),
1556
+ name: import_zod16.z.string(),
1557
+ description: import_zod16.z.string(),
1558
+ code: import_zod16.z.string(),
1559
+ redeemed: import_zod16.z.boolean(),
1560
+ redeemsProducts: quantifiable(storefrontProductSchema).array(),
1561
+ redeemsBundles: quantifiable(storefrontBundleSchema).array(),
1562
+ properties: import_zod16.z.record(rawPropertyValueSchema).nullish()
1563
+ });
1564
+
1565
+ // src/vouchers/endpoints.ts
1566
+ var VoucherEndpoints = class {
1567
+ constructor(api) {
1568
+ this.api = api;
1569
+ }
1570
+ async peek(code) {
1571
+ const response = await this.api.fetch(`/api/customer/vouchers?code=${encodeURIComponent(code)}`, voucherSchema);
1572
+ return response.data;
1573
+ }
1574
+ async redeem(code) {
1575
+ const response = await this.api.authenticatedFetch(
1576
+ `/api/customer/vouchers/redeem?code=${encodeURIComponent(code)}`,
1577
+ voucherSchema,
1578
+ {
1579
+ method: "POST"
1580
+ }
1581
+ );
1582
+ return response.data;
1583
+ }
1584
+ };
1585
+
1586
+ // src/utils/logger.ts
1587
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
1588
+ LogLevel2[LogLevel2["Debug"] = 0] = "Debug";
1589
+ LogLevel2[LogLevel2["Information"] = 1] = "Information";
1590
+ LogLevel2[LogLevel2["Warn"] = 2] = "Warn";
1591
+ LogLevel2[LogLevel2["Error"] = 3] = "Error";
1592
+ return LogLevel2;
1593
+ })(LogLevel || {});
1594
+ var ConsoleLogger = class {
1595
+ constructor(level = 2 /* Warn */) {
1596
+ this.level = level;
1597
+ }
1598
+ debug(message, ...optionalParams) {
1599
+ if (this.level <= 0 /* Debug */) console.debug(message, ...optionalParams);
1600
+ }
1601
+ log(message, ...optionalParams) {
1602
+ if (this.level <= 1 /* Information */) console.log(message, ...optionalParams);
1603
+ }
1604
+ warn(message, ...optionalParams) {
1605
+ if (this.level <= 2 /* Warn */) console.warn(message, ...optionalParams);
1606
+ }
1607
+ error(message, ...optionalParams) {
1608
+ if (this.level <= 3 /* Error */) console.error(message, ...optionalParams);
1609
+ }
1610
+ };
1611
+
1612
+ // src/schemas.ts
1613
+ var schemas_exports12 = {};
1614
+ __export(schemas_exports12, {
1615
+ activationRequests: () => schemas_exports3,
1616
+ communications: () => schemas_exports4,
1617
+ identity: () => schemas_exports5,
1618
+ inventory: () => schemas_exports11,
1619
+ orders: () => schemas_exports7,
1620
+ storefront: () => schemas_exports2,
1621
+ vendor: () => schemas_exports9,
1622
+ vouchers: () => schemas_exports10
1623
+ });
1624
+
1625
+ // src/inventory/schemas.ts
1626
+ var schemas_exports11 = {};
1627
+ __export(schemas_exports11, {
1628
+ licenses: () => schemas_exports6,
1629
+ products: () => schemas_exports,
1630
+ subscriptions: () => schemas_exports8
1631
+ });
1632
+
1633
+ // src/utils/discount.ts
1634
+ var DiscountUtils = class {
1635
+ static apply(discount, price) {
1636
+ switch (discount.type) {
1637
+ case "PercentageOffDiscount":
1638
+ return Object.fromEntries(Object.entries(price).map(([currency, amount]) => [currency, amount * discount.percentage]));
1639
+ case "FlatAmountOffDiscount":
1640
+ return Object.fromEntries(Object.entries(price).map(([currency, amount]) => {
1641
+ var _a, _b;
1642
+ return [currency, Math.min(amount, (_b = (_a = discount.total) == null ? void 0 : _a[currency]) != null ? _b : 0)];
1643
+ }));
1644
+ }
1645
+ }
1646
+ };
1647
+
1648
+ // src/utils/money.ts
1649
+ var MoneyCollectionUtils = class {
1650
+ static sum(a, b) {
1651
+ return Object.fromEntries(Object.entries(a).map(([currency, amount]) => [currency, amount + b[currency]]));
1652
+ }
1653
+ static subtract(a, b) {
1654
+ return Object.fromEntries(Object.entries(a).map(([currency, amount]) => [currency, amount - b[currency]]));
1655
+ }
1656
+ };
1657
+
1658
+ // src/utils/offer.ts
1659
+ var OfferUtils = class _OfferUtils {
1660
+ static eligible(offer, order) {
1661
+ switch (offer.condition.type) {
1662
+ case "CartContainsItems":
1663
+ const relevantItems = order.items.filter(
1664
+ (i) => i.type === "Product" && offer.condition.relevantItemVariations[`Product/${i.productId}`] && offer.condition.relevantItemVariations[`Product/${i.productId}`].includes(i.variationId) || i.type === "Bundle" && offer.condition.relevantItemVariations[`Bundle/${i.bundleId}`] && offer.condition.relevantItemVariations[`Bundle/${i.bundleId}`].includes(i.variationId)
1665
+ );
1666
+ const relevantReplacedItems = order.items.flatMap((i) => {
1667
+ var _a;
1668
+ return offer.id === i.offerId && i.type === "Bundle" && _OfferUtils.targetContainsBundle(offer, i.id) ? (_a = i.replaced) != null ? _a : [] : [];
1669
+ }).filter((ref) => {
1670
+ const [productId, variationId] = ref.split("/");
1671
+ return offer.condition.relevantItemVariations[`Product/${productId}`] && offer.condition.relevantItemVariations[`Product/${productId}`].includes(variationId);
1672
+ });
1673
+ return relevantItems.length + relevantReplacedItems.length >= offer.condition.minimumItems;
1674
+ }
1675
+ console.warn("Unsupported offer condition found:", offer.condition);
1676
+ return false;
1677
+ }
1678
+ // The relevant targets of an offer with more than a single target needs to:
1679
+ // a. Not be owned, or all targets need to be owned
1680
+ // b. Not already in the cart
1681
+ static relevantTargets(offer, cartItems) {
1682
+ if (Array.isArray(offer.target)) {
1683
+ const allOwned = offer.target.every((i) => i.owned);
1684
+ return offer.target.filter((i) => (allOwned || !i.owned) && !cartItems.some((l) => l.type === i.type && i.id === (l.type === "Product" ? l.productId : l.bundleId)));
1685
+ }
1686
+ return [offer.target];
1687
+ }
1688
+ static applyToVariation(offer, variation) {
1689
+ const discount = DiscountUtils.apply(offer.discount, variation.price);
1690
+ return {
1691
+ ...variation,
1692
+ price: MoneyCollectionUtils.subtract(variation.price, discount),
1693
+ hasDiscount: Object.values(discount).some((v) => v > 0) || variation.hasDiscount
1694
+ };
1695
+ }
1696
+ static targetContainsBundle(offer, bundleId) {
1697
+ if (Array.isArray(offer.target)) return offer.target.some((i) => i.type === "Bundle" && i.id === bundleId);
1698
+ }
1699
+ };
1700
+
1701
+ // src/utils/utm.ts
1702
+ function parseOffSiteReferrer(rawReferrer, currentOrigin) {
1703
+ if (!rawReferrer)
1704
+ return void 0;
1705
+ try {
1706
+ const referrerUrl = new URL(rawReferrer);
1707
+ if (referrerUrl.origin === currentOrigin)
1708
+ return void 0;
1709
+ return referrerUrl.host || void 0;
1710
+ } catch (e) {
1711
+ return void 0;
1712
+ }
1713
+ }
1714
+ function resolveUtm(cached, fresh) {
1715
+ const freshHasUtm = !!(fresh.source || fresh.medium || fresh.campaign || fresh.term || fresh.content);
1716
+ const freshIsExternalArrival = freshHasUtm || !!fresh.referrer;
1717
+ if (freshIsExternalArrival)
1718
+ return fresh;
1719
+ return cached != null ? cached : fresh;
1720
+ }
1721
+
1722
+ // src/index.ts
1723
+ var MoonbaseClient = class {
1724
+ constructor(configuration) {
1725
+ var _a;
1726
+ this.configuration = configuration;
1727
+ this.configuration.endpoint = this.configuration.endpoint.replace(/\/$/, "");
1728
+ this.logger = (_a = this.configuration.logger) != null ? _a : new ConsoleLogger();
1729
+ this.tokenStore = new TokenStore(configuration);
1730
+ this.api = new MoonbaseApi(this.configuration.endpoint, this.tokenStore, this.logger);
1731
+ this.storefront = new StorefrontEndpoints(this.api, this.configuration);
1732
+ this.identity = new IdentityEndpoints(this.api, this.tokenStore, this.logger);
1733
+ this.communications = new CommunicationsEndpoints(this.api);
1734
+ this.vouchers = new VoucherEndpoints(this.api);
1735
+ this.orders = new OrderEndpoints(this.api);
1736
+ this.inventory = new InventoryEndpoints(this.api, this.configuration);
1737
+ this.activationRequests = new ActivationRequestEndpoints(this.api);
1738
+ this.vendor = new VendorEndpoints(this.api);
1739
+ }
1740
+ };
1741
+ // Annotate the CommonJS export names for ESM import in node:
1742
+ 0 && (module.exports = {
1743
+ ActivationMethod,
1744
+ ActivationRequestFulfillmentType,
1745
+ ActivationRequestStatus,
1746
+ ActivationStatus,
1747
+ Architecture,
1748
+ ConnectableAccountProvider,
1749
+ ConsoleLogger,
1750
+ CycleLength,
1751
+ DiscountUtils,
1752
+ InMemoryStore,
1753
+ LicenseStatus,
1754
+ LocalStorageStore,
1755
+ LogLevel,
1756
+ MarketingConsentType,
1757
+ MoneyCollectionUtils,
1758
+ MoonbaseApi,
1759
+ MoonbaseClient,
1760
+ MoonbaseError,
1761
+ NotAuthenticatedError,
1762
+ NotAuthorizedError,
1763
+ NotFoundError,
1764
+ OfferUtils,
1765
+ OrderStatus,
1766
+ Platform,
1767
+ SubscriptionStatus,
1768
+ TokenStore,
1769
+ objectToQuery,
1770
+ parseOffSiteReferrer,
1771
+ problemDetailsSchema,
1772
+ resolveUtm,
1773
+ schemas,
1774
+ utmToObject
1775
+ });