@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/server.js CHANGED
@@ -1,6 +1,3 @@
1
- // src/core/collection/http-client.ts
2
- import { stringify } from "qs-esm";
3
-
4
1
  // src/core/errors.ts
5
2
  var SDK_ERROR_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError");
6
3
  var SDK_ERROR_TYPE_BRAND = /* @__PURE__ */ Symbol.for("@01.software/sdk/SDKError.type");
@@ -1004,1046 +1001,1234 @@ function stockSnapshotSearchParams(params) {
1004
1001
  return `variantIds=${params.variantIds.map(encodeURIComponent).join(",")}`;
1005
1002
  }
1006
1003
 
1007
- // src/core/collection/http-client.ts
1008
- function validateWhere(where) {
1009
- if (where === void 0) return false;
1010
- let hasNull = false;
1011
- function visit(value, depth, key) {
1012
- if (depth > 10) {
1013
- throw createValidationError(
1014
- "Collection where must not exceed nesting depth 10."
1015
- );
1016
- }
1017
- if (value === null && (key === "equals" || key === "not_equals")) {
1018
- hasNull = true;
1019
- return;
1020
- }
1021
- if (value == null) {
1022
- throw createValidationError(
1023
- "Collection where must not contain null or undefined values."
1024
- );
1025
- }
1026
- if (Array.isArray(value)) {
1027
- if (value.length === 0) {
1028
- throw createValidationError(
1029
- "Collection where must not contain empty arrays, including and/or."
1030
- );
1031
- }
1032
- if (value.length > 1e3) {
1033
- throw createValidationError(
1034
- "Collection where arrays must not contain more than 1000 elements."
1035
- );
1036
- }
1037
- for (const item of value) visit(item, depth + 1);
1038
- } else if (typeof value === "object" && !(value instanceof Date)) {
1039
- const values = Object.entries(value);
1040
- if (values.length === 0) {
1041
- throw createValidationError(
1042
- "Collection where must not contain empty condition objects."
1043
- );
1044
- }
1045
- for (const [key2, item] of values) visit(item, depth + 1, key2);
1046
- }
1004
+ // src/core/api/parse-response.ts
1005
+ async function parseApiResponse(response, endpoint, options = {}) {
1006
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
1007
+ return void 0;
1047
1008
  }
1048
- visit(where, 0);
1049
- return hasNull;
1050
- }
1051
- var HttpClient = class {
1052
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1053
- this.publishableKey = requirePublishableKeyForSecret(
1054
- "CollectionClient",
1055
- publishableKey,
1056
- secretKey
1009
+ let parsed;
1010
+ try {
1011
+ parsed = await response.json();
1012
+ } catch {
1013
+ throw createApiError(
1014
+ `Invalid JSON response from ${endpoint}`,
1015
+ response.status,
1016
+ void 0,
1017
+ "Server returned an invalid response.",
1018
+ "Check if the API endpoint is available."
1057
1019
  );
1058
- this.secretKey = secretKey;
1059
- this.getCustomerToken = getCustomerToken;
1060
- this.onUnauthorized = onUnauthorized;
1061
- this.onRequestId = onRequestId;
1062
- this.apiUrl = apiUrl;
1063
- }
1064
- get defaultOptions() {
1065
- const opts = {
1066
- apiUrl: this.apiUrl,
1067
- publishableKey: this.publishableKey,
1068
- secretKey: this.secretKey
1069
- };
1070
- const token = this.getCustomerToken?.();
1071
- if (token) {
1072
- opts.customerToken = token;
1073
- if (this.onUnauthorized) {
1074
- opts.onUnauthorized = this.onUnauthorized;
1075
- }
1076
- }
1077
- return opts;
1078
- }
1079
- async fetchWithTracking(url, opts) {
1080
- try {
1081
- const response = await httpFetch(url, opts);
1082
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1083
- return response;
1084
- } catch (err) {
1085
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1086
- this.onRequestId?.(id);
1087
- throw err;
1088
- }
1089
- }
1090
- buildUrl(endpoint, options) {
1091
- if (!options) return endpoint;
1092
- const { fallbackLocale, ...rest } = options;
1093
- const queryOptions = fallbackLocale === void 0 ? rest : {
1094
- ...rest,
1095
- "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1096
- };
1097
- const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1098
- const queryString = stringify(encodedOptions, { addQueryPrefix: true });
1099
- return queryString ? `${endpoint}${queryString}` : endpoint;
1100
- }
1101
- assertJsonResponse(response) {
1102
- const contentType = response.headers.get("content-type");
1103
- if (!contentType?.includes("application/json")) {
1104
- throw createApiError("Response is not in JSON format.", response.status, {
1105
- contentType
1106
- });
1107
- }
1108
- }
1109
- /**
1110
- * Parse Payload CMS find response (list query)
1111
- * Returns native Payload response structure
1112
- */
1113
- async parseFindResponse(response) {
1114
- const contentType = response.headers.get("content-type");
1115
- try {
1116
- this.assertJsonResponse(response);
1117
- const jsonData = await response.json();
1118
- if (jsonData.docs === void 0) {
1119
- throw createApiError("Invalid find response.", response.status, {
1120
- jsonData
1121
- });
1122
- }
1123
- return {
1124
- docs: jsonData.docs,
1125
- totalDocs: jsonData.totalDocs ?? 0,
1126
- limit: jsonData.limit || 20,
1127
- totalPages: jsonData.totalPages ?? 0,
1128
- page: jsonData.page || 1,
1129
- pagingCounter: jsonData.pagingCounter || 1,
1130
- hasPrevPage: jsonData.hasPrevPage ?? false,
1131
- hasNextPage: jsonData.hasNextPage ?? false,
1132
- prevPage: jsonData.prevPage ?? null,
1133
- nextPage: jsonData.nextPage ?? null
1134
- };
1135
- } catch (error) {
1136
- if (error instanceof SDKError) throw error;
1137
- throw createApiError("Failed to parse response.", response.status, {
1138
- contentType,
1139
- error: error instanceof Error ? error.message : error
1140
- });
1141
- }
1142
1020
  }
1143
- /**
1144
- * Parse Payload CMS mutation response (create/update)
1145
- * Returns native Payload response structure
1146
- */
1147
- async parseMutationResponse(response) {
1148
- const contentType = response.headers.get("content-type");
1149
- try {
1150
- this.assertJsonResponse(response);
1151
- const jsonData = await response.json();
1152
- if (jsonData.doc === void 0) {
1153
- throw createApiError("Invalid mutation response.", response.status, {
1154
- jsonData
1155
- });
1156
- }
1157
- return {
1158
- message: jsonData.message || "",
1159
- doc: jsonData.doc,
1160
- errors: jsonData.errors
1161
- };
1162
- } catch (error) {
1163
- if (error instanceof SDKError) throw error;
1164
- throw createApiError("Failed to parse response.", response.status, {
1165
- contentType,
1166
- error: error instanceof Error ? error.message : error
1167
- });
1168
- }
1021
+ if (parsed === null || typeof parsed !== "object") {
1022
+ return parsed;
1169
1023
  }
1170
- /**
1171
- * Parse Payload CMS document response (findById/delete)
1172
- * Returns document directly without wrapper
1173
- */
1174
- async parseDocumentResponse(response) {
1175
- const contentType = response.headers.get("content-type");
1176
- try {
1177
- this.assertJsonResponse(response);
1178
- const jsonData = await response.json();
1179
- return jsonData;
1180
- } catch (error) {
1181
- if (error instanceof SDKError) throw error;
1182
- throw createApiError("Failed to parse response.", response.status, {
1183
- contentType,
1184
- error: error instanceof Error ? error.message : error
1185
- });
1024
+ const data = parsed;
1025
+ const hasCommerceEnvelopeSignal = options.errorFamily === "commerce" && ["error", "reason", "requestId", "retryable", "details"].some(
1026
+ (key) => Object.prototype.hasOwnProperty.call(data, key)
1027
+ );
1028
+ if (data.error || hasCommerceEnvelopeSignal) {
1029
+ const errorMessage = typeof data.error === "string" ? data.error : "Unknown API error";
1030
+ const reason = typeof data.reason === "string" ? data.reason : void 0;
1031
+ const requestId = response.headers.get("x-request-id") ?? void 0;
1032
+ const retryAfter = parseRetryAfter(response).seconds;
1033
+ let error;
1034
+ if (reason === "validation_failed") {
1035
+ error = createValidationError(errorMessage, data, errorMessage);
1036
+ } else if (reason === "token_expired" || reason === "token_invalid" || reason === "preview_token_invalid" || reason === "preview_token_required" || reason === "key_invalid" || reason === "key_revoked") {
1037
+ error = createAuthError(errorMessage, data, errorMessage);
1038
+ } else if (reason === "forbidden") {
1039
+ error = createPermissionError(errorMessage, data, errorMessage);
1040
+ } else if (reason === "rate_limit_exceeded") {
1041
+ error = createRateLimitError(errorMessage, retryAfter, data, errorMessage);
1042
+ } else if (reason === "not_found") {
1043
+ error = createNotFoundError(errorMessage, data, errorMessage);
1044
+ } else if (reason === "conflict") {
1045
+ error = createConflictError(errorMessage, data, errorMessage);
1046
+ } else {
1047
+ error = createApiError(
1048
+ errorMessage,
1049
+ response.status,
1050
+ data,
1051
+ errorMessage,
1052
+ "An error occurred while processing the request."
1053
+ );
1186
1054
  }
1055
+ const withRequestId = attachRequestId(error, requestId);
1056
+ if (retryAfter !== void 0) Object.assign(withRequestId, { retryAfter });
1057
+ throw options.errorFamily === "commerce" ? enhanceCommerceError(withRequestId, data, requestId) : enhanceNonCommerceError(withRequestId, reason);
1187
1058
  }
1188
- };
1189
-
1190
- // src/utils/types.ts
1191
- function resolveRelation(ref) {
1192
- if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1193
- return null;
1194
- return ref;
1059
+ return data;
1195
1060
  }
1196
1061
 
1197
- // src/core/metadata/index.ts
1198
- var OPEN_GRAPH_IMAGE_SIZE = "1200";
1199
- var LEGACY_OPEN_GRAPH_IMAGE_SIZE = "1536";
1200
- function extractSeo(doc) {
1201
- const seo = doc.seo ?? {};
1202
- const og = seo.openGraph ?? {};
1203
- return {
1204
- title: seo.title ?? doc.title ?? null,
1205
- description: seo.description ?? null,
1206
- noIndex: seo.noIndex ?? null,
1207
- canonical: seo.canonical ?? null,
1208
- openGraph: {
1209
- title: og.title ?? null,
1210
- description: og.description ?? null,
1211
- image: og.image ?? null
1212
- }
1213
- };
1214
- }
1215
- function generateMetadata(input, options) {
1216
- const title = input.title ?? void 0;
1217
- const description = input.description ?? void 0;
1218
- const ogTitle = input.openGraph?.title ?? title;
1219
- const ogDescription = input.openGraph?.description ?? description;
1220
- const image = resolveMetaImage(input.openGraph?.image);
1221
- return {
1222
- title,
1223
- description,
1224
- ...input.noIndex && { robots: { index: false, follow: false } },
1225
- ...input.canonical && { alternates: { canonical: input.canonical } },
1226
- openGraph: {
1227
- ...ogTitle && { title: ogTitle },
1228
- ...ogDescription && { description: ogDescription },
1229
- ...options?.siteName && { siteName: options.siteName },
1230
- ...image && { images: [image] }
1062
+ // ../../internal/http-contracts/src/index.ts
1063
+ var operationBrand = /* @__PURE__ */ Symbol("sdk-http-operation");
1064
+ var PORTONE_STANDARD_ACTION_CAPABILITIES_MEDIA_TYPE = "application/vnd.01software.portone-action-capabilities.v1+json";
1065
+ var operation = (collection, method, path, errorFamily) => Object.freeze({
1066
+ [operationBrand]: true,
1067
+ collection,
1068
+ method,
1069
+ path,
1070
+ ...errorFamily && { errorFamily }
1071
+ });
1072
+ var strictCommerceOperation = (collection, method, path) => operation(collection, method, path, "commerce");
1073
+ var selectiveCommerceOperation = (collection, method, path, typedCommerceErrorReasons) => Object.freeze({
1074
+ ...operation(collection, method, path),
1075
+ typedCommerceErrorReasons: Object.freeze([...typedCommerceErrorReasons])
1076
+ });
1077
+ var COMMERCE_ENDPOINT_OPERATIONS = {
1078
+ products: {
1079
+ detail: operation("products", "get", "/detail"),
1080
+ detailCatalog: operation("products", "get", "/detail/catalog"),
1081
+ listingGroups: operation("products", "get", "/listing-groups"),
1082
+ listingGroupsCatalog: operation(
1083
+ "products",
1084
+ "get",
1085
+ "/listing-groups/catalog"
1086
+ ),
1087
+ listingGroupsQuery: operation("products", "post", "/listing-groups/query"),
1088
+ listingGroupsQueryGet: operation(
1089
+ "products",
1090
+ "get",
1091
+ "/listing-groups/query"
1092
+ ),
1093
+ listingGroupsQueryCatalog: operation(
1094
+ "products",
1095
+ "get",
1096
+ "/listing-groups/query/catalog"
1097
+ ),
1098
+ stockCheck: operation("products", "post", "/stock-check"),
1099
+ stockSnapshot: operation("products", "get", "/stock"),
1100
+ upsert: operation("products", "post", "/upsert"),
1101
+ graphRevision: operation("products", "get", "/:id/graph-revision"),
1102
+ variantsPatch: operation("products", "patch", "/:id/variants")
1103
+ },
1104
+ orders: {
1105
+ create: operation("orders", "post", "/create"),
1106
+ update: operation("orders", "post", "/update"),
1107
+ confirmPayment: operation("orders", "post", "/confirm-payment"),
1108
+ byPayment: operation("orders", "get", "/by-payment"),
1109
+ cancel: operation("orders", "post", "/cancel"),
1110
+ resolveCancelRefund: selectiveCommerceOperation(
1111
+ "orders",
1112
+ "post",
1113
+ "/resolve-cancel-refund",
1114
+ ["managed_refund_attestation_forbidden"]
1115
+ ),
1116
+ checkout: strictCommerceOperation("orders", "post", "/checkout"),
1117
+ createFulfillment: operation("orders", "post", "/create-fulfillment"),
1118
+ updateFulfillment: operation("orders", "post", "/update-fulfillment")
1119
+ },
1120
+ checkouts: {
1121
+ detail: strictCommerceOperation("checkouts", "post", "/detail"),
1122
+ query: strictCommerceOperation("checkouts", "post", "/query")
1123
+ },
1124
+ draftOrders: {
1125
+ calculate: operation("draft-orders", "post", "/:id/calculate"),
1126
+ complete: operation("draft-orders", "post", "/:id/complete"),
1127
+ finalize: operation("draft-orders", "post", "/:id/finalize")
1128
+ },
1129
+ transactions: {
1130
+ update: operation("transactions", "post", "/update")
1131
+ },
1132
+ returns: {
1133
+ create: operation("returns", "post", "/create"),
1134
+ update: operation("returns", "post", "/update"),
1135
+ returnRefund: operation("returns", "post", "/return-refund")
1136
+ },
1137
+ fulfillmentOrders: {
1138
+ prepare: operation(
1139
+ "fulfillment-orders",
1140
+ "post",
1141
+ "/prepare-fulfillment-order"
1142
+ )
1143
+ },
1144
+ fulfillments: {
1145
+ bulkImport: operation("fulfillments", "post", "/bulk-import")
1146
+ },
1147
+ carts: {
1148
+ create: strictCommerceOperation("carts", "post", "/create"),
1149
+ retrieve: strictCommerceOperation("carts", "post", "/retrieve"),
1150
+ mine: strictCommerceOperation("carts", "post", "/mine"),
1151
+ merge: strictCommerceOperation("carts", "post", "/merge"),
1152
+ addItem: strictCommerceOperation("carts", "post", "/add-item"),
1153
+ updateItem: strictCommerceOperation("carts", "post", "/update-item"),
1154
+ removeItem: strictCommerceOperation("carts", "post", "/remove-item"),
1155
+ updateDiscountCodes: strictCommerceOperation(
1156
+ "carts",
1157
+ "post",
1158
+ "/update-discount-codes"
1159
+ ),
1160
+ updateAttributes: strictCommerceOperation(
1161
+ "carts",
1162
+ "post",
1163
+ "/update-attributes"
1164
+ ),
1165
+ clear: strictCommerceOperation("carts", "post", "/clear")
1166
+ },
1167
+ paymentSessions: {
1168
+ create: strictCommerceOperation("payment-sessions", "post", "/create"),
1169
+ retrieve: strictCommerceOperation("payment-sessions", "post", "/retrieve"),
1170
+ cancel: strictCommerceOperation("payment-sessions", "post", "/cancel"),
1171
+ server: {
1172
+ create: strictCommerceOperation(
1173
+ "payment-sessions",
1174
+ "post",
1175
+ "/server/create"
1176
+ ),
1177
+ retrieve: strictCommerceOperation(
1178
+ "payment-sessions",
1179
+ "post",
1180
+ "/server/retrieve"
1181
+ ),
1182
+ cancel: strictCommerceOperation(
1183
+ "payment-sessions",
1184
+ "post",
1185
+ "/server/cancel"
1186
+ ),
1187
+ confirm: strictCommerceOperation(
1188
+ "payment-sessions",
1189
+ "post",
1190
+ "/server/confirm"
1191
+ ),
1192
+ findPortOne: strictCommerceOperation(
1193
+ "payment-sessions",
1194
+ "post",
1195
+ "/server/portone/find"
1196
+ ),
1197
+ reconcilePortOne: strictCommerceOperation(
1198
+ "payment-sessions",
1199
+ "post",
1200
+ "/server/portone/reconcile"
1201
+ )
1202
+ },
1203
+ custom: {
1204
+ create: operation("orders", "post", "/custom-payment-sessions"),
1205
+ retrieve: operation(
1206
+ "orders",
1207
+ "post",
1208
+ "/custom-payment-sessions/retrieve"
1209
+ ),
1210
+ confirm: operation("orders", "post", "/custom-payment-sessions/confirm")
1211
+ }
1212
+ },
1213
+ shippingPolicies: {
1214
+ calculate: operation("shipping-policies", "post", "/calculate")
1215
+ },
1216
+ discounts: {
1217
+ validate: operation("discounts", "post", "/validate")
1218
+ }
1219
+ };
1220
+ var portOneStandardActionCapabilityOperations = /* @__PURE__ */ new Set([
1221
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.create,
1222
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.retrieve,
1223
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.create,
1224
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.retrieve
1225
+ ]);
1226
+ var MEMBERSHIP_ENDPOINT_OPERATIONS = {
1227
+ subscribe: operation(null, "post", "/memberships/subscribe"),
1228
+ billingCustody: operation(null, "post", "/memberships/billing-custody"),
1229
+ cancel: operation(null, "post", "/memberships/:id/cancel"),
1230
+ me: operation(null, "get", "/memberships/me"),
1231
+ chargeResult: operation(null, "post", "/memberships/:id/charge-result"),
1232
+ refundResult: operation(null, "post", "/memberships/:id/refund-result"),
1233
+ revoke: operation(null, "post", "/memberships/:id/revoke")
1234
+ };
1235
+ var EXTERNAL_EFFECT_CLAIM_ENDPOINT_OPERATIONS = {
1236
+ claim: operation(null, "post", "/external-effect-claims/claim"),
1237
+ get: operation(null, "post", "/external-effect-claims/get"),
1238
+ arm: operation(null, "post", "/external-effect-claims/arm"),
1239
+ release: operation(null, "post", "/external-effect-claims/release"),
1240
+ report: operation(null, "post", "/external-effect-claims/report"),
1241
+ recovery: operation(null, "post", "/external-effect-claims/recovery")
1242
+ };
1243
+ var INSTALLATION_CREDENTIAL_ENDPOINT_OPERATIONS = {
1244
+ create: operation(null, "post", "/installation-credentials/create"),
1245
+ get: operation(null, "post", "/installation-credentials/get"),
1246
+ replace: operation(null, "post", "/installation-credentials/replace"),
1247
+ dispose: operation(null, "post", "/installation-credentials/dispose")
1248
+ };
1249
+ var EXTERNAL_CUSTOMER_LINK_ENDPOINT_OPERATIONS = {
1250
+ connect: operation("customers", "post", "/external-links/connect"),
1251
+ get: operation("customers", "post", "/external-links/get"),
1252
+ list: operation("customers", "post", "/external-links/list"),
1253
+ unlink: operation("customers", "post", "/external-links/unlink"),
1254
+ capturePreviousState: operation(
1255
+ "customers",
1256
+ "post",
1257
+ "/external-links/capture-previous-state"
1258
+ ),
1259
+ clearPreviousState: operation(
1260
+ "customers",
1261
+ "post",
1262
+ "/external-links/clear-previous-state"
1263
+ )
1264
+ };
1265
+ var BENEFIT_VOUCHER_ENDPOINT_OPERATIONS = {
1266
+ issue: operation("customers", "post", "/benefit-vouchers/issue"),
1267
+ get: operation("customers", "post", "/benefit-vouchers/get"),
1268
+ list: operation("customers", "post", "/benefit-vouchers/list"),
1269
+ redeem: operation("customers", "post", "/benefit-vouchers/redeem"),
1270
+ void: operation("customers", "post", "/benefit-vouchers/void"),
1271
+ listMine: operation("customers", "get", "/me/benefit-vouchers")
1272
+ };
1273
+ var CUSTOMER_GROUP_ENDPOINT_OPERATIONS = {
1274
+ members: operation("customer-groups", "get", "/:id/members"),
1275
+ grant: operation("customer-groups", "post", "/:id/members/grant"),
1276
+ revoke: operation("customer-groups", "post", "/:id/members/revoke")
1277
+ };
1278
+ var CUSTOMER_AUTH_ENDPOINT_OPERATIONS = {
1279
+ register: operation("customers", "post", "/register"),
1280
+ login: operation("customers", "post", "/login"),
1281
+ refresh: operation("customers", "post", "/refresh"),
1282
+ me: operation("customers", "get", "/me"),
1283
+ updateProfile: operation("customers", "patch", "/me"),
1284
+ forgotPassword: operation("customers", "post", "/forgot-password"),
1285
+ resetPassword: operation("customers", "post", "/reset-password"),
1286
+ changePassword: operation("customers", "post", "/change-password"),
1287
+ revokeRefresh: operation("customers", "post", "/revoke-refresh"),
1288
+ withdraw: operation("customers", "post", "/withdraw")
1289
+ };
1290
+ var EMBEDDED_ADMIN_ENDPOINT_OPERATIONS = {
1291
+ show: operation("tenants", "get", "/embedded-admin-app"),
1292
+ configure: operation("tenants", "patch", "/embedded-admin-app"),
1293
+ disable: operation("tenants", "delete", "/embedded-admin-app")
1294
+ };
1295
+ var EVENTS_ENDPOINT_OPERATIONS = {
1296
+ registrations: {
1297
+ listMine: operation("event-registrations", "get", "/my")
1298
+ },
1299
+ events: {
1300
+ convertSchedule: operation("events", "post", "/:id/schedule")
1301
+ },
1302
+ occurrences: {
1303
+ range: operation("event-occurrences", "get", "/range"),
1304
+ admissionAvailability: operation(
1305
+ "event-occurrences",
1306
+ "get",
1307
+ "/admission-availability"
1308
+ )
1309
+ }
1310
+ };
1311
+ var COMMUNITY_ENDPOINT_OPERATIONS = {
1312
+ posts: {
1313
+ detail: operation("posts", "get", "/detail")
1314
+ }
1315
+ };
1316
+ var GALLERY_ENDPOINT_OPERATIONS = {
1317
+ items: {
1318
+ storefront: operation("gallery-items", "get", "/storefront")
1319
+ }
1320
+ };
1321
+ var VIDEO_ENDPOINT_OPERATIONS = {
1322
+ playback: operation("videos", "post", "/:id/playback")
1323
+ };
1324
+ function resolveOperationTemplate(descriptor) {
1325
+ return descriptor.collection ? `/api/${descriptor.collection}${descriptor.path}` : `/api${descriptor.path}`;
1326
+ }
1327
+ function resolveOperationPath(descriptor, options) {
1328
+ const path = resolveOperationTemplate(descriptor).replace(
1329
+ /:([A-Za-z][A-Za-z0-9_]*)/g,
1330
+ (_, key) => {
1331
+ const value = options?.pathParams?.[key];
1332
+ if (value === void 0) {
1333
+ throw new TypeError(`Missing path parameter: ${key}`);
1334
+ }
1335
+ return encodeURIComponent(value);
1336
+ }
1337
+ );
1338
+ const unresolved = path.match(/:([A-Za-z][A-Za-z0-9_]*)/);
1339
+ if (unresolved) {
1340
+ throw new TypeError(`Missing path parameter: ${unresolved[1]}`);
1341
+ }
1342
+ const query = options?.query?.toString().replace(/^\?/, "");
1343
+ return query ? `${path}?${query}` : path;
1344
+ }
1345
+ function resolveOperationMethod(descriptor) {
1346
+ return descriptor.method.toUpperCase();
1347
+ }
1348
+
1349
+ // src/core/api/endpoints.ts
1350
+ var sharedEndpoint = (descriptor) => descriptor;
1351
+ function resolveOperationErrorFamily(descriptor) {
1352
+ return descriptor.errorFamily;
1353
+ }
1354
+ function resolveOperationTypedCommerceErrorReasons(descriptor) {
1355
+ return descriptor.typedCommerceErrorReasons;
1356
+ }
1357
+ var COMMERCE_ENDPOINTS = {
1358
+ products: {
1359
+ detail: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.products.detail),
1360
+ detailCatalog: sharedEndpoint(
1361
+ COMMERCE_ENDPOINT_OPERATIONS.products.detailCatalog
1362
+ ),
1363
+ listingGroups: sharedEndpoint(
1364
+ COMMERCE_ENDPOINT_OPERATIONS.products.listingGroups
1365
+ ),
1366
+ listingGroupsCatalog: sharedEndpoint(
1367
+ COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsCatalog
1368
+ ),
1369
+ // The manifest keeps the GET read and the POST body-query apart; this
1370
+ // semantic name has always resolved to the GET one.
1371
+ listingGroupsQuery: sharedEndpoint(
1372
+ COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsQueryGet
1373
+ ),
1374
+ listingGroupsQueryCatalog: sharedEndpoint(
1375
+ COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsQueryCatalog
1376
+ ),
1377
+ stockCheck: sharedEndpoint(
1378
+ COMMERCE_ENDPOINT_OPERATIONS.products.stockCheck
1379
+ ),
1380
+ stockSnapshot: sharedEndpoint(
1381
+ COMMERCE_ENDPOINT_OPERATIONS.products.stockSnapshot
1382
+ ),
1383
+ upsert: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.products.upsert)
1384
+ },
1385
+ orders: {
1386
+ update: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.update),
1387
+ byPayment: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.byPayment),
1388
+ cancel: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.cancel),
1389
+ resolveCancelRefund: sharedEndpoint(
1390
+ COMMERCE_ENDPOINT_OPERATIONS.orders.resolveCancelRefund
1391
+ ),
1392
+ createFulfillment: sharedEndpoint(
1393
+ COMMERCE_ENDPOINT_OPERATIONS.orders.createFulfillment
1394
+ ),
1395
+ updateFulfillment: sharedEndpoint(
1396
+ COMMERCE_ENDPOINT_OPERATIONS.orders.updateFulfillment
1397
+ )
1398
+ },
1399
+ checkouts: {
1400
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.checkout),
1401
+ retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.detail),
1402
+ server: {
1403
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.checkout),
1404
+ retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.detail),
1405
+ query: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.query)
1406
+ }
1407
+ },
1408
+ returns: {
1409
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.returns.create),
1410
+ update: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.returns.update),
1411
+ returnRefund: sharedEndpoint(
1412
+ COMMERCE_ENDPOINT_OPERATIONS.returns.returnRefund
1413
+ )
1414
+ },
1415
+ fulfillmentOrders: {
1416
+ prepare: sharedEndpoint(
1417
+ COMMERCE_ENDPOINT_OPERATIONS.fulfillmentOrders.prepare
1418
+ )
1419
+ },
1420
+ fulfillments: {
1421
+ bulkImport: sharedEndpoint(
1422
+ COMMERCE_ENDPOINT_OPERATIONS.fulfillments.bulkImport
1423
+ )
1424
+ },
1425
+ carts: {
1426
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.create),
1427
+ retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.retrieve),
1428
+ mine: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.mine),
1429
+ merge: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.merge),
1430
+ server: {
1431
+ // Server credentials are an authorization lane, not a second Cart
1432
+ // transport. These must stay bound to the registered shared operations.
1433
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.create),
1434
+ retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.retrieve),
1435
+ mine: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.mine),
1436
+ merge: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.merge),
1437
+ addItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.addItem),
1438
+ updateItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.updateItem),
1439
+ removeItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.removeItem),
1440
+ updateDiscountCodes: sharedEndpoint(
1441
+ COMMERCE_ENDPOINT_OPERATIONS.carts.updateDiscountCodes
1442
+ ),
1443
+ updateAttributes: sharedEndpoint(
1444
+ COMMERCE_ENDPOINT_OPERATIONS.carts.updateAttributes
1445
+ ),
1446
+ clear: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.clear)
1231
1447
  },
