@01.software/sdk 0.67.0 → 0.69.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 (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +124 -6
  3. package/dist/client.cjs +422 -319
  4. package/dist/client.cjs.map +1 -1
  5. package/dist/client.d.cts +11 -6
  6. package/dist/client.d.ts +11 -6
  7. package/dist/client.js +422 -319
  8. package/dist/client.js.map +1 -1
  9. package/dist/{collection-client-D4HEOoO_.d.ts → collection-client-C2VGBnCC.d.ts} +4 -4
  10. package/dist/{collection-client-jrNFGbrO.d.cts → collection-client-DvWkDxSM.d.cts} +4 -4
  11. package/dist/{const-CCQ3MdLE.d.cts → const-AtPEgg__.d.cts} +2 -2
  12. package/dist/{const-BU79hCFB.d.ts → const-DR96Chal.d.ts} +2 -2
  13. package/dist/embedded-admin/server.cjs +19 -1
  14. package/dist/embedded-admin/server.cjs.map +1 -1
  15. package/dist/embedded-admin/server.d.cts +4 -2
  16. package/dist/embedded-admin/server.d.ts +4 -2
  17. package/dist/embedded-admin/server.js +19 -1
  18. package/dist/embedded-admin/server.js.map +1 -1
  19. package/dist/embedded-admin.cjs +22 -0
  20. package/dist/embedded-admin.cjs.map +1 -1
  21. package/dist/embedded-admin.d.cts +7 -1
  22. package/dist/embedded-admin.d.ts +7 -1
  23. package/dist/embedded-admin.js +22 -0
  24. package/dist/embedded-admin.js.map +1 -1
  25. package/dist/errors.cjs +3 -0
  26. package/dist/errors.cjs.map +1 -1
  27. package/dist/errors.d.cts +3 -3
  28. package/dist/errors.d.ts +3 -3
  29. package/dist/errors.js +3 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/{index-DiyhsVHd.d.cts → index-Ce11c_Oh.d.cts} +3 -3
  32. package/dist/{index-CwKxWHIa.d.ts → index-D8fmTrZk.d.ts} +3 -3
  33. package/dist/index.cjs +427 -323
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +427 -323
  38. package/dist/index.js.map +1 -1
  39. package/dist/{payload-types-jdsUXunB.d.cts → payload-types-rhnw3rR8.d.cts} +48 -1
  40. package/dist/{payload-types-jdsUXunB.d.ts → payload-types-rhnw3rR8.d.ts} +48 -1
  41. package/dist/query.cjs +11 -0
  42. package/dist/query.cjs.map +1 -1
  43. package/dist/query.d.cts +5 -5
  44. package/dist/query.d.ts +5 -5
  45. package/dist/query.js +11 -0
  46. package/dist/query.js.map +1 -1
  47. package/dist/realtime.d.cts +2 -2
  48. package/dist/realtime.d.ts +2 -2
  49. package/dist/server.cjs +1186 -1071
  50. package/dist/server.cjs.map +1 -1
  51. package/dist/server.d.cts +9 -8
  52. package/dist/server.d.ts +9 -8
  53. package/dist/server.js +1186 -1071
  54. package/dist/server.js.map +1 -1
  55. package/dist/storefront-cache.cjs +3 -0
  56. package/dist/storefront-cache.cjs.map +1 -1
  57. package/dist/storefront-cache.js +3 -0
  58. package/dist/storefront-cache.js.map +1 -1
  59. package/dist/{types-CvdBV3ri.d.cts → types-B99utaKU.d.cts} +147 -40
  60. package/dist/{types-BPwXAFZ7.d.cts → types-BR0D4AaW.d.cts} +2 -2
  61. package/dist/{types-BusejG-v.d.ts → types-CHK8VIPa.d.ts} +2 -2
  62. package/dist/{types-I2k6Laad.d.ts → types-L0xmn_iT.d.ts} +147 -40
  63. package/dist/ui/form.d.cts +1 -1
  64. package/dist/ui/form.d.ts +1 -1
  65. package/dist/ui/video.d.cts +1 -1
  66. package/dist/ui/video.d.ts +1 -1
  67. package/dist/webhook.d.cts +5 -5
  68. package/dist/webhook.d.ts +5 -5
  69. package/package.json +2 -2
package/dist/client.cjs CHANGED
@@ -41,9 +41,6 @@ __export(client_exports, {
41
41
  });
42
42
  module.exports = __toCommonJS(client_exports);
43
43
 
44
- // src/core/collection/http-client.ts
45
- var import_qs_esm = require("qs-esm");
46
-
47
44
  // src/core/errors.ts
48
45
  var SDK_ERROR_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError");
49
46
  var SDK_ERROR_TYPE_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError.type");
@@ -157,6 +154,7 @@ var COMMERCE_ERROR_CODES = [
157
154
  "admission_metadata_invalid",
158
155
  "admission_metadata_required",
159
156
  "capacity_exceeded",
157
+ "admission_required",
160
158
  "occurrence_lock_unavailable",
161
159
  "occurrence_not_open",
162
160
  "admission_type_capacity_exceeded",
@@ -175,6 +173,8 @@ var COMMERCE_ERROR_CODES = [
175
173
  "variant_inactive",
176
174
  "variant_product_mismatch",
177
175
  "product_not_public",
176
+ "product_not_eligible",
177
+ "purchase_limit_exceeded",
178
178
  "market_not_found",
179
179
  "market_shipping_currency_unsupported",
180
180
  "missing_market_rate",
@@ -1047,281 +1047,6 @@ function stockSnapshotSearchParams(params) {
1047
1047
  return `variantIds=${params.variantIds.map(encodeURIComponent).join(",")}`;
1048
1048
  }
1049
1049
 
1050
- // src/core/collection/http-client.ts
1051
- function validateWhere(where) {
1052
- if (where === void 0) return false;
1053
- let hasNull = false;
1054
- function visit(value, depth, key) {
1055
- if (depth > 10) {
1056
- throw createValidationError(
1057
- "Collection where must not exceed nesting depth 10."
1058
- );
1059
- }
1060
- if (value === null && (key === "equals" || key === "not_equals")) {
1061
- hasNull = true;
1062
- return;
1063
- }
1064
- if (value == null) {
1065
- throw createValidationError(
1066
- "Collection where must not contain null or undefined values."
1067
- );
1068
- }
1069
- if (Array.isArray(value)) {
1070
- if (value.length === 0) {
1071
- throw createValidationError(
1072
- "Collection where must not contain empty arrays, including and/or."
1073
- );
1074
- }
1075
- if (value.length > 1e3) {
1076
- throw createValidationError(
1077
- "Collection where arrays must not contain more than 1000 elements."
1078
- );
1079
- }
1080
- for (const item of value) visit(item, depth + 1);
1081
- } else if (typeof value === "object" && !(value instanceof Date)) {
1082
- const values = Object.entries(value);
1083
- if (values.length === 0) {
1084
- throw createValidationError(
1085
- "Collection where must not contain empty condition objects."
1086
- );
1087
- }
1088
- for (const [key2, item] of values) visit(item, depth + 1, key2);
1089
- }
1090
- }
1091
- visit(where, 0);
1092
- return hasNull;
1093
- }
1094
- var HttpClient = class {
1095
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1096
- this.publishableKey = requirePublishableKeyForSecret(
1097
- "CollectionClient",
1098
- publishableKey,
1099
- secretKey
1100
- );
1101
- this.secretKey = secretKey;
1102
- this.getCustomerToken = getCustomerToken;
1103
- this.onUnauthorized = onUnauthorized;
1104
- this.onRequestId = onRequestId;
1105
- this.apiUrl = apiUrl;
1106
- }
1107
- get defaultOptions() {
1108
- const opts = {
1109
- apiUrl: this.apiUrl,
1110
- publishableKey: this.publishableKey,
1111
- secretKey: this.secretKey
1112
- };
1113
- const token = this.getCustomerToken?.();
1114
- if (token) {
1115
- opts.customerToken = token;
1116
- if (this.onUnauthorized) {
1117
- opts.onUnauthorized = this.onUnauthorized;
1118
- }
1119
- }
1120
- return opts;
1121
- }
1122
- async fetchWithTracking(url, opts) {
1123
- try {
1124
- const response = await httpFetch(url, opts);
1125
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1126
- return response;
1127
- } catch (err) {
1128
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1129
- this.onRequestId?.(id);
1130
- throw err;
1131
- }
1132
- }
1133
- buildUrl(endpoint, options) {
1134
- if (!options) return endpoint;
1135
- const { fallbackLocale, ...rest } = options;
1136
- const queryOptions = fallbackLocale === void 0 ? rest : {
1137
- ...rest,
1138
- "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1139
- };
1140
- const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1141
- const queryString = (0, import_qs_esm.stringify)(encodedOptions, { addQueryPrefix: true });
1142
- return queryString ? `${endpoint}${queryString}` : endpoint;
1143
- }
1144
- assertJsonResponse(response) {
1145
- const contentType = response.headers.get("content-type");
1146
- if (!contentType?.includes("application/json")) {
1147
- throw createApiError("Response is not in JSON format.", response.status, {
1148
- contentType
1149
- });
1150
- }
1151
- }
1152
- /**
1153
- * Parse Payload CMS find response (list query)
1154
- * Returns native Payload response structure
1155
- */
1156
- async parseFindResponse(response) {
1157
- const contentType = response.headers.get("content-type");
1158
- try {
1159
- this.assertJsonResponse(response);
1160
- const jsonData = await response.json();
1161
- if (jsonData.docs === void 0) {
1162
- throw createApiError("Invalid find response.", response.status, {
1163
- jsonData
1164
- });
1165
- }
1166
- return {
1167
- docs: jsonData.docs,
1168
- totalDocs: jsonData.totalDocs ?? 0,
1169
- limit: jsonData.limit || 20,
1170
- totalPages: jsonData.totalPages ?? 0,
1171
- page: jsonData.page || 1,
1172
- pagingCounter: jsonData.pagingCounter || 1,
1173
- hasPrevPage: jsonData.hasPrevPage ?? false,
1174
- hasNextPage: jsonData.hasNextPage ?? false,
1175
- prevPage: jsonData.prevPage ?? null,
1176
- nextPage: jsonData.nextPage ?? null
1177
- };
1178
- } catch (error) {
1179
- if (error instanceof SDKError) throw error;
1180
- throw createApiError("Failed to parse response.", response.status, {
1181
- contentType,
1182
- error: error instanceof Error ? error.message : error
1183
- });
1184
- }
1185
- }
1186
- /**
1187
- * Parse Payload CMS mutation response (create/update)
1188
- * Returns native Payload response structure
1189
- */
1190
- async parseMutationResponse(response) {
1191
- const contentType = response.headers.get("content-type");
1192
- try {
1193
- this.assertJsonResponse(response);
1194
- const jsonData = await response.json();
1195
- if (jsonData.doc === void 0) {
1196
- throw createApiError("Invalid mutation response.", response.status, {
1197
- jsonData
1198
- });
1199
- }
1200
- return {
1201
- message: jsonData.message || "",
1202
- doc: jsonData.doc,
1203
- errors: jsonData.errors
1204
- };
1205
- } catch (error) {
1206
- if (error instanceof SDKError) throw error;
1207
- throw createApiError("Failed to parse response.", response.status, {
1208
- contentType,
1209
- error: error instanceof Error ? error.message : error
1210
- });
1211
- }
1212
- }
1213
- /**
1214
- * Parse Payload CMS document response (findById/delete)
1215
- * Returns document directly without wrapper
1216
- */
1217
- async parseDocumentResponse(response) {
1218
- const contentType = response.headers.get("content-type");
1219
- try {
1220
- this.assertJsonResponse(response);
1221
- const jsonData = await response.json();
1222
- return jsonData;
1223
- } catch (error) {
1224
- if (error instanceof SDKError) throw error;
1225
- throw createApiError("Failed to parse response.", response.status, {
1226
- contentType,
1227
- error: error instanceof Error ? error.message : error
1228
- });
1229
- }
1230
- }
1231
- };
1232
-
1233
- // src/core/collection/query-builder.ts
1234
- var PUBLIC_READ_DEPTH_ERROR = "Publishable collection reads require depth: 0. Use a shaped commerce endpoint or server client for populated data.";
1235
- var PUBLIC_READ_JOINS_ERROR = "Publishable collection reads require joins: false. Use a shaped commerce endpoint or server client for joined data.";
1236
- var PUBLIC_READ_POPULATE_ERROR = "Publishable collection reads do not support populate. Use a shaped commerce endpoint or server client for populated data.";
1237
- function withDefaultPublicReadOptions(options) {
1238
- const rawOptions = options;
1239
- if (rawOptions?.depth !== void 0 && rawOptions.depth !== 0) {
1240
- throw createValidationError(PUBLIC_READ_DEPTH_ERROR);
1241
- }
1242
- if (rawOptions?.joins !== void 0 && rawOptions.joins !== false) {
1243
- throw createValidationError(PUBLIC_READ_JOINS_ERROR);
1244
- }
1245
- if (rawOptions?.populate !== void 0) {
1246
- throw createValidationError(PUBLIC_READ_POPULATE_ERROR);
1247
- }
1248
- return {
1249
- ...options,
1250
- depth: options?.depth ?? 0,
1251
- joins: options?.joins ?? false
1252
- };
1253
- }
1254
- var ReadOnlyCollectionQueryBuilder = class {
1255
- constructor(api, collection) {
1256
- this.api = api;
1257
- this.collection = collection;
1258
- }
1259
- async find(options) {
1260
- return this.api.requestFind(
1261
- `/api/${String(this.collection)}`,
1262
- withDefaultPublicReadOptions(options)
1263
- );
1264
- }
1265
- async findById(id, options) {
1266
- return this.api.requestFindById(
1267
- `/api/${String(this.collection)}/${String(id)}`,
1268
- withDefaultPublicReadOptions(options)
1269
- );
1270
- }
1271
- async count(options) {
1272
- return this.api.requestCount(
1273
- `/api/${String(this.collection)}/count`,
1274
- withDefaultPublicReadOptions(options)
1275
- );
1276
- }
1277
- };
1278
-
1279
- // src/core/collection/collection-client.ts
1280
- var ReadOnlyCollectionClient = class extends HttpClient {
1281
- from(collection) {
1282
- return new ReadOnlyCollectionQueryBuilder(this, collection);
1283
- }
1284
- async requestFind(endpoint, options) {
1285
- const url = this.buildUrl(endpoint, options);
1286
- const response = await this.fetchWithTracking(url, {
1287
- ...this.defaultOptions,
1288
- method: "GET"
1289
- });
1290
- return this.parseFindResponse(response);
1291
- }
1292
- async requestFindEndpoint(endpoint, data) {
1293
- const response = await this.fetchWithTracking(endpoint, {
1294
- ...this.defaultOptions,
1295
- method: "POST",
1296
- body: data ? JSON.stringify(data) : void 0
1297
- });
1298
- return this.parseFindResponse(response);
1299
- }
1300
- async requestFindEndpointGet(endpoint) {
1301
- const response = await this.fetchWithTracking(endpoint, {
1302
- ...this.defaultOptions,
1303
- method: "GET"
1304
- });
1305
- return this.parseFindResponse(response);
1306
- }
1307
- async requestFindById(endpoint, options) {
1308
- const url = this.buildUrl(endpoint, options);
1309
- const response = await this.fetchWithTracking(url, {
1310
- ...this.defaultOptions,
1311
- method: "GET"
1312
- });
1313
- return this.parseDocumentResponse(response);
1314
- }
1315
- async requestCount(endpoint, options) {
1316
- const url = this.buildUrl(endpoint, options);
1317
- const response = await this.fetchWithTracking(url, {
1318
- ...this.defaultOptions,
1319
- method: "GET"
1320
- });
1321
- return this.parseDocumentResponse(response);
1322
- }
1323
- };
1324
-
1325
1050
  // src/core/api/parse-response.ts
1326
1051
  async function parseApiResponse(response, endpoint, options = {}) {
1327
1052
  if (response.status === 204 || response.headers.get("content-length") === "0") {
@@ -1583,6 +1308,14 @@ var EXTERNAL_CUSTOMER_LINK_ENDPOINT_OPERATIONS = {
1583
1308
  "/external-links/clear-previous-state"
1584
1309
  )
1585
1310
  };
1311
+ var BENEFIT_VOUCHER_ENDPOINT_OPERATIONS = {
1312
+ issue: operation("customers", "post", "/benefit-vouchers/issue"),
1313
+ get: operation("customers", "post", "/benefit-vouchers/get"),
1314
+ list: operation("customers", "post", "/benefit-vouchers/list"),
1315
+ redeem: operation("customers", "post", "/benefit-vouchers/redeem"),
1316
+ void: operation("customers", "post", "/benefit-vouchers/void"),
1317
+ listMine: operation("customers", "get", "/me/benefit-vouchers")
1318
+ };
1586
1319
  var CUSTOMER_GROUP_ENDPOINT_OPERATIONS = {
1587
1320
  members: operation("customer-groups", "get", "/:id/members"),
1588
1321
  grant: operation("customer-groups", "post", "/:id/members/grant"),
@@ -1820,62 +1553,422 @@ var CustomerScopedTransport = class {
1820
1553
  );
1821
1554
  }
1822
1555
  this.publishableKey = requirePublishableKeyForSecret(
1823
- apiName,
1824
- options.publishableKey,
1825
- options.secretKey
1556
+ apiName,
1557
+ options.publishableKey,
1558
+ options.secretKey
1559
+ );
1560
+ this.secretKey = options.secretKey;
1561
+ this.apiUrl = options.apiUrl;
1562
+ this.customerToken = options.customerToken;
1563
+ this.onUnauthorized = options.onUnauthorized;
1564
+ this.onRequestId = options.onRequestId;
1565
+ }
1566
+ async request(endpoint, options) {
1567
+ const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
1568
+ try {
1569
+ const response = await httpFetch(endpoint, {
1570
+ method: options.method,
1571
+ apiUrl: this.apiUrl,
1572
+ publishableKey: this.publishableKey,
1573
+ secretKey: this.secretKey,
1574
+ customerToken: token ?? void 0,
1575
+ ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
1576
+ ...options.body !== void 0 && {
1577
+ body: JSON.stringify(options.body)
1578
+ },
1579
+ ...options.headers && { headers: options.headers },
1580
+ ...options.errorFamily && { errorFamily: options.errorFamily }
1581
+ });
1582
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1583
+ return parseApiResponse(response, endpoint, {
1584
+ errorFamily: options.errorFamily
1585
+ });
1586
+ } catch (err) {
1587
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1588
+ this.onRequestId?.(id);
1589
+ throw err;
1590
+ }
1591
+ }
1592
+ };
1593
+ var CustomerScopedApi = class {
1594
+ constructor(apiName, options) {
1595
+ this.transport = new CustomerScopedTransport(apiName, options);
1596
+ }
1597
+ requestEndpoint(endpoint, body, options) {
1598
+ return this.transport.request(resolveOperationPath(endpoint, options), {
1599
+ method: resolveOperationMethod(endpoint),
1600
+ body,
1601
+ headers: options?.headers,
1602
+ errorFamily: resolveOperationErrorFamily(endpoint)
1603
+ });
1604
+ }
1605
+ };
1606
+ var RawCustomerScopedApi = class {
1607
+ constructor(apiName, options) {
1608
+ this.transport = new CustomerScopedTransport(apiName, options);
1609
+ }
1610
+ request(endpoint, options) {
1611
+ return this.transport.request(endpoint, options);
1612
+ }
1613
+ };
1614
+
1615
+ // src/core/api/benefit-voucher-types.ts
1616
+ var BENEFIT_VOUCHER_VOID_REASONS = [
1617
+ "issued_in_error",
1618
+ "benefit_revoked",
1619
+ "customer_request",
1620
+ "other"
1621
+ ];
1622
+ function invalidBenefitVoucherResponse() {
1623
+ throw createApiError("Invalid benefit voucher response", 200);
1624
+ }
1625
+ function object(value, keys) {
1626
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some((key) => !(key in value)))
1627
+ invalidBenefitVoucherResponse();
1628
+ return value;
1629
+ }
1630
+ var uuid = (v) => typeof v === "string" && (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
1631
+ v
1632
+ ) || v === "00000000-0000-0000-0000-000000000000" || v.toLowerCase() === "ffffffff-ffff-ffff-ffff-ffffffffffff");
1633
+ var time = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}T/.test(v) && Number.isFinite(Date.parse(v)) && new Date(Date.parse(v)).toISOString() === v;
1634
+ var actor = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(v);
1635
+ function parseBenefitVoucher(value, mine = false) {
1636
+ const v = object(value, [
1637
+ "id",
1638
+ "name",
1639
+ "description",
1640
+ "state",
1641
+ "issuedAt",
1642
+ "expiresAt",
1643
+ ...mine ? ["closedAt"] : ["customerId", "definitionId", "source", "closed"]
1644
+ ]);
1645
+ if (!uuid(v.id) || typeof v.name !== "string" || !v.name.length || v.name.length > 120 || v.description !== null && (typeof v.description !== "string" || v.description.length > 1e3) || !["issued", "redeemed", "expired", "voided"].includes(v.state) || !time(v.issuedAt) || !time(v.expiresAt))
1646
+ invalidBenefitVoucherResponse();
1647
+ if (mine) {
1648
+ if (v.closedAt !== null && !time(v.closedAt))
1649
+ invalidBenefitVoucherResponse();
1650
+ } else {
1651
+ if (!uuid(v.customerId) || !uuid(v.definitionId))
1652
+ invalidBenefitVoucherResponse();
1653
+ const source = object(v.source, ["namespace", "ref"]);
1654
+ if (typeof source.namespace !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(source.namespace) || typeof source.ref !== "string" || !source.ref.length || source.ref.length > 256)
1655
+ invalidBenefitVoucherResponse();
1656
+ if (v.closed !== null) {
1657
+ const closed = object(v.closed, [
1658
+ "at",
1659
+ "channel",
1660
+ "actor",
1661
+ "actorRef",
1662
+ "voidReason"
1663
+ ]);
1664
+ const principal = object(closed.actor, ["type", "id"]);
1665
+ if (!time(closed.at) || !uuid(principal.id) || !["server", "console"].includes(closed.channel) || !["server_credential", "operator"].includes(principal.type) || closed.actorRef !== null && !actor(closed.actorRef) || closed.voidReason !== null && !BENEFIT_VOUCHER_VOID_REASONS.includes(closed.voidReason))
1666
+ invalidBenefitVoucherResponse();
1667
+ }
1668
+ }
1669
+ return value;
1670
+ }
1671
+ function parseBenefitVoucherList(value, mine = false) {
1672
+ const v = object(value, ["vouchers", "nextCursor", "evaluatedAt"]);
1673
+ if (!Array.isArray(v.vouchers) || v.vouchers.length > 100 || !time(v.evaluatedAt) || v.nextCursor !== null && (typeof v.nextCursor !== "string" || !v.nextCursor.length || v.nextCursor.length > 2048))
1674
+ invalidBenefitVoucherResponse();
1675
+ for (const row of v.vouchers) {
1676
+ if (mine) parseBenefitVoucher(row, true);
1677
+ else parseBenefitVoucher(row);
1678
+ }
1679
+ return value;
1680
+ }
1681
+
1682
+ // src/core/api/customer-benefit-vouchers-api.ts
1683
+ var CustomerBenefitVouchersApi = class extends CustomerScopedApi {
1684
+ async listMine(params = {}) {
1685
+ const query = new URLSearchParams();
1686
+ for (const [key, value] of Object.entries(params))
1687
+ if (value !== void 0) query.set(key, String(value));
1688
+ return parseBenefitVoucherList(
1689
+ await this.requestEndpoint(
1690
+ BENEFIT_VOUCHER_ENDPOINT_OPERATIONS.listMine,
1691
+ void 0,
1692
+ { query }
1693
+ ),
1694
+ true
1695
+ );
1696
+ }
1697
+ };
1698
+
1699
+ // src/core/collection/http-client.ts
1700
+ var import_qs_esm = require("qs-esm");
1701
+ function validateWhere(where) {
1702
+ if (where === void 0) return false;
1703
+ let hasNull = false;
1704
+ function visit(value, depth, key) {
1705
+ if (depth > 10) {
1706
+ throw createValidationError(
1707
+ "Collection where must not exceed nesting depth 10."
1708
+ );
1709
+ }
1710
+ if (value === null && (key === "equals" || key === "not_equals")) {
1711
+ hasNull = true;
1712
+ return;
1713
+ }
1714
+ if (value == null) {
1715
+ throw createValidationError(
1716
+ "Collection where must not contain null or undefined values."
1717
+ );
1718
+ }
1719
+ if (Array.isArray(value)) {
1720
+ if (value.length === 0) {
1721
+ throw createValidationError(
1722
+ "Collection where must not contain empty arrays, including and/or."
1723
+ );
1724
+ }
1725
+ if (value.length > 1e3) {
1726
+ throw createValidationError(
1727
+ "Collection where arrays must not contain more than 1000 elements."
1728
+ );
1729
+ }
1730
+ for (const item of value) visit(item, depth + 1);
1731
+ } else if (typeof value === "object" && !(value instanceof Date)) {
1732
+ const values = Object.entries(value);
1733
+ if (values.length === 0) {
1734
+ throw createValidationError(
1735
+ "Collection where must not contain empty condition objects."
1736
+ );
1737
+ }
1738
+ for (const [key2, item] of values) visit(item, depth + 1, key2);
1739
+ }
1740
+ }
1741
+ visit(where, 0);
1742
+ return hasNull;
1743
+ }
1744
+ var HttpClient = class {
1745
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1746
+ this.publishableKey = requirePublishableKeyForSecret(
1747
+ "CollectionClient",
1748
+ publishableKey,
1749
+ secretKey
1826
1750
  );
1827
- this.secretKey = options.secretKey;
1828
- this.apiUrl = options.apiUrl;
1829
- this.customerToken = options.customerToken;
1830
- this.onUnauthorized = options.onUnauthorized;
1831
- this.onRequestId = options.onRequestId;
1751
+ this.secretKey = secretKey;
1752
+ this.getCustomerToken = getCustomerToken;
1753
+ this.onUnauthorized = onUnauthorized;
1754
+ this.onRequestId = onRequestId;
1755
+ this.apiUrl = apiUrl;
1832
1756
  }
