@01.software/sdk 0.67.0 → 0.69.0

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