1232
- twitter: {
1233
- card: image ? "summary_large_image" : "summary",
1234
- ...ogTitle && { title: ogTitle },
1235
- ...ogDescription && { description: ogDescription },
1236
- ...image && { images: [image.url] }
1237
- }
1238
- };
1239
- }
1240
- function resolveMetaImage(ref) {
1241
- const image = resolveRelation(ref);
1242
- if (!image) return null;
1243
- const sized = image.sizes?.[OPEN_GRAPH_IMAGE_SIZE] ?? image.sizes?.[LEGACY_OPEN_GRAPH_IMAGE_SIZE];
1244
- const url = sized?.url || image.url;
1245
- if (!url) return null;
1246
- const width = sized?.url ? sized.width : image.width;
1247
- const height = sized?.url ? sized.height : image.height;
1248
- return {
1249
- url,
1250
- ...width && { width },
1251
- ...height && { height },
1252
- ...image.alt && { alt: image.alt }
1253
- };
1254
- }
1255
-
1256
- // src/core/collection/query-builder.ts
1257
- var CollectionQueryBuilder = class {
1258
- constructor(api, collection) {
1259
- this.api = api;
1260
- this.collection = collection;
1261
- }
1262
- /**
1263
- * Find documents (list query)
1264
- * GET /api/{collection}
1265
- * @returns Payload CMS find response with docs array and pagination
1266
- */
1267
- async find(options) {
1268
- return this.api.requestFind(
1269
- `/api/${String(this.collection)}`,
1270
- options
1271
- );
1272
- }
1273
- /**
1274
- * Find document by ID
1275
- * GET /api/{collection}/{id}
1276
- * @returns Document object directly (no wrapper)
1277
- */
1278
- async findById(id, options) {
1279
- return this.api.requestFindById(
1280
- `/api/${String(this.collection)}/${String(id)}`,
1281
- options
1282
- );
1283
- }
1284
- /**
1285
- * Create a new document
1286
- * POST /api/{collection}
1287
- * @returns Payload CMS mutation response with doc and message
1288
- */
1289
- async create(data, options) {
1290
- const endpoint = `/api/${String(this.collection)}`;
1291
- if (options?.file) {
1292
- return this.api.requestCreateWithFile(
1293
- endpoint,
1294
- data,
1295
- options.file,
1296
- options.filename
1297
- );
1448
+ addItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.addItem),
1449
+ updateItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.updateItem),
1450
+ removeItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.removeItem),
1451
+ updateDiscountCodes: sharedEndpoint(
1452
+ COMMERCE_ENDPOINT_OPERATIONS.carts.updateDiscountCodes
1453
+ ),
1454
+ updateAttributes: sharedEndpoint(
1455
+ COMMERCE_ENDPOINT_OPERATIONS.carts.updateAttributes
1456
+ ),
1457
+ clear: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.clear)
1458
+ },
1459
+ paymentSessions: {
1460
+ create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.create),
1461
+ retrieve: sharedEndpoint(
1462
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.retrieve
1463
+ ),
1464
+ cancel: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.cancel),
1465
+ custom: {
1466
+ create: sharedEndpoint(
1467
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.create
1468
+ ),
1469
+ retrieve: sharedEndpoint(
1470
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.retrieve
1471
+ ),
1472
+ confirm: sharedEndpoint(
1473
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.confirm
1474
+ )
1475
+ },
1476
+ server: {
1477
+ create: sharedEndpoint(
1478
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.create
1479
+ ),
1480
+ retrieve: sharedEndpoint(
1481
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.retrieve
1482
+ ),
1483
+ cancel: sharedEndpoint(
1484
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.cancel
1485
+ ),
1486
+ confirm: sharedEndpoint(
1487
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.confirm
1488
+ ),
1489
+ findPortOne: sharedEndpoint(
1490
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.findPortOne
1491
+ ),
1492
+ reconcilePortOne: sharedEndpoint(
1493
+ COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.reconcilePortOne
1494
+ )
1298
1495
  }
