@01.software/sdk 0.67.0 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +122 -6
  3. package/dist/client.cjs +419 -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 +419 -319
  8. package/dist/client.js.map +1 -1
  9. package/dist/{collection-client-D4HEOoO_.d.ts → collection-client-IOaWsTMI.d.ts} +4 -4
  10. package/dist/{collection-client-jrNFGbrO.d.cts → collection-client-MbIJ5KzW.d.cts} +4 -4
  11. package/dist/{const-BU79hCFB.d.ts → const-Do27Udj6.d.ts} +2 -2
  12. package/dist/{const-CCQ3MdLE.d.cts → const-Dw5ElJs_.d.cts} +2 -2
  13. package/dist/embedded-admin/server.cjs +16 -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 +16 -1
  18. package/dist/embedded-admin/server.js.map +1 -1
  19. package/dist/embedded-admin.cjs +19 -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 +19 -0
  24. package/dist/embedded-admin.js.map +1 -1
  25. package/dist/errors.d.cts +2 -2
  26. package/dist/errors.d.ts +2 -2
  27. package/dist/{index-CwKxWHIa.d.ts → index-DcYsLOja.d.ts} +3 -3
  28. package/dist/{index-DiyhsVHd.d.cts → index-gnVxTKXu.d.cts} +3 -3
  29. package/dist/index.cjs +424 -323
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +7 -7
  32. package/dist/index.d.ts +7 -7
  33. package/dist/index.js +424 -323
  34. package/dist/index.js.map +1 -1
  35. package/dist/{payload-types-jdsUXunB.d.cts → payload-types-BY1uZFRf.d.cts} +34 -1
  36. package/dist/{payload-types-jdsUXunB.d.ts → payload-types-BY1uZFRf.d.ts} +34 -1
  37. package/dist/query.cjs +8 -0
  38. package/dist/query.cjs.map +1 -1
  39. package/dist/query.d.cts +5 -5
  40. package/dist/query.d.ts +5 -5
  41. package/dist/query.js +8 -0
  42. package/dist/query.js.map +1 -1
  43. package/dist/realtime.d.cts +2 -2
  44. package/dist/realtime.d.ts +2 -2
  45. package/dist/server.cjs +1183 -1071
  46. package/dist/server.cjs.map +1 -1
  47. package/dist/server.d.cts +9 -8
  48. package/dist/server.d.ts +9 -8
  49. package/dist/server.js +1183 -1071
  50. package/dist/server.js.map +1 -1
  51. package/dist/{types-BusejG-v.d.ts → types-AWSVpuPE.d.ts} +2 -2
  52. package/dist/{types-I2k6Laad.d.ts → types-CLRw0aDa.d.ts} +147 -40
  53. package/dist/{types-BPwXAFZ7.d.cts → types-DnIuxgu2.d.cts} +2 -2
  54. package/dist/{types-CvdBV3ri.d.cts → types-csjaig4G.d.cts} +147 -40
  55. package/dist/ui/form.d.cts +1 -1
  56. package/dist/ui/form.d.ts +1 -1
  57. package/dist/ui/video.d.cts +1 -1
  58. package/dist/ui/video.d.ts +1 -1
  59. package/dist/webhook.d.cts +5 -5
  60. package/dist/webhook.d.ts +5 -5
  61. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -141,9 +141,6 @@ __export(src_exports, {
141
141
  });
142
142
  module.exports = __toCommonJS(src_exports);
143
143
 
144
- // src/core/collection/http-client.ts
145
- var import_qs_esm = require("qs-esm");
146
-
147
144
  // src/core/errors.ts
148
145
  var SDK_ERROR_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError");
149
146
  var SDK_ERROR_TYPE_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError.type");
@@ -1147,288 +1144,6 @@ function stockSnapshotSearchParams(params) {
1147
1144
  return `variantIds=${params.variantIds.map(encodeURIComponent).join(",")}`;
1148
1145
  }
1149
1146
 