1833
- async request(endpoint, options) {
1834
- const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
1757
+ get defaultOptions() {
1758
+ const opts = {
1759
+ apiUrl: this.apiUrl,
1760
+ publishableKey: this.publishableKey,
1761
+ secretKey: this.secretKey
1762
+ };
1763
+ const token = this.getCustomerToken?.();
1764
+ if (token) {
1765
+ opts.customerToken = token;
1766
+ if (this.onUnauthorized) {
1767
+ opts.onUnauthorized = this.onUnauthorized;
1768
+ }
1769
+ }
1770
+ return opts;
1771
+ }
1772
+ async fetchWithTracking(url, opts) {
1835
1773
  try {
1836
- const response = await httpFetch(endpoint, {
1837
- method: options.method,
1838
- apiUrl: this.apiUrl,
1839
- publishableKey: this.publishableKey,
1840
- secretKey: this.secretKey,
1841
- customerToken: token ?? void 0,
1842
- ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
1843
- ...options.body !== void 0 && {
1844
- body: JSON.stringify(options.body)
1845
- },
1846
- ...options.headers && { headers: options.headers },
1847
- ...options.errorFamily && { errorFamily: options.errorFamily }
1848
- });
1774
+ const response = await httpFetch(url, opts);
1849
1775
  this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1850
- return parseApiResponse(response, endpoint, {
1851
- errorFamily: options.errorFamily
1852
- });
1776
+ return response;
1853
1777
  } catch (err) {
1854
1778
  const id = err instanceof SDKError ? err.requestId ?? null : null;
1855
1779
  this.onRequestId?.(id);
1856
1780
  throw err;
1857
1781
  }
1858
1782
  }
1783
+ buildUrl(endpoint, options) {
1784
+ if (!options) return endpoint;
1785
+ const { fallbackLocale, ...rest } = options;
1786
+ const queryOptions = fallbackLocale === void 0 ? rest : {
1787
+ ...rest,
1788
+ "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1789
+ };
1790
+ const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1791
+ const queryString = (0, import_qs_esm.stringify)(encodedOptions, { addQueryPrefix: true });
1792
+ return queryString ? `${endpoint}${queryString}` : endpoint;
1793
+ }
1794
+ assertJsonResponse(response) {
1795
+ const contentType = response.headers.get("content-type");
1796
+ if (!contentType?.includes("application/json")) {
1797
+ throw createApiError("Response is not in JSON format.", response.status, {
1798
+ contentType
1799
+ });
1800
+ }
1801
+ }
1802
+ /**
1803
+ * Parse Payload CMS find response (list query)
1804
+ * Returns native Payload response structure
1805
+ */
1806
+ async parseFindResponse(response) {
1807
+ const contentType = response.headers.get("content-type");
1808
+ try {
1809
+ this.assertJsonResponse(response);
1810
+ const jsonData = await response.json();
1811
+ if (jsonData.docs === void 0) {
1812
+ throw createApiError("Invalid find response.", response.status, {
1813
+ jsonData
1814
+ });
1815
+ }
1816
+ return {
1817
+ docs: jsonData.docs,
1818
+ totalDocs: jsonData.totalDocs ?? 0,
1819
+ limit: jsonData.limit || 20,
1820
+ totalPages: jsonData.totalPages ?? 0,
1821
+ page: jsonData.page || 1,
1822
+ pagingCounter: jsonData.pagingCounter || 1,
1823
+ hasPrevPage: jsonData.hasPrevPage ?? false,
1824
+ hasNextPage: jsonData.hasNextPage ?? false,
1825
+ prevPage: jsonData.prevPage ?? null,
1826
+ nextPage: jsonData.nextPage ?? null
1827
+ };
1828
+ } catch (error) {
1829
+ if (error instanceof SDKError) throw error;
1830
+ throw createApiError("Failed to parse response.", response.status, {
1831
+ contentType,
1832
+ error: error instanceof Error ? error.message : error
1833
+ });
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Parse Payload CMS mutation response (create/update)
1838
+ * Returns native Payload response structure
1839
+ */
1840
+ async parseMutationResponse(response) {
1841
+ const contentType = response.headers.get("content-type");
1842
+ try {
1843
+ this.assertJsonResponse(response);
1844
+ const jsonData = await response.json();
1845
+ if (jsonData.doc === void 0) {
1846
+ throw createApiError("Invalid mutation response.", response.status, {
1847
+ jsonData
1848
+ });
1849
+ }
1850
+ return {
1851
+ message: jsonData.message || "",
1852
+ doc: jsonData.doc,
1853
+ errors: jsonData.errors
1854
+ };
1855
+ } catch (error) {
1856
+ if (error instanceof SDKError) throw error;
1857
+ throw createApiError("Failed to parse response.", response.status, {
1858
+ contentType,
1859
+ error: error instanceof Error ? error.message : error
1860
+ });
1861
+ }
1862
+ }
1863
+ /**
1864
+ * Parse Payload CMS document response (findById/delete)
1865
+ * Returns document directly without wrapper
1866
+ */
1867
+ async parseDocumentResponse(response) {
1868
+ const contentType = response.headers.get("content-type");
1869
+ try {
1870
+ this.assertJsonResponse(response);
1871
+ const jsonData = await response.json();
1872
+ return jsonData;
1873
+ } catch (error) {
1874
+ if (error instanceof SDKError) throw error;
1875
+ throw createApiError("Failed to parse response.", response.status, {
1876
+ contentType,
1877
+ error: error instanceof Error ? error.message : error
1878
+ });
1879
+ }
1880
+ }
1859
1881
  };
1860
- var CustomerScopedApi = class {
1861
- constructor(apiName, options) {
1862
- this.transport = new CustomerScopedTransport(apiName, options);
1882
+
1883
+ // src/core/collection/query-builder.ts
1884
+ var PUBLIC_READ_DEPTH_ERROR = "Publishable collection reads require depth: 0. Use a shaped commerce endpoint or server client for populated data.";
1885
+ var PUBLIC_READ_JOINS_ERROR = "Publishable collection reads require joins: false. Use a shaped commerce endpoint or server client for joined data.";
1886
+ var PUBLIC_READ_POPULATE_ERROR = "Publishable collection reads do not support populate. Use a shaped commerce endpoint or server client for populated data.";
1887
+ function withDefaultPublicReadOptions(options) {
1888
+ const rawOptions = options;
1889
+ if (rawOptions?.depth !== void 0 && rawOptions.depth !== 0) {
1890
+ throw createValidationError(PUBLIC_READ_DEPTH_ERROR);
1863
1891
  }
1864
- requestEndpoint(endpoint, body, options) {
1865
- return this.transport.request(resolveOperationPath(endpoint, options), {
1866
- method: resolveOperationMethod(endpoint),
1867
- body,
1868
- headers: options?.headers,
1869
- errorFamily: resolveOperationErrorFamily(endpoint)
1870
- });
1892
+ if (rawOptions?.joins !== void 0 && rawOptions.joins !== false) {
1893
+ throw createValidationError(PUBLIC_READ_JOINS_ERROR);
1894
+ }
1895
+ if (rawOptions?.populate !== void 0) {
1896
+ throw createValidationError(PUBLIC_READ_POPULATE_ERROR);
1897
+ }
1898
+ return {
1899
+ ...options,
1900
+ depth: options?.depth ?? 0,
1901
+ joins: options?.joins ?? false
1902
+ };
1903
+ }
1904
+ var ReadOnlyCollectionQueryBuilder = class {
1905
+ constructor(api, collection) {
1906
+ this.api = api;
1907
+ this.collection = collection;
1908
+ }
1909
+ async find(options) {
1910
+ return this.api.requestFind(
1911
+ `/api/${String(this.collection)}`,
1912
+ withDefaultPublicReadOptions(options)
1913
+ );
1914
+ }
1915
+ async findById(id, options) {
1916
+ return this.api.requestFindById(
1917
+ `/api/${String(this.collection)}/${String(id)}`,
1918
+ withDefaultPublicReadOptions(options)
1919
+ );
1920
+ }
1921
+ async count(options) {
1922
+ return this.api.requestCount(
1923
+ `/api/${String(this.collection)}/count`,
1924
+ withDefaultPublicReadOptions(options)
1925
+ );
1871
1926
  }
1872
1927
  };
1873
- var RawCustomerScopedApi = class {
1874
- constructor(apiName, options) {
1875
- this.transport = new CustomerScopedTransport(apiName, options);
1928
+
1929
+ // src/core/collection/collection-client.ts
1930
+ var ReadOnlyCollectionClient = class extends HttpClient {
1931
+ from(collection) {
1932
+ return new ReadOnlyCollectionQueryBuilder(this, collection);
1876
1933
  }
1877
- request(endpoint, options) {
1878
- return this.transport.request(endpoint, options);
1934
+ async requestFind(endpoint, options) {
1935
+ const url = this.buildUrl(endpoint, options);
1936
+ const response = await this.fetchWithTracking(url, {
1937
+ ...this.defaultOptions,
1938
+ method: "GET"
1939
+ });
1940
+ return this.parseFindResponse(response);
1941
+ }
1942
+ async requestFindEndpoint(endpoint, data) {
1943
+ const response = await this.fetchWithTracking(endpoint, {
1944
+ ...this.defaultOptions,
1945
+ method: "POST",
1946
+ body: data ? JSON.stringify(data) : void 0
1947
+ });
1948
+ return this.parseFindResponse(response);
1949
+ }
1950
+ async requestFindEndpointGet(endpoint) {
1951
+ const response = await this.fetchWithTracking(endpoint, {
1952
+ ...this.defaultOptions,
1953
+ method: "GET"
1954
+ });
1955
+ return this.parseFindResponse(response);
1956
+ }
1957
+ async requestFindById(endpoint, options) {
1958
+ const url = this.buildUrl(endpoint, options);
1959
+ const response = await this.fetchWithTracking(url, {
1960
+ ...this.defaultOptions,
1961
+ method: "GET"
1962
+ });
1963
+ return this.parseDocumentResponse(response);
1964
+ }
1965
+ async requestCount(endpoint, options) {
1966
+ const url = this.buildUrl(endpoint, options);
1967
+ const response = await this.fetchWithTracking(url, {
1968
+ ...this.defaultOptions,
1969
+ method: "GET"
1970
+ });
1971
+ return this.parseDocumentResponse(response);
1879
1972
  }
1880
1973
  };
1881
1974
 
@@ -6486,6 +6579,16 @@ var Client = class _Client {
6486
6579
  this.markets = new MarketDiscovery(
6487
6580
  (options2) => this.collections.from("markets").find(options2)
6488
6581
  );
6582
+ this.benefitVouchers = new CustomerBenefitVouchersApi(
6583
+ "CustomerBenefitVouchersApi",
6584
+ {
6585
+ publishableKey: this.config.publishableKey,
6586
+ apiUrl: this.config.apiUrl,
6587
+ customerToken: () => this.customer.auth.getToken(),
6588
+ onUnauthorized,
6589
+ onRequestId
6590
+ }
6591
+ );
6489
6592
  const membershipApi = new BrowserMembershipApi("MembershipApi", {
6490
6593
  publishableKey: this.config.publishableKey,
6491
6594
  apiUrl: this.config.apiUrl,