1299
- return this.api.requestCreate(endpoint, data);
1496
+ },
1497
+ shippingPolicies: {
1498
+ calculate: sharedEndpoint(
1499
+ COMMERCE_ENDPOINT_OPERATIONS.shippingPolicies.calculate
1500
+ )
1300
1501
  }
1301
- /**
1302
- * Update a document by ID
1303
- * PATCH /api/{collection}/{id}
1304
- * @returns Payload CMS mutation response with doc and message
1305
- */
1306
- async update(id, data, options) {
1307
- const endpoint = `/api/${String(this.collection)}/${String(id)}`;
1308
- if (options?.file) {
1309
- return this.api.requestUpdateWithFile(
1310
- endpoint,
1311
- data,
1312
- options.file,
1313
- options.filename
1314
- );
1502
+ };
1503
+
1504
+ // src/core/api/base-api.ts
1505
+ var ServerApiTransport = class {
1506
+ constructor(apiName, options) {
1507
+ if (!options.secretKey) {
1508
+ throw createConfigError(`secretKey is required for ${apiName}.`);
1315
1509
  }
1316
- return this.api.requestUpdate(endpoint, data);
1317
- }
1318
- /**
1319
- * Count documents
1320
- * GET /api/{collection}/count
1321
- * @returns Count response with totalDocs
1322
- */
1323
- async count(options) {
1324
- return this.api.requestCount(
1325
- `/api/${String(this.collection)}/count`,
1326
- options
1327
- );
1328
- }
1329
- /**
1330
- * Find first matching document and return its Next.js Metadata.
1331
- * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
1332
- * @returns Metadata or null if no document matches
1333
- */
1334
- async findMetadata(options, metadataOptions) {
1335
- const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
1336
- const doc = docs[0];
1337
- if (!doc) return null;
1338
- return generateMetadata(
1339
- extractSeo(doc),
1340
- metadataOptions
1510
+ this.publishableKey = requirePublishableKeyForSecret(
1511
+ apiName,
1512
+ options.publishableKey,
1513
+ options.secretKey
1341
1514
  );
1515
+ this.secretKey = options.secretKey;
1516
+ this.apiUrl = options.apiUrl;
1517
+ this.onRequestId = options.onRequestId;
1342
1518
  }
1343
- /**
1344
- * Find document by ID and return its Next.js Metadata.
1345
- * Applies depth: 1 (SEO image populate) automatically.
1346
- * @returns Metadata (throws on 404)
1347
- */
1348
- async findMetadataById(id, metadataOptions) {
1349
- const doc = await this.findById(id, { depth: 1 });
1350
- return generateMetadata(
1351
- extractSeo(doc),
1352
- metadataOptions
1353
- );
1519
+ async request(endpoint, body, options) {
1520
+ const method = options?.method ?? "POST";
1521
+ try {
1522
+ const response = await httpFetch(endpoint, {
1523
+ method,
1524
+ apiUrl: this.apiUrl,
1525
+ publishableKey: this.publishableKey,
1526
+ secretKey: this.secretKey,
1527
+ ...body !== void 0 && { body: JSON.stringify(body) },
1528
+ ...options?.headers && { headers: options.headers },
1529
+ ...options?.errorFamily && { errorFamily: options.errorFamily },
1530
+ ...options?.typedCommerceErrorReasons && {
1531
+ typedCommerceErrorReasons: options.typedCommerceErrorReasons
1532
+ }
1533
+ });
1534
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1535
+ return parseApiResponse(response, endpoint, {
1536
+ errorFamily: options?.errorFamily
1537
+ });
1538
+ } catch (err) {
1539
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1540
+ this.onRequestId?.(id);
1541
+ throw err;
1542
+ }
1354
1543
  }
1355
- /**
1356
- * Update multiple documents (bulk update)
1357
- * PATCH /api/{collection}
1358
- * @returns Payload CMS find response with updated docs
1359
- */
1360
- async updateMany(where, data) {
1361
- return this.api.requestUpdateMany(
1362
- `/api/${String(this.collection)}`,
1363
- { where, data }
1364
- );
1544
+ };
1545
+ var BaseApi = class {
1546
+ constructor(apiName, options) {
1547
+ this.transport = new ServerApiTransport(apiName, options);
1365
1548
  }
1366
- /**
1367
- * Delete a document by ID
1368
- * DELETE /api/{collection}/{id}
1369
- * @returns Deleted document object directly (no wrapper)
1370
- */
1371
- async remove(id, options) {
1372
- return this.api.requestDelete(
1373
- `/api/${String(this.collection)}/${String(id)}`,
1374
- options
1549
+ requestEndpoint(endpoint, body, options) {
1550
+ return this.transport.request(
1551
+ resolveOperationPath(endpoint, options),
1552
+ body,
1553
+ {
1554
+ method: resolveOperationMethod(endpoint),
1555
+ headers: options?.headers,
1556
+ errorFamily: resolveOperationErrorFamily(endpoint),
1557
+ typedCommerceErrorReasons: resolveOperationTypedCommerceErrorReasons(endpoint)
1558
+ }
1375
1559
  );
1376
1560
  }
1377
- /**
1378
- * Delete multiple documents (bulk delete)
1379
- * DELETE /api/{collection}
1380
- * @returns Payload CMS find response with deleted docs
1381
- */
1382
- async removeMany(where) {
1383
- return this.api.requestDeleteMany(
1384
- `/api/${String(this.collection)}`,
1385
- { where }
1561
+ };
1562
+ var RawBaseApi = class {
1563
+ constructor(apiName, options) {
1564
+ this.transport = new ServerApiTransport(apiName, options);
1565
+ this.publishableKey = requirePublishableKeyForSecret(
1566
+ apiName,
1567
+ options.publishableKey,
1568
+ options.secretKey
1386
1569
  );
1570
+ this.secretKey = options.secretKey;
1571
+ this.apiUrl = options.apiUrl;
1572
+ this.onRequestId = options.onRequestId;
1573
+ }
1574
+ request(endpoint, body, options) {
1575
+ return this.transport.request(endpoint, body, options);
1387
1576
  }
1388
- };
1389
- var ServerCollectionQueryBuilder = class extends CollectionQueryBuilder {
1390
1577
  };
1391
1578
 
1392
- // src/core/collection/collection-client.ts
1393
- function buildPayloadFormData(data, file, filename) {
1394
- const formData = new FormData();
1395
- formData.append("file", file, filename);
1396
- if (data != null) {
1397
- formData.append("_payload", JSON.stringify(data));
1398
- }
1399
- return formData;
1579
+ // src/core/api/benefit-voucher-types.ts
1580
+ var BENEFIT_VOUCHER_VOID_REASONS = [
1581
+ "issued_in_error",
1582
+ "benefit_revoked",
1583
+ "customer_request",
1584
+ "other"
1585
+ ];
1586
+ function invalidBenefitVoucherResponse() {
1587
+ throw createApiError("Invalid benefit voucher response", 200);
1400
1588
  }
1401
- var CollectionClient = class extends HttpClient {
1402
- from(collection) {
1403
- return new CollectionQueryBuilder(this, collection);
1404
- }
1405
- // ============================================================================
1406
- // Payload-native methods
1407
- // ============================================================================
1408
- /**
1409
- * Find documents (list query)
1410
- * GET /api/{collection}
1411
- */
1412
- async requestFind(endpoint, options) {
1413
- const url = this.buildUrl(endpoint, options);
1414
- const response = await this.fetchWithTracking(url, {
1415
- ...this.defaultOptions,
1416
- method: "GET"
1417
- });
1418
- return this.parseFindResponse(response);
1419
- }
1420
- /**
1421
- * Find-like response from a custom endpoint
1422
- * POST /api/...custom-endpoint
1423
- */
1424
- async requestFindEndpoint(endpoint, data) {
1425
- const response = await this.fetchWithTracking(endpoint, {
1426
- ...this.defaultOptions,
1427
- method: "POST",
1428
- body: data ? JSON.stringify(data) : void 0
1429
- });
1430
- return this.parseFindResponse(response);
1431
- }
1432
- /**
1433
- * Find-like response from a cacheable GET custom endpoint.
1434
- */
1435
- async requestFindEndpointGet(endpoint) {
1436
- const response = await this.fetchWithTracking(endpoint, {
1437
- ...this.defaultOptions,
1438
- method: "GET"
1439
- });
1440
- return this.parseFindResponse(response);
1441
- }
1442
- /**
1443
- * Find document by ID
1444
- * GET /api/{collection}/{id}
1445
- */
1446
- async requestFindById(endpoint, options) {
1447
- const url = this.buildUrl(endpoint, options);
1448
- const response = await this.fetchWithTracking(url, {
1449
- ...this.defaultOptions,
1450
- method: "GET"
1451
- });
1452
- return this.parseDocumentResponse(response);
1453
- }
1454
- /**
1455
- * Create document
1456
- * POST /api/{collection}
1457
- */
1458
- async requestCreate(endpoint, data) {
1459
- const response = await this.fetchWithTracking(endpoint, {
1460
- ...this.defaultOptions,
1461
- method: "POST",
1462
- body: data ? JSON.stringify(data) : void 0
1463
- });
1464
- return this.parseMutationResponse(response);
1465
- }
1466
- /**
1467
- * Update document
1468
- * PATCH /api/{collection}/{id}
1469
- */
1470
- async requestUpdate(endpoint, data) {
1471
- const response = await this.fetchWithTracking(endpoint, {
1472
- ...this.defaultOptions,
1473
- method: "PATCH",
1474
- body: data ? JSON.stringify(data) : void 0
1475
- });
1476
- return this.parseMutationResponse(response);
1589
+ function object(value, keys) {
1590
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some((key) => !(key in value)))
1591
+ invalidBenefitVoucherResponse();
1592
+ return value;
1593
+ }
1594
+ 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(
1595
+ v
1596
+ ) || v === "00000000-0000-0000-0000-000000000000" || v.toLowerCase() === "ffffffff-ffff-ffff-ffff-ffffffffffff");
1597
+ 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;
1598
+ var actor = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(v);
1599
+ function parseBenefitVoucher(value, mine = false) {
1600
+ const v = object(value, [
1601
+ "id",
1602
+ "name",
1603
+ "description",
1604
+ "state",
1605
+ "issuedAt",
1606
+ "expiresAt",
1607
+ ...mine ? ["closedAt"] : ["customerId", "definitionId", "source", "closed"]
1608
+ ]);
1609
+ 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))
1610
+ invalidBenefitVoucherResponse();
1611
+ if (mine) {
1612
+ if (v.closedAt !== null && !time(v.closedAt))
1613
+ invalidBenefitVoucherResponse();
1614
+ } else {
1615
+ if (!uuid(v.customerId) || !uuid(v.definitionId))
1616
+ invalidBenefitVoucherResponse();
1617
+ const source = object(v.source, ["namespace", "ref"]);
1618
+ 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)
1619
+ invalidBenefitVoucherResponse();
1620
+ if (v.closed !== null) {
1621
+ const closed = object(v.closed, [
1622
+ "at",
1623
+ "channel",
1624
+ "actor",
1625
+ "actorRef",
1626
+ "voidReason"
1627
+ ]);
1628
+ const principal = object(closed.actor, ["type", "id"]);
1629
+ 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))
1630
+ invalidBenefitVoucherResponse();
1631
+ }
1477
1632
  }
1478
- /**
1479
- * Count documents
1480
- * GET /api/{collection}/count
1481
- */
1482
- async requestCount(endpoint, options) {
1483
- const url = this.buildUrl(endpoint, options);
1484
- const response = await this.fetchWithTracking(url, {
1485
- ...this.defaultOptions,
1486
- method: "GET"
1487
- });
1488
- return this.parseDocumentResponse(response);
1633
+ return value;
1634
+ }
1635
+ function parseBenefitVoucherList(value, mine = false) {
1636
+ const v = object(value, ["vouchers", "nextCursor", "evaluatedAt"]);
1637
+ 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))
1638
+ invalidBenefitVoucherResponse();
1639
+ for (const row of v.vouchers) {
1640
+ if (mine) parseBenefitVoucher(row, true);
1641
+ else parseBenefitVoucher(row);
1489
1642
  }
1490
- /**
1491
- * Update multiple documents (bulk update)
1492
- * PATCH /api/{collection}
1493
- */
1494
- async requestUpdateMany(endpoint, data) {
1495
- const url = this.buildUrl(endpoint, { where: data.where });
1496
- const response = await this.fetchWithTracking(url, {
1497
- ...this.defaultOptions,
1498
- method: "PATCH",
1499
- body: JSON.stringify(data.data)
1500
- });
1501
- return this.parseFindResponse(response);
1643
+ return value;
1644
+ }
1645
+
1646
+ // src/core/api/benefit-vouchers-api.ts
1647
+ var BenefitVouchersApi = class extends BaseApi {
1648
+ constructor(options) {
1649
+ super("BenefitVouchersApi", options);
1650
+ }
1651
+ async command(name, input) {
1652
+ const result = await this.requestEndpoint(BENEFIT_VOUCHER_ENDPOINT_OPERATIONS[name], input);
1653
+ if (!result || typeof result !== "object" || !("voucher" in result))
1654
+ invalidBenefitVoucherResponse();
1655
+ const voucher = parseBenefitVoucher(result.voucher);
1656
+ const key = name === "issue" ? "created" : name === "get" ? null : "replayed";
1657
+ if (Object.keys(result).length !== (key ? 2 : 1) || key && typeof result[key] !== "boolean")
1658
+ invalidBenefitVoucherResponse();
1659
+ return {
1660
+ voucher,
1661
+ ...key ? { [key]: result[key] } : {}
1662
+ };
1502
1663
  }
1503
- /**
1504
- * Delete document
1505
- * DELETE /api/{collection}/{id}
1506
- */
1507
- async requestDelete(endpoint, options) {
1508
- const url = this.buildUrl(endpoint, options);
1509
- const response = await this.fetchWithTracking(url, {
1510
- ...this.defaultOptions,
1511
- method: "DELETE"
1512
- });
1513
- return this.parseDocumentResponse(response);
1664
+ async issue(input) {
1665
+ return await this.command("issue", input);
1514
1666
  }
1515
- /**
1516
- * Delete multiple documents (bulk delete)
1517
- * DELETE /api/{collection}
1518
- */
1519
- async requestDeleteMany(endpoint, data) {
1520
- const url = this.buildUrl(endpoint, { where: data.where });
1521
- const response = await this.fetchWithTracking(url, {
1522
- ...this.defaultOptions,
1523
- method: "DELETE"
1524
- });
1525
- return this.parseFindResponse(response);
1667
+ async get(input) {
1668
+ return this.command("get", input);
1526
1669
  }
1527
- /**
1528
- * Create document with file upload
1529
- * POST /api/{collection} (multipart/form-data)
1530
- */
1531
- async requestCreateWithFile(endpoint, data, file, filename) {
1532
- const response = await this.fetchWithTracking(endpoint, {
1533
- ...this.defaultOptions,
1534
- method: "POST",
1535
- body: buildPayloadFormData(data, file, filename)
1536
- });
1537
- return this.parseMutationResponse(response);
1670
+ async list(input) {
1671
+ return parseBenefitVoucherList(
1672
+ await this.requestEndpoint(BENEFIT_VOUCHER_ENDPOINT_OPERATIONS.list, input)
1673
+ );
1538
1674
  }
1539
- /**
1540
- * Update document with file upload
1541
- * PATCH /api/{collection}/{id} (multipart/form-data)
1542
- */
1543
- async requestUpdateWithFile(endpoint, data, file, filename) {
1544
- const response = await this.fetchWithTracking(endpoint, {
1545
- ...this.defaultOptions,
1546
- method: "PATCH",
1547
- body: buildPayloadFormData(data, file, filename)
1548
- });
1549
- return this.parseMutationResponse(response);
1675
+ async redeem(input) {
1676
+ return await this.command("redeem", input);
1550
1677
  }
1551
- };
1552
- var ServerCollectionClient = class extends CollectionClient {
1553
- from(collection) {
1554
- return new ServerCollectionQueryBuilder(this, collection);
1678
+ async voidVoucher(input) {
1679
+ return await this.command("void", input);
1555
1680
  }
1556
1681
  };
1557
1682
 
1558
- // src/core/api/parse-response.ts
1559
- async function parseApiResponse(response, endpoint, options = {}) {
1560
- if (response.status === 204 || response.headers.get("content-length") === "0") {
1561
- return void 0;
1683
+ // src/core/collection/http-client.ts
1684
+ import { stringify } from "qs-esm";
1685
+ function validateWhere(where) {
1686
+ if (where === void 0) return false;
1687
+ let hasNull = false;
1688
+ function visit(value, depth, key) {
1689
+ if (depth > 10) {
1690
+ throw createValidationError(
1691
+ "Collection where must not exceed nesting depth 10."
1692
+ );
1693
+ }
1694
+ if (value === null && (key === "equals" || key === "not_equals")) {
1695
+ hasNull = true;
1696
+ return;
1697
+ }
1698
+ if (value == null) {
1699
+ throw createValidationError(
1700
+ "Collection where must not contain null or undefined values."
1701
+ );
1702
+ }
1703
+ if (Array.isArray(value)) {
1704
+ if (value.length === 0) {
1705
+ throw createValidationError(
1706
+ "Collection where must not contain empty arrays, including and/or."
1707
+ );
1708
+ }
1709
+ if (value.length > 1e3) {
1710
+ throw createValidationError(
1711
+ "Collection where arrays must not contain more than 1000 elements."
1712
+ );
1713
+ }
1714
+ for (const item of value) visit(item, depth + 1);
1715
+ } else if (typeof value === "object" && !(value instanceof Date)) {
1716
+ const values = Object.entries(value);
1717
+ if (values.length === 0) {
1718
+ throw createValidationError(
1719
+ "Collection where must not contain empty condition objects."
1720
+ );
1721
+ }
1722
+ for (const [key2, item] of values) visit(item, depth + 1, key2);
1723
+ }
1562
1724
  }
1563
- let parsed;
1564
- try {
1565
- parsed = await response.json();
1566
- } catch {
1567
- throw createApiError(
1568
- `Invalid JSON response from ${endpoint}`,
1569
- response.status,
1570
- void 0,
1571
- "Server returned an invalid response.",
1572
- "Check if the API endpoint is available."
1725
+ visit(where, 0);
1726
+ return hasNull;
1727
+ }
1728
+ var HttpClient = class {
1729
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1730
+ this.publishableKey = requirePublishableKeyForSecret(
1731
+ "CollectionClient",
1732
+ publishableKey,
1733
+ secretKey
1573
1734
  );
1735
+ this.secretKey = secretKey;
1736
+ this.getCustomerToken = getCustomerToken;
1737
+ this.onUnauthorized = onUnauthorized;
1738
+ this.onRequestId = onRequestId;
1739
+ this.apiUrl = apiUrl;
1574
1740
  }
1575
- if (parsed === null || typeof parsed !== "object") {
1576
- return parsed;
1741
+ get defaultOptions() {
1742
+ const opts = {
1743
+ apiUrl: this.apiUrl,
1744
+ publishableKey: this.publishableKey,
1745
+ secretKey: this.secretKey
1746
+ };
1747
+ const token = this.getCustomerToken?.();
1748
+ if (token) {
1749
+ opts.customerToken = token;
1750
+ if (this.onUnauthorized) {
1751
+ opts.onUnauthorized = this.onUnauthorized;
1752
+ }
1753
+ }
1754
+ return opts;
1577
1755
  }
1578
- const data = parsed;
1579
- const hasCommerceEnvelopeSignal = options.errorFamily === "commerce" && ["error", "reason", "requestId", "retryable", "details"].some(
1580
- (key) => Object.prototype.hasOwnProperty.call(data, key)
1581
- );
1582
- if (data.error || hasCommerceEnvelopeSignal) {
1583
- const errorMessage = typeof data.error === "string" ? data.error : "Unknown API error";
1584
- const reason = typeof data.reason === "string" ? data.reason : void 0;
1585
- const requestId = response.headers.get("x-request-id") ?? void 0;
1586
- const retryAfter = parseRetryAfter(response).seconds;
1587
- let error;
1588
- if (reason === "validation_failed") {
1589
- error = createValidationError(errorMessage, data, errorMessage);
1590
- } else if (reason === "token_expired" || reason === "token_invalid" || reason === "preview_token_invalid" || reason === "preview_token_required" || reason === "key_invalid" || reason === "key_revoked") {
1591
- error = createAuthError(errorMessage, data, errorMessage);
1592
- } else if (reason === "forbidden") {
1593
- error = createPermissionError(errorMessage, data, errorMessage);
1594
- } else if (reason === "rate_limit_exceeded") {
1595
- error = createRateLimitError(errorMessage, retryAfter, data, errorMessage);
1596
- } else if (reason === "not_found") {
1597
- error = createNotFoundError(errorMessage, data, errorMessage);
1598
- } else if (reason === "conflict") {
1599
- error = createConflictError(errorMessage, data, errorMessage);
1600
- } else {
1601
- error = createApiError(
1602
- errorMessage,
1603
- response.status,
1604
- data,
1605
- errorMessage,
1606
- "An error occurred while processing the request."
1607
- );
1756
+ async fetchWithTracking(url, opts) {
1757
+ try {
1758
+ const response = await httpFetch(url, opts);
1759
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1760
+ return response;
1761
+ } catch (err) {
1762
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1763
+ this.onRequestId?.(id);
1764
+ throw err;
1608
1765
  }
1609
- const withRequestId = attachRequestId(error, requestId);
1610
- if (retryAfter !== void 0) Object.assign(withRequestId, { retryAfter });
1611
- throw options.errorFamily === "commerce" ? enhanceCommerceError(withRequestId, data, requestId) : enhanceNonCommerceError(withRequestId, reason);
1612
1766
  }
1613
- return data;
1614
- }
1615
-
1616
- // ../../internal/http-contracts/src/index.ts
1617
- var operationBrand = /* @__PURE__ */ Symbol("sdk-http-operation");
1618
- var PORTONE_STANDARD_ACTION_CAPABILITIES_MEDIA_TYPE = "application/vnd.01software.portone-action-capabilities.v1+json";
1619
- var operation = (collection, method, path, errorFamily) => Object.freeze({
1620
- [operationBrand]: true,
1621
- collection,
1622
- method,
1623
- path,
1624
- ...errorFamily && { errorFamily }
1625
- });
1626
- var strictCommerceOperation = (collection, method, path) => operation(collection, method, path, "commerce");
1627
- var selectiveCommerceOperation = (collection, method, path, typedCommerceErrorReasons) => Object.freeze({
1628
- ...operation(collection, method, path),
1629
- typedCommerceErrorReasons: Object.freeze([...typedCommerceErrorReasons])
1630
- });
1631
- var COMMERCE_ENDPOINT_OPERATIONS = {
1632
- products: {
1633
- detail: operation("products", "get", "/detail"),
1634
- detailCatalog: operation("products", "get", "/detail/catalog"),
1635
- listingGroups: operation("products", "get", "/listing-groups"),
1636
- listingGroupsCatalog: operation(
1637
- "products",
1638
- "get",
1639
- "/listing-groups/catalog"
1640
- ),
1641
- listingGroupsQuery: operation("products", "post", "/listing-groups/query"),
1642
- listingGroupsQueryGet: operation(
1643
- "products",
1644
- "get",
1645
- "/listing-groups/query"
1646
- ),
1647
- listingGroupsQueryCatalog: operation(
1648
- "products",
1649
- "get",
1650
- "/listing-groups/query/catalog"
1651
- ),
1652
- stockCheck: operation("products", "post", "/stock-check"),
1653
- stockSnapshot: operation("products", "get", "/stock"),
1654
- upsert: operation("products", "post", "/upsert"),
1655
- graphRevision: operation("products", "get", "/:id/graph-revision"),
1656
- variantsPatch: operation("products", "patch", "/:id/variants")
1657
- },
1658
- orders: {
1659
- create: operation("orders", "post", "/create"),
1660
- update: operation("orders", "post", "/update"),
1661
- confirmPayment: operation("orders", "post", "/confirm-payment"),
1662
- byPayment: operation("orders", "get", "/by-payment"),
1663
- cancel: operation("orders", "post", "/cancel"),
1664
- resolveCancelRefund: selectiveCommerceOperation(
1665
- "orders",
1666
- "post",
1667
- "/resolve-cancel-refund",
1668
- ["managed_refund_attestation_forbidden"]
1669
- ),
1670
- checkout: strictCommerceOperation("orders", "post", "/checkout"),
1671
- createFulfillment: operation("orders", "post", "/create-fulfillment"),
1672
- updateFulfillment: operation("orders", "post", "/update-fulfillment")
1673
- },
1674
- checkouts: {
1675
- detail: strictCommerceOperation("checkouts", "post", "/detail"),
1676
- query: strictCommerceOperation("checkouts", "post", "/query")
1677
- },
1678
- draftOrders: {
1679
- calculate: operation("draft-orders", "post", "/:id/calculate"),
1680
- complete: operation("draft-orders", "post", "/:id/complete"),
1681
- finalize: operation("draft-orders", "post", "/:id/finalize")
1682
- },
1683
- transactions: {
1684
- update: operation("transactions", "post", "/update")
1685
- },
1686
- returns: {
1687
- create: operation("returns", "post", "/create"),
1688
- update: operation("returns", "post", "/update"),
1689
- returnRefund: operation("returns", "post", "/return-refund")
1690
- },
1691
- fulfillmentOrders: {
1692
- prepare: operation(
1693
- "fulfillment-orders",
1694
- "post",
1695
- "/prepare-fulfillment-order"
1696
- )
1697
- },
1698
- fulfillments: {
1699
- bulkImport: operation("fulfillments", "post", "/bulk-import")
1700
- },
1701
- carts: {
1702
- create: strictCommerceOperation("carts", "post", "/create"),
1703
- retrieve: strictCommerceOperation("carts", "post", "/retrieve"),
1704
- mine: strictCommerceOperation("carts", "post", "/mine"),
1705
- merge: strictCommerceOperation("carts", "post", "/merge"),
1706
- addItem: strictCommerceOperation("carts", "post", "/add-item"),
1707
- updateItem: strictCommerceOperation("carts", "post", "/update-item"),
1708
- removeItem: strictCommerceOperation("carts", "post", "/remove-item"),
1709
- updateDiscountCodes: strictCommerceOperation(
1710
- "carts",
1711
- "post",
1712
- "/update-discount-codes"
1713
- ),
1714
- updateAttributes: strictCommerceOperation(
1715
- "carts",
1716
- "post",
1717
- "/update-attributes"
1718
- ),
1719
- clear: strictCommerceOperation("carts", "post", "/clear")
1720
- },
1721
- paymentSessions: {
1722
- create: strictCommerceOperation("payment-sessions", "post", "/create"),
1723
- retrieve: strictCommerceOperation("payment-sessions", "post", "/retrieve"),
1724
- cancel: strictCommerceOperation("payment-sessions", "post", "/cancel"),
1725
- server: {
1726
- create: strictCommerceOperation(
1727
- "payment-sessions",
1728
- "post",
1729
- "/server/create"
1730
- ),
1731
- retrieve: strictCommerceOperation(
1732
- "payment-sessions",
1733
- "post",
1734
- "/server/retrieve"
1735
- ),
1736
- cancel: strictCommerceOperation(
1737
- "payment-sessions",
1738
- "post",
1739
- "/server/cancel"
1740
- ),
1741
- confirm: strictCommerceOperation(
1742
- "payment-sessions",
1743
- "post",
1744
- "/server/confirm"
1745
- ),
1746
- findPortOne: strictCommerceOperation(
1747
- "payment-sessions",
1748
- "post",
1749
- "/server/portone/find"
1750
- ),
1751
- reconcilePortOne: strictCommerceOperation(
1752
- "payment-sessions",
1753
- "post",
1754
- "/server/portone/reconcile"
1755
- )
1756
- },
1757
- custom: {
1758
- create: operation("orders", "post", "/custom-payment-sessions"),
1759
- retrieve: operation(
1760
- "orders",
1761
- "post",
1762
- "/custom-payment-sessions/retrieve"
1763
- ),
1764
- confirm: operation("orders", "post", "/custom-payment-sessions/confirm")
1767
+ buildUrl(endpoint, options) {
1768
+ if (!options) return endpoint;
1769
+ const { fallbackLocale, ...rest } = options;
1770
+ const queryOptions = fallbackLocale === void 0 ? rest : {
1771
+ ...rest,
1772
+ "fallback-locale": fallbackLocale === false ? "none" : fallbackLocale
1773
+ };
1774
+ const encodedOptions = validateWhere(queryOptions.where) ? { ...queryOptions, where: JSON.stringify(queryOptions.where) } : queryOptions;
1775
+ const queryString = stringify(encodedOptions, { addQueryPrefix: true });
1776
+ return queryString ? `${endpoint}${queryString}` : endpoint;
1777
+ }
1778
+ assertJsonResponse(response) {
1779
+ const contentType = response.headers.get("content-type");
1780
+ if (!contentType?.includes("application/json")) {
1781
+ throw createApiError("Response is not in JSON format.", response.status, {
1782
+ contentType
1783
+ });
1784
+ }
1785
+ }
1786
+ /**
1787
+ * Parse Payload CMS find response (list query)
1788
+ * Returns native Payload response structure
1789
+ */
1790
+ async parseFindResponse(response) {
1791
+ const contentType = response.headers.get("content-type");
1792
+ try {
1793
+ this.assertJsonResponse(response);
1794
+ const jsonData = await response.json();
1795
+ if (jsonData.docs === void 0) {
1796
+ throw createApiError("Invalid find response.", response.status, {
1797
+ jsonData
1798
+ });
1799
+ }
1800
+ return {
1801
+ docs: jsonData.docs,
1802
+ totalDocs: jsonData.totalDocs ?? 0,
1803
+ limit: jsonData.limit || 20,
1804
+ totalPages: jsonData.totalPages ?? 0,
1805
+ page: jsonData.page || 1,
1806
+ pagingCounter: jsonData.pagingCounter || 1,
1807
+ hasPrevPage: jsonData.hasPrevPage ?? false,
1808
+ hasNextPage: jsonData.hasNextPage ?? false,
1809
+ prevPage: jsonData.prevPage ?? null,
1810
+ nextPage: jsonData.nextPage ?? null
1811
+ };
1812
+ } catch (error) {
1813
+ if (error instanceof SDKError) throw error;
1814
+ throw createApiError("Failed to parse response.", response.status, {
1815
+ contentType,
1816
+ error: error instanceof Error ? error.message : error
1817
+ });
1818
+ }
1819
+ }
1820
+ /**
1821
+ * Parse Payload CMS mutation response (create/update)
1822
+ * Returns native Payload response structure
1823
+ */
1824
+ async parseMutationResponse(response) {
1825
+ const contentType = response.headers.get("content-type");
1826
+ try {
1827
+ this.assertJsonResponse(response);
1828
+ const jsonData = await response.json();
1829
+ if (jsonData.doc === void 0) {
1830
+ throw createApiError("Invalid mutation response.", response.status, {
1831
+ jsonData
1832
+ });
1833
+ }
1834
+ return {
1835
+ message: jsonData.message || "",
1836
+ doc: jsonData.doc,
1837
+ errors: jsonData.errors
1838
+ };
1839
+ } catch (error) {
1840
+ if (error instanceof SDKError) throw error;
1841
+ throw createApiError("Failed to parse response.", response.status, {
1842
+ contentType,
1843
+ error: error instanceof Error ? error.message : error
1844
+ });
1845
+ }
1846
+ }
1847
+ /**
1848
+ * Parse Payload CMS document response (findById/delete)
1849
+ * Returns document directly without wrapper
1850
+ */
1851
+ async parseDocumentResponse(response) {
1852
+ const contentType = response.headers.get("content-type");
1853
+ try {
1854
+ this.assertJsonResponse(response);
1855
+ const jsonData = await response.json();
1856
+ return jsonData;
1857
+ } catch (error) {
1858
+ if (error instanceof SDKError) throw error;
1859
+ throw createApiError("Failed to parse response.", response.status, {
1860
+ contentType,
1861
+ error: error instanceof Error ? error.message : error
1862
+ });
1765
1863
  }
1766
- },
1767
- shippingPolicies: {
1768
- calculate: operation("shipping-policies", "post", "/calculate")
1769
- },
1770
- discounts: {
1771
- validate: operation("discounts", "post", "/validate")
1772
1864
  }
1773
1865
  };
1774
- var portOneStandardActionCapabilityOperations = /* @__PURE__ */ new Set([
1775
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.create,
1776
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.retrieve,
1777
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.create,
1778
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.retrieve
1779
- ]);
1780
- var MEMBERSHIP_ENDPOINT_OPERATIONS = {
1781
- subscribe: operation(null, "post", "/memberships/subscribe"),
1782
- billingCustody: operation(null, "post", "/memberships/billing-custody"),
1783
- cancel: operation(null, "post", "/memberships/:id/cancel"),
1784
- me: operation(null, "get", "/memberships/me"),
1785
- chargeResult: operation(null, "post", "/memberships/:id/charge-result"),
1786
- refundResult: operation(null, "post", "/memberships/:id/refund-result"),
1787
- revoke: operation(null, "post", "/memberships/:id/revoke")
1788
- };
1789
- var EXTERNAL_EFFECT_CLAIM_ENDPOINT_OPERATIONS = {
1790
- claim: operation(null, "post", "/external-effect-claims/claim"),
1791
- get: operation(null, "post", "/external-effect-claims/get"),
1792
- arm: operation(null, "post", "/external-effect-claims/arm"),
1793
- release: operation(null, "post", "/external-effect-claims/release"),
1794
- report: operation(null, "post", "/external-effect-claims/report"),
1795
- recovery: operation(null, "post", "/external-effect-claims/recovery")
1796
- };
1797
- var INSTALLATION_CREDENTIAL_ENDPOINT_OPERATIONS = {
1798
- create: operation(null, "post", "/installation-credentials/create"),
1799
- get: operation(null, "post", "/installation-credentials/get"),
1800
- replace: operation(null, "post", "/installation-credentials/replace"),
1801
- dispose: operation(null, "post", "/installation-credentials/dispose")
1802
- };
1803
- var EXTERNAL_CUSTOMER_LINK_ENDPOINT_OPERATIONS = {
1804
- connect: operation("customers", "post", "/external-links/connect"),
1805
- get: operation("customers", "post", "/external-links/get"),
1806
- list: operation("customers", "post", "/external-links/list"),
1807
- unlink: operation("customers", "post", "/external-links/unlink"),
1808
- capturePreviousState: operation(
1809
- "customers",
1810
- "post",
1811
- "/external-links/capture-previous-state"
1812
- ),
1813
- clearPreviousState: operation(
1814
- "customers",
1815
- "post",
1816
- "/external-links/clear-previous-state"
1817
- )
1818
- };
1819
- var CUSTOMER_GROUP_ENDPOINT_OPERATIONS = {
1820
- members: operation("customer-groups", "get", "/:id/members"),
1821
- grant: operation("customer-groups", "post", "/:id/members/grant"),
1822
- revoke: operation("customer-groups", "post", "/:id/members/revoke")
1823
- };
1824
- var CUSTOMER_AUTH_ENDPOINT_OPERATIONS = {
1825
- register: operation("customers", "post", "/register"),
1826
- login: operation("customers", "post", "/login"),
1827
- refresh: operation("customers", "post", "/refresh"),
1828
- me: operation("customers", "get", "/me"),
1829
- updateProfile: operation("customers", "patch", "/me"),
1830
- forgotPassword: operation("customers", "post", "/forgot-password"),
1831
- resetPassword: operation("customers", "post", "/reset-password"),
1832
- changePassword: operation("customers", "post", "/change-password"),
1833
- revokeRefresh: operation("customers", "post", "/revoke-refresh"),
1834
- withdraw: operation("customers", "post", "/withdraw")
1835
- };
1836
- var EMBEDDED_ADMIN_ENDPOINT_OPERATIONS = {
1837
- show: operation("tenants", "get", "/embedded-admin-app"),
1838
- configure: operation("tenants", "patch", "/embedded-admin-app"),
1839
- disable: operation("tenants", "delete", "/embedded-admin-app")
1840
- };
1841
- var EVENTS_ENDPOINT_OPERATIONS = {
1842
- registrations: {
1843
- listMine: operation("event-registrations", "get", "/my")
1844
- },
1845
- events: {
1846
- convertSchedule: operation("events", "post", "/:id/schedule")
1847
- },
1848
- occurrences: {
1849
- range: operation("event-occurrences", "get", "/range"),
1850
- admissionAvailability: operation(
1851
- "event-occurrences",
1852
- "get",
1853
- "/admission-availability"
1854
- )
1866
+
1867
+ // src/utils/types.ts
1868
+ function resolveRelation(ref) {
1869
+ if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1870
+ return null;
1871
+ return ref;
1872
+ }
1873
+
1874
+ // src/core/metadata/index.ts
1875
+ var OPEN_GRAPH_IMAGE_SIZE = "1200";
1876
+ var LEGACY_OPEN_GRAPH_IMAGE_SIZE = "1536";
1877
+ function extractSeo(doc) {
1878
+ const seo = doc.seo ?? {};
1879
+ const og = seo.openGraph ?? {};
1880
+ return {
1881
+ title: seo.title ?? doc.title ?? null,
1882
+ description: seo.description ?? null,
1883
+ noIndex: seo.noIndex ?? null,
1884
+ canonical: seo.canonical ?? null,
1885
+ openGraph: {
1886
+ title: og.title ?? null,
1887
+ description: og.description ?? null,
1888
+ image: og.image ?? null
1889
+ }
1890
+ };
1891
+ }
1892
+ function generateMetadata(input, options) {
1893
+ const title = input.title ?? void 0;
1894
+ const description = input.description ?? void 0;
1895
+ const ogTitle = input.openGraph?.title ?? title;
1896
+ const ogDescription = input.openGraph?.description ?? description;
1897
+ const image = resolveMetaImage(input.openGraph?.image);
1898
+ return {
1899
+ title,
1900
+ description,
1901
+ ...input.noIndex && { robots: { index: false, follow: false } },
1902
+ ...input.canonical && { alternates: { canonical: input.canonical } },
1903
+ openGraph: {
1904
+ ...ogTitle && { title: ogTitle },
1905
+ ...ogDescription && { description: ogDescription },
1906
+ ...options?.siteName && { siteName: options.siteName },
1907
+ ...image && { images: [image] }
1908
+ },
1909
+ twitter: {
1910
+ card: image ? "summary_large_image" : "summary",
1911
+ ...ogTitle && { title: ogTitle },
1912
+ ...ogDescription && { description: ogDescription },
1913
+ ...image && { images: [image.url] }
1914
+ }
1915
+ };
1916
+ }
1917
+ function resolveMetaImage(ref) {
1918
+ const image = resolveRelation(ref);
1919
+ if (!image) return null;
1920
+ const sized = image.sizes?.[OPEN_GRAPH_IMAGE_SIZE] ?? image.sizes?.[LEGACY_OPEN_GRAPH_IMAGE_SIZE];
1921
+ const url = sized?.url || image.url;
1922
+ if (!url) return null;
1923
+ const width = sized?.url ? sized.width : image.width;
1924
+ const height = sized?.url ? sized.height : image.height;
1925
+ return {
1926
+ url,
1927
+ ...width && { width },
1928
+ ...height && { height },
1929
+ ...image.alt && { alt: image.alt }
1930
+ };
1931
+ }
1932
+
1933
+ // src/core/collection/query-builder.ts
1934
+ var CollectionQueryBuilder = class {
1935
+ constructor(api, collection) {
1936
+ this.api = api;
1937
+ this.collection = collection;
1938
+ }
1939
+ /**
1940
+ * Find documents (list query)
1941
+ * GET /api/{collection}
1942
+ * @returns Payload CMS find response with docs array and pagination
1943
+ */
1944
+ async find(options) {
1945
+ return this.api.requestFind(
1946
+ `/api/${String(this.collection)}`,
1947
+ options
1948
+ );
1949
+ }
1950
+ /**
1951
+ * Find document by ID
1952
+ * GET /api/{collection}/{id}
1953
+ * @returns Document object directly (no wrapper)
1954
+ */
1955
+ async findById(id, options) {
1956
+ return this.api.requestFindById(
1957
+ `/api/${String(this.collection)}/${String(id)}`,
1958
+ options
1959
+ );
1960
+ }
1961
+ /**
1962
+ * Create a new document
1963
+ * POST /api/{collection}
1964
+ * @returns Payload CMS mutation response with doc and message
1965
+ */
1966
+ async create(data, options) {
1967
+ const endpoint = `/api/${String(this.collection)}`;
1968
+ if (options?.file) {
1969
+ return this.api.requestCreateWithFile(
1970
+ endpoint,
1971
+ data,
1972
+ options.file,
1973
+ options.filename
1974
+ );
1975
+ }
1976
+ return this.api.requestCreate(endpoint, data);
1855
1977
  }
1856
- };
1857
- var COMMUNITY_ENDPOINT_OPERATIONS = {
1858
- posts: {
1859
- detail: operation("posts", "get", "/detail")
1978
+ /**
1979
+ * Update a document by ID
1980
+ * PATCH /api/{collection}/{id}
1981
+ * @returns Payload CMS mutation response with doc and message
1982
+ */
1983
+ async update(id, data, options) {
1984
+ const endpoint = `/api/${String(this.collection)}/${String(id)}`;
1985
+ if (options?.file) {
1986
+ return this.api.requestUpdateWithFile(
1987
+ endpoint,
1988
+ data,
1989
+ options.file,
1990
+ options.filename
1991
+ );
1992
+ }
1993
+ return this.api.requestUpdate(endpoint, data);
1860
1994
  }
1861
- };
1862
- var GALLERY_ENDPOINT_OPERATIONS = {
1863
- items: {
1864
- storefront: operation("gallery-items", "get", "/storefront")
1995
+ /**
1996
+ * Count documents
1997
+ * GET /api/{collection}/count
1998
+ * @returns Count response with totalDocs
1999
+ */
2000
+ async count(options) {
2001
+ return this.api.requestCount(
2002
+ `/api/${String(this.collection)}/count`,
2003
+ options
2004
+ );
2005
+ }
2006
+ /**
2007
+ * Find first matching document and return its Next.js Metadata.
2008
+ * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
2009
+ * @returns Metadata or null if no document matches
2010
+ */
2011
+ async findMetadata(options, metadataOptions) {
2012
+ const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
2013
+ const doc = docs[0];
2014
+ if (!doc) return null;
2015
+ return generateMetadata(
2016
+ extractSeo(doc),
2017
+ metadataOptions
2018
+ );
2019
+ }
2020
+ /**
2021
+ * Find document by ID and return its Next.js Metadata.
2022
+ * Applies depth: 1 (SEO image populate) automatically.
2023
+ * @returns Metadata (throws on 404)
2024
+ */
2025
+ async findMetadataById(id, metadataOptions) {
2026
+ const doc = await this.findById(id, { depth: 1 });
2027
+ return generateMetadata(
2028
+ extractSeo(doc),
2029
+ metadataOptions
2030
+ );
2031
+ }
2032
+ /**
2033
+ * Update multiple documents (bulk update)
2034
+ * PATCH /api/{collection}
2035
+ * @returns Payload CMS find response with updated docs
2036
+ */
2037
+ async updateMany(where, data) {
2038
+ return this.api.requestUpdateMany(
2039
+ `/api/${String(this.collection)}`,
2040
+ { where, data }
2041
+ );
2042
+ }
2043
+ /**
2044
+ * Delete a document by ID
2045
+ * DELETE /api/{collection}/{id}
2046
+ * @returns Deleted document object directly (no wrapper)
2047
+ */
2048
+ async remove(id, options) {
2049
+ return this.api.requestDelete(
2050
+ `/api/${String(this.collection)}/${String(id)}`,
2051
+ options
2052
+ );
2053
+ }
2054
+ /**
2055
+ * Delete multiple documents (bulk delete)
2056
+ * DELETE /api/{collection}
2057
+ * @returns Payload CMS find response with deleted docs
2058
+ */
2059
+ async removeMany(where) {
2060
+ return this.api.requestDeleteMany(
2061
+ `/api/${String(this.collection)}`,
2062
+ { where }
2063
+ );
1865
2064
  }
1866
2065
  };
1867
- var VIDEO_ENDPOINT_OPERATIONS = {
1868
- playback: operation("videos", "post", "/:id/playback")
2066
+ var ServerCollectionQueryBuilder = class extends CollectionQueryBuilder {
1869
2067
  };
1870
- function resolveOperationTemplate(descriptor) {
1871
- return descriptor.collection ? `/api/${descriptor.collection}${descriptor.path}` : `/api${descriptor.path}`;
2068
+
2069
+ // src/core/collection/collection-client.ts
2070
+ function buildPayloadFormData(data, file, filename) {
2071
+ const formData = new FormData();
2072
+ formData.append("file", file, filename);
2073
+ if (data != null) {
2074
+ formData.append("_payload", JSON.stringify(data));
2075
+ }
2076
+ return formData;
1872
2077
  }
1873
- function resolveOperationPath(descriptor, options) {
1874
- const path = resolveOperationTemplate(descriptor).replace(
1875
- /:([A-Za-z][A-Za-z0-9_]*)/g,
1876
- (_, key) => {
1877
- const value = options?.pathParams?.[key];
1878
- if (value === void 0) {
1879
- throw new TypeError(`Missing path parameter: ${key}`);
1880
- }
1881
- return encodeURIComponent(value);
1882
- }
1883
- );
1884
- const unresolved = path.match(/:([A-Za-z][A-Za-z0-9_]*)/);
1885
- if (unresolved) {
1886
- throw new TypeError(`Missing path parameter: ${unresolved[1]}`);
2078
+ var CollectionClient = class extends HttpClient {
2079
+ from(collection) {
2080
+ return new CollectionQueryBuilder(this, collection);
2081
+ }
2082
+ // ============================================================================
2083
+ // Payload-native methods
2084
+ // ============================================================================
2085
+ /**
2086
+ * Find documents (list query)
2087
+ * GET /api/{collection}
2088
+ */
2089
+ async requestFind(endpoint, options) {
2090
+ const url = this.buildUrl(endpoint, options);
2091
+ const response = await this.fetchWithTracking(url, {
2092
+ ...this.defaultOptions,
2093
+ method: "GET"
2094
+ });
2095
+ return this.parseFindResponse(response);
2096
+ }
2097
+ /**
2098
+ * Find-like response from a custom endpoint
2099
+ * POST /api/...custom-endpoint
2100
+ */
2101
+ async requestFindEndpoint(endpoint, data) {
2102
+ const response = await this.fetchWithTracking(endpoint, {
2103
+ ...this.defaultOptions,
2104
+ method: "POST",
2105
+ body: data ? JSON.stringify(data) : void 0
2106
+ });
2107
+ return this.parseFindResponse(response);
2108
+ }
2109
+ /**
2110
+ * Find-like response from a cacheable GET custom endpoint.
2111
+ */
2112
+ async requestFindEndpointGet(endpoint) {
2113
+ const response = await this.fetchWithTracking(endpoint, {
2114
+ ...this.defaultOptions,
2115
+ method: "GET"
2116
+ });
2117
+ return this.parseFindResponse(response);
2118
+ }
2119
+ /**
2120
+ * Find document by ID
2121
+ * GET /api/{collection}/{id}
2122
+ */
2123
+ async requestFindById(endpoint, options) {
2124
+ const url = this.buildUrl(endpoint, options);
2125
+ const response = await this.fetchWithTracking(url, {
2126
+ ...this.defaultOptions,
2127
+ method: "GET"
2128
+ });
2129
+ return this.parseDocumentResponse(response);
2130
+ }
2131
+ /**
2132
+ * Create document
2133
+ * POST /api/{collection}
2134
+ */
2135
+ async requestCreate(endpoint, data) {
2136
+ const response = await this.fetchWithTracking(endpoint, {
2137
+ ...this.defaultOptions,
2138
+ method: "POST",
2139
+ body: data ? JSON.stringify(data) : void 0
2140
+ });
2141
+ return this.parseMutationResponse(response);
2142
+ }
2143
+ /**
2144
+ * Update document
2145
+ * PATCH /api/{collection}/{id}
2146
+ */
2147
+ async requestUpdate(endpoint, data) {
2148
+ const response = await this.fetchWithTracking(endpoint, {
2149
+ ...this.defaultOptions,
2150
+ method: "PATCH",
2151
+ body: data ? JSON.stringify(data) : void 0
2152
+ });
2153
+ return this.parseMutationResponse(response);
2154
+ }
2155
+ /**
2156
+ * Count documents
2157
+ * GET /api/{collection}/count
2158
+ */
2159
+ async requestCount(endpoint, options) {
2160
+ const url = this.buildUrl(endpoint, options);
2161
+ const response = await this.fetchWithTracking(url, {
2162
+ ...this.defaultOptions,
2163
+ method: "GET"
2164
+ });
2165
+ return this.parseDocumentResponse(response);
2166
+ }
2167
+ /**
2168
+ * Update multiple documents (bulk update)
2169
+ * PATCH /api/{collection}
2170
+ */
2171
+ async requestUpdateMany(endpoint, data) {
2172
+ const url = this.buildUrl(endpoint, { where: data.where });
2173
+ const response = await this.fetchWithTracking(url, {
2174
+ ...this.defaultOptions,
2175
+ method: "PATCH",
2176
+ body: JSON.stringify(data.data)
2177
+ });
2178
+ return this.parseFindResponse(response);
2179
+ }
2180
+ /**
2181
+ * Delete document
2182
+ * DELETE /api/{collection}/{id}
2183
+ */
2184
+ async requestDelete(endpoint, options) {
2185
+ const url = this.buildUrl(endpoint, options);
2186
+ const response = await this.fetchWithTracking(url, {
2187
+ ...this.defaultOptions,
2188
+ method: "DELETE"
2189
+ });
2190
+ return this.parseDocumentResponse(response);
2191
+ }
2192
+ /**
2193
+ * Delete multiple documents (bulk delete)
2194
+ * DELETE /api/{collection}
2195
+ */
2196
+ async requestDeleteMany(endpoint, data) {
2197
+ const url = this.buildUrl(endpoint, { where: data.where });
2198
+ const response = await this.fetchWithTracking(url, {
2199
+ ...this.defaultOptions,
2200
+ method: "DELETE"
2201
+ });
2202
+ return this.parseFindResponse(response);
2203
+ }
2204
+ /**
2205
+ * Create document with file upload
2206
+ * POST /api/{collection} (multipart/form-data)
2207
+ */
2208
+ async requestCreateWithFile(endpoint, data, file, filename) {
2209
+ const response = await this.fetchWithTracking(endpoint, {
2210
+ ...this.defaultOptions,
2211
+ method: "POST",
2212
+ body: buildPayloadFormData(data, file, filename)
2213
+ });
2214
+ return this.parseMutationResponse(response);
1887
2215
  }
1888
- const query = options?.query?.toString().replace(/^\?/, "");
1889
- return query ? `${path}?${query}` : path;
1890
- }
1891
- function resolveOperationMethod(descriptor) {
1892
- return descriptor.method.toUpperCase();
1893
- }
1894
-
1895
- // src/core/api/endpoints.ts
1896
- var sharedEndpoint = (descriptor) => descriptor;
1897
- function resolveOperationErrorFamily(descriptor) {
1898
- return descriptor.errorFamily;
1899
- }
1900
- function resolveOperationTypedCommerceErrorReasons(descriptor) {
1901
- return descriptor.typedCommerceErrorReasons;
1902
- }
1903
- var COMMERCE_ENDPOINTS = {
1904
- products: {
1905
- detail: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.products.detail),
1906
- detailCatalog: sharedEndpoint(
1907
- COMMERCE_ENDPOINT_OPERATIONS.products.detailCatalog
1908
- ),
1909
- listingGroups: sharedEndpoint(
1910
- COMMERCE_ENDPOINT_OPERATIONS.products.listingGroups
1911
- ),
1912
- listingGroupsCatalog: sharedEndpoint(
1913
- COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsCatalog
1914
- ),
1915
- // The manifest keeps the GET read and the POST body-query apart; this
1916
- // semantic name has always resolved to the GET one.
1917
- listingGroupsQuery: sharedEndpoint(
1918
- COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsQueryGet
1919
- ),
1920
- listingGroupsQueryCatalog: sharedEndpoint(
1921
- COMMERCE_ENDPOINT_OPERATIONS.products.listingGroupsQueryCatalog
1922
- ),
1923
- stockCheck: sharedEndpoint(
1924
- COMMERCE_ENDPOINT_OPERATIONS.products.stockCheck
1925
- ),
1926
- stockSnapshot: sharedEndpoint(
1927
- COMMERCE_ENDPOINT_OPERATIONS.products.stockSnapshot
1928
- ),
1929
- upsert: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.products.upsert)
1930
- },
1931
- orders: {
1932
- update: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.update),
1933
- byPayment: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.byPayment),
1934
- cancel: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.cancel),
1935
- resolveCancelRefund: sharedEndpoint(
1936
- COMMERCE_ENDPOINT_OPERATIONS.orders.resolveCancelRefund
1937
- ),
1938
- createFulfillment: sharedEndpoint(
1939
- COMMERCE_ENDPOINT_OPERATIONS.orders.createFulfillment
1940
- ),
1941
- updateFulfillment: sharedEndpoint(
1942
- COMMERCE_ENDPOINT_OPERATIONS.orders.updateFulfillment
1943
- )
1944
- },
1945
- checkouts: {
1946
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.checkout),
1947
- retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.detail),
1948
- server: {
1949
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.orders.checkout),
1950
- retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.detail),
1951
- query: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.checkouts.query)
1952
- }
1953
- },
1954
- returns: {
1955
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.returns.create),
1956
- update: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.returns.update),
1957
- returnRefund: sharedEndpoint(
1958
- COMMERCE_ENDPOINT_OPERATIONS.returns.returnRefund
1959
- )
1960
- },
1961
- fulfillmentOrders: {
1962
- prepare: sharedEndpoint(
1963
- COMMERCE_ENDPOINT_OPERATIONS.fulfillmentOrders.prepare
1964
- )
1965
- },
1966
- fulfillments: {
1967
- bulkImport: sharedEndpoint(
1968
- COMMERCE_ENDPOINT_OPERATIONS.fulfillments.bulkImport
1969
- )
1970
- },
1971
- carts: {
1972
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.create),
1973
- retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.retrieve),
1974
- mine: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.mine),
1975
- merge: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.merge),
1976
- server: {
1977
- // Server credentials are an authorization lane, not a second Cart
1978
- // transport. These must stay bound to the registered shared operations.
1979
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.create),
1980
- retrieve: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.retrieve),
1981
- mine: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.mine),
1982
- merge: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.merge),
1983
- addItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.addItem),
1984
- updateItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.updateItem),
1985
- removeItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.removeItem),
1986
- updateDiscountCodes: sharedEndpoint(
1987
- COMMERCE_ENDPOINT_OPERATIONS.carts.updateDiscountCodes
1988
- ),
1989
- updateAttributes: sharedEndpoint(
1990
- COMMERCE_ENDPOINT_OPERATIONS.carts.updateAttributes
1991
- ),
1992
- clear: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.clear)
1993
- },
1994
- addItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.addItem),
1995
- updateItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.updateItem),
1996
- removeItem: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.removeItem),
1997
- updateDiscountCodes: sharedEndpoint(
1998
- COMMERCE_ENDPOINT_OPERATIONS.carts.updateDiscountCodes
1999
- ),
2000
- updateAttributes: sharedEndpoint(
2001
- COMMERCE_ENDPOINT_OPERATIONS.carts.updateAttributes
2002
- ),
2003
- clear: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.carts.clear)
2004
- },
2005
- paymentSessions: {
2006
- create: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.create),
2007
- retrieve: sharedEndpoint(
2008
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.retrieve
2009
- ),
2010
- cancel: sharedEndpoint(COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.cancel),
2011
- custom: {
2012
- create: sharedEndpoint(
2013
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.create
2014
- ),
2015
- retrieve: sharedEndpoint(
2016
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.retrieve
2017
- ),
2018
- confirm: sharedEndpoint(
2019
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.custom.confirm
2020
- )
2021
- },
2022
- server: {
2023
- create: sharedEndpoint(
2024
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.create
2025
- ),
2026
- retrieve: sharedEndpoint(
2027
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.retrieve
2028
- ),
2029
- cancel: sharedEndpoint(
2030
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.cancel
2031
- ),
2032
- confirm: sharedEndpoint(
2033
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.confirm
2034
- ),
2035
- findPortOne: sharedEndpoint(
2036
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.findPortOne
2037
- ),
2038
- reconcilePortOne: sharedEndpoint(
2039
- COMMERCE_ENDPOINT_OPERATIONS.paymentSessions.server.reconcilePortOne
2040
- )
2041
- }
2042
- },
2043
- shippingPolicies: {
2044
- calculate: sharedEndpoint(
2045
- COMMERCE_ENDPOINT_OPERATIONS.shippingPolicies.calculate
2046
- )
2216
+ /**
2217
+ * Update document with file upload
2218
+ * PATCH /api/{collection}/{id} (multipart/form-data)
2219
+ */
2220
+ async requestUpdateWithFile(endpoint, data, file, filename) {
2221
+ const response = await this.fetchWithTracking(endpoint, {
2222
+ ...this.defaultOptions,
2223
+ method: "PATCH",
2224
+ body: buildPayloadFormData(data, file, filename)
2225
+ });
2226
+ return this.parseMutationResponse(response);
2227
+ }
2228
+ };
2229
+ var ServerCollectionClient = class extends CollectionClient {
2230
+ from(collection) {
2231
+ return new ServerCollectionQueryBuilder(this, collection);
2047
2232
  }
2048
2233
  };
