@01.software/sdk 0.37.0 → 0.38.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 (48) hide show
  1. package/README.md +75 -53
  2. package/dist/client.cjs +67 -104
  3. package/dist/client.cjs.map +1 -1
  4. package/dist/client.d.cts +6 -6
  5. package/dist/client.d.ts +6 -6
  6. package/dist/client.js +67 -104
  7. package/dist/client.js.map +1 -1
  8. package/dist/{collection-client-zOmnxwdA.d.cts → collection-client-B0J9wMNE.d.cts} +5 -5
  9. package/dist/{collection-client-DyELGUcL.d.ts → collection-client-BroIWHY1.d.ts} +5 -5
  10. package/dist/const-6XHz_jej.d.ts +32 -0
  11. package/dist/const-B5KT72c7.d.cts +32 -0
  12. package/dist/{index-DRJs7QIh.d.cts → index-BOLQxveo.d.cts} +3 -3
  13. package/dist/{index-DTqoUZk_.d.ts → index-CSwR2HSg.d.ts} +3 -3
  14. package/dist/index.cjs +95 -123
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +9 -9
  17. package/dist/index.d.ts +9 -9
  18. package/dist/index.js +95 -123
  19. package/dist/index.js.map +1 -1
  20. package/dist/{payload-types-CREOjFNT.d.cts → payload-types-m3jjhxk9.d.cts} +418 -106
  21. package/dist/{payload-types-CREOjFNT.d.ts → payload-types-m3jjhxk9.d.ts} +418 -106
  22. package/dist/query.cjs +3 -1035
  23. package/dist/query.cjs.map +1 -1
  24. package/dist/query.d.cts +13 -13
  25. package/dist/query.d.ts +13 -13
  26. package/dist/query.js +3 -1035
  27. package/dist/query.js.map +1 -1
  28. package/dist/realtime.d.cts +2 -2
  29. package/dist/realtime.d.ts +2 -2
  30. package/dist/server.cjs +42 -21
  31. package/dist/server.cjs.map +1 -1
  32. package/dist/server.d.cts +7 -7
  33. package/dist/server.d.ts +7 -7
  34. package/dist/server.js +42 -21
  35. package/dist/server.js.map +1 -1
  36. package/dist/{types-DMvVHdb1.d.ts → types-CIGscmus.d.cts} +1455 -1208
  37. package/dist/{types-CxzWHspI.d.ts → types-Cmrd1ezc.d.ts} +1 -15
  38. package/dist/{types-BkZNhuBh.d.cts → types-D0ubzQw0.d.cts} +1 -15
  39. package/dist/{types-BWMUr3Zw.d.cts → types-D2xYdz4P.d.ts} +1455 -1208
  40. package/dist/ui/form.d.cts +1 -1
  41. package/dist/ui/form.d.ts +1 -1
  42. package/dist/ui/video.d.cts +1 -1
  43. package/dist/ui/video.d.ts +1 -1
  44. package/dist/webhook.d.cts +4 -4
  45. package/dist/webhook.d.ts +4 -4
  46. package/package.json +3 -3
  47. package/dist/const-CK_FPaIn.d.cts +0 -32
  48. package/dist/const-Dqz05oaG.d.ts +0 -32
package/dist/query.js CHANGED
@@ -377,115 +377,13 @@ var SDKError = class extends Error {
377
377
  };
378
378
  }
379
379
  };
380
- var NetworkError = class extends SDKError {
381
- constructor(message, status, details, userMessage, suggestion) {
382
- super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
383
- this.name = "NetworkError";
384
- }
385
- };
386
- var ValidationError = class extends SDKError {
387
- constructor(message, details, userMessage, suggestion, status = 400) {
388
- super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
389
- this.name = "ValidationError";
390
- }
391
- };
392
- var ApiError = class extends SDKError {
393
- constructor(message, status, details, userMessage, suggestion, requestId) {
394
- super(
395
- "API_ERROR",
396
- message,
397
- status,
398
- details,
399
- userMessage,
400
- suggestion,
401
- requestId
402
- );
403
- this.name = "ApiError";
404
- }
405
- };
406
380
  var ConfigError = class extends SDKError {
407
381
  constructor(message, details, userMessage, suggestion) {
408
382
  super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
409
383
  this.name = "ConfigError";
410
384
  }
411
385
  };