1150
- // src/core/collection/http-client.ts
1151
- function validateWhere(where) {
1152
- if (where === void 0) return false;
1153
- let hasNull = false;
1154
- function visit(value, depth, key) {
1155
- if (depth > 10) {
1156
- throw createValidationError(
1157
- "Collection where must not exceed nesting depth 10."
1158
- );
1159
- }
1160
- if (value === null && (key === "equals" || key === "not_equals")) {
1161
- hasNull = true;
1162
- return;
1163
- }
1164
- if (value == null) {
1165
- throw createValidationError(
1166
- "Collection where must not contain null or undefined values."
1167
- );
1168
- }
1169
- if (Array.isArray(value)) {
1170
- if (value.length === 0) {
1171
- throw createValidationError(
1172
- "Collection where must not contain empty arrays, including and/or."
1173
- );
1174
- }
1175
- if (value.length > 1e3) {
1176
- throw createValidationError(
1177
- "Collection where arrays must not contain more than 1000 elements."
1178
- );
1179
- }
1180
- for (const item of value) visit(item, depth + 1);
1181
- } else if (typeof value === "object" && !(value instanceof Date)) {
1182
- const values = Object.entries(value);
1183
- if (values.length === 0) {
1184
- throw createValidationError(
1185
- "Collection where must not contain empty condition objects."
1186
- );
1187
- }
1188
- for (const [key2, item] of values) visit(item, depth + 1, key2);
1189
- }
1190
- }
1191
- visit(where, 0);
1192
- return hasNull;
1193
- }
1194
- var HttpClient = class {
1195
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1196
- this.publishableKey = requirePublishableKeyForSecret(
1197
- "CollectionClient",
1198
- publishableKey,
1199
- secretKey
1200
- );
1201
- this.secretKey = secretKey;
1202
- this.getCustomerToken = getCustomerToken;
1203
- this.onUnauthorized = onUnauthorized;
1204
- this.onRequestId = onRequestId;
1205
- this.apiUrl = apiUrl;
1206
- }
1207
- get defaultOptions() {
1208
- const opts = {
1209
- apiUrl: this.apiUrl,
1210
- publishableKey: this.publishableKey,
1211
- secretKey: this.secretKey
1212
- };
1213
- const token = this.getCustomerToken?.();
1214
- if (token) {
1215
- opts.customerToken = token;
1216
- if (this.onUnauthorized) {
1217
- opts.onUnauthorized = this.onUnauthorized;
1218
- }
1219
- }
1220
- return opts;
1221
- }
1222
- async fetchWithTracking(url, opts) {
1223
- try {
1224
- const response = await httpFetch(url, opts);
1225
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1226
- return response;
1227
- } catch (err) {
1228
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1229
- this.onRequestId?.(id);
1230
- throw err;
1231
- }
1232
- }
1233
- buildUrl(endpoint, options) {
1234
- if (!options) return endpoint;
1235
- const { fallbackLocale, ...rest } = options;
1236
- const queryOptions = fallbackLocale === void 0 ? rest : {
1237
- ...rest,
1238
- "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1239
- };
1240
- const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1241
- const queryString = (0, import_qs_esm.stringify)(encodedOptions, { addQueryPrefix: true });
1242
- return queryString ? `${endpoint}${queryString}` : endpoint;
1243
- }
1244
- assertJsonResponse(response) {
1245
- const contentType = response.headers.get("content-type");
1246
- if (!contentType?.includes("application/json")) {
1247
- throw createApiError("Response is not in JSON format.", response.status, {
1248
- contentType
1249
- });
1250
- }
1251
- }
1252
- /**
1253
- * Parse Payload CMS find response (list query)
1254
- * Returns native Payload response structure
1255
- */
1256
- async parseFindResponse(response) {
1257
- const contentType = response.headers.get("content-type");
1258
- try {
1259
- this.assertJsonResponse(response);
1260
- const jsonData = await response.json();
1261
- if (jsonData.docs === void 0) {
1262
- throw createApiError("Invalid find response.", response.status, {
1263
- jsonData
1264
- });
1265
- }
1266
- return {
1267
- docs: jsonData.docs,
1268
- totalDocs: jsonData.totalDocs ?? 0,
1269
- limit: jsonData.limit || 20,
1270
- totalPages: jsonData.totalPages ?? 0,
1271
- page: jsonData.page || 1,
1272
- pagingCounter: jsonData.pagingCounter || 1,
1273
- hasPrevPage: jsonData.hasPrevPage ?? false,
1274
- hasNextPage: jsonData.hasNextPage ?? false,
1275
- prevPage: jsonData.prevPage ?? null,
1276
- nextPage: jsonData.nextPage ?? null
1277
- };
1278
- } catch (error) {
1279
- if (error instanceof SDKError) throw error;
1280
- throw createApiError("Failed to parse response.", response.status, {
1281
- contentType,
1282
- error: error instanceof Error ? error.message : error
1283
- });
1284
- }
1285
- }
1286
- /**
1287
- * Parse Payload CMS mutation response (create/update)
1288
- * Returns native Payload response structure
1289
- */
1290
- async parseMutationResponse(response) {
1291
- const contentType = response.headers.get("content-type");
1292
- try {
1293
- this.assertJsonResponse(response);
1294
- const jsonData = await response.json();
1295
- if (jsonData.doc === void 0) {
1296
- throw createApiError("Invalid mutation response.", response.status, {
1297
- jsonData
1298
- });
1299
- }
1300
- return {
1301
- message: jsonData.message || "",
1302
- doc: jsonData.doc,
1303
- errors: jsonData.errors
1304
- };
1305
- } catch (error) {
1306
- if (error instanceof SDKError) throw error;
1307
- throw createApiError("Failed to parse response.", response.status, {
1308
- contentType,
1309
- error: error instanceof Error ? error.message : error
1310
- });
1311
- }
1312
- }
1313
- /**
1314
- * Parse Payload CMS document response (findById/delete)
1315
- * Returns document directly without wrapper
1316
- */
1317
- async parseDocumentResponse(response) {
1318
- const contentType = response.headers.get("content-type");
1319
- try {
1320
- this.assertJsonResponse(response);
1321
- const jsonData = await response.json();
1322
- return jsonData;
1323
- } catch (error) {
1324
- if (error instanceof SDKError) throw error;
1325
- throw createApiError("Failed to parse response.", response.status, {
1326
- contentType,
1327
- error: error instanceof Error ? error.message : error
1328
- });
1329
- }
1330
- }
1331
- };
1332
-
1333
- // src/utils/types.ts
1334
- function resolveRelation(ref) {
1335
- if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1336
- return null;
1337
- return ref;
1338
- }
1339
-
1340
- // src/core/collection/query-builder.ts
1341
- var PUBLIC_READ_DEPTH_ERROR = "Publishable collection reads require depth: 0. Use a shaped commerce endpoint or server client for populated data.";
1342
- var PUBLIC_READ_JOINS_ERROR = "Publishable collection reads require joins: false. Use a shaped commerce endpoint or server client for joined data.";
1343
- var PUBLIC_READ_POPULATE_ERROR = "Publishable collection reads do not support populate. Use a shaped commerce endpoint or server client for populated data.";
1344
- function withDefaultPublicReadOptions(options) {
1345
- const rawOptions = options;
1346
- if (rawOptions?.depth !== void 0 && rawOptions.depth !== 0) {
1347
- throw createValidationError(PUBLIC_READ_DEPTH_ERROR);
1348
- }
1349
- if (rawOptions?.joins !== void 0 && rawOptions.joins !== false) {
1350
- throw createValidationError(PUBLIC_READ_JOINS_ERROR);
1351
- }
1352
- if (rawOptions?.populate !== void 0) {
1353
- throw createValidationError(PUBLIC_READ_POPULATE_ERROR);
1354
- }
1355
- return {
1356
- ...options,
1357
- depth: options?.depth ?? 0,
1358
- joins: options?.joins ?? false
1359
- };
1360
- }
1361
- var ReadOnlyCollectionQueryBuilder = class {
1362
- constructor(api, collection) {
1363
- this.api = api;
1364
- this.collection = collection;
1365
- }
1366
- async find(options) {
1367
- return this.api.requestFind(
1368
- `/api/${String(this.collection)}`,
1369
- withDefaultPublicReadOptions(options)
1370
- );
1371
- }
1372
- async findById(id, options) {
1373
- return this.api.requestFindById(
1374
- `/api/${String(this.collection)}/${String(id)}`,
1375
- withDefaultPublicReadOptions(options)
1376
- );
1377
- }
1378
- async count(options) {
1379
- return this.api.requestCount(
1380
- `/api/${String(this.collection)}/count`,
1381
- withDefaultPublicReadOptions(options)
1382
- );
1383
- }
1384
- };
1385
-
1386
- // src/core/collection/collection-client.ts
1387
- var ReadOnlyCollectionClient = class extends HttpClient {
1388
- from(collection) {
1389
- return new ReadOnlyCollectionQueryBuilder(this, collection);
1390
- }
1391
- async requestFind(endpoint, options) {
1392
- const url = this.buildUrl(endpoint, options);
1393
- const response = await this.fetchWithTracking(url, {
1394
- ...this.defaultOptions,
1395
- method: "GET"
1396
- });
1397
- return this.parseFindResponse(response);
1398
- }
1399
- async requestFindEndpoint(endpoint, data) {
1400
- const response = await this.fetchWithTracking(endpoint, {
1401
- ...this.defaultOptions,
1402
- method: "POST",
1403
- body: data ? JSON.stringify(data) : void 0
1404
- });
1405
- return this.parseFindResponse(response);
1406
- }
1407
- async requestFindEndpointGet(endpoint) {
1408
- const response = await this.fetchWithTracking(endpoint, {
1409
- ...this.defaultOptions,
1410
- method: "GET"
1411
- });
1412
- return this.parseFindResponse(response);
1413
- }
1414
- async requestFindById(endpoint, options) {
1415
- const url = this.buildUrl(endpoint, options);
1416
- const response = await this.fetchWithTracking(url, {
1417
- ...this.defaultOptions,
1418
- method: "GET"
1419
- });
1420
- return this.parseDocumentResponse(response);
1421
- }
1422
- async requestCount(endpoint, options) {
1423
- const url = this.buildUrl(endpoint, options);
1424
- const response = await this.fetchWithTracking(url, {
1425
- ...this.defaultOptions,
1426
- method: "GET"
1427
- });
1428
- return this.parseDocumentResponse(response);
1429
- }
1430
- };
1431
-
1432
1147
  // src/core/api/parse-response.ts
