@01.software/sdk 0.65.1 → 0.68.0

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