412
- var TimeoutError = class extends SDKError {
413
- constructor(message = "Request timed out.", details, userMessage, suggestion) {
414
- super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
415
- this.name = "TimeoutError";
416
- }
417
- };
418
- var UsageLimitError = class extends SDKError {
419
- constructor(message, usage, details, userMessage, suggestion) {
420
- super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
421
- this.name = "UsageLimitError";
422
- this.usage = usage;
423
- }
424
- toJSON() {
425
- return {
426
- ...super.toJSON(),
427
- usage: this.usage
428
- };
429
- }
430
- };
431
- var AuthError = class extends SDKError {
432
- constructor(message, details, userMessage, suggestion, requestId) {
433
- super(
434
- "auth_error",
435
- message,
436
- 401,
437
- details,
438
- userMessage,
439
- suggestion,
440
- requestId
441
- );
442
- this.name = "AuthError";
443
- }
444
- };
445
- var PermissionError = class extends SDKError {
446
- constructor(message, details, userMessage, suggestion, requestId) {
447
- super(
448
- "permission_error",
449
- message,
450
- 403,
451
- details,
452
- userMessage,
453
- suggestion,
454
- requestId
455
- );
456
- this.name = "PermissionError";
457
- }
458
- };
459
- var NotFoundError = class extends SDKError {
460
- constructor(message, details, userMessage, suggestion, requestId) {
461
- super(
462
- "not_found",
463
- message,
464
- 404,
465
- details,
466
- userMessage,
467
- suggestion,
468
- requestId
469
- );
470
- this.name = "NotFoundError";
471
- }
472
- };
473
- var ConflictError = class extends SDKError {
474
- constructor(message, details, userMessage, suggestion, requestId) {
475
- super("conflict", message, 409, details, userMessage, suggestion, requestId);
476
- this.name = "ConflictError";
477
- }
478
- };
479
- var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
480
- var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
481
- var createApiError = (message, status, details, userMessage, suggestion, requestId) => new ApiError(message, status, details, userMessage, suggestion, requestId);
482
386
  var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
483
- var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
484
- var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
485
- var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
486
- var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
487
- var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
488
- var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
489
387
 
490
388
  // src/core/query/customer-hooks.ts