1433
1148
  async function parseApiResponse(response, endpoint, options = {}) {
1434
1149
  if (response.status === 204 || response.headers.get("content-length") === "0") {
@@ -1690,6 +1405,14 @@ var EXTERNAL_CUSTOMER_LINK_ENDPOINT_OPERATIONS = {
1690
1405
  "/external-links/clear-previous-state"
1691
1406
  )
1692
1407
  };
1408
+ var BENEFIT_VOUCHER_ENDPOINT_OPERATIONS = {
1409
+ issue: operation("customers", "post", "/benefit-vouchers/issue"),
1410
+ get: operation("customers", "post", "/benefit-vouchers/get"),
1411
+ list: operation("customers", "post", "/benefit-vouchers/list"),
1412
+ redeem: operation("customers", "post", "/benefit-vouchers/redeem"),
1413
+ void: operation("customers", "post", "/benefit-vouchers/void"),
1414
+ listMine: operation("customers", "get", "/me/benefit-vouchers")
1415
+ };
1693
1416
  var CUSTOMER_GROUP_ENDPOINT_OPERATIONS = {
1694
1417
  members: operation("customer-groups", "get", "/:id/members"),
1695
1418
  grant: operation("customer-groups", "post", "/:id/members/grant"),
@@ -1931,58 +1654,425 @@ var CustomerScopedTransport = class {
1931
1654
  options.publishableKey,
1932
1655
  options.secretKey
1933
1656
  );
1934
- this.secretKey = options.secretKey;
1935
- this.apiUrl = options.apiUrl;
1936
- this.customerToken = options.customerToken;
1937
- this.onUnauthorized = options.onUnauthorized;
1938
- this.onRequestId = options.onRequestId;
1657
+ this.secretKey = options.secretKey;
1658
+ this.apiUrl = options.apiUrl;
1659
+ this.customerToken = options.customerToken;
1660
+ this.onUnauthorized = options.onUnauthorized;
1661
+ this.onRequestId = options.onRequestId;
1662
+ }
1663
+ async request(endpoint, options) {
1664
+ const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
1665
+ try {
1666
+ const response = await httpFetch(endpoint, {
1667
+ method: options.method,
1668
+ apiUrl: this.apiUrl,
1669
+ publishableKey: this.publishableKey,
1670
+ secretKey: this.secretKey,
1671
+ customerToken: token ?? void 0,
1672
+ ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
1673
+ ...options.body !== void 0 && {
1674
+ body: JSON.stringify(options.body)
1675
+ },
1676
+ ...options.headers && { headers: options.headers },
1677
+ ...options.errorFamily && { errorFamily: options.errorFamily }
1678
+ });
1679
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1680
+ return parseApiResponse(response, endpoint, {
1681
+ errorFamily: options.errorFamily
1682
+ });
1683
+ } catch (err) {
1684
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1685
+ this.onRequestId?.(id);
1686
+ throw err;
1687
+ }
1688
+ }
1689
+ };
1690
+ var CustomerScopedApi = class {
1691
+ constructor(apiName, options) {
1692
+ this.transport = new CustomerScopedTransport(apiName, options);
1693
+ }
1694
+ requestEndpoint(endpoint, body, options) {
1695
+ return this.transport.request(resolveOperationPath(endpoint, options), {
1696
+ method: resolveOperationMethod(endpoint),
1697
+ body,
1698
+ headers: options?.headers,
1699
+ errorFamily: resolveOperationErrorFamily(endpoint)
1700
+ });
1701
+ }
1702
+ };
1703
+ var RawCustomerScopedApi = class {
1704
+ constructor(apiName, options) {
1705
+ this.transport = new CustomerScopedTransport(apiName, options);
1706
+ }
1707
+ request(endpoint, options) {
1708
+ return this.transport.request(endpoint, options);
1709
+ }
1710
+ };
1711
+
1712
+ // src/core/api/benefit-voucher-types.ts
1713
+ var BENEFIT_VOUCHER_VOID_REASONS = [
1714
+ "issued_in_error",
1715
+ "benefit_revoked",
1716
+ "customer_request",
1717
+ "other"
1718
+ ];
1719
+ function invalidBenefitVoucherResponse() {
1720
+ throw createApiError("Invalid benefit voucher response", 200);
1721
+ }
1722
+ function object(value, keys) {
1723
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some((key) => !(key in value)))
1724
+ invalidBenefitVoucherResponse();
1725
+ return value;
1726
+ }
1727
+ 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(
1728
+ v
1729
+ ) || v === "00000000-0000-0000-0000-000000000000" || v.toLowerCase() === "ffffffff-ffff-ffff-ffff-ffffffffffff");
1730
+ 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;
1731
+ var actor = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(v);
1732
+ function parseBenefitVoucher(value, mine = false) {
1733
+ const v = object(value, [
1734
+ "id",
1735
+ "name",
1736
+ "description",
1737
+ "state",
1738
+ "issuedAt",
1739
+ "expiresAt",
1740
+ ...mine ? ["closedAt"] : ["customerId", "definitionId", "source", "closed"]
1741
+ ]);
1742
+ 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))
1743
+ invalidBenefitVoucherResponse();
1744
+ if (mine) {
1745
+ if (v.closedAt !== null && !time(v.closedAt))
1746
+ invalidBenefitVoucherResponse();
1747
+ } else {
1748
+ if (!uuid(v.customerId) || !uuid(v.definitionId))
1749
+ invalidBenefitVoucherResponse();
1750
+ const source = object(v.source, ["namespace", "ref"]);
1751
+ 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)
1752
+ invalidBenefitVoucherResponse();
1753
+ if (v.closed !== null) {
1754
+ const closed = object(v.closed, [
1755
+ "at",
1756
+ "channel",
1757
+ "actor",
1758
+ "actorRef",
1759
+ "voidReason"
1760
+ ]);
1761
+ const principal = object(closed.actor, ["type", "id"]);
1762
+ 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))
1763
+ invalidBenefitVoucherResponse();
1764
+ }
1765
+ }
1766
+ return value;
1767
+ }
1768
+ function parseBenefitVoucherList(value, mine = false) {
1769
+ const v = object(value, ["vouchers", "nextCursor", "evaluatedAt"]);
1770
+ 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))
1771
+ invalidBenefitVoucherResponse();
1772
+ for (const row of v.vouchers) {
1773
+ if (mine) parseBenefitVoucher(row, true);
1774
+ else parseBenefitVoucher(row);
1775
+ }
1776
+ return value;
1777
+ }
1778
+
1779
+ // src/core/api/customer-benefit-vouchers-api.ts
1780
+ var CustomerBenefitVouchersApi = class extends CustomerScopedApi {
1781
+ async listMine(params = {}) {
1782
+ const query = new URLSearchParams();
1783
+ for (const [key, value] of Object.entries(params))
1784
+ if (value !== void 0) query.set(key, String(value));
1785
+ return parseBenefitVoucherList(
1786
+ await this.requestEndpoint(
1787
+ BENEFIT_VOUCHER_ENDPOINT_OPERATIONS.listMine,
1788
+ void 0,
1789
+ { query }
1790
+ ),
1791
+ true
1792
+ );
1793
+ }
1794
+ };
1795
+
1796
+ // src/core/collection/http-client.ts
1797
+ var import_qs_esm = require("qs-esm");
1798
+ function validateWhere(where) {
1799
+ if (where === void 0) return false;
1800
+ let hasNull = false;
1801
+ function visit(value, depth, key) {
1802
+ if (depth > 10) {
1803
+ throw createValidationError(
1804
+ "Collection where must not exceed nesting depth 10."
1805
+ );
1806
+ }
1807
+ if (value === null && (key === "equals" || key === "not_equals")) {
1808
+ hasNull = true;
1809
+ return;
1810
+ }
1811
+ if (value == null) {
1812
+ throw createValidationError(
1813
+ "Collection where must not contain null or undefined values."
1814
+ );
1815
+ }
1816
+ if (Array.isArray(value)) {
1817
+ if (value.length === 0) {
1818
+ throw createValidationError(
1819
+ "Collection where must not contain empty arrays, including and/or."
1820
+ );
1821
+ }
1822
+ if (value.length > 1e3) {
1823
+ throw createValidationError(
1824
+ "Collection where arrays must not contain more than 1000 elements."
1825
+ );
1826
+ }
1827
+ for (const item of value) visit(item, depth + 1);
1828
+ } else if (typeof value === "object" && !(value instanceof Date)) {
1829
+ const values = Object.entries(value);
1830
+ if (values.length === 0) {
1831
+ throw createValidationError(
1832
+ "Collection where must not contain empty condition objects."
1833
+ );
1834
+ }
1835
+ for (const [key2, item] of values) visit(item, depth + 1, key2);
1836
+ }
1837
+ }
1838
+ visit(where, 0);
1839
+ return hasNull;
1840
+ }
1841
+ var HttpClient = class {
1842
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1843
+ this.publishableKey = requirePublishableKeyForSecret(
1844
+ "CollectionClient",
1845
+ publishableKey,
1846
+ secretKey
1847
+ );
1848
+ this.secretKey = secretKey;
1849
+ this.getCustomerToken = getCustomerToken;
1850
+ this.onUnauthorized = onUnauthorized;
1851
+ this.onRequestId = onRequestId;
1852
+ this.apiUrl = apiUrl;
1939
1853
  }