2049
2234
 
@@ -2454,81 +2639,6 @@ var CommunityClient = class extends RawCustomerScopedApi {
2454
2639
  }
2455
2640
  };
2456
2641
 
2457
- // src/core/api/base-api.ts
2458
- var ServerApiTransport = class {
2459
- constructor(apiName, options) {
2460
- if (!options.secretKey) {
2461
- throw createConfigError(`secretKey is required for ${apiName}.`);
2462
- }
2463
- this.publishableKey = requirePublishableKeyForSecret(
2464
- apiName,
2465
- options.publishableKey,
2466
- options.secretKey
2467
- );
2468
- this.secretKey = options.secretKey;
2469
- this.apiUrl = options.apiUrl;
2470
- this.onRequestId = options.onRequestId;
2471
- }
2472
- async request(endpoint, body, options) {
2473
- const method = options?.method ?? "POST";
2474
- try {
2475
- const response = await httpFetch(endpoint, {
2476
- method,
2477
- apiUrl: this.apiUrl,
2478
- publishableKey: this.publishableKey,
2479
- secretKey: this.secretKey,
2480
- ...body !== void 0 && { body: JSON.stringify(body) },
2481
- ...options?.headers && { headers: options.headers },
2482
- ...options?.errorFamily && { errorFamily: options.errorFamily },
2483
- ...options?.typedCommerceErrorReasons && {
2484
- typedCommerceErrorReasons: options.typedCommerceErrorReasons
2485
- }
2486
- });
2487
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
2488
- return parseApiResponse(response, endpoint, {
2489
- errorFamily: options?.errorFamily
2490
- });
2491
- } catch (err) {
2492
- const id = err instanceof SDKError ? err.requestId ?? null : null;
2493
- this.onRequestId?.(id);
2494
- throw err;
2495
- }
2496
- }
2497
- };
2498
- var BaseApi = class {
2499
- constructor(apiName, options) {
2500
- this.transport = new ServerApiTransport(apiName, options);
2501
- }
2502
- requestEndpoint(endpoint, body, options) {
2503
- return this.transport.request(
2504
- resolveOperationPath(endpoint, options),
2505
- body,
2506
- {
2507
- method: resolveOperationMethod(endpoint),
2508
- headers: options?.headers,
2509
- errorFamily: resolveOperationErrorFamily(endpoint),
2510
- typedCommerceErrorReasons: resolveOperationTypedCommerceErrorReasons(endpoint)
2511
- }
2512
- );
2513
- }
2514
- };
2515
- var RawBaseApi = class {
2516
- constructor(apiName, options) {
2517
- this.transport = new ServerApiTransport(apiName, options);
2518
- this.publishableKey = requirePublishableKeyForSecret(
2519
- apiName,
2520
- options.publishableKey,
2521
- options.secretKey
2522
- );
2523
- this.secretKey = options.secretKey;
2524
- this.apiUrl = options.apiUrl;
2525
- this.onRequestId = options.onRequestId;
2526
- }
2527
- request(endpoint, body, options) {
2528
- return this.transport.request(endpoint, body, options);
2529
- }
2530
- };
2531
-
2532
2642
  // src/core/community/moderation-api.ts
