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