1940
- async request(endpoint, options) {
1941
- const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
1854
+ get defaultOptions() {
1855
+ const opts = {
1856
+ apiUrl: this.apiUrl,
1857
+ publishableKey: this.publishableKey,
1858
+ secretKey: this.secretKey
1859
+ };
1860
+ const token = this.getCustomerToken?.();
1861
+ if (token) {
1862
+ opts.customerToken = token;
1863
+ if (this.onUnauthorized) {
1864
+ opts.onUnauthorized = this.onUnauthorized;
1865
+ }
1866
+ }
1867
+ return opts;
1868
+ }
1869
+ async fetchWithTracking(url, opts) {
1942
1870
  try {
1943
- const response = await httpFetch(endpoint, {
1944
- method: options.method,
1945
- apiUrl: this.apiUrl,
1946
- publishableKey: this.publishableKey,
1947
- secretKey: this.secretKey,
1948
- customerToken: token ?? void 0,
1949
- ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
1950
- ...options.body !== void 0 && {
1951
- body: JSON.stringify(options.body)
1952
- },
1953
- ...options.headers && { headers: options.headers },
1954
- ...options.errorFamily && { errorFamily: options.errorFamily }
1955
- });
1871
+ const response = await httpFetch(url, opts);
1956
1872
  this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1957
- return parseApiResponse(response, endpoint, {
1958
- errorFamily: options.errorFamily
1959
- });
1873
+ return response;
1960
1874
  } catch (err) {
1961
1875
  const id = err instanceof SDKError ? err.requestId ?? null : null;
1962
1876
  this.onRequestId?.(id);
1963
1877
  throw err;
1964
1878
  }
1965
1879
  }
1880
+ buildUrl(endpoint, options) {
1881
+ if (!options) return endpoint;
1882
+ const { fallbackLocale, ...rest } = options;
1883
+ const queryOptions = fallbackLocale === void 0 ? rest : {
1884
+ ...rest,
1885
+ "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1886
+ };
1887
+ const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1888
+ const queryString = (0, import_qs_esm.stringify)(encodedOptions, { addQueryPrefix: true });
1889
+ return queryString ? `${endpoint}${queryString}` : endpoint;
1890
+ }
1891
+ assertJsonResponse(response) {
1892
+ const contentType = response.headers.get("content-type");
1893
+ if (!contentType?.includes("application/json")) {
1894
+ throw createApiError("Response is not in JSON format.", response.status, {
1895
+ contentType
1896
+ });
1897
+ }
1898
+ }
1899
+ /**
1900
+ * Parse Payload CMS find response (list query)
1901
+ * Returns native Payload response structure
1902
+ */
1903
+ async parseFindResponse(response) {
1904
+ const contentType = response.headers.get("content-type");
1905
+ try {
1906
+ this.assertJsonResponse(response);
1907
+ const jsonData = await response.json();
1908
+ if (jsonData.docs === void 0) {
1909
+ throw createApiError("Invalid find response.", response.status, {
1910
+ jsonData
1911
+ });
1912
+ }
1913
+ return {
1914
+ docs: jsonData.docs,
1915
+ totalDocs: jsonData.totalDocs ?? 0,
1916
+ limit: jsonData.limit || 20,
1917
+ totalPages: jsonData.totalPages ?? 0,
1918
+ page: jsonData.page || 1,
1919
+ pagingCounter: jsonData.pagingCounter || 1,
1920
+ hasPrevPage: jsonData.hasPrevPage ?? false,
1921
+ hasNextPage: jsonData.hasNextPage ?? false,
1922
+ prevPage: jsonData.prevPage ?? null,
1923
+ nextPage: jsonData.nextPage ?? null
1924
+ };
1925
+ } catch (error) {
1926
+ if (error instanceof SDKError) throw error;
1927
+ throw createApiError("Failed to parse response.", response.status, {
1928
+ contentType,
1929
+ error: error instanceof Error ? error.message : error
1930
+ });
1931
+ }
1932
+ }
1933
+ /**
1934
+ * Parse Payload CMS mutation response (create/update)
1935
+ * Returns native Payload response structure
1936
+ */
1937
+ async parseMutationResponse(response) {
1938
+ const contentType = response.headers.get("content-type");
1939
+ try {
1940
+ this.assertJsonResponse(response);
1941
+ const jsonData = await response.json();
1942
+ if (jsonData.doc === void 0) {
1943
+ throw createApiError("Invalid mutation response.", response.status, {
1944
+ jsonData
1945
+ });
1946
+ }
1947
+ return {
1948
+ message: jsonData.message || "",
1949
+ doc: jsonData.doc,
1950
+ errors: jsonData.errors
1951
+ };
1952
+ } catch (error) {
1953
+ if (error instanceof SDKError) throw error;
1954
+ throw createApiError("Failed to parse response.", response.status, {
1955
+ contentType,
1956
+ error: error instanceof Error ? error.message : error
1957
+ });
1958
+ }
1959
+ }
1960
+ /**
1961
+ * Parse Payload CMS document response (findById/delete)
1962
+ * Returns document directly without wrapper
1963
+ */
1964
+ async parseDocumentResponse(response) {
1965
+ const contentType = response.headers.get("content-type");
1966
+ try {
1967
+ this.assertJsonResponse(response);
1968
+ const jsonData = await response.json();
1969
+ return jsonData;
1970
+ } catch (error) {
1971
+ if (error instanceof SDKError) throw error;
1972
+ throw createApiError("Failed to parse response.", response.status, {
1973
+ contentType,
1974
+ error: error instanceof Error ? error.message : error
1975
+ });
1976
+ }
1977
+ }
1966
1978
  };