2533
2643
  var ModerationApi = class extends RawBaseApi {
2534
2644
  constructor(options) {
@@ -6609,8 +6719,8 @@ var InstallationCredentialsApi = class extends BaseApi {
6609
6719
  function invalidResponse3() {
6610
6720
  throw createApiError("Invalid external-customer link response", 200);
6611
6721
  }
6612
- var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6613
- var isUuid = (value) => typeof value === "string" && (uuid.test(value) || value === "00000000-0000-0000-0000-000000000000" || value.toLowerCase() === "ffffffff-ffff-ffff-ffff-ffffffffffff");
6722
+ var uuid2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6723
+ var isUuid = (value) => typeof value === "string" && (uuid2.test(value) || value === "00000000-0000-0000-0000-000000000000" || value.toLowerCase() === "ffffffff-ffff-ffff-ffff-ffffffffffff");
6614
6724
  var isIdentity = (value) => typeof value === "string" && value.length > 0 && value.length <= 256 && value === value.trim() && // eslint-disable-next-line no-control-regex -- Normalized identity forbids C0 controls.
6615
6725
  !/[\u0000-\u001f]/.test(value) && !/[\uD800-\uDFFF]/u.test(value);
6616
6726
  var isDateTime = (value) => {
@@ -6757,6 +6867,7 @@ var ServerClient = class _ServerClient {
6757
6867
  this.customerGroups = new CustomerGroupApi(serverOptions);
6758
6868
  this.externalEffectClaims = new ExternalEffectClaimsApi(serverOptions);
6759
6869
  this.installationCredentials = new InstallationCredentialsApi(serverOptions);
6870
+ this.benefitVouchers = new BenefitVouchersApi(serverOptions);
6760
6871
  this.externalCustomerLinks = new ExternalCustomerLinksApi(serverOptions);
6761
6872
  const tenantIntrospectionApi = new TenantIntrospectionApi(serverOptions);
6762
6873
  this.tenant = {
@@ -6831,6 +6942,7 @@ function createServerClient(options) {
6831
6942
  return new ServerClient(options);
6832
6943
  }
6833
6944
  export {
6945
+ BenefitVouchersApi,
6834
6946
  CollectionClient,
6835
6947
  CommunityClient,
6836
6948
  CustomerGroupApi,