491
389
  function createMutation(mutationFn, callbacks, onSuccessExtra) {
@@ -983,7 +881,7 @@ var RealtimeConnection = class {
983
881
  }
984
882
  scheduleReconnect() {
985
883
  if (this.reconnectTimer) return;
986
- const delay2 = Math.min(
884
+ const delay = Math.min(
987
885
  INITIAL_RECONNECT_DELAY * Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),
988
886
  MAX_RECONNECT_DELAY
989
887
  );
@@ -992,918 +890,7 @@ var RealtimeConnection = class {
992
890
  this.reconnectTimer = null;
993
891
  this.abortController = new AbortController();
994
892
  this.startStream(this.abortController.signal);
995
- }, delay2);
996
- }
997
- };
998
-
999
- // src/utils/types.ts
1000
- function resolveRelation(ref) {
1001
- if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1002
- return null;
1003
- return ref;
1004
- }
1005
-
1006
- // src/core/metadata/index.ts
1007
- var OPEN_GRAPH_IMAGE_SIZE = "1200";
1008
- var LEGACY_OPEN_GRAPH_IMAGE_SIZE = "1536";
1009
- function extractSeo(doc) {
1010
- const seo = doc.seo ?? {};
1011
- const og = seo.openGraph ?? {};
1012
- return {
1013
- title: seo.title ?? doc.title ?? null,
1014
- description: seo.description ?? null,
1015
- noIndex: seo.noIndex ?? null,
1016
- canonical: seo.canonical ?? null,
1017
- openGraph: {
1018
- title: og.title ?? null,
1019
- description: og.description ?? null,
1020
- image: og.image ?? null
1021
- }
1022
- };
1023
- }
1024
- function generateMetadata(input, options) {
1025
- const title = input.title ?? void 0;
1026
- const description = input.description ?? void 0;
1027
- const ogTitle = input.openGraph?.title ?? title;
1028
- const ogDescription = input.openGraph?.description ?? description;
1029
- const image = resolveMetaImage(input.openGraph?.image);
1030
- return {
1031
- title,
1032
- description,
1033
- ...input.noIndex && { robots: { index: false, follow: false } },
1034
- ...input.canonical && { alternates: { canonical: input.canonical } },
1035
- openGraph: {
1036
- ...ogTitle && { title: ogTitle },
1037
- ...ogDescription && { description: ogDescription },
1038
- ...options?.siteName && { siteName: options.siteName },
1039
- ...image && { images: [image] }
1040
- },
1041
- twitter: {
1042
- card: image ? "summary_large_image" : "summary",
1043
- ...ogTitle && { title: ogTitle },
1044
- ...ogDescription && { description: ogDescription },
1045
- ...image && { images: [image.url] }
1046
- }
1047
- };
1048
- }
1049
- function resolveMetaImage(ref) {
1050
- const image = resolveRelation(ref);
1051
- if (!image) return null;
1052
- const sized = image.sizes?.[OPEN_GRAPH_IMAGE_SIZE] ?? image.sizes?.[LEGACY_OPEN_GRAPH_IMAGE_SIZE];
1053
- const url = sized?.url || image.url;
1054
- if (!url) return null;
1055
- const width = sized?.url ? sized.width : image.width;
1056
- const height = sized?.url ? sized.height : image.height;
1057
- return {
1058
- url,
1059
- ...width && { width },
1060
- ...height && { height },
1061
- ...image.alt && { alt: image.alt }
1062
- };
1063
- }
1064
-
1065
- // src/core/collection/query-builder.ts
1066
- var CollectionQueryBuilder = class {
1067
- constructor(api, collection) {
1068
- this.api = api;
1069
- this.collection = collection;
1070
- }
1071
- /**
1072
- * Find documents (list query)
1073
- * GET /api/{collection}
1074
- * @returns Payload CMS find response with docs array and pagination
1075
- */
1076
- async find(options) {
1077
- return this.api.requestFind(
1078
- `/api/${String(this.collection)}`,
1079
- options
1080
- );
1081
- }
1082
- /**
1083
- * Find document by ID
1084
- * GET /api/{collection}/{id}
1085
- * @returns Document object directly (no wrapper)
1086
- */
1087
- async findById(id, options) {
1088
- return this.api.requestFindById(
1089
- `/api/${String(this.collection)}/${String(id)}`,
1090
- options
1091
- );
1092
- }
1093
- /**
1094
- * Create a new document
1095
- * POST /api/{collection}
1096
- * @returns Payload CMS mutation response with doc and message
1097
- */
1098
- async create(data, options) {
1099
- const endpoint = `/api/${String(this.collection)}`;
1100
- if (options?.file) {
1101
- return this.api.requestCreateWithFile(
1102
- endpoint,
1103
- data,
1104
- options.file,
1105
- options.filename
1106
- );
1107
- }
1108
- return this.api.requestCreate(endpoint, data);
1109
- }
1110
- /**
1111
- * Update a document by ID
1112
- * PATCH /api/{collection}/{id}
1113
- * @returns Payload CMS mutation response with doc and message
1114
- */
1115
- async update(id, data, options) {
1116
- const endpoint = `/api/${String(this.collection)}/${String(id)}`;
1117
- if (options?.file) {
1118
- return this.api.requestUpdateWithFile(
1119
- endpoint,
1120
- data,
1121
- options.file,
1122
- options.filename
1123
- );
1124
- }
1125
- return this.api.requestUpdate(endpoint, data);
1126
- }
1127
- /**
1128
- * Count documents
1129
- * GET /api/{collection}/count
1130
- * @returns Count response with totalDocs
1131
- */
1132
- async count(options) {
1133
- return this.api.requestCount(
1134
- `/api/${String(this.collection)}/count`,
1135
- options
1136
- );
1137
- }
1138
- /**
1139
- * Find first matching document and return its Next.js Metadata.
1140
- * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
1141
- * @returns Metadata or null if no document matches
1142
- */
1143
- async findMetadata(options, metadataOptions) {
1144
- const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
1145
- const doc = docs[0];
1146
- if (!doc) return null;
1147
- return generateMetadata(
1148
- extractSeo(doc),
1149
- metadataOptions
1150
- );
1151
- }
1152
- /**
1153
- * Find document by ID and return its Next.js Metadata.
1154
- * Applies depth: 1 (SEO image populate) automatically.
1155
- * @returns Metadata (throws on 404)
1156
- */
1157
- async findMetadataById(id, metadataOptions) {
1158
- const doc = await this.findById(id, { depth: 1 });
1159
- return generateMetadata(
1160
- extractSeo(doc),
1161
- metadataOptions
1162
- );
1163
- }
1164
- /**
1165
- * Update multiple documents (bulk update)
1166
- * PATCH /api/{collection}
1167
- * @returns Payload CMS find response with updated docs
1168
- */
1169
- async updateMany(where, data) {
1170
- return this.api.requestUpdateMany(
1171
- `/api/${String(this.collection)}`,
1172
- { where, data }
1173
- );
1174
- }
1175
- /**
1176
- * Delete a document by ID
1177
- * DELETE /api/{collection}/{id}
1178
- * @returns Deleted document object directly (no wrapper)
1179
- */
1180
- async remove(id) {
1181
- return this.api.requestDelete(
1182
- `/api/${String(this.collection)}/${String(id)}`
1183
- );
1184
- }
1185
- /**
1186
- * Delete multiple documents (bulk delete)
1187
- * DELETE /api/{collection}
1188
- * @returns Payload CMS find response with deleted docs
1189
- */
1190
- async removeMany(where) {
1191
- return this.api.requestDeleteMany(
1192
- `/api/${String(this.collection)}`,
1193
- { where }
1194
- );
1195
- }
1196
- };
1197
-
1198
- // src/core/collection/http-client.ts
1199
- import { stringify } from "qs-esm";
1200
-
1201
- // src/core/internal/utils/credentials.ts
1202
- function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
1203
- if (secretKey && !publishableKey) {
1204
- throw createConfigError(
1205
- `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
1206
- );
1207
- }
1208
- return publishableKey ?? "";
1209
- }
1210
-
1211
- // src/core/client/types.ts
1212
- function resolveApiUrl(apiUrl) {
1213
- if (apiUrl) {
1214
- return apiUrl.replace(/\/$/, "");
1215
- }
1216
- if (typeof process !== "undefined" && process.env) {
1217
- const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
1218
- if (envUrl) {
1219
- return envUrl.replace(/\/$/, "");
1220
- }
1221
- }
1222
- return "https://api.01.software";
1223
- }
1224
-
1225
- // src/core/internal/utils/http.ts
1226
- var DEFAULT_TIMEOUT = 3e4;
1227
- var STOREFRONT_BROWSER_TIMEOUT = 15e3;
1228
- var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
1229
- var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
1230
- var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
1231
- var DEFAULT_MAX_RETRIES = 3;
1232
- var STOREFRONT_BROWSER_MAX_RETRIES = 1;
1233
- function debugLog(debug, type, message, data) {
1234
- if (!debug) return;
1235
- const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
1236
- if (shouldLog) {
1237
- console.group(`[SDK ${type.toUpperCase()}] ${message}`);
1238
- if (data) console.log(data);
1239
- console.groupEnd();
1240
- }
1241
- }
1242
- function redactSensitiveHeader(value) {
1243
- const prefix = value.toLowerCase().startsWith("bearer ") ? "Bearer " : "";
1244
- return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : "****";
1245
- }
1246
- function redactSensitiveHeaders(headers) {
1247
- const redacted = Object.fromEntries(headers.entries());
1248
- if (redacted.authorization) {
1249
- redacted.authorization = redactSensitiveHeader(redacted.authorization);
1250
- }
1251
- if (redacted["x-preview-token"]) {
1252
- redacted["x-preview-token"] = redactSensitiveHeader(
1253
- redacted["x-preview-token"]
1254
- );
1255
- }
1256
- return redacted;
1257
- }
1258
- function getErrorSuggestion(status) {
1259
- if (status === 400)
1260
- return "The request data failed validation. Check field values and types.";
1261
- if (status === 401) return "Please check your authentication credentials.";
1262
- if (status === 403)
1263
- return "Access denied. Check your credentials or permissions.";
1264
- if (status === 404) return "The requested resource was not found.";
1265
- if (status === 422) return "The request data failed validation.";
1266
- if (status >= 500) return "A server error occurred. Please try again later.";
1267
- return void 0;
1268
- }
1269
- function isUsageLimitExceededResponse(response) {
1270
- if (response.status !== 429) return false;
1271
- const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
1272
- const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
1273
- if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
1274
- return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
1275
- }
1276
- async function parseErrorBody(response) {
1277
- const fallback = {
1278
- errorMessage: `HTTP ${response.status}: ${response.statusText}`,
1279
- userMessage: `Request failed (status: ${response.status})`
1280
- };
1281
- try {
1282
- const body = await response.json();
1283
- const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
1284
- if (body.errors && Array.isArray(body.errors)) {
1285
- const fieldErrors = [];
1286
- for (const e of body.errors) {
1287
- if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
1288
- for (const fe of e.data.errors) {
1289
- fieldErrors.push({
1290
- field: fe.path || fe.field,
1291
- message: fe.message
1292
- });
1293
- }
1294
- } else if (e.field || e.message) {
1295
- fieldErrors.push({ field: e.field, message: e.message });
1296
- }
1297
- }
1298
- const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
1299
- (e) => e.field ? `${e.field}: ${e.message}` : e.message
1300
- ).filter(Boolean).join("; ");
1301
- if (details) {
1302
- return {
1303
- errorMessage: `HTTP ${response.status}: ${details}`,
1304
- userMessage: details,
1305
- reason,
1306
- body,
1307
- errors: fieldErrors.length > 0 ? fieldErrors : body.errors
1308
- };
1309
- }
1310
- }
1311
- if (typeof body.error === "string") {
1312
- return {
1313
- errorMessage: `HTTP ${response.status}: ${body.error}`,
1314
- userMessage: body.error,
1315
- reason,
1316
- body
1317
- };
1318
- }
1319
- if (body.message) {
1320
- return {
1321
- errorMessage: `HTTP ${response.status}: ${body.message}`,
1322
- userMessage: body.message,
1323
- reason,
1324
- body
1325
- };
1326
- }
1327
- return { ...fallback, reason, body };
1328
- } catch {
1329
- return fallback;
1330
- }
1331
- }
1332
- function getParsedErrorSuggestion(status, parsed) {
1333
- if (status === 403 && parsed.reason === "origin_not_allowed") {
1334
- return "Add the request origin to the tenant Browser API origins, then retry the browser request.";
1335
- }
1336
- return getErrorSuggestion(status);
1337
- }
1338
- async function delay(ms) {
1339
- return new Promise((resolve) => setTimeout(resolve, ms));
1340
- }
1341
- function attachRequestId(err, id) {
1342
- if (id) err.requestId = id;
1343
- return err;
1344
- }
1345
- function createHttpStatusError(status, parsed, details, requestId) {
1346
- const errorDetails = {
1347
- ...details,
1348
- ...parsed.errors && { errors: parsed.errors },
1349
- ...parsed.body && { body: parsed.body }
1350
- };
1351
- const suggestion = getParsedErrorSuggestion(status, parsed);
1352
- if (status === 400 || status === 422) {
1353
- return attachRequestId(
1354
- createValidationError(
1355
- parsed.errorMessage,
1356
- errorDetails,
1357
- parsed.userMessage,
1358
- suggestion,
1359
- status
1360
- ),
1361
- requestId
1362
- );
1363
- }
1364
- if (status === 401) {
1365
- return attachRequestId(
1366
- createAuthError(
1367
- parsed.errorMessage,
1368
- errorDetails,
1369
- parsed.userMessage,
1370
- suggestion
1371
- ),
1372
- requestId
1373
- );
1374
- }
1375
- if (status === 403) {
1376
- return attachRequestId(
1377
- createPermissionError(
1378
- parsed.errorMessage,
1379
- errorDetails,
1380
- parsed.userMessage,
1381
- suggestion
1382
- ),
1383
- requestId
1384
- );
1385
- }
1386
- if (status === 404) {
1387
- return attachRequestId(
1388
- createNotFoundError(
1389
- parsed.errorMessage,
1390
- errorDetails,
1391
- parsed.userMessage,
1392
- suggestion
1393
- ),
1394
- requestId
1395
- );
1396
- }
1397
- if (status === 409) {
1398
- return attachRequestId(
1399
- createConflictError(
1400
- parsed.errorMessage,
1401
- errorDetails,
1402
- parsed.userMessage,
1403
- suggestion
1404
- ),
1405
- requestId
1406
- );
1407
- }
1408
- return attachRequestId(
1409
- createNetworkError(
1410
- parsed.errorMessage,
1411
- status,
1412
- errorDetails,
1413
- parsed.userMessage,
1414
- suggestion
1415
- ),
1416
- requestId
1417
- );
1418
- }
1419
- async function httpFetch(url, options) {
1420
- const {
1421
- apiUrl,
1422
- publishableKey,
1423
- secretKey,
1424
- customerToken,
1425
- timeout: timeoutOption = DEFAULT_TIMEOUT,
1426
- debug,
1427
- retry,
1428
- onUnauthorized,
1429
- ...requestInit
1430
- } = options || {};
1431
- const baseUrl = resolveApiUrl(apiUrl);
1432
- const method = (requestInit.method || "GET").toUpperCase();
1433
- const isPublishableKeyBrowserGet = typeof window !== "undefined" && !secretKey && !customerToken && Boolean(publishableKey) && SAFE_METHODS.includes(method);
1434
- const timeout = timeoutOption === DEFAULT_TIMEOUT && isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_TIMEOUT : timeoutOption;
1435
- const retryConfig = {
1436
- maxRetries: retry?.maxRetries ?? (isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_MAX_RETRIES : DEFAULT_MAX_RETRIES),
1437
- retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
1438
- retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
1439
- };
1440
- let authToken;
1441
- if (secretKey) {
1442
- authToken = secretKey;
1443
- } else if (customerToken) {
1444
- authToken = customerToken;
1445
- }
1446
- let lastError;
1447
- let hasRetried401 = false;
1448
- for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
1449
- try {
1450
- const headers = new Headers(requestInit.headers);
1451
- if (publishableKey) {
1452
- headers.set("X-Publishable-Key", publishableKey);
1453
- }
1454
- if (authToken) {
1455
- headers.set("Authorization", `Bearer ${authToken}`);
1456
- }
1457
- if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
1458
- headers.set("Content-Type", "application/json");
1459
- }
1460
- const redactedHeaders = redactSensitiveHeaders(headers);
1461
- debugLog(debug, "request", url, {
1462
- method: requestInit.method || "GET",
1463
- headers: redactedHeaders,
1464
- attempt: attempt + 1
1465
- });
1466
- const controller = new AbortController();
1467
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1468
- const response = await fetch(`${baseUrl}${url}`, {
1469
- ...requestInit,
1470
- headers,
1471
- signal: controller.signal
1472
- });
1473
- clearTimeout(timeoutId);
1474
- const requestId = response.headers.get("x-request-id") ?? void 0;
1475
- debugLog(debug, "response", url, {
1476
- status: response.status,
1477
- statusText: response.statusText,
1478
- headers: redactSensitiveHeaders(response.headers)
1479
- });
1480
- if (!response.ok) {
1481
- if (isUsageLimitExceededResponse(response)) {
1482
- const limit = parseInt(
1483
- response.headers.get("X-Usage-Limit") || "0",
1484
- 10
1485
- );
1486
- const current = parseInt(
1487
- response.headers.get("X-Usage-Current") || "0",
1488
- 10
1489
- );
1490
- const remaining = parseInt(
1491
- response.headers.get("X-Usage-Remaining") || "0",
1492
- 10
1493
- );
1494
- throw attachRequestId(
1495
- createUsageLimitError(
1496
- `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
1497
- { limit, current, remaining },
1498
- {
1499
- url,
1500
- method: requestInit.method || "GET",
1501
- attempt: attempt + 1
1502
- },
1503
- "Monthly API call limit exceeded. Please upgrade your plan.",
1504
- "Upgrade your tenant plan to increase the monthly API call limit."
1505
- ),
1506
- requestId
1507
- );
1508
- }
1509
- const parsed = await parseErrorBody(response);
1510
- if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
1511
- hasRetried401 = true;
1512
- try {
1513
- const newToken = await onUnauthorized();
1514
- if (newToken) {
1515
- authToken = newToken;
1516
- continue;
1517
- }
1518
- } catch {
1519
- }
1520
- }
1521
- const details = {
1522
- url,
1523
- method: requestInit.method || "GET",
1524
- attempt: attempt + 1
1525
- };
1526
- if (NON_RETRYABLE_STATUSES.includes(response.status)) {
1527
- throw createHttpStatusError(
1528
- response.status,
1529
- parsed,
1530
- details,
1531
- requestId
1532
- );
1533
- }
1534
- const error = attachRequestId(
1535
- createNetworkError(
1536
- parsed.errorMessage,
1537
- response.status,
1538
- details,
1539
- parsed.userMessage,
1540
- getErrorSuggestion(response.status)
1541
- ),
1542
- requestId
1543
- );
1544
- const method2 = (requestInit.method || "GET").toUpperCase();
1545
- if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method2) && retryConfig.retryableStatuses.includes(response.status)) {
1546
- lastError = error;
1547
- const retryDelay = retryConfig.retryDelay(attempt);
1548
- debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
1549
- await delay(retryDelay);
1550
- continue;
1551
- }
1552
- throw error;
1553
- }
1554
- return response;
1555
- } catch (error) {
1556
- debugLog(debug, "error", url, error);
1557
- const method2 = (requestInit.method || "GET").toUpperCase();
1558
- const isSafe = SAFE_METHODS.includes(method2);
1559
- if (error instanceof Error && error.name === "AbortError") {
1560
- const timeoutError = createTimeoutError(
1561
- `Request timed out after ${timeout}ms.`,
1562
- { url, timeout, attempt: attempt + 1 },
1563
- "The request timed out.",
1564
- "Please check your network connection or try again later."
1565
- );
1566
- if (isSafe && attempt < retryConfig.maxRetries) {
1567
- lastError = timeoutError;
1568
- await delay(retryConfig.retryDelay(attempt));
1569
- continue;
1570
- }
1571
- throw timeoutError;
1572
- }
1573
- if (error instanceof TypeError) {
1574
- const networkError = createNetworkError(
1575
- "Network connection failed.",
1576
- void 0,
1577
- { url, originalError: error.message, attempt: attempt + 1 },
1578
- "Network connection failed.",
1579
- "Please check your internet connection and try again."
1580
- );
1581
- if (isSafe && attempt < retryConfig.maxRetries) {
1582
- lastError = networkError;
1583
- await delay(retryConfig.retryDelay(attempt));
1584
- continue;
1585
- }
1586
- throw networkError;
1587
- }
1588
- if (error instanceof NetworkError || error instanceof TimeoutError) {
1589
- if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
1590
- lastError = error;
1591
- await delay(retryConfig.retryDelay(attempt));
1592
- continue;
1593
- }
1594
- throw error;
1595
- }
1596
- if (error instanceof SDKError) {
1597
- throw error;
1598
- }
1599
- const unknownError = createNetworkError(
1600
- error instanceof Error ? error.message : "An unknown network error occurred.",
1601
- void 0,
1602
- { url, originalError: error, attempt: attempt + 1 },
1603
- "An unknown error occurred.",
1604
- "Please try again later."
1605
- );
1606
- if (isSafe && attempt < retryConfig.maxRetries) {
1607
- lastError = unknownError;
1608
- await delay(retryConfig.retryDelay(attempt));
1609
- continue;
1610
- }
1611
- throw unknownError;
1612
- }
1613
- }
1614
- throw lastError ?? new NetworkError("Request failed after retries");
1615
- }
1616
-
1617
- // src/core/collection/http-client.ts
1618
- var HttpClient = class {
1619
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1620
- this.publishableKey = requirePublishableKeyForSecret(
1621
- "CollectionClient",
1622
- publishableKey,
1623
- secretKey
1624
- );
1625
- this.secretKey = secretKey;
1626
- this.getCustomerToken = getCustomerToken;
1627
- this.onUnauthorized = onUnauthorized;
1628
- this.onRequestId = onRequestId;
1629
- this.apiUrl = apiUrl;
1630
- }
1631
- get defaultOptions() {
1632
- const opts = {
1633
- apiUrl: this.apiUrl,
1634
- publishableKey: this.publishableKey,
1635
- secretKey: this.secretKey
1636
- };
1637
- const token = this.getCustomerToken?.();
1638
- if (token) {
1639
- opts.customerToken = token;
1640
- if (this.onUnauthorized) {
1641
- opts.onUnauthorized = this.onUnauthorized;
1642
- }
1643
- }
1644
- return opts;
1645
- }
1646
- async fetchWithTracking(url, opts) {
1647
- try {
1648
- const response = await httpFetch(url, opts);
1649
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1650
- return response;
1651
- } catch (err) {
1652
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1653
- this.onRequestId?.(id);
1654
- throw err;
1655
- }
1656
- }
1657
- buildUrl(endpoint, options) {
1658
- if (!options) return endpoint;
1659
- const queryString = stringify(options, { addQueryPrefix: true });
1660
- return queryString ? `${endpoint}${queryString}` : endpoint;
1661
- }
1662
- assertJsonResponse(response) {
1663
- const contentType = response.headers.get("content-type");
1664
- if (!contentType?.includes("application/json")) {
1665
- throw createApiError("Response is not in JSON format.", response.status, {
1666
- contentType
1667
- });
1668
- }
1669
- }
1670
- /**
1671
- * Parse Payload CMS find response (list query)
1672
- * Returns native Payload response structure
1673
- */
1674
- async parseFindResponse(response) {
1675
- const contentType = response.headers.get("content-type");
1676
- try {
1677
- this.assertJsonResponse(response);
1678
- const jsonData = await response.json();
1679
- if (jsonData.docs === void 0) {
1680
- throw createApiError("Invalid find response.", response.status, {
1681
- jsonData
1682
- });
1683
- }
1684
- return {
1685
- docs: jsonData.docs,
1686
- totalDocs: jsonData.totalDocs ?? 0,
1687
- limit: jsonData.limit || 20,
1688
- totalPages: jsonData.totalPages ?? 0,
1689
- page: jsonData.page || 1,
1690
- pagingCounter: jsonData.pagingCounter || 1,
1691
- hasPrevPage: jsonData.hasPrevPage ?? false,
1692
- hasNextPage: jsonData.hasNextPage ?? false,
1693
- prevPage: jsonData.prevPage ?? null,
1694
- nextPage: jsonData.nextPage ?? null
1695
- };
1696
- } catch (error) {
1697
- if (error instanceof SDKError) throw error;
1698
- throw createApiError("Failed to parse response.", response.status, {
1699
- contentType,
1700
- error: error instanceof Error ? error.message : error
1701
- });
1702
- }
1703
- }
1704
- /**
1705
- * Parse Payload CMS mutation response (create/update)
1706
- * Returns native Payload response structure
1707
- */
1708
- async parseMutationResponse(response) {
1709
- const contentType = response.headers.get("content-type");
1710
- try {
1711
- this.assertJsonResponse(response);
1712
- const jsonData = await response.json();
1713
- if (jsonData.doc === void 0) {
1714
- throw createApiError("Invalid mutation response.", response.status, {
1715
- jsonData
1716
- });
1717
- }
1718
- return {
1719
- message: jsonData.message || "",
1720
- doc: jsonData.doc,
1721
- errors: jsonData.errors
1722
- };
1723
- } catch (error) {
1724
- if (error instanceof SDKError) throw error;
1725
- throw createApiError("Failed to parse response.", response.status, {
1726
- contentType,
1727
- error: error instanceof Error ? error.message : error
1728
- });
1729
- }
1730
- }
1731
- /**
1732
- * Parse Payload CMS document response (findById/delete)
1733
- * Returns document directly without wrapper
1734
- */
1735
- async parseDocumentResponse(response) {
1736
- const contentType = response.headers.get("content-type");
1737
- try {
1738
- this.assertJsonResponse(response);
1739
- const jsonData = await response.json();
1740
- return jsonData;
1741
- } catch (error) {
1742
- if (error instanceof SDKError) throw error;
1743
- throw createApiError("Failed to parse response.", response.status, {
1744
- contentType,
1745
- error: error instanceof Error ? error.message : error
1746
- });
1747
- }
1748
- }
1749
- };
1750
-
1751
- // src/core/collection/collection-client.ts
1752
- function buildPayloadFormData(data, file, filename) {
1753
- const formData = new FormData();
1754
- formData.append("file", file, filename);
1755
- if (data != null) {
1756
- formData.append("_payload", JSON.stringify(data));
1757
- }
1758
- return formData;
1759
- }
1760
- var CollectionClient = class extends HttpClient {
1761
- from(collection) {
1762
- return new CollectionQueryBuilder(this, collection);
1763
- }
1764
- // ============================================================================
1765
- // Payload-native methods
1766
- // ============================================================================
1767
- /**
1768
- * Find documents (list query)
1769
- * GET /api/{collection}
1770
- */
1771
- async requestFind(endpoint, options) {
1772
- const url = this.buildUrl(endpoint, options);
1773
- const response = await this.fetchWithTracking(url, {
1774
- ...this.defaultOptions,
1775
- method: "GET"
1776
- });
1777
- return this.parseFindResponse(response);
1778
- }
1779
- /**
1780
- * Find-like response from a custom endpoint
1781
- * POST /api/...custom-endpoint
1782
- */
1783
- async requestFindEndpoint(endpoint, data) {
1784
- const response = await this.fetchWithTracking(endpoint, {
1785
- ...this.defaultOptions,
1786
- method: "POST",
1787
- body: data ? JSON.stringify(data) : void 0
1788
- });
1789
- return this.parseFindResponse(response);
1790
- }
1791
- /**
1792
- * Find-like response from a cacheable GET custom endpoint.
1793
- */
1794
- async requestFindEndpointGet(endpoint) {
1795
- const response = await this.fetchWithTracking(endpoint, {
1796
- ...this.defaultOptions,
1797
- method: "GET"
1798
- });
1799
- return this.parseFindResponse(response);
1800
- }
1801
- /**
1802
- * Find document by ID
1803
- * GET /api/{collection}/{id}
1804
- */
1805
- async requestFindById(endpoint, options) {
1806
- const url = this.buildUrl(endpoint, options);
1807
- const response = await this.fetchWithTracking(url, {
1808
- ...this.defaultOptions,
1809
- method: "GET"
1810
- });
1811
- return this.parseDocumentResponse(response);
1812
- }
1813
- /**
1814
- * Create document
1815
- * POST /api/{collection}
1816
- */
1817
- async requestCreate(endpoint, data) {
1818
- const response = await this.fetchWithTracking(endpoint, {
1819
- ...this.defaultOptions,
1820
- method: "POST",
1821
- body: data ? JSON.stringify(data) : void 0
1822
- });
1823
- return this.parseMutationResponse(response);
1824
- }
1825
- /**
1826
- * Update document
1827
- * PATCH /api/{collection}/{id}
1828
- */
1829
- async requestUpdate(endpoint, data) {
1830
- const response = await this.fetchWithTracking(endpoint, {
1831
- ...this.defaultOptions,
1832
- method: "PATCH",
1833
- body: data ? JSON.stringify(data) : void 0
1834
- });
1835
- return this.parseMutationResponse(response);
1836
- }
1837
- /**
1838
- * Count documents
1839
- * GET /api/{collection}/count
1840
- */
1841
- async requestCount(endpoint, options) {
1842
- const url = this.buildUrl(endpoint, options);
1843
- const response = await this.fetchWithTracking(url, {
1844
- ...this.defaultOptions,
1845
- method: "GET"
1846
- });
1847
- return this.parseDocumentResponse(response);
1848
- }
1849
- /**
1850
- * Update multiple documents (bulk update)
1851
- * PATCH /api/{collection}
1852
- */
1853
- async requestUpdateMany(endpoint, data) {
1854
- const response = await this.fetchWithTracking(endpoint, {
1855
- ...this.defaultOptions,
1856
- method: "PATCH",
1857
- body: JSON.stringify(data)
1858
- });
1859
- return this.parseFindResponse(response);
1860
- }
1861
- /**
1862
- * Delete document
1863
- * DELETE /api/{collection}/{id}
1864
- */
1865
- async requestDelete(endpoint) {
1866
- const response = await this.fetchWithTracking(endpoint, {
1867
- ...this.defaultOptions,
1868
- method: "DELETE"
1869
- });
1870
- return this.parseDocumentResponse(response);
1871
- }
1872
- /**
1873
- * Delete multiple documents (bulk delete)
1874
- * DELETE /api/{collection}
1875
- */
1876
- async requestDeleteMany(endpoint, data) {
1877
- const response = await this.fetchWithTracking(endpoint, {
1878
- ...this.defaultOptions,
1879
- method: "DELETE",
1880
- body: JSON.stringify(data)
1881
- });
1882
- return this.parseFindResponse(response);
1883
- }
1884
- /**
1885
- * Create document with file upload
1886
- * POST /api/{collection} (multipart/form-data)
1887
- */
1888
- async requestCreateWithFile(endpoint, data, file, filename) {
1889
- const response = await this.fetchWithTracking(endpoint, {
1890
- ...this.defaultOptions,
1891
- method: "POST",
1892
- body: buildPayloadFormData(data, file, filename)
1893
- });
1894
- return this.parseMutationResponse(response);
1895
- }
1896
- /**
1897
- * Update document with file upload
1898
- * PATCH /api/{collection}/{id} (multipart/form-data)
1899
- */
1900
- async requestUpdateWithFile(endpoint, data, file, filename) {
1901
- const response = await this.fetchWithTracking(endpoint, {
1902
- ...this.defaultOptions,
1903
- method: "PATCH",
1904
- body: buildPayloadFormData(data, file, filename)
1905
- });
1906
- return this.parseMutationResponse(response);
893
+ }, delay);
1907
894
  }
1908
895
  };
1909
896
 
@@ -1946,28 +933,9 @@ function createReadOnlyQueryHooksFacade(hooks) {
1946
933
  };
1947
934
  }
1948
935
  function createQueryHooks(client, queryClient = getQueryClient()) {
1949
- const config = client.getConfig();
1950
- const onUnauthorized = async () => {
1951
- try {
1952
- const result = await client.customer.auth.refreshToken();
1953
- return result.token ?? null;
1954
- } catch {
1955
- return null;
1956
- }
1957
- };
1958
- const collectionClient = new CollectionClient(
1959
- config.publishableKey,
1960
- void 0,
1961
- () => client.customer.auth.getToken(),
1962
- onUnauthorized,
1963
- (id) => {
1964
- client.lastRequestId = id;
1965
- },
1966
- config.apiUrl
1967
- );
1968
936
  const hooks = new QueryHooks(
1969
937
  queryClient,
1970
- collectionClient,
938
+ client.collections,
1971
939
  client.customer.auth,
1972
940
  client.commerce
1973
941
  );