1967
- var CustomerScopedApi = class {
1968
- constructor(apiName, options) {
1969
- this.transport = new CustomerScopedTransport(apiName, options);
1979
+
1980
+ // src/utils/types.ts
1981
+ function resolveRelation(ref) {
1982
+ if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1983
+ return null;
1984
+ return ref;
1985
+ }
1986
+
1987
+ // src/core/collection/query-builder.ts
1988
+ var PUBLIC_READ_DEPTH_ERROR = "Publishable collection reads require depth: 0. Use a shaped commerce endpoint or server client for populated data.";
1989
+ var PUBLIC_READ_JOINS_ERROR = "Publishable collection reads require joins: false. Use a shaped commerce endpoint or server client for joined data.";
1990
+ var PUBLIC_READ_POPULATE_ERROR = "Publishable collection reads do not support populate. Use a shaped commerce endpoint or server client for populated data.";
1991
+ function withDefaultPublicReadOptions(options) {
1992
+ const rawOptions = options;
1993
+ if (rawOptions?.depth !== void 0 && rawOptions.depth !== 0) {
1994
+ throw createValidationError(PUBLIC_READ_DEPTH_ERROR);
1970
1995
  }
1971
- requestEndpoint(endpoint, body, options) {
1972
- return this.transport.request(resolveOperationPath(endpoint, options), {
1973
- method: resolveOperationMethod(endpoint),
1974
- body,
1975
- headers: options?.headers,
1976
- errorFamily: resolveOperationErrorFamily(endpoint)
1977
- });
1996
+ if (rawOptions?.joins !== void 0 && rawOptions.joins !== false) {
1997
+ throw createValidationError(PUBLIC_READ_JOINS_ERROR);
1998
+ }
1999
+ if (rawOptions?.populate !== void 0) {
2000
+ throw createValidationError(PUBLIC_READ_POPULATE_ERROR);
2001
+ }
2002
+ return {
2003
+ ...options,
2004
+ depth: options?.depth ?? 0,
2005
+ joins: options?.joins ?? false
2006
+ };
2007
+ }
2008
+ var ReadOnlyCollectionQueryBuilder = class {
2009
+ constructor(api, collection) {
2010
+ this.api = api;
2011
+ this.collection = collection;
2012
+ }
2013
+ async find(options) {
2014
+ return this.api.requestFind(
2015
+ `/api/${String(this.collection)}`,
2016
+ withDefaultPublicReadOptions(options)
2017
+ );
2018
+ }
2019
+ async findById(id, options) {
2020
+ return this.api.requestFindById(
2021
+ `/api/${String(this.collection)}/${String(id)}`,
2022
+ withDefaultPublicReadOptions(options)
2023
+ );
2024
+ }
2025
+ async count(options) {
2026
+ return this.api.requestCount(
2027
+ `/api/${String(this.collection)}/count`,
2028
+ withDefaultPublicReadOptions(options)
2029
+ );
1978
2030
  }
1979
2031
  };
1980
- var RawCustomerScopedApi = class {
1981
- constructor(apiName, options) {
1982
- this.transport = new CustomerScopedTransport(apiName, options);
2032
+
2033
+ // src/core/collection/collection-client.ts
2034
+ var ReadOnlyCollectionClient = class extends HttpClient {
2035
+ from(collection) {
2036
+ return new ReadOnlyCollectionQueryBuilder(this, collection);
1983
2037
  }
1984
- request(endpoint, options) {
1985
- return this.transport.request(endpoint, options);
2038
+ async requestFind(endpoint, options) {
2039
+ const url = this.buildUrl(endpoint, options);
2040
+ const response = await this.fetchWithTracking(url, {
2041
+ ...this.defaultOptions,
2042
+ method: "GET"
2043
+ });
2044
+ return this.parseFindResponse(response);
2045
+ }
2046
+ async requestFindEndpoint(endpoint, data) {
2047
+ const response = await this.fetchWithTracking(endpoint, {
2048
+ ...this.defaultOptions,
2049
+ method: "POST",
2050
+ body: data ? JSON.stringify(data) : void 0
2051
+ });
2052
+ return this.parseFindResponse(response);
2053
+ }
2054
+ async requestFindEndpointGet(endpoint) {
2055
+ const response = await this.fetchWithTracking(endpoint, {
2056
+ ...this.defaultOptions,
2057
+ method: "GET"
2058
+ });
2059
+ return this.parseFindResponse(response);
2060
+ }
2061
+ async requestFindById(endpoint, options) {
2062
+ const url = this.buildUrl(endpoint, options);
2063
+ const response = await this.fetchWithTracking(url, {
2064
+ ...this.defaultOptions,
2065
+ method: "GET"
2066
+ });
2067
+ return this.parseDocumentResponse(response);
2068
+ }
2069
+ async requestCount(endpoint, options) {
2070
+ const url = this.buildUrl(endpoint, options);
2071
+ const response = await this.fetchWithTracking(url, {
2072
+ ...this.defaultOptions,
2073
+ method: "GET"
2074
+ });
2075
+ return this.parseDocumentResponse(response);
1986
2076
  }
1987
2077
  };
1988
2078
 
@@ -7313,6 +7403,16 @@ var Client = class _Client {
7313
7403
  this.markets = new MarketDiscovery(
7314
7404
  (options2) => this.collections.from("markets").find(options2)
7315
7405
  );
7406
+ this.benefitVouchers = new CustomerBenefitVouchersApi(
7407
+ "CustomerBenefitVouchersApi",
7408
+ {
7409
+ publishableKey: this.config.publishableKey,
7410
+ apiUrl: this.config.apiUrl,
7411
+ customerToken: () => this.customer.auth.getToken(),
7412
+ onUnauthorized,
7413
+ onRequestId
7414
+ }
7415
+ );
7316
7416
  const membershipApi = new BrowserMembershipApi("MembershipApi", {
7317
7417
  publishableKey: this.config.publishableKey,
7318
7418
  apiUrl: this.config.apiUrl,
@@ -7692,6 +7792,7 @@ function createTypedWebhookHandler(collection, handler) {
7692
7792
 
7693
7793
  // src/core/collection/const.ts
7694
7794
  var INTERNAL_COLLECTIONS = [
7795
+ "benefit-voucher-definitions",
7695
7796
  "users",
7696
7797
  "payload-kv",
7697
7798
  "payload-locked-documents",