@relyio/sdk 0.12.0 → 0.14.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/CHANGELOG.md +228 -0
  2. package/dist/{chunk-3DRDHXLY.js → chunk-5UMY6CS4.js} +435 -23
  3. package/dist/{chunk-FRJEUAAF.js → chunk-DBBZVZOS.js} +968 -2670
  4. package/dist/{chunk-DXCVO6M5.cjs → chunk-GUPV2M3X.cjs} +969 -2680
  5. package/dist/{chunk-POEEDYFM.js → chunk-PCFTJLEP.js} +543 -260
  6. package/dist/{chunk-FI5VIF4M.cjs → chunk-RSHMA4KT.cjs} +442 -22
  7. package/dist/{chunk-3MSFWXQL.cjs → chunk-X4KSS7PP.cjs} +542 -260
  8. package/dist/client/index.cjs +3 -3
  9. package/dist/client/index.d.cts +4 -5
  10. package/dist/client/index.d.ts +4 -5
  11. package/dist/client/index.js +1 -1
  12. package/dist/{include-paths-CL4gHv6I.d.cts → define-content-type-BUZeWtpk.d.cts} +4458 -1312
  13. package/dist/{include-paths-CrJNTsMl.d.ts → define-content-type-DOrZb_a_.d.ts} +4458 -1312
  14. package/dist/define-schema-5aHmsA8j.d.ts +699 -0
  15. package/dist/define-schema-nCfZeboB.d.cts +699 -0
  16. package/dist/index-B97ZDj44.d.ts +507 -0
  17. package/dist/index-C-pcllqY.d.cts +507 -0
  18. package/dist/index-DOhFQbv7.d.ts +3065 -0
  19. package/dist/index-DgVV5Nj7.d.cts +3065 -0
  20. package/dist/index.cjs +114 -147
  21. package/dist/index.d.cts +49 -87
  22. package/dist/index.d.ts +49 -87
  23. package/dist/index.js +5 -29
  24. package/dist/markdown/index.cjs +13750 -0
  25. package/dist/markdown/index.d.cts +111 -0
  26. package/dist/markdown/index.d.ts +111 -0
  27. package/dist/markdown/index.js +13742 -0
  28. package/dist/rich-text/index.cjs +26 -6
  29. package/dist/rich-text/index.d.cts +3 -148
  30. package/dist/rich-text/index.d.ts +3 -148
  31. package/dist/rich-text/index.js +1 -1
  32. package/dist/rich-text.d-BWc-5gX1.d.cts +326 -0
  33. package/dist/rich-text.d-BWc-5gX1.d.ts +326 -0
  34. package/dist/schema/index.cjs +33 -37
  35. package/dist/schema/index.d.cts +37 -191
  36. package/dist/schema/index.d.ts +37 -191
  37. package/dist/schema/index.js +1 -1
  38. package/dist/types/index.d.cts +2 -3
  39. package/dist/types/index.d.ts +2 -3
  40. package/package.json +14 -3
  41. package/dist/define-schema-DgctHlI2.d.cts +0 -1034
  42. package/dist/define-schema-mrEZbY1h.d.ts +0 -1034
  43. package/dist/index-B9RfZVF1.d.ts +0 -861
  44. package/dist/index-BrvEg6-A.d.cts +0 -3729
  45. package/dist/index-Pw0onkJe.d.ts +0 -3729
  46. package/dist/index-b-AkfTUv.d.cts +0 -861
  47. package/dist/rich-text.d-rKmpgdGd.d.cts +0 -200
  48. package/dist/rich-text.d-rKmpgdGd.d.ts +0 -200
@@ -302,6 +302,10 @@ function isResourceNotFound(error) {
302
302
  return error instanceof ResourceNotFoundError;
303
303
  }
304
304
  __name(isResourceNotFound, "isResourceNotFound");
305
+ function isMissingEntry(error) {
306
+ return error instanceof ResourceNotFoundError && error.context?.resourceType === "entry";
307
+ }
308
+ __name(isMissingEntry, "isMissingEntry");
305
309
 
306
310
  // src/errors/network-errors.ts
307
311
  var _NetworkError = class _NetworkError extends SDKError {
@@ -461,9 +465,12 @@ __name(refuseMismatchedAlternate, "refuseMismatchedAlternate");
461
465
 
462
466
  // ../../platform/api-contract/dist/index.js
463
467
  var HEADER_RETRY_AFTER = { name: "Retry-After" };
464
- var HEADER_ENTITY_TAG = { name: "X-Entity-Tag" };
465
468
  var HEADER_IF_MATCH = {
466
469
  name: "If-Match"};
470
+ function entityTag(parts) {
471
+ return `"${parts.entryUid}:${parts.locale}:${parts.version}:${parts.sharedVersion}"`;
472
+ }
473
+ __name(entityTag, "entityTag");
467
474
  var HEADER_IDEMPOTENCY_KEY = {
468
475
  name: "Idempotency-Key"};
469
476
  var FRESH_PARAMETER = "_fresh";
@@ -698,6 +705,7 @@ function parseRetryAfterMs(value, nowMs) {
698
705
  __name(parseRetryAfterMs, "parseRetryAfterMs");
699
706
 
700
707
  // src/errors/error-mapper.ts
708
+ var STALE_VERSION_GUIDANCE = "The entry changed since it was read: re-read it with `fresh: true` and retry the write with what that read returns.";
701
709
  var _ErrorMapper = class _ErrorMapper {
702
710
  /** Map a non-2xx response to an SDK error. */
703
711
  static mapHttpError(response, requestContext) {
@@ -765,10 +773,16 @@ var _ErrorMapper = class _ErrorMapper {
765
773
  });
766
774
  }
767
775
  case "RESOURCE_CONFLICT": {
768
- return new ResourceConflictError(message, 409, void 0, {
776
+ const expectedVersion = detailNumber(refusal, "expectedVersion");
777
+ const guidance = expectedVersion === void 0 ? message : `${message.endsWith(".") ? message : `${message}.`} ${STALE_VERSION_GUIDANCE}`;
778
+ return new ResourceConflictError(guidance, 409, void 0, {
769
779
  ...context,
770
- expectedVersion: detailNumber(refusal, "expectedVersion"),
771
- actualVersion: detailNumber(refusal, "actualVersion")
780
+ expectedVersion,
781
+ actualVersion: detailNumber(refusal, "actualVersion"),
782
+ // The shared fields' counter, which the `If-Match` tag carries beside the locale's and a
783
+ // write that changes a shared field is checked against (REL-2363).
784
+ expectedSharedVersion: detailNumber(refusal, "expectedSharedVersion"),
785
+ actualSharedVersion: detailNumber(refusal, "actualSharedVersion")
772
786
  });
773
787
  }
774
788
  case "RESOURCE_EXPIRED": {
@@ -930,6 +944,7 @@ var DECLARED_PATHS = {
930
944
  "/v1/meta/schema/{contentType}": true,
931
945
  "/v1/meta/schema/{contentType}/fields": true,
932
946
  "/v1/project": true,
947
+ "/v1/queries/{name}": true,
933
948
  "/v1/query": true,
934
949
  "/v1/search": true,
935
950
  "/v1/search/autocomplete": true,
@@ -1092,9 +1107,27 @@ var _HttpClient = class _HttpClient {
1092
1107
  constructor(config) {
1093
1108
  /** What every request reads off the configuration, derived by {@link configure} and nowhere else. */
1094
1109
  __publicField(this, "connection");
1110
+ /**
1111
+ * Set on a view {@link withHeaders} made: the client every request is sent through, and the
1112
+ * headers laid beneath each request's own. A view keeps no connection of its own that matters —
1113
+ * everything it is asked to change, it changes on that client.
1114
+ */
1115
+ __publicField(this, "view");
1095
1116
  this.connection = connectionFor(config);
1096
1117
  this.announce();
1097
1118
  }
1119
+ /**
1120
+ * A view of this client that sends every request through it with `headers` added — beneath the
1121
+ * request's own, over this client's — and changes nothing else: its key, base URL, timeout,
1122
+ * retries and `fetch` are this client's as they are when each request is sent, so a later
1123
+ * `configure()` or `setApiKey()` on this client reaches the view, and one on the view reaches
1124
+ * this client. `client.with({ dataset })` is one (REL-2417).
1125
+ */
1126
+ withHeaders(headers) {
1127
+ const view = new _HttpClient(this.connection.config);
1128
+ view.view = { client: this, headers: { ...headers } };
1129
+ return view;
1130
+ }
1098
1131
  /**
1099
1132
  * Run on `config` from now on: every later request — whoever holds this client — is sent to its
1100
1133
  * `baseUrl`, with its headers, key and dataset, its timeout and retries, through its `fetch`, and
@@ -1106,6 +1139,7 @@ var _HttpClient = class _HttpClient {
1106
1139
  * replaced by what `config` says.
1107
1140
  */
1108
1141
  configure(config) {
1142
+ if (this.view !== void 0) return this.view.client.configure(config);
1109
1143
  this.connection = connectionFor(config);
1110
1144
  this.announce();
1111
1145
  }
@@ -1164,6 +1198,12 @@ var _HttpClient = class _HttpClient {
1164
1198
  * given none.
1165
1199
  */
1166
1200
  async request(config) {
1201
+ if (this.view !== void 0) {
1202
+ return this.view.client.request({
1203
+ ...config,
1204
+ headers: layerHeaders(this.view.headers, config.headers)
1205
+ });
1206
+ }
1167
1207
  if (config.timeout !== void 0) assertRequestTimeout(config.timeout);
1168
1208
  const mergedConfig = this.mergeRequestConfig(config);
1169
1209
  if (presentKey(headerValue(mergedConfig.headers, API_KEY_HEADER)) === void 0) {
@@ -1274,6 +1314,7 @@ var _HttpClient = class _HttpClient {
1274
1314
  * matched without regard to case — until the client is next configured.
1275
1315
  */
1276
1316
  setDefaultHeaders(headers) {
1317
+ if (this.view !== void 0) return this.view.client.setDefaultHeaders(headers);
1277
1318
  this.connection = {
1278
1319
  ...this.connection,
1279
1320
  defaultHeaders: layerHeaders(this.connection.defaultHeaders, headers)
@@ -1297,6 +1338,7 @@ var _HttpClient = class _HttpClient {
1297
1338
  * never touched: the API reads `X-API-Key` first, so the old key was the one used (REL-1385).
1298
1339
  */
1299
1340
  setApiKey(apiKey) {
1341
+ if (this.view !== void 0) return this.view.client.setApiKey(apiKey);
1300
1342
  const { config } = this.connection;
1301
1343
  config.apiKey = apiKey;
1302
1344
  config.headers = layerHeaders(config.headers, { [API_KEY_HEADER]: null });
@@ -1311,18 +1353,23 @@ var _HttpClient = class _HttpClient {
1311
1353
  * Get current default headers
1312
1354
  */
1313
1355
  getDefaultHeaders() {
1356
+ if (this.view !== void 0) {
1357
+ return layerHeaders(this.view.client.getDefaultHeaders(), this.view.headers);
1358
+ }
1314
1359
  return { ...this.connection.defaultHeaders };
1315
1360
  }
1316
1361
  /**
1317
1362
  * Update base URL
1318
1363
  */
1319
1364
  setBaseUrl(baseUrl) {
1365
+ if (this.view !== void 0) return this.view.client.setBaseUrl(baseUrl);
1320
1366
  this.connection = { ...this.connection, baseUrl };
1321
1367
  }
1322
1368
  /**
1323
1369
  * Get current base URL
1324
1370
  */
1325
1371
  getBaseUrl() {
1372
+ if (this.view !== void 0) return this.view.client.getBaseUrl();
1326
1373
  return this.connection.baseUrl;
1327
1374
  }
1328
1375
  /**
@@ -1590,6 +1637,31 @@ function credentialsModeFor(includeCredentials) {
1590
1637
  }
1591
1638
  __name(credentialsModeFor, "credentialsModeFor");
1592
1639
 
1640
+ // src/http/write-options.ts
1641
+ function versionCheckOf(entry) {
1642
+ const { id, locale, version, sharedVersion } = entry._metadata;
1643
+ return { id, locale, ifMatch: entityTag({ entryUid: id, locale, version, sharedVersion }) };
1644
+ }
1645
+ __name(versionCheckOf, "versionCheckOf");
1646
+ function mintIdempotencyKey() {
1647
+ const webCrypto = globalThis.crypto;
1648
+ if (typeof webCrypto?.randomUUID !== "function") return void 0;
1649
+ return webCrypto.randomUUID();
1650
+ }
1651
+ __name(mintIdempotencyKey, "mintIdempotencyKey");
1652
+ function writeHeaders(options) {
1653
+ const headers = {};
1654
+ if (options?.ifMatch !== void 0) {
1655
+ headers[HEADER_IF_MATCH.name] = options.ifMatch;
1656
+ }
1657
+ const idempotencyKey = options?.idempotencyKey ?? mintIdempotencyKey();
1658
+ if (idempotencyKey !== void 0) {
1659
+ headers[HEADER_IDEMPOTENCY_KEY.name] = idempotencyKey;
1660
+ }
1661
+ return Object.keys(headers).length > 0 ? headers : void 0;
1662
+ }
1663
+ __name(writeHeaders, "writeHeaders");
1664
+
1593
1665
  // src/content/client-locale.ts
1594
1666
  function callLocale(named, clientLocale) {
1595
1667
  if (named !== void 0) return named;
@@ -1601,7 +1673,12 @@ function readClientLocale(locale) {
1601
1673
  }
1602
1674
  __name(readClientLocale, "readClientLocale");
1603
1675
 
1604
- // src/content/query-builder.ts
1676
+ // src/content/read-terms.ts
1677
+ function writeChildrenQuery(params, options) {
1678
+ params.children = options.depth === void 0 ? "true" : `${options.depth}`;
1679
+ if (options.limit !== void 0) params.childrenLimit = options.limit;
1680
+ }
1681
+ __name(writeChildrenQuery, "writeChildrenQuery");
1605
1682
  function namesMetadata(key) {
1606
1683
  return key === "_metadata" || key.startsWith("_metadata.");
1607
1684
  }
@@ -1619,887 +1696,309 @@ function refuseMetadataConditions(conditions) {
1619
1696
  );
1620
1697
  }
1621
1698
  __name(refuseMetadataConditions, "refuseMetadataConditions");
1622
- var _ContentQueryBuilder = class _ContentQueryBuilder {
1623
- /**
1624
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent when the
1625
- * query names none: the function `TypedRelyIOClient` hands over, or a locale fixed for it
1626
- */
1627
- constructor(httpClient, contentType, locale) {
1628
- this.httpClient = httpClient;
1629
- this.contentType = contentType;
1630
- __publicField(this, "queryOptions", {});
1631
- __publicField(this, "localeValue");
1632
- __publicField(this, "localesArray");
1633
- __publicField(this, "fetchAllLocales", false);
1634
- __publicField(this, "fieldsProjection");
1635
- __publicField(this, "childrenOptions");
1636
- __publicField(this, "pageNumber");
1637
- __publicField(this, "pageSizeValue");
1638
- __publicField(this, "requestHeaders");
1639
- /** The client's locale, asked when the query is sent rather than copied when it was built. */
1640
- __publicField(this, "clientLocale");
1641
- __publicField(this, "freshValue");
1642
- this.clientLocale = readClientLocale(locale);
1643
- }
1644
- /**
1645
- * The feed position this read follows — a change's `fresh` (`FeedChange`), or a resync's. Sent as
1646
- * `?_fresh`, the one term the API declares for it: no cache — the Content API's edge or the
1647
- * browser's own — holds an answer for that position from before it, so the read is answered after
1648
- * the change, and every read naming the same position shares that answer. The answer is the
1649
- * read's own; omit it for a read no change prompted.
1650
- */
1651
- fresh(position) {
1652
- this.freshValue = position;
1653
- return this;
1654
- }
1655
- /**
1656
- * Headers this query adds to the client's own, e.g. `X-RelyIO-Dataset` to list another dataset
1657
- * the key can see. A name the client already sends is replaced for this query only; the client
1658
- * is not changed.
1659
- */
1660
- headers(headers) {
1661
- this.requestHeaders = headers;
1662
- return this;
1663
- }
1664
- /**
1665
- * Add where conditions to the query: conditions on the fields the content type declares. A
1666
- * condition on `_metadata` is refused here, before anything is sent (`refuseMetadataConditions`).
1667
- */
1668
- where(conditions) {
1669
- refuseMetadataConditions(conditions);
1670
- this.queryOptions.where = {
1671
- ...this.queryOptions.where,
1672
- ...conditions
1673
- };
1674
- return this;
1675
- }
1676
- /**
1677
- * Select specific fields to return
1678
- */
1679
- select(fields) {
1680
- this.queryOptions.select = fields;
1681
- return this;
1682
- }
1683
- /**
1684
- * Expand references into the entries they point at: one include path per element (REL-1801).
1685
- * A path names fields through lists, page builders, objects and references —
1686
- * `'sections.features'`, `'sections.customers.logo'` — and may pick the fields each entry returns,
1687
- * `'sections.features(name,slug)'`. Each is checked against the schema: a path that holds no
1688
- * reference does not compile, and the read's type follows the paths — an expanded reference is the
1689
- * entry, every other one its id.
1690
- */
1691
- include(paths) {
1692
- this.queryOptions.include = [
1693
- ...this.queryOptions.include ?? [],
1694
- ...paths
1695
- ];
1696
- return this;
1699
+
1700
+ // src/content/read-options.ts
1701
+ function listQuery(options, clientLocale) {
1702
+ const query = {};
1703
+ if (options.where !== void 0) {
1704
+ refuseMetadataConditions(options.where);
1705
+ if (Object.keys(options.where).length > 0) query.filters = JSON.stringify(options.where);
1697
1706
  }
1698
- sort(fieldOrOptions, direction) {
1699
- if (typeof fieldOrOptions === "string") {
1700
- this.queryOptions.sort = {
1701
- ...this.queryOptions.sort,
1702
- [fieldOrOptions]: direction ?? "asc"
1703
- };
1704
- } else {
1705
- this.queryOptions.sort = {
1706
- ...this.queryOptions.sort,
1707
- ...fieldOrOptions
1708
- };
1709
- }
1710
- return this;
1707
+ if (options.select !== void 0 && options.select.length > 0) {
1708
+ query.fields = options.select.join(",");
1711
1709
  }
1712
- /**
1713
- * Sort by a specific field in ascending order
1714
- */
1715
- sortAsc(field) {
1716
- return this.sort(field, "asc");
1710
+ if (options.sort !== void 0) {
1711
+ const order = Object.entries(options.sort).flatMap(
1712
+ ([key, direction]) => direction === void 0 ? [] : [`${key}:${direction}`]
1713
+ );
1714
+ if (order.length > 0) query.sort = order.join(",");
1717
1715
  }
1718
- /**
1719
- * Sort by a specific field in descending order
1720
- */
1721
- sortDesc(field) {
1722
- return this.sort(field, "desc");
1716
+ if (options.limit !== void 0) query.limit = options.limit;
1717
+ if (options.cursor !== void 0) query.cursor = options.cursor;
1718
+ if (options.page !== void 0) query.page = options.page;
1719
+ writeReadTerms(query, options, clientLocale);
1720
+ return query;
1721
+ }
1722
+ __name(listQuery, "listQuery");
1723
+ function entryQuery(options, clientLocale) {
1724
+ const query = {};
1725
+ writeReadTerms(query, options, clientLocale);
1726
+ return query;
1727
+ }
1728
+ __name(entryQuery, "entryQuery");
1729
+ function documentQuery(options, clientLocale) {
1730
+ const query = {};
1731
+ writeDocumentTerms(query, options, clientLocale);
1732
+ return query;
1733
+ }
1734
+ __name(documentQuery, "documentQuery");
1735
+ function writeReadTerms(query, options, clientLocale) {
1736
+ writeDocumentTerms(query, options, clientLocale);
1737
+ if (options.children !== void 0) {
1738
+ writeChildrenQuery(query, options.children === true ? {} : options.children);
1723
1739
  }
1724
- /**
1725
- * Limit the number of results
1726
- */
1727
- limit(count) {
1728
- this.queryOptions.limit = count;
1729
- return this;
1740
+ }
1741
+ __name(writeReadTerms, "writeReadTerms");
1742
+ function writeDocumentTerms(query, options, clientLocale) {
1743
+ if (options.include !== void 0 && options.include.length > 0) {
1744
+ query.include = options.include.join(",");
1730
1745
  }
1731
- /**
1732
- * Set offset for pagination
1733
- */
1734
- offset(count) {
1735
- this.queryOptions.offset = count;
1736
- return this;
1746
+ writeLocale(query, options.locale ?? clientLocale);
1747
+ if (typeof options.fresh === "string") query[FRESH_PARAMETER] = options.fresh;
1748
+ }
1749
+ __name(writeDocumentTerms, "writeDocumentTerms");
1750
+ function writeLocale(query, locale) {
1751
+ if (locale === void 0) return;
1752
+ if (typeof locale === "string") {
1753
+ if (locale !== "") query.locale = locale;
1754
+ return;
1755
+ }
1756
+ if (locale.length === 0) {
1757
+ throw new ValidationError(
1758
+ "`locale` is an empty list, which names no locale to read. Name one code, a list of codes or '*'.",
1759
+ [{ field: "locale", code: "EMPTY_LOCALE_LIST", message: "locale names no code" }]
1760
+ );
1737
1761
  }
1762
+ query.locales = locale.join(",");
1763
+ }
1764
+ __name(writeLocale, "writeLocale");
1765
+ function readHeaders(options) {
1766
+ const headers = {};
1767
+ if (options.dataset !== void 0) headers[DATASET_HEADER] = options.dataset;
1768
+ if (options.fresh === true) headers["Cache-Control"] = "no-cache";
1769
+ return Object.keys(headers).length > 0 ? headers : void 0;
1770
+ }
1771
+ __name(readHeaders, "readHeaders");
1772
+
1773
+ // src/content/entry-handle.ts
1774
+ var _EntryHandle = class _EntryHandle {
1738
1775
  /**
1739
- * Set cursor for cursor-based pagination
1776
+ * @param typeName - The content or asset type the routes are addressed by
1777
+ * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, asked on
1778
+ * every call
1740
1779
  */
1741
- cursor(cursor) {
1742
- this.queryOptions.cursor = cursor;
1743
- return this;
1780
+ constructor(httpClient, typeName, locale) {
1781
+ this.httpClient = httpClient;
1782
+ this.typeName = typeName;
1783
+ /** The client's locale, asked on every call rather than copied when this handle was taken. */
1784
+ __publicField(this, "clientLocale");
1785
+ this.clientLocale = readClientLocale(locale);
1744
1786
  }
1745
1787
  /**
1746
- * Set locale for localized content
1747
- * @param locale - Locale code (e.g., 'en-US', 'de-DE', 'fr-FR')
1788
+ * One page of this type's entries: the API's own `{ data, page }`, as it answered (REL-2415).
1748
1789
  *
1749
- * @example
1750
- * ```typescript
1751
- * // Fetch in Spanish
1752
- * .locale('es-ES')
1753
- * ```
1754
- */
1755
- locale(locale) {
1756
- this.localeValue = locale;
1757
- this.localesArray = void 0;
1758
- this.fetchAllLocales = false;
1759
- return this;
1760
- }
1761
- /**
1762
- * Fetch content in multiple specific locales
1763
- * Returns primary locale at top level, others in _metadata.localizations
1790
+ * Page by `cursor` — the `page.nextCursor` a page handed back — to walk, or by `page` number for an
1791
+ * archive page like `/blog/page/3`; `limit` is the page size for both. The page is the cursor
1792
+ * dialect's `{ nextCursor, hasMore }`: a list carries no total.
1764
1793
  *
1765
- * @param localeCodes - Array of locale codes to fetch
1794
+ * The rest of the options have one name per concern (REL-2417): `select` the entry's own Fields,
1795
+ * `sort` an order whose key order is the priority, `locale` a code, a list of codes or `'*'`,
1796
+ * `dataset` this read's dataset, `fresh` how fresh the answer must be, `children` the children to
1797
+ * embed. See `ListReadOptions`.
1766
1798
  *
1767
1799
  * @example
1768
1800
  * ```typescript
1769
- * const product = await client.content('product')
1770
- * .findById('prod_123')
1771
- * .locales(['en-US', 'es-ES', 'de-DE'])
1772
- * .execute()
1773
- *
1774
- * // Access: product.title (first locale)
1775
- * // Access: product._metadata.localizations['es-ES'].title
1801
+ * const { data, page } = await relyio.content('post').list({
1802
+ * where: { category: 'news' },
1803
+ * include: ['author'],
1804
+ * select: ['title', 'slug'],
1805
+ * sort: { featured: 'desc', publishedAt: 'desc' },
1806
+ * limit: 10,
1807
+ * page: 3,
1808
+ * })
1776
1809
  * ```
1777
1810
  */
1778
- locales(localeCodes) {
1779
- this.localesArray = localeCodes;
1780
- this.localeValue = void 0;
1781
- this.fetchAllLocales = false;
1782
- return this;
1811
+ async list(options = {}) {
1812
+ const response = await this.httpClient.send(
1813
+ "/v1/{contentType}",
1814
+ "get",
1815
+ {
1816
+ path: { contentType: this.typeName },
1817
+ query: listQuery(options, this.clientLocale()),
1818
+ headers: readHeaders(options)
1819
+ }
1820
+ );
1821
+ return response.body;
1783
1822
  }
1784
1823
  /**
1785
- * Fetch content in all available locales
1786
- * Returns default locale at top level, others in _metadata.localizations
1787
- *
1788
- * @example
1789
- * ```typescript
1790
- * const product = await client.content('product')
1791
- * .findById('prod_123')
1792
- * .allLocales()
1793
- * .execute()
1824
+ * Every entry of this type that `where` keeps, page after page, as an async iterable: the walk
1825
+ * follows each page's cursor and stops where the API says there is no more (REL-2415).
1826
+ * `Array.fromAsync(relyio.content('post').listAll())` makes it an array. `limit` is how many each
1827
+ * request reads; every other option is a list's, sent with each page.
1794
1828
  *
1795
- * // Access: product.title (default locale)
1796
- * // Access: product._metadata.localizations['es-ES'].title
1797
- * // Access: product._metadata.availableLocales
1798
- * ```
1829
+ * Iterating throws when a page says there is more and hands back no cursor to read it by, rather
1830
+ * than ending the walk short.
1799
1831
  */
1800
- allLocales() {
1801
- this.fetchAllLocales = true;
1802
- this.localeValue = void 0;
1803
- this.localesArray = void 0;
1804
- return this;
1832
+ listAll(options = {}) {
1833
+ return this.walk(options);
1805
1834
  }
1806
- /**
1807
- * Select specific fields to return (projection)
1808
- * @param fieldNames - Array of field names to include
1809
- *
1810
- * @example
1811
- * ```typescript
1812
- * .fields(['id', 'title', 'price', 'brand.name'])
1813
- * ```
1814
- */
1815
- fields(fieldNames) {
1816
- this.fieldsProjection = fieldNames;
1817
- return this;
1835
+ async *walk(options) {
1836
+ let cursor;
1837
+ for (; ; ) {
1838
+ const { data, page } = await this.list(
1839
+ cursor === void 0 ? options : { ...options, cursor }
1840
+ );
1841
+ yield* data;
1842
+ if (!page.hasMore) return;
1843
+ if (page.nextCursor === null) {
1844
+ throw new Error(
1845
+ `${this.typeName}: a page of the list says there is more and hands back no cursor to read it by`
1846
+ );
1847
+ }
1848
+ cursor = page.nextCursor;
1849
+ }
1818
1850
  }
1819
1851
  /**
1820
- * Include children in results (for hierarchical content)
1821
- * @param options - Children options or boolean to enable with defaults
1852
+ * One entry by its id or slug, or `null` when there is no such entry (REL-2415).
1853
+ *
1854
+ * `null` only for a missing **entry**: a type the schema does not declare, or a dataset with no
1855
+ * schema deployed, throws `ResourceNotFoundError` naming which (`context.resourceType`), so an
1856
+ * undeployed type never reads as a missing page.
1857
+ *
1858
+ * It takes the options of a list that are not about which entries or in what order — `include`,
1859
+ * `locale`, `dataset`, `fresh`, `children` (REL-2417). The route declares no `fields`, so there is
1860
+ * no `select`.
1822
1861
  *
1823
1862
  * @example
1824
1863
  * ```typescript
1825
- * // Include all children
1826
- * .children(true)
1827
- *
1828
- * // Include with options
1829
- * .children({ contentTypes: ['variant'], limit: 10 })
1864
+ * const post = await relyio.content('post').get('hello-world', { include: ['author'] })
1865
+ * if (post === null) return notFound()
1830
1866
  * ```
1831
1867
  */
1832
- children(options) {
1833
- if (typeof options === "boolean") {
1834
- this.childrenOptions = options ? {} : void 0;
1835
- } else {
1836
- this.childrenOptions = options;
1868
+ async get(idOrSlug, options = {}) {
1869
+ try {
1870
+ return await this.httpClient.fetchPayload("/v1/{contentType}/{id}", "get", {
1871
+ path: { contentType: this.typeName, id: idOrSlug },
1872
+ query: entryQuery(options, this.clientLocale()),
1873
+ headers: readHeaders(options)
1874
+ });
1875
+ } catch (error) {
1876
+ if (isMissingEntry(error)) return null;
1877
+ throw error;
1837
1878
  }
1838
- return this;
1839
- }
1840
- /**
1841
- * Set page number for page-based pagination
1842
- * @param pageNum - Page number (1-based)
1843
- */
1844
- page(pageNum) {
1845
- this.pageNumber = pageNum;
1846
- return this;
1847
1879
  }
1848
- /**
1849
- * Set page size for page-based pagination
1850
- * @param size - Items per page
1851
- */
1852
- pageSize(size) {
1853
- this.pageSizeValue = size;
1854
- return this;
1880
+ async update(target, data, options) {
1881
+ const { idempotencyKey, locale, ...placement } = options ?? {};
1882
+ const write = typeof target === "string" ? { id: target, locale: callLocale(locale, this.clientLocale()), ifMatch: void 0 } : versionCheckOf(target);
1883
+ return this.httpClient.fetchPayload(
1884
+ "/v1/{contentType}/{id}",
1885
+ "patch",
1886
+ {
1887
+ path: { contentType: this.typeName, id: write.id },
1888
+ body: {
1889
+ content: data,
1890
+ ...placement,
1891
+ ...write.locale === void 0 ? {} : { locale: write.locale }
1892
+ },
1893
+ headers: writeHeaders({ idempotencyKey, ifMatch: write.ifMatch })
1894
+ }
1895
+ );
1855
1896
  }
1856
- /**
1857
- * Execute the query and return all matching results
1858
- */
1859
- async execute() {
1860
- return readPayload(await this.executeWithMeta());
1897
+ async delete(target, options) {
1898
+ const write = typeof target === "string" ? { id: target, ifMatch: void 0 } : versionCheckOf(target);
1899
+ await this.httpClient.send("/v1/{contentType}/{id}", "delete", {
1900
+ path: { contentType: this.typeName, id: write.id },
1901
+ headers: writeHeaders({ idempotencyKey: options?.idempotencyKey, ifMatch: write.ifMatch })
1902
+ });
1861
1903
  }
1904
+ };
1905
+ __name(_EntryHandle, "EntryHandle");
1906
+ var EntryHandle = _EntryHandle;
1907
+
1908
+ // src/content/content-client.ts
1909
+ var _ContentClient = class _ContentClient extends EntryHandle {
1862
1910
  /**
1863
- * Execute the query and return the whole body — the items under `data`, the
1864
- * cursor facts under `page`.
1911
+ * Create a new content entry.
1912
+ *
1913
+ * `locale` defaults to the client's own, and `dataset` to the client's (`client.with({ dataset })`
1914
+ * sets it for every call).
1915
+ *
1916
+ * @example
1917
+ * ```typescript
1918
+ * const post = await relyio.content('post').create({ title: 'Hello' }, { slug: 'hello' })
1919
+ * ```
1865
1920
  */
1866
- async executeWithMeta() {
1867
- const response = await this.httpClient.send(
1921
+ async create(data, options = {}) {
1922
+ const { idempotencyKey, dataset, locale, ...body } = options;
1923
+ const sent = callLocale(locale, this.clientLocale());
1924
+ return this.httpClient.fetchPayload(
1868
1925
  "/v1/{contentType}",
1869
- "get",
1926
+ "post",
1870
1927
  {
1871
- path: { contentType: this.contentType },
1872
- query: this.buildQueryParams(),
1873
- headers: this.requestHeaders
1928
+ path: { contentType: this.typeName },
1929
+ body: { content: data, ...body, ...sent === void 0 ? {} : { locale: sent } },
1930
+ headers: { ...readHeaders({ dataset }), ...writeHeaders({ idempotencyKey }) }
1874
1931
  }
1875
1932
  );
1876
- return response.body;
1877
- }
1878
- /**
1879
- * Execute the query and return a single result (first match)
1880
- */
1881
- async first() {
1882
- const originalLimit = this.queryOptions.limit;
1883
- this.limit(1);
1884
- try {
1885
- const results = await this.execute();
1886
- return results.length > 0 ? results[0] ?? null : null;
1887
- } finally {
1888
- if (originalLimit !== void 0) {
1889
- this.queryOptions.limit = originalLimit;
1890
- } else {
1891
- delete this.queryOptions.limit;
1892
- }
1893
- }
1894
- }
1895
- /**
1896
- * Get paginated results
1897
- */
1898
- async paginate(limit = 20) {
1899
- return this.limit(limit).executeWithMeta();
1900
1933
  }
1901
1934
  /**
1902
- * Create an async iterator for streaming results
1935
+ * Get version history for one locale of an entry.
1936
+ *
1937
+ * Versions are numbered per locale, so this is one locale's timeline: `locale` defaults to the
1938
+ * client's own, else the schema default; no fallback is applied, and a locale
1939
+ * with no history returns an empty array rather than another locale's rows. Every row names the
1940
+ * locale it belongs to.
1903
1941
  */
1904
- async *[Symbol.asyncIterator]() {
1905
- const limit = this.queryOptions.limit ?? 100;
1906
- let cursor;
1907
- let hasMore = true;
1908
- while (hasMore) {
1909
- if (cursor != null && cursor !== "") {
1910
- this.cursor(cursor);
1911
- }
1912
- const result = await this.limit(limit).executeWithMeta();
1913
- for (const item of readPayload(result)) {
1914
- yield item;
1942
+ async versions(id, options) {
1943
+ const locale = callLocale(options?.locale, this.clientLocale());
1944
+ return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions", "get", {
1945
+ path: { contentType: this.typeName, id },
1946
+ query: {
1947
+ limit: options?.limit ?? 10,
1948
+ ...locale === void 0 ? {} : { locale }
1915
1949
  }
1916
- hasMore = result.page.hasMore;
1917
- cursor = result.page.nextCursor ?? void 0;
1918
- }
1919
- }
1920
- /**
1921
- * Execute the query and return all results as an array (for large datasets)
1922
- */
1923
- async all() {
1924
- const allItems = [];
1925
- for await (const item of this) {
1926
- allItems.push(item);
1927
- }
1928
- return allItems;
1950
+ });
1929
1951
  }
1930
1952
  /**
1931
- * Clone the query builder
1953
+ * One version of an entry: `version(id, { version, locale })`.
1954
+ *
1955
+ * `locale` defaults to the client's own, else the schema default. Version numbers are per locale,
1956
+ * so version 2 is different content in each one.
1957
+ *
1958
+ * There is no `null`: a version the locale does not have, an entry that is not there, a type the
1959
+ * schema does not declare and a dataset with no schema all throw `ResourceNotFoundError`, its
1960
+ * `context.resourceType` naming which (REL-2409 Q12).
1932
1961
  */
1933
- clone() {
1934
- const cloned = new _ContentQueryBuilder(
1935
- this.httpClient,
1936
- this.contentType,
1937
- this.clientLocale
1938
- );
1939
- cloned.queryOptions = JSON.parse(JSON.stringify(this.queryOptions));
1940
- cloned.localeValue = this.localeValue;
1941
- cloned.localesArray = this.localesArray ? [...this.localesArray] : void 0;
1942
- cloned.fetchAllLocales = this.fetchAllLocales;
1943
- cloned.fieldsProjection = this.fieldsProjection ? [...this.fieldsProjection] : void 0;
1944
- cloned.pageNumber = this.pageNumber;
1945
- cloned.pageSizeValue = this.pageSizeValue;
1946
- cloned.requestHeaders = this.requestHeaders ? { ...this.requestHeaders } : void 0;
1947
- cloned.freshValue = this.freshValue;
1948
- return cloned;
1962
+ async version(id, options) {
1963
+ const locale = callLocale(options.locale, this.clientLocale());
1964
+ return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions/{versionNumber}", "get", {
1965
+ path: {
1966
+ contentType: this.typeName,
1967
+ id,
1968
+ versionNumber: String(options.version)
1969
+ },
1970
+ query: locale === void 0 ? void 0 : { locale }
1971
+ });
1949
1972
  }
1950
- /**
1951
- * Get the current query options
1952
- */
1953
- getQueryOptions() {
1954
- return { ...this.queryOptions };
1973
+ async restore(target, options) {
1974
+ const { version, locale, idempotencyKey } = options;
1975
+ const write = typeof target === "string" ? { id: target, locale, ifMatch: void 0 } : versionCheckOf(target);
1976
+ return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions/{versionNumber}/restore", "post", {
1977
+ path: {
1978
+ contentType: this.typeName,
1979
+ id: write.id,
1980
+ versionNumber: String(version)
1981
+ },
1982
+ body: { locale: write.locale },
1983
+ headers: writeHeaders({ idempotencyKey, ifMatch: write.ifMatch })
1984
+ });
1955
1985
  }
1956
1986
  /**
1957
- * Execute the query and return the whole body.
1987
+ * The direct children of a hierarchical entry, each read as `get` reads an entry.
1958
1988
  *
1959
- * Identical to {@link executeWithMeta} now that the list serves one shape;
1960
- * kept as the name callers already import.
1961
- */
1962
- async executeWithMetaExtended() {
1963
- return this.executeWithMeta();
1964
- }
1965
- /**
1966
- * `count()` and `exists()` are gone, and their absence is the honest answer
1967
- * rather than an omission (`INV-RD-CAPABILITY-IS-HONEST`).
1989
+ * It takes `get`'s options — `include` (checked against the type), `locale` (a code, a list or
1990
+ * `'*'`), `dataset`, `fresh` and `children` — the terms its route declares as the entry route
1991
+ * does, sent the same way. The route lists one level and takes no depth (REL-2195); a tree nested
1992
+ * under each child is the `children` option.
1968
1993
  *
1969
- * `count()` sent `withCount` and read `pagination.total`; API2 moved the
1970
- * customer list onto the **cursor** dialect, whose page facts are
1971
- * `{ nextCursor, hasMore }` and nothing else, so no total reaches this
1972
- * surface at all. Keeping the method would have meant either a request that
1973
- * always throws or a number assembled from a page the caller happened to
1974
- * fetch — a count of what was returned, presented as a count of what matched
1975
- * (rule 6). The plan's §3.3 listed `count` among six methods a type would
1976
- * repair; what the type actually shows is that the capability is no longer
1977
- * there. A caller that wants "is there at least one" fetches one and looks at
1978
- * `data.length`; a caller that wants a true total uses `POST /v1/search`,
1979
- * which is the offset dialect precisely because a facet-bearing result wants
1980
- * one (Decision 5).
1981
- */
1982
- /**
1983
- * Build query parameters for the HTTP request
1994
+ * @param id - Parent entry ID
1984
1995
  */
1985
- buildQueryParams() {
1986
- const params = {};
1987
- if (this.queryOptions.where && Object.keys(this.queryOptions.where).length > 0) {
1988
- params.filters = JSON.stringify(this.queryOptions.where);
1989
- }
1990
- if (this.queryOptions.select) {
1991
- params.fields = this.queryOptions.select.join(",");
1992
- }
1993
- if (this.fieldsProjection) {
1994
- params.fields = this.fieldsProjection.join(",");
1995
- }
1996
- if (this.queryOptions.include) {
1997
- params.include = this.queryOptions.include.join(",");
1998
- }
1999
- if (this.queryOptions.sort) {
2000
- const sortArray = Object.entries(this.queryOptions.sort).map(
2001
- ([field, direction]) => `${field}:${direction}`
2002
- );
2003
- params.sort = sortArray.join(",");
2004
- }
2005
- if (this.queryOptions.limit !== void 0) {
2006
- params.limit = this.queryOptions.limit;
2007
- }
2008
- if (this.queryOptions.offset !== void 0) {
2009
- params.offset = this.queryOptions.offset;
2010
- }
2011
- if (this.queryOptions.cursor !== void 0) {
2012
- params.cursor = this.queryOptions.cursor;
2013
- }
2014
- const clientLocale = this.clientLocale();
2015
- if (this.localeValue != null && this.localeValue !== "") {
2016
- params.locale = this.localeValue;
2017
- } else if (this.fetchAllLocales) {
2018
- params.locale = "*";
2019
- } else if (this.localesArray && this.localesArray.length > 0) {
2020
- params.locales = this.localesArray.join(",");
2021
- } else if (clientLocale != null && clientLocale !== "") {
2022
- params.locale = clientLocale;
2023
- }
2024
- if (this.pageNumber !== void 0) {
2025
- params.page = this.pageNumber;
2026
- }
2027
- if (this.pageSizeValue !== void 0) {
2028
- params.pageSize = this.pageSizeValue;
2029
- }
2030
- if (this.childrenOptions) {
2031
- if (this.childrenOptions.contentTypes) {
2032
- params.children = this.childrenOptions.contentTypes.join(",");
2033
- } else {
2034
- params.children = "true";
2035
- }
2036
- if (this.childrenOptions.limit !== void 0) {
2037
- params.childrenLimit = this.childrenOptions.limit;
2038
- }
2039
- }
2040
- if (this.freshValue !== void 0) {
2041
- params[FRESH_PARAMETER] = this.freshValue;
2042
- }
2043
- return params;
2044
- }
2045
- };
2046
- __name(_ContentQueryBuilder, "ContentQueryBuilder");
2047
- var ContentQueryBuilder = _ContentQueryBuilder;
2048
- var _ContentByIdBuilder = class _ContentByIdBuilder {
2049
- /**
2050
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent when the
2051
- * read names none: the function `TypedRelyIOClient` hands over, or a locale fixed for it
2052
- */
2053
- constructor(httpClient, contentType, id, locale) {
2054
- this.httpClient = httpClient;
2055
- this.contentType = contentType;
2056
- this.id = id;
2057
- __publicField(this, "includeRelations");
2058
- __publicField(this, "localeValue");
2059
- __publicField(this, "localesArray");
2060
- __publicField(this, "fetchAllLocales", false);
2061
- __publicField(this, "childrenOptions");
2062
- __publicField(this, "requestHeaders");
2063
- /** The client's locale, asked when the read is sent rather than copied when it was built. */
2064
- __publicField(this, "clientLocale");
2065
- __publicField(this, "freshValue");
2066
- this.clientLocale = readClientLocale(locale);
2067
- }
2068
- /**
2069
- * The feed position this read follows — a change's `fresh` (`FeedChange`), or a resync's. Sent as
2070
- * `?_fresh`, the one term the API declares for it: no cache — the Content API's edge or the
2071
- * browser's own — holds an answer for that position from before it, so the read is answered after
2072
- * the change, and every read naming the same position shares that answer. The answer is the
2073
- * read's own; omit it for a read no change prompted.
2074
- */
2075
- fresh(position) {
2076
- this.freshValue = position;
2077
- return this;
2078
- }
2079
- /**
2080
- * Expand references into the entries they point at: one include path per element (REL-1801).
2081
- * A path names fields through lists, page builders, objects and references —
2082
- * `'sections.features'`, `'sections.customers.logo'` — and may pick the fields each entry returns,
2083
- * `'sections.features(name,slug)'`. Each is checked against the schema: a path that holds no
2084
- * reference does not compile, and the read's type follows the paths — an expanded reference is the
2085
- * entry, every other one its id. A second call adds to the first.
2086
- */
2087
- include(paths) {
2088
- this.includeRelations = [...this.includeRelations ?? [], ...paths];
2089
- return this;
2090
- }
2091
- /**
2092
- * Set locale for localized content
2093
- * @param locale - Locale code (e.g., 'en-US', 'de-DE', 'fr-FR')
2094
- */
2095
- locale(locale) {
2096
- this.localeValue = locale;
2097
- this.localesArray = void 0;
2098
- this.fetchAllLocales = false;
2099
- return this;
2100
- }
2101
- /**
2102
- * Fetch content in multiple specific locales
2103
- * Returns primary locale at top level, others in _metadata.localizations
2104
- *
2105
- * @param localeCodes - Array of locale codes to fetch
2106
- */
2107
- locales(localeCodes) {
2108
- this.localesArray = localeCodes;
2109
- this.localeValue = void 0;
2110
- this.fetchAllLocales = false;
2111
- return this;
2112
- }
2113
- /**
2114
- * Headers this one read adds to the client's own, e.g. `X-RelyIO-Dataset` to read another dataset
2115
- * the key can see. A name the client already sends is replaced for this request only; the client
2116
- * is not changed.
2117
- */
2118
- headers(headers) {
2119
- this.requestHeaders = headers;
2120
- return this;
2121
- }
2122
- /**
2123
- * Fetch content in all available locales
2124
- * Returns default locale at top level, others in _metadata.localizations
2125
- */
2126
- allLocales() {
2127
- this.fetchAllLocales = true;
2128
- this.localeValue = void 0;
2129
- this.localesArray = void 0;
2130
- return this;
2131
- }
2132
- /**
2133
- * Include children in results (for hierarchical content)
2134
- * @param options - Children options or boolean to enable with defaults
2135
- */
2136
- children(options) {
2137
- if (typeof options === "boolean") {
2138
- this.childrenOptions = options ? {} : void 0;
2139
- } else {
2140
- this.childrenOptions = options;
2141
- }
2142
- return this;
2143
- }
2144
- /**
2145
- * Execute the query and return the content item
2146
- */
2147
- async execute() {
2148
- const params = {};
2149
- if (this.includeRelations != null) {
2150
- params.include = this.includeRelations.join(",");
2151
- }
2152
- const clientLocale = this.clientLocale();
2153
- if (this.localeValue != null && this.localeValue !== "") {
2154
- params.locale = this.localeValue;
2155
- } else if (this.fetchAllLocales) {
2156
- params.locale = "*";
2157
- } else if (this.localesArray && this.localesArray.length > 0) {
2158
- params.locales = this.localesArray.join(",");
2159
- } else if (clientLocale != null && clientLocale !== "") {
2160
- params.locale = clientLocale;
2161
- }
2162
- if (this.childrenOptions != null) {
2163
- if (this.childrenOptions.contentTypes) {
2164
- params.children = this.childrenOptions.contentTypes.join(",");
2165
- } else {
2166
- params.children = "true";
2167
- }
2168
- if (this.childrenOptions.limit !== void 0) {
2169
- params.childrenLimit = this.childrenOptions.limit;
2170
- }
2171
- }
2172
- if (this.freshValue !== void 0) {
2173
- params[FRESH_PARAMETER] = this.freshValue;
2174
- }
2175
- try {
2176
- return await this.httpClient.fetchPayload(
2177
- "/v1/{contentType}/{id}",
2178
- "get",
2179
- {
2180
- path: { contentType: this.contentType, id: this.id },
2181
- query: params,
2182
- headers: this.requestHeaders
2183
- }
2184
- );
2185
- } catch (error) {
2186
- if (isResourceNotFound(error)) return null;
2187
- throw error;
2188
- }
2189
- }
2190
- };
2191
- __name(_ContentByIdBuilder, "ContentByIdBuilder");
2192
- var ContentByIdBuilder = _ContentByIdBuilder;
2193
-
2194
- // src/http/write-options.ts
2195
- function mintIdempotencyKey() {
2196
- const webCrypto = globalThis.crypto;
2197
- if (typeof webCrypto?.randomUUID !== "function") return void 0;
2198
- return webCrypto.randomUUID();
2199
- }
2200
- __name(mintIdempotencyKey, "mintIdempotencyKey");
2201
- function writeHeaders(options) {
2202
- const headers = {};
2203
- if (options !== void 0 && "ifMatch" in options && options.ifMatch !== void 0) {
2204
- headers[HEADER_IF_MATCH.name] = options.ifMatch;
2205
- }
2206
- const idempotencyKey = options?.idempotencyKey ?? mintIdempotencyKey();
2207
- if (idempotencyKey !== void 0) {
2208
- headers[HEADER_IDEMPOTENCY_KEY.name] = idempotencyKey;
2209
- }
2210
- return Object.keys(headers).length > 0 ? headers : void 0;
2211
- }
2212
- __name(writeHeaders, "writeHeaders");
2213
- function requestHeaders(headers, typed) {
2214
- if (headers === void 0) return typed;
2215
- if (typed === void 0) return headers;
2216
- const typedNames = new Set(Object.keys(typed).map((name) => name.toLowerCase()));
2217
- const own = Object.entries(headers).filter(([name]) => !typedNames.has(name.toLowerCase()));
2218
- return { ...Object.fromEntries(own), ...typed };
2219
- }
2220
- __name(requestHeaders, "requestHeaders");
2221
- function entityTagOf(response) {
2222
- return headerValue(response.headers, HEADER_ENTITY_TAG.name);
2223
- }
2224
- __name(entityTagOf, "entityTagOf");
2225
-
2226
- // src/content/content-client.ts
2227
- var _ContentClient = class _ContentClient {
2228
- /**
2229
- * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, asked on
2230
- * every call, or a locale fixed for this client
2231
- */
2232
- constructor(httpClient, contentType, locale) {
2233
- this.httpClient = httpClient;
2234
- this.contentType = contentType;
2235
- /** The client's locale, asked on every call rather than copied when this client was taken. */
2236
- __publicField(this, "clientLocale");
2237
- this.clientLocale = readClientLocale(locale);
2238
- }
2239
- /**
2240
- * Create a new query builder for this content type
2241
- */
2242
- query() {
2243
- return new ContentQueryBuilder(this.httpClient, this.contentType, this.clientLocale);
2244
- }
2245
- /**
2246
- * Find content by ID with fluent options
2247
- */
2248
- findById(id) {
2249
- return new ContentByIdBuilder(this.httpClient, this.contentType, id, this.clientLocale);
2250
- }
2251
- /**
2252
- * Fetch all content items
2253
- * @param locale - Optional locale for localized content
2254
- */
2255
- async fetchAll(locale) {
2256
- const builder = this.query();
2257
- if (locale != null && locale !== "") {
2258
- builder.locale(locale);
2259
- }
2260
- return builder.execute();
2261
- }
2262
- async fetch(options) {
2263
- const builder = this.query();
2264
- if (options?.where) {
2265
- builder.where(options.where);
2266
- }
2267
- if (options?.limit != null) {
2268
- builder.limit(options.limit);
2269
- }
2270
- if (options?.offset != null) {
2271
- builder.offset(options.offset);
2272
- }
2273
- if (options?.sort) {
2274
- builder.sort(options.sort);
2275
- }
2276
- if (options?.include) {
2277
- builder.include([...options.include]);
2278
- }
2279
- if (options?.locale != null && options.locale !== "") {
2280
- builder.locale(options.locale);
2281
- }
2282
- if (options?.fields != null) {
2283
- builder.fields(options.fields);
2284
- }
2285
- if (options?.children != null) {
2286
- builder.children(options.children);
2287
- }
2288
- return builder.execute();
2289
- }
2290
- async fetchOne(id, options) {
2291
- const builder = this.findById(id);
2292
- if (options?.include != null) {
2293
- builder.include([...options.include]);
2294
- }
2295
- if (options?.locale != null && options.locale !== "") {
2296
- builder.locale(options.locale);
2297
- }
2298
- if (options?.headers != null) {
2299
- builder.headers(options.headers);
2300
- }
2301
- return builder.execute();
2302
- }
2303
- async fetchOneWithTag(id, options) {
2304
- const query = {};
2305
- if (options?.include != null) {
2306
- query.include = options.include.join(",");
2307
- }
2308
- const locale = options?.locale ?? this.clientLocale();
2309
- if (locale != null && locale !== "") query.locale = locale;
2310
- const response = await this.httpClient.send(
2311
- "/v1/{contentType}/{id}",
2312
- "get",
2313
- { path: { contentType: this.contentType, id }, query, headers: options?.headers }
2314
- );
2315
- return { entry: readPayload(response.body), entityTag: entityTagOf(response) };
2316
- }
2317
- /**
2318
- * Fetch the first content item matching the conditions
2319
- * @param where - Filter conditions
2320
- * @param locale - Optional locale
2321
- */
2322
- async fetchFirst(where, locale) {
2323
- const builder = this.query();
2324
- if (where != null) {
2325
- builder.where(where);
2326
- }
2327
- if (locale != null && locale !== "") {
2328
- builder.locale(locale);
2329
- }
2330
- return builder.first();
2331
- }
2332
- /**
2333
- * Create a new content item
2334
- * @param data - Content data
2335
- * @param options - Create options (slug, locale, parentId, sortOrder), and `headers` this one
2336
- * request adds — e.g. `{ 'X-RelyIO-Dataset': 'staging' }` to write a dataset other than the
2337
- * client's. They are sent, never put in the body; `idempotencyKey` still wins over an
2338
- * `Idempotency-Key` among them. `locale` defaults to the client's own (`withLocale()`).
2339
- */
2340
- async create(data, options) {
2341
- const { idempotencyKey, headers, locale, ...body } = options ?? {};
2342
- const sent = callLocale(locale, this.clientLocale());
2343
- return this.httpClient.fetchPayload(
2344
- "/v1/{contentType}",
2345
- "post",
2346
- {
2347
- path: { contentType: this.contentType },
2348
- body: { content: data, ...body, ...sent === void 0 ? {} : { locale: sent } },
2349
- headers: requestHeaders(headers, writeHeaders({ idempotencyKey }))
2350
- }
2351
- );
2352
- }
2353
- /**
2354
- * Update a content item by ID (partial update)
2355
- * @param id - Entry ID
2356
- * @param data - Fields to update
2357
- * @param options - Update options (slug, locale, parentId, sortOrder), and `headers` this one
2358
- * request adds, as for {@link create}. `ifMatch` and `idempotencyKey` win over the same
2359
- * header among them. `locale` defaults to the client's own, the locale whose entity tag
2360
- * {@link fetchOneWithTag} reads, so the tag it hands back is checked against the same locale.
2361
- */
2362
- async update(id, data, options) {
2363
- const { idempotencyKey, ifMatch, headers, locale, ...body } = options ?? {};
2364
- const sent = callLocale(locale, this.clientLocale());
2365
- return this.httpClient.fetchPayload(
2366
- "/v1/{contentType}/{id}",
2367
- "patch",
2368
- {
2369
- path: { contentType: this.contentType, id },
2370
- body: { content: data, ...body, ...sent === void 0 ? {} : { locale: sent } },
2371
- headers: requestHeaders(headers, writeHeaders({ idempotencyKey, ifMatch }))
2372
- }
2373
- );
2374
- }
2375
- /**
2376
- * Delete a content item by ID
2377
- */
2378
- async delete(id, options) {
2379
- await this.httpClient.send("/v1/{contentType}/{id}", "delete", {
2380
- path: { contentType: this.contentType, id },
2381
- headers: writeHeaders(options)
2382
- });
2383
- }
2384
- /**
2385
- * Check if content exists by ID
2386
- */
2387
- async exists(id) {
2388
- try {
2389
- const item = await this.fetchOne(id);
2390
- return item !== null;
2391
- } catch (error) {
2392
- if (error instanceof ResourceNotFoundError) {
2393
- return false;
2394
- }
2395
- throw error;
2396
- }
2397
- }
2398
- /**
2399
- * Get version history for one locale of an entry.
2400
- *
2401
- * Versions are numbered per locale, so this is one locale's timeline: `locale` defaults to the
2402
- * client's own (`withLocale()`), else the schema default; no fallback is applied, and a locale
2403
- * with no history returns an empty array rather than another locale's rows. Every row names the
2404
- * locale it belongs to.
2405
- */
2406
- async versions(id, options) {
2407
- const locale = callLocale(options?.locale, this.clientLocale());
2408
- return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions", "get", {
2409
- path: { contentType: this.contentType, id },
2410
- query: {
2411
- limit: options?.limit ?? 10,
2412
- ...locale === void 0 ? {} : { locale }
2413
- }
2414
- });
2415
- }
2416
- /**
2417
- * Get a specific version of an entry.
2418
- *
2419
- * `locale` defaults to the client's own (`withLocale()`), else the schema default. Version
2420
- * numbers are per locale, so version 2 is different content in each one.
2421
- */
2422
- async version(id, versionNumber, options) {
2423
- const locale = callLocale(options?.locale, this.clientLocale());
2424
- return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions/{versionNumber}", "get", {
2425
- path: {
2426
- contentType: this.contentType,
2427
- id,
2428
- versionNumber: String(versionNumber)
2429
- },
2430
- query: locale === void 0 ? void 0 : { locale }
2431
- });
2432
- }
2433
- /**
2434
- * Revert one locale of an entry to a previous version.
2435
- *
2436
- * `locale` is **required**, and that is not a convention: versions are numbered per locale, so
2437
- * `versionNumber` alone is ambiguous, and defaulting it would silently revert the wrong
2438
- * translation. Only that locale's fields change — shared fields and every other locale are left
2439
- * untouched.
2440
- *
2441
- * The restore is validated as strictly as a publish, so it cannot publish invalid content, and it
2442
- * records a new version of its own rather than rewinding the counter — so the revert is auditable
2443
- * and itself reversible.
2444
- */
2445
- async restore(id, versionNumber, locale, options) {
2446
- return this.httpClient.fetchPayload("/v1/{contentType}/{id}/versions/{versionNumber}/restore", "post", {
2447
- path: {
2448
- contentType: this.contentType,
2449
- id,
2450
- versionNumber: String(versionNumber)
2451
- },
2452
- body: { locale },
2453
- headers: writeHeaders(options)
2454
- });
2455
- }
2456
- /**
2457
- * Get children of a hierarchical entry
2458
- * @param id - Parent entry ID
2459
- * @param options - Fetch options
2460
- */
2461
- async children(id, options) {
2462
- const params = {};
2463
- if (options?.depth != null) {
2464
- params.depth = options.depth;
2465
- }
2466
- if (options?.include != null) {
2467
- params.include = options.include.join(",");
2468
- }
2469
- const locale = options?.locale ?? this.clientLocale();
2470
- if (locale != null && locale !== "") {
2471
- params.locale = locale;
2472
- }
2473
- return this.httpClient.fetchPayload(
2474
- "/v1/{contentType}/{id}/children",
2475
- "get",
2476
- { path: { contentType: this.contentType, id }, query: params }
2477
- );
2478
- }
2479
- /**
2480
- * Get the content type name
2481
- */
2482
- getContentType() {
2483
- return this.contentType;
2484
- }
2485
- /**
2486
- * Create a new ContentClient for a different content type
2487
- */
2488
- ofType(contentType) {
2489
- return new _ContentClient(this.httpClient, contentType, this.clientLocale);
2490
- }
2491
- /**
2492
- * Create a new ContentClient with a different default locale, fixed: an update of the client's
2493
- * locale (`updateConfig({ locale })`) does not reach it
2494
- */
2495
- withLocale(locale) {
2496
- return new _ContentClient(this.httpClient, this.contentType, locale);
2497
- }
2498
- /**
2499
- * Get the default locale as it is now: the client's, or the one `withLocale()` fixed
2500
- */
2501
- getDefaultLocale() {
2502
- return this.clientLocale();
1996
+ async children(id, options = {}) {
1997
+ return this.httpClient.fetchPayload("/v1/{contentType}/{id}/children", "get", {
1998
+ path: { contentType: this.typeName, id },
1999
+ query: entryQuery(options, this.clientLocale()),
2000
+ headers: readHeaders(options)
2001
+ });
2503
2002
  }
2504
2003
  };
2505
2004
  __name(_ContentClient, "ContentClient");
@@ -2638,16 +2137,16 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2638
2137
  get target() {
2639
2138
  return { contentType: this.assetType, id: this.entryUid };
2640
2139
  }
2641
- withLocale(locale) {
2140
+ localeOf(locale) {
2642
2141
  return locale ?? this.clientLocale();
2643
2142
  }
2644
2143
  /**
2645
2144
  * The `locale` body field of a multipart call: the session's, else the client's. The API finds
2646
- * the binding by it, so a session a `withLocale()` client opened must name the same locale on
2145
+ * the binding by it, so a session a `with({ locale })` client opened must name the same locale on
2647
2146
  * every later call or its `objectKey` is refused as another binding's.
2648
2147
  */
2649
2148
  localeField(locale) {
2650
- const sent = this.withLocale(locale);
2149
+ const sent = this.localeOf(locale);
2651
2150
  return hasText(sent) ? { locale: sent } : {};
2652
2151
  }
2653
2152
  /**
@@ -2655,7 +2154,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2655
2154
  * Cloudflare Stream direct-creator URL (video). Resumable multipart is plan 17.
2656
2155
  */
2657
2156
  async presign(input) {
2658
- const locale = this.withLocale(input.locale);
2157
+ const locale = this.localeOf(input.locale);
2659
2158
  return this.httpClient.fetchPayload("/v1/{contentType}/{id}/file/presign", "post", {
2660
2159
  path: this.target,
2661
2160
  body: {
@@ -2672,7 +2171,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2672
2171
  * R2; a no-op for Stream, whose readiness is webhook-driven).
2673
2172
  */
2674
2173
  async confirm(input = {}) {
2675
- const locale = this.withLocale(input.locale);
2174
+ const locale = this.localeOf(input.locale);
2676
2175
  return this.httpClient.fetchPayload("/v1/{contentType}/{id}/file/confirm", "post", {
2677
2176
  path: this.target,
2678
2177
  body: {
@@ -2687,7 +2186,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2687
2186
  // ──────────────────────────────────────────────────────────────────────────
2688
2187
  /** Open an R2 multipart session for a large file (standalone of `presign`). */
2689
2188
  async createMultipart(input) {
2690
- const locale = this.withLocale(input.locale);
2189
+ const locale = this.localeOf(input.locale);
2691
2190
  return this.httpClient.fetchPayload("/v1/{contentType}/{id}/file/multipart/create", "post", {
2692
2191
  path: this.target,
2693
2192
  body: {
@@ -2752,7 +2251,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2752
2251
  */
2753
2252
  async url(input = {}) {
2754
2253
  const params = {};
2755
- const locale = this.withLocale(input.locale);
2254
+ const locale = this.localeOf(input.locale);
2756
2255
  if (hasText(locale)) params.locale = locale;
2757
2256
  if (hasText(input.variantId)) params.variantId = input.variantId;
2758
2257
  if (input.purpose !== void 0) params.purpose = input.purpose;
@@ -2773,7 +2272,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2773
2272
  */
2774
2273
  async status(options = {}) {
2775
2274
  const params = {};
2776
- const locale = this.withLocale(options.locale);
2275
+ const locale = this.localeOf(options.locale);
2777
2276
  if (hasText(locale)) params.locale = locale;
2778
2277
  return this.httpClient.fetchPayload(
2779
2278
  "/v1/{contentType}/{id}/file",
@@ -2786,7 +2285,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2786
2285
  * a downgrade purges the gateway cache). Returns the refreshed asset entry.
2787
2286
  */
2788
2287
  async updateVisibility(visibility, options = {}) {
2789
- const locale = this.withLocale(options.locale);
2288
+ const locale = this.localeOf(options.locale);
2790
2289
  return this.httpClient.fetchPayload("/v1/{contentType}/{id}/file", "patch", {
2791
2290
  path: this.target,
2792
2291
  body: { visibility, ...hasText(locale) ? { locale } : {} }
@@ -2799,7 +2298,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2799
2298
  * refreshed asset entry.
2800
2299
  */
2801
2300
  async setFocalPoint(focalPoint, options = {}) {
2802
- const locale = this.withLocale(options.locale);
2301
+ const locale = this.localeOf(options.locale);
2803
2302
  return this.httpClient.fetchPayload("/v1/{contentType}/{id}/file", "patch", {
2804
2303
  path: this.target,
2805
2304
  body: { focalPoint, ...hasText(locale) ? { locale } : {} }
@@ -2811,7 +2310,7 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2811
2310
  */
2812
2311
  async delete(options = {}) {
2813
2312
  const params = {};
2814
- const locale = this.withLocale(options.locale);
2313
+ const locale = this.localeOf(options.locale);
2815
2314
  if (hasText(locale)) params.locale = locale;
2816
2315
  await this.httpClient.send("/v1/{contentType}/{id}/file", "delete", {
2817
2316
  path: this.target,
@@ -2837,22 +2336,27 @@ var _AssetFileBuilder = class _AssetFileBuilder {
2837
2336
  * @throws {ReadOnlyKeyError} When the key's lens does not show the asset and the key may not read
2838
2337
  * its binding either: nothing it can read would ever report the file.
2839
2338
  */
2339
+ /** The asset entry through the key's lens, or `null` where that lens finds none. */
2340
+ async readEntry(locale) {
2341
+ try {
2342
+ return await this.httpClient.fetchPayload("/v1/{contentType}/{id}", "get", {
2343
+ path: this.target,
2344
+ query: hasText(locale) ? { locale } : {}
2345
+ });
2346
+ } catch (error) {
2347
+ if (isResourceNotFound(error)) return null;
2348
+ throw error;
2349
+ }
2350
+ }
2840
2351
  async waitUntilReady(options = {}) {
2841
2352
  assertWaitOptions(options);
2842
2353
  const timeoutMs = options.timeoutMs ?? 6e4;
2843
2354
  const pollIntervalMs = options.pollIntervalMs ?? 1500;
2844
- const locale = this.withLocale(options.locale);
2355
+ const locale = this.localeOf(options.locale);
2845
2356
  const deadline = Date.now() + timeoutMs;
2846
2357
  const subject = `${this.assetType}/${this.entryUid}`;
2847
2358
  for (; ; ) {
2848
- const builder = new ContentByIdBuilder(
2849
- this.httpClient,
2850
- this.assetType,
2851
- this.entryUid,
2852
- locale
2853
- );
2854
- if (hasText(locale)) builder.locale(locale);
2855
- const entry = await builder.execute();
2359
+ const entry = await this.readEntry(locale);
2856
2360
  let status;
2857
2361
  if (entry === null) {
2858
2362
  const binding = await this.status({ ...hasText(locale) ? { locale } : {} });
@@ -3135,56 +2639,12 @@ var _AssetUploadBuilder = class _AssetUploadBuilder {
3135
2639
  };
3136
2640
  __name(_AssetUploadBuilder, "AssetUploadBuilder");
3137
2641
  var AssetUploadBuilder = _AssetUploadBuilder;
3138
- var _AssetClient = class _AssetClient {
3139
- /**
3140
- * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, asked on
3141
- * every call, or a locale fixed for this client
3142
- */
3143
- constructor(httpClient, assetType, locale) {
3144
- this.httpClient = httpClient;
3145
- this.assetType = assetType;
3146
- /** The client's locale, asked on every call rather than copied when this client was taken. */
3147
- __publicField(this, "clientLocale");
3148
- this.clientLocale = readClientLocale(locale);
3149
- }
3150
- /**
3151
- * Create a query builder for this asset type. It resolves asset reads; its conditions name the
3152
- * asset type's fields, which the `file` and `urls` blocks are not.
3153
- */
3154
- query() {
3155
- return new ContentQueryBuilder(
3156
- this.httpClient,
3157
- this.assetType,
3158
- this.clientLocale
3159
- );
3160
- }
3161
- /** Find an asset entry by id (or slug) with fluent options. */
3162
- findById(id) {
3163
- return new ContentByIdBuilder(
3164
- this.httpClient,
3165
- this.assetType,
3166
- id,
3167
- this.clientLocale
3168
- );
3169
- }
3170
- async fetchOne(id, options) {
3171
- const builder = this.findById(id);
3172
- if (options?.include != null) builder.include([...options.include]);
3173
- if (options?.locale != null && options.locale !== "") builder.locale(options.locale);
3174
- return builder.execute();
3175
- }
3176
- /** Fetch the first asset entry matching the conditions, or `null`. */
3177
- async fetchFirst(where, locale) {
3178
- const builder = this.query();
3179
- if (where != null) builder.where(where);
3180
- if (locale != null && locale !== "") builder.locale(locale);
3181
- return builder.first();
3182
- }
2642
+ var _AssetClient = class _AssetClient extends EntryHandle {
3183
2643
  /**
3184
2644
  * Create a new asset entry as a draft. The binary is uploaded separately via
3185
2645
  * `file(uid)` (or use the high-level `upload()` helper), and the entry
3186
2646
  * auto-publishes when its file becomes ready (unless `publish: false`).
3187
- * `locale` defaults to the client's own (`withLocale()`).
2647
+ * `locale` defaults to the client's own.
3188
2648
  */
3189
2649
  async create(data, options) {
3190
2650
  const { idempotencyKey, locale, ...rest } = options ?? {};
@@ -3193,58 +2653,19 @@ var _AssetClient = class _AssetClient {
3193
2653
  "/v1/{contentType}",
3194
2654
  "post",
3195
2655
  {
3196
- path: { contentType: this.assetType },
2656
+ path: { contentType: this.typeName },
3197
2657
  body: { content: data, ...rest, ...sent === void 0 ? {} : { locale: sent } },
3198
2658
  headers: writeHeaders({ idempotencyKey })
3199
2659
  }
3200
2660
  );
3201
2661
  }
3202
- /**
3203
- * Update an asset entry's metadata fields (and/or slug). `locale` defaults to the client's own
3204
- * (`withLocale()`).
3205
- */
3206
- async update(id, data, options) {
3207
- const { idempotencyKey, ifMatch, locale, ...rest } = options ?? {};
3208
- const sent = callLocale(locale, this.clientLocale());
3209
- return this.httpClient.fetchPayload(
3210
- "/v1/{contentType}/{id}",
3211
- "patch",
3212
- {
3213
- path: { contentType: this.assetType, id },
3214
- body: { content: data, ...rest, ...sent === void 0 ? {} : { locale: sent } },
3215
- headers: writeHeaders({ idempotencyKey, ifMatch })
3216
- }
3217
- );
3218
- }
3219
- /** Delete an asset entry (cascades file-byte cleanup + gateway purge). */
3220
- async delete(id, options) {
3221
- await this.httpClient.send("/v1/{contentType}/{id}", "delete", {
3222
- path: { contentType: this.assetType, id },
3223
- headers: writeHeaders(options)
3224
- });
3225
- }
3226
2662
  /** Get the file sub-resource builder for a specific asset entry. */
3227
2663
  file(entryUid) {
3228
- return new AssetFileBuilder(this.httpClient, this.assetType, entryUid, this.clientLocale);
2664
+ return new AssetFileBuilder(this.httpClient, this.typeName, entryUid, this.clientLocale);
3229
2665
  }
3230
2666
  /** Start a high-level upload (create → presign → PUT → confirm). */
3231
2667
  upload(file) {
3232
- return new AssetUploadBuilder(this.httpClient, this.assetType, file, this.clientLocale);
3233
- }
3234
- /** Get the asset type id. */
3235
- getAssetType() {
3236
- return this.assetType;
3237
- }
3238
- /** Get the default locale as it is now: the client's, or the one `withLocale()` fixed. */
3239
- getDefaultLocale() {
3240
- return this.clientLocale();
3241
- }
3242
- /**
3243
- * Create a new AssetClient for this type with a different default locale, fixed: an update of the
3244
- * client's locale (`updateConfig({ locale })`) does not reach it.
3245
- */
3246
- withLocale(locale) {
3247
- return new _AssetClient(this.httpClient, this.assetType, locale);
2668
+ return new AssetUploadBuilder(this.httpClient, this.typeName, file, this.clientLocale);
3248
2669
  }
3249
2670
  };
3250
2671
  __name(_AssetClient, "AssetClient");
@@ -3256,1539 +2677,222 @@ function isAssetEntry(entry) {
3256
2677
  }
3257
2678
  __name(isAssetEntry, "isAssetEntry");
3258
2679
 
3259
- // src/content/singleton-client.ts
3260
- var _SingletonClient = class _SingletonClient {
2680
+ // src/content/document-handle.ts
2681
+ var _DocumentHandle = class _DocumentHandle {
3261
2682
  /**
2683
+ * @param name - The singleton key or settings group id the routes are addressed by
3262
2684
  * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, asked on
3263
- * every call, or a locale fixed for this client
2685
+ * every call
3264
2686
  */
3265
- constructor(httpClient, singletonKey, locale) {
2687
+ constructor(httpClient, name, locale) {
3266
2688
  this.httpClient = httpClient;
3267
- this.singletonKey = singletonKey;
3268
- __publicField(this, "includeFields");
3269
- __publicField(this, "localeValue");
3270
- /** The client's locale, asked on every call rather than copied when this client was taken. */
2689
+ this.name = name;
2690
+ /** The client's locale, asked on every call rather than copied when this handle was taken. */
3271
2691
  __publicField(this, "clientLocale");
3272
2692
  this.clientLocale = readClientLocale(locale);
3273
2693
  }
3274
- /**
3275
- * Expand references into the entries they point at: one include path per element (REL-1801).
3276
- * A path names fields through lists, objects and references — `'hero.media.image'`,
3277
- * `'featured.author'` — and may pick the fields each entry returns, `'featured(title,slug)'`.
3278
- * Each is checked against the schema: a path that holds no reference does not compile, and the
3279
- * read's type follows the paths — an expanded reference is the entry, every other one its id. A
3280
- * second call adds to the first.
3281
- */
3282
- include(paths) {
3283
- this.includeFields = [...this.includeFields ?? [], ...paths];
3284
- return this;
3285
- }
3286
- /**
3287
- * Set locale for localized content
3288
- * @param locale - Locale code (e.g., 'en', 'de', 'fr')
3289
- */
3290
- locale(locale) {
3291
- this.localeValue = locale;
3292
- return this;
3293
- }
3294
- async fetch(options) {
3295
- try {
3296
- return (await this.fetchWithTag(options)).content;
3297
- } catch (error) {
3298
- if (isResourceNotFound(error)) return null;
3299
- throw error;
2694
+ async update(...args) {
2695
+ if (isCheckedUpdate(args)) {
2696
+ const [read, content2, options2] = args;
2697
+ const { locale, ifMatch } = versionCheckOf(read);
2698
+ return this.patch({ content: content2, locale, ifMatch }, options2);
3300
2699
  }
3301
- }
3302
- /**
3303
- * Fetch the singleton **and the entity tag that read served**, which is what
3304
- * `update`'s `ifMatch` takes (`INV-API-CONDITIONAL-WRITE-IS-REACHABLE`).
3305
- *
3306
- * `entityTag` is absent on a cache HIT: a cached body cannot know the current
3307
- * version, and a stale tag would refuse the very next write.
3308
- */
3309
- async fetchWithTag(options) {
3310
- const query = {};
3311
- const includeValue = this.includeFields === void 0 && options?.include === void 0 ? void 0 : [...this.includeFields ?? [], ...options?.include ?? []];
3312
- const localeValueFinal = options?.locale ?? this.localeValue ?? this.clientLocale();
3313
- if (includeValue) query.include = includeValue.join(",");
3314
- if (localeValueFinal != null && localeValueFinal !== "") query.locale = localeValueFinal;
3315
- if (options?.fresh !== void 0) query[FRESH_PARAMETER] = options.fresh;
3316
- const response = await this.httpClient.send(
3317
- "/v1/singletons/{key}",
3318
- "get",
3319
- { path: { key: this.singletonKey }, query }
3320
- );
3321
- return { content: readPayload(response.body), entityTag: entityTagOf(response) };
3322
- }
3323
- /**
3324
- * Update singleton content. The API auto-publishes on PATCH — there is no
3325
- * separate publish route; calling `update()` writes and publishes.
3326
- * @param data - The content fields to update
3327
- * @param locale - Optional locale for localized content (overrides the fluent locale, which
3328
- * overrides the client's own)
3329
- * @param options - `If-Match` / `Idempotency-Key`, both declared on this route
3330
- */
3331
- async update(data, locale, options) {
3332
- const finalLocale = this.localeOf(locale);
3333
- return this.httpClient.fetchPayload(
3334
- "/v1/singletons/{key}",
3335
- "patch",
3336
- {
3337
- path: { key: this.singletonKey },
3338
- body: {
3339
- content: data,
3340
- ...finalLocale != null && finalLocale !== "" && { locale: finalLocale }
3341
- },
3342
- headers: writeHeaders(options)
3343
- }
2700
+ const [content, options] = args;
2701
+ return this.patch(
2702
+ { content, locale: this.localeOf(options?.locale), ifMatch: void 0 },
2703
+ options
3344
2704
  );
3345
2705
  }
3346
2706
  /**
3347
- * Check if singleton exists
3348
- */
3349
- async exists() {
3350
- try {
3351
- const result = await this.fetch();
3352
- return result !== null;
3353
- } catch {
3354
- return false;
3355
- }
3356
- }
3357
- /**
3358
- * Get version history for one locale of the singleton.
2707
+ * Version history for one locale of the document.
3359
2708
  *
3360
2709
  * Versions are numbered per locale, so this is one locale's timeline: `locale` defaults to the
3361
- * fluent `.locale()`, then the client's own (`withLocale()`), then the schema default; no
3362
- * fallback is applied, and a locale with no history returns an empty array rather than another
3363
- * locale's rows. Every row names the locale it belongs to.
3364
- */
3365
- async versions(options) {
3366
- const locale = this.localeOf(options?.locale);
3367
- const payload = await this.httpClient.fetchPayload("/v1/singletons/{key}/versions", "get", {
3368
- path: { key: this.singletonKey },
3369
- query: {
3370
- limit: options?.limit ?? 10,
3371
- ...locale === void 0 ? {} : { locale }
3372
- }
2710
+ * client's own, then the schema default; no fallback is applied, and a locale with no history
2711
+ * returns an empty array rather than another locale's rows. Every row names the locale it belongs
2712
+ * to.
2713
+ */
2714
+ async versions(options = {}) {
2715
+ const locale = this.localeOf(options.locale);
2716
+ const payload = await this.readVersions({
2717
+ limit: options.limit ?? 10,
2718
+ ...locale === void 0 ? {} : { locale }
3373
2719
  });
3374
2720
  return payload.versions;
3375
2721
  }
3376
2722
  /**
3377
- * Get a specific version of the singleton.
2723
+ * One version of the document: `version({ version, locale })`. `locale` defaults to the client's
2724
+ * own, then the schema default; version numbers are per locale, so version 2 is different content
2725
+ * in each one.
3378
2726
  *
3379
- * `locale` defaults to the fluent `.locale()`, then the client's own (`withLocale()`), then the
3380
- * schema default. Version numbers are per locale, so version 2 is different content in each one.
2727
+ * There is no `null`: a version the locale does not have, a document nobody has written, one the
2728
+ * schema does not declare and a dataset with no schema all throw `ResourceNotFoundError`, its
2729
+ * `context.resourceType` naming which (REL-2409 Q12).
3381
2730
  */
3382
- async version(versionNumber, options) {
3383
- const locale = this.localeOf(options?.locale);
3384
- try {
3385
- return await this.httpClient.fetchPayload("/v1/singletons/{key}/versions/{versionNumber}", "get", {
3386
- path: { key: this.singletonKey, versionNumber: String(versionNumber) },
3387
- query: locale === void 0 ? void 0 : { locale }
3388
- });
3389
- } catch (error) {
3390
- if (isResourceNotFound(error)) return null;
3391
- throw error;
3392
- }
2731
+ async version(options) {
2732
+ const locale = this.localeOf(options.locale);
2733
+ return this.readVersion(String(options.version), locale === void 0 ? {} : { locale });
3393
2734
  }
3394
- /** The locale a write or history read sends: the call's, the fluent one, else the client's. */
2735
+ /** The locale a write or a history read sends: the call's, else the client's. */
3395
2736
  localeOf(named) {
3396
- return callLocale(named ?? this.localeValue, this.clientLocale());
3397
- }
3398
- /**
3399
- * Get the singleton key
3400
- */
3401
- getSingletonKey() {
3402
- return this.singletonKey;
3403
- }
3404
- /**
3405
- * Reset fluent options for reuse
3406
- */
3407
- reset() {
3408
- this.includeFields = void 0;
3409
- this.localeValue = void 0;
3410
- return this;
3411
- }
3412
- };
3413
- __name(_SingletonClient, "SingletonClient");
3414
- var SingletonClient = _SingletonClient;
3415
-
3416
- // src/content/settings-client.ts
3417
- var _SettingsClient = class _SettingsClient {
3418
- /**
3419
- * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, asked on
3420
- * every call, or a locale fixed for this client
3421
- */
3422
- constructor(httpClient, groupId, locale) {
3423
- this.httpClient = httpClient;
3424
- this.groupId = groupId;
3425
- __publicField(this, "includeFields");
3426
- __publicField(this, "localeValue");
3427
- /** The client's locale, asked on every call rather than copied when this client was taken. */
3428
- __publicField(this, "clientLocale");
3429
- this.clientLocale = readClientLocale(locale);
3430
- }
3431
- /**
3432
- * Expand references into the entries they point at: one include path per element (REL-1801).
3433
- * A path names fields through lists, objects and references — `'hero.media.image'`,
3434
- * `'featured.author'` — and may pick the fields each entry returns, `'featured(title,slug)'`.
3435
- * Each is checked against the schema: a path that holds no reference does not compile, and the
3436
- * read's type follows the paths — an expanded reference is the entry, every other one its id. A
3437
- * second call adds to the first.
3438
- */
3439
- include(paths) {
3440
- this.includeFields = [...this.includeFields ?? [], ...paths];
3441
- return this;
3442
- }
3443
- /**
3444
- * Set locale for localized settings
3445
- * @param locale - Locale code (e.g., 'en', 'de', 'fr')
3446
- */
3447
- locale(locale) {
3448
- this.localeValue = locale;
3449
- return this;
3450
- }
3451
- async fetch(options) {
3452
- try {
3453
- return (await this.fetchWithTag(options)).settings;
3454
- } catch (error) {
3455
- if (isResourceNotFound(error)) return null;
3456
- throw error;
3457
- }
2737
+ return callLocale(named, this.clientLocale());
3458
2738
  }
3459
- /**
3460
- * Update settings group
3461
- *
3462
- * The fields travel as `content` beside an optional `locale`, the body the route validates
3463
- * (`UpdateSettingsDto`); any other top-level key is refused `REQUEST_INVALID`.
3464
- *
3465
- * @param settings - The settings fields to update
3466
- * @param locale - Optional locale for localized settings (overrides the fluent locale, which
3467
- * overrides the client's own)
3468
- */
3469
- async update(settings, locale, options) {
3470
- const finalLocale = this.localeOf(locale);
3471
- const body = {
3472
- content: settings,
3473
- ...finalLocale != null && finalLocale !== "" ? { locale: finalLocale } : {}
2739
+ /** The write's body: its data, and the locale it names when it names one. */
2740
+ static bodyOf(write) {
2741
+ return {
2742
+ content: write.content,
2743
+ ...write.locale === void 0 ? {} : { locale: write.locale }
3474
2744
  };
3475
- return this.httpClient.fetchPayload(
3476
- "/v1/settings/{groupId}",
3477
- "patch",
3478
- { path: { groupId: this.groupId }, body, headers: writeHeaders(options) }
3479
- );
3480
- }
3481
- /**
3482
- * Fetch the group **and the entity tag that read served**, which is what
3483
- * `update`'s and `reset`'s `ifMatch` take
3484
- * (`INV-API-CONDITIONAL-WRITE-IS-REACHABLE`).
3485
- */
3486
- async fetchWithTag(options) {
3487
- const query = {};
3488
- const includeValue = this.includeFields === void 0 && options?.include === void 0 ? void 0 : [...this.includeFields ?? [], ...options?.include ?? []];
3489
- const localeValueFinal = options?.locale ?? this.localeValue ?? this.clientLocale();
3490
- if (includeValue) query.include = includeValue.join(",");
3491
- if (localeValueFinal != null && localeValueFinal !== "") query.locale = localeValueFinal;
3492
- const response = await this.httpClient.send(
3493
- "/v1/settings/{groupId}",
3494
- "get",
3495
- { path: { groupId: this.groupId }, query }
3496
- );
3497
- return { settings: readPayload(response.body), entityTag: entityTagOf(response) };
3498
- }
3499
- /**
3500
- * Reset settings to default values
3501
- *
3502
- * The route reads its locale from `?locale=` and takes no body, so that is where it is sent.
3503
- *
3504
- * @param locale - Optional locale for localized settings (overrides the fluent locale, which
3505
- * overrides the client's own)
3506
- */
3507
- async reset(locale, options) {
3508
- const finalLocale = this.localeOf(locale);
3509
- return this.httpClient.fetchPayload(
3510
- "/v1/settings/{groupId}/reset",
3511
- "post",
3512
- {
3513
- path: { groupId: this.groupId },
3514
- query: finalLocale != null && finalLocale !== "" ? { locale: finalLocale } : void 0,
3515
- headers: writeHeaders(options)
3516
- }
3517
- );
3518
- }
3519
- /**
3520
- * Get default settings for this group
3521
- */
3522
- async getDefaults() {
3523
- return this.httpClient.fetchPayload(
3524
- "/v1/settings/{groupId}/defaults",
3525
- "get",
3526
- { path: { groupId: this.groupId } }
3527
- );
3528
- }
3529
- /**
3530
- * Check if settings group exists
3531
- */
3532
- async exists() {
3533
- try {
3534
- const result = await this.fetch();
3535
- return result !== null;
3536
- } catch (error) {
3537
- if (isResourceNotFound(error)) return false;
3538
- throw error;
3539
- }
3540
- }
3541
- /**
3542
- * Get version history for one locale of the settings group.
3543
- *
3544
- * Versions are numbered per locale, so this is one locale's timeline: `locale` defaults to the
3545
- * fluent `.locale()`, then the client's own (`withLocale()`), then the schema default; no
3546
- * fallback is applied, and a locale with no history returns an empty array rather than another
3547
- * locale's rows. Every row names the locale it belongs to.
3548
- */
3549
- async versions(options) {
3550
- const locale = this.localeOf(options?.locale);
3551
- const payload = await this.httpClient.fetchPayload("/v1/settings/{groupId}/versions", "get", {
3552
- path: { groupId: this.groupId },
3553
- query: {
3554
- limit: options?.limit ?? 10,
3555
- ...locale === void 0 ? {} : { locale }
3556
- }
3557
- });
3558
- return payload.versions;
3559
- }
3560
- /**
3561
- * Get a specific version of the settings.
3562
- *
3563
- * `locale` defaults to the fluent `.locale()`, then the client's own (`withLocale()`), then the
3564
- * schema default. Version numbers are per locale, so version 2 is different content in each one.
3565
- */
3566
- async version(versionNumber, options) {
3567
- const locale = this.localeOf(options?.locale);
3568
- try {
3569
- return await this.httpClient.fetchPayload("/v1/settings/{groupId}/versions/{versionNumber}", "get", {
3570
- path: { groupId: this.groupId, versionNumber: String(versionNumber) },
3571
- query: locale === void 0 ? void 0 : { locale }
3572
- });
3573
- } catch (error) {
3574
- if (isResourceNotFound(error)) return null;
3575
- throw error;
3576
- }
3577
- }
3578
- /** The locale a write or history read sends: the call's, the fluent one, else the client's. */
3579
- localeOf(named) {
3580
- return callLocale(named ?? this.localeValue, this.clientLocale());
3581
- }
3582
- /**
3583
- * Get the settings group ID
3584
- */
3585
- getGroupId() {
3586
- return this.groupId;
3587
2745
  }
3588
- /**
3589
- * Reset fluent options for reuse
3590
- */
3591
- resetOptions() {
3592
- this.includeFields = void 0;
3593
- this.localeValue = void 0;
3594
- return this;
2746
+ /** The two headers a write sends: its check, when it has one, and its `Idempotency-Key`. */
2747
+ static headersOf(write, options) {
2748
+ return writeHeaders({ idempotencyKey: options?.idempotencyKey, ifMatch: write.ifMatch });
3595
2749
  }
3596
2750
  };
3597
- __name(_SettingsClient, "SettingsClient");
3598
- var SettingsClient = _SettingsClient;
2751
+ __name(_DocumentHandle, "DocumentHandle");
2752
+ var DocumentHandle = _DocumentHandle;
2753
+ function isCheckedUpdate(args) {
2754
+ return isRead(args[0]);
2755
+ }
2756
+ __name(isCheckedUpdate, "isCheckedUpdate");
2757
+ function isRead(value) {
2758
+ return "_metadata" in value && typeof value._metadata === "object" && value._metadata !== null;
2759
+ }
2760
+ __name(isRead, "isRead");
3599
2761
 
3600
- // src/search/search-client.ts
3601
- var _SearchBuilder = class _SearchBuilder {
3602
- /**
3603
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent when
3604
- * `.locale()` names none: the function `TypedRelyIOClient` hands over, or a locale fixed for it
3605
- */
3606
- constructor(httpClient, query, locale) {
3607
- this.httpClient = httpClient;
3608
- __publicField(this, "query");
3609
- __publicField(this, "searchOptions", {});
3610
- __publicField(this, "requestHeaders");
3611
- __publicField(this, "freshValue");
3612
- /** The client's locale, asked when the query is sent rather than copied when it was built. */
3613
- __publicField(this, "clientLocale");
3614
- this.query = query;
3615
- this.clientLocale = readClientLocale(locale);
3616
- }
3617
- /**
3618
- * Headers this search adds to the client's own, e.g. `X-RelyIO-Dataset` to search another
3619
- * dataset the key can see. A name the client already sends is replaced for this search only.
3620
- */
3621
- headers(headers) {
3622
- this.requestHeaders = headers;
3623
- return this;
3624
- }
3625
- /**
3626
- * The feed position this search follows — a change's `fresh` (`FeedChange`), or a resync's. Sent
3627
- * as `?_fresh` on the query string beside the body: the edge keys a search on both, so no answer
3628
- * it holds from before that position can answer it. The answer is the search's own.
3629
- */
3630
- fresh(position) {
3631
- this.freshValue = position;
3632
- return this;
3633
- }
3634
- /**
3635
- * Search within a single content type. Where a schema types the client, the name is one of its
3636
- * content types and the results are that type's entries.
3637
- * @param contentType - Content type to search in
3638
- */
3639
- in(contentType) {
3640
- this.searchOptions.contentType = contentType;
3641
- this.searchOptions.contentTypes = void 0;
3642
- return this;
3643
- }
3644
- /**
3645
- * Search across multiple content types. Where a schema types the client, the names are its content
3646
- * types and the results are a union of their entries — every type's, for `'*'`.
3647
- * @param contentTypes - Array of content types or '*' for all
3648
- */
3649
- across(contentTypes) {
3650
- this.searchOptions.contentTypes = contentTypes;
3651
- this.searchOptions.contentType = void 0;
3652
- return this;
3653
- }
3654
- /**
3655
- * Add filter conditions, on the fields the content types declare. A condition on `_metadata` is
3656
- * refused here, before anything is sent.
3657
- * @param conditions - Filter conditions
3658
- */
3659
- where(conditions) {
3660
- refuseMetadataConditions(conditions);
3661
- this.searchOptions.where = {
3662
- ...this.searchOptions.where,
3663
- ...conditions
3664
- };
3665
- return this;
3666
- }
3667
- /**
3668
- * Specify which fields to search in
3669
- * @param fields - Field names to search
3670
- */
3671
- searchFields(fields) {
3672
- this.searchOptions.searchFields = fields;
3673
- return this;
3674
- }
3675
- /**
3676
- * Project specific fields in results
3677
- * @param projection - Field mapping
3678
- */
3679
- fields(projection) {
3680
- this.searchOptions.fields = projection;
3681
- return this;
3682
- }
3683
- /**
3684
- * Order the results by a field instead of by relevance. Called again, it adds a tie-breaker.
3685
- * `_score` names relevance itself.
3686
- * @param field - Field path to sort by (e.g. `updatedAt`, `pricing.basePrice`)
3687
- * @param direction - `asc` or `desc` (the route's default is `desc`)
3688
- */
3689
- sort(field, direction = "desc") {
3690
- this.searchOptions.sort = [...this.searchOptions.sort ?? [], { field, direction }];
3691
- return this;
3692
- }
3693
- /**
3694
- * Limit number of results
3695
- * @param count - Maximum results
3696
- */
3697
- limit(count) {
3698
- this.searchOptions.limit = count;
3699
- return this;
3700
- }
3701
- /**
3702
- * Skip results for pagination
3703
- * @param count - Number to skip
3704
- */
3705
- offset(count) {
3706
- this.searchOptions.offset = count;
3707
- return this;
3708
- }
3709
- /**
3710
- * Include relevance scores in results
3711
- */
3712
- includeScore() {
3713
- this.searchOptions.includeScore = true;
3714
- return this;
3715
- }
3716
- /**
3717
- * Include score breakdown explanation
3718
- */
3719
- explain() {
3720
- this.searchOptions.explain = true;
3721
- return this;
3722
- }
3723
- /**
3724
- * Set locale for localized content
3725
- * @param locale - Locale code
3726
- */
3727
- locale(locale) {
3728
- this.searchOptions.locale = locale;
3729
- return this;
3730
- }
3731
- /**
3732
- * Execute the search query
3733
- */
3734
- async execute() {
3735
- const body = {
3736
- q: this.query
3737
- };
3738
- if (this.searchOptions.contentType != null && this.searchOptions.contentType !== "") {
3739
- body.contentType = this.searchOptions.contentType;
3740
- }
3741
- if (this.searchOptions.contentTypes != null) {
3742
- body.contentTypes = this.searchOptions.contentTypes;
3743
- }
3744
- if (this.searchOptions.where && Object.keys(this.searchOptions.where).length > 0) {
3745
- body.where = this.searchOptions.where;
3746
- }
3747
- if (this.searchOptions.searchFields) {
3748
- body.searchFields = this.searchOptions.searchFields;
3749
- }
3750
- if (this.searchOptions.fields) {
3751
- body.fields = this.searchOptions.fields;
3752
- }
3753
- if (this.searchOptions.sort) {
3754
- body.sort = this.searchOptions.sort;
3755
- }
3756
- if (this.searchOptions.limit !== void 0) {
3757
- body.limit = this.searchOptions.limit;
3758
- }
3759
- if (this.searchOptions.offset !== void 0) {
3760
- body.offset = this.searchOptions.offset;
3761
- }
3762
- if (this.searchOptions.includeScore === true) {
3763
- body.includeScore = true;
3764
- }
3765
- if (this.searchOptions.explain === true) {
3766
- body.explain = true;
3767
- }
3768
- const locale = this.searchOptions.locale ?? this.clientLocale();
3769
- if (locale != null && locale !== "") {
3770
- body.locale = locale;
3771
- }
3772
- const response = await this.httpClient.send(
3773
- "/v1/search",
3774
- "post",
3775
- {
3776
- body,
3777
- headers: this.requestHeaders,
3778
- ...this.freshValue === void 0 ? {} : { query: { [FRESH_PARAMETER]: this.freshValue } }
3779
- }
3780
- );
3781
- return response.body;
3782
- }
3783
- /**
3784
- * Execute and return just the items (convenience method)
3785
- */
3786
- async items() {
3787
- return readPayload(await this.execute());
3788
- }
3789
- /**
3790
- * Get the first result
3791
- */
3792
- async first() {
3793
- return readPayload(await this.limit(1).execute())[0] ?? null;
3794
- }
3795
- };
3796
- __name(_SearchBuilder, "SearchBuilder");
3797
- var SearchBuilder = _SearchBuilder;
3798
- var _AutocompleteBuilder = class _AutocompleteBuilder {
3799
- /**
3800
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent when
3801
- * `.locale()` names none: the function `TypedRelyIOClient` hands over, or a locale fixed for it
3802
- */
3803
- constructor(httpClient, query, locale) {
3804
- this.httpClient = httpClient;
3805
- __publicField(this, "query");
3806
- __publicField(this, "autocompleteOptions", {});
3807
- /** The client's locale, asked when the query is sent rather than copied when it was built. */
3808
- __publicField(this, "clientLocale");
3809
- this.query = query;
3810
- this.clientLocale = readClientLocale(locale);
3811
- }
3812
- /**
3813
- * Autocomplete within a content type
3814
- * @param contentType - Content type to search
3815
- */
3816
- in(contentType) {
3817
- this.autocompleteOptions.contentType = contentType;
3818
- return this;
3819
- }
3820
- /**
3821
- * Field to autocomplete on
3822
- * @param fieldName - Field name (supports nested like 'category.name')
3823
- */
3824
- field(fieldName) {
3825
- this.autocompleteOptions.field = fieldName;
3826
- return this;
3827
- }
3828
- /**
3829
- * Enable fuzzy matching for typo tolerance
3830
- */
3831
- fuzzy() {
3832
- this.autocompleteOptions.fuzzy = true;
3833
- return this;
3834
- }
3835
- /**
3836
- * Add filter conditions, on the fields the content types declare. A condition on `_metadata` is
3837
- * refused here, before anything is sent.
3838
- * @param conditions - Filter conditions
3839
- */
3840
- where(conditions) {
3841
- refuseMetadataConditions(conditions);
3842
- this.autocompleteOptions.where = {
3843
- ...this.autocompleteOptions.where,
3844
- ...conditions
3845
- };
3846
- return this;
3847
- }
3848
- /**
3849
- * Limit number of suggestions
3850
- * @param count - Maximum suggestions
3851
- */
3852
- limit(count) {
3853
- this.autocompleteOptions.limit = count;
3854
- return this;
3855
- }
3856
- /**
3857
- * Set locale for localized content
3858
- * @param locale - Locale code
3859
- */
3860
- locale(locale) {
3861
- this.autocompleteOptions.locale = locale;
3862
- return this;
3863
- }
3864
- /**
3865
- * Execute the autocomplete query
3866
- */
3867
- async execute() {
3868
- if (this.autocompleteOptions.contentType == null || this.autocompleteOptions.contentType === "") {
3869
- throw new Error('Content type is required for autocomplete. Use .in("contentType")');
3870
- }
3871
- if (this.autocompleteOptions.field == null || this.autocompleteOptions.field === "") {
3872
- throw new Error('Field is required for autocomplete. Use .field("fieldName")');
3873
- }
3874
- const body = {
3875
- q: this.query,
3876
- contentType: this.autocompleteOptions.contentType,
3877
- field: this.autocompleteOptions.field
3878
- };
3879
- if (this.autocompleteOptions.fuzzy === true) {
3880
- body.fuzzy = true;
3881
- }
3882
- if (this.autocompleteOptions.where && Object.keys(this.autocompleteOptions.where).length > 0) {
3883
- body.where = this.autocompleteOptions.where;
3884
- }
3885
- if (this.autocompleteOptions.limit !== void 0) {
3886
- body.limit = this.autocompleteOptions.limit;
3887
- }
3888
- const locale = this.autocompleteOptions.locale ?? this.clientLocale();
3889
- if (locale != null && locale !== "") {
3890
- body.locale = locale;
3891
- }
3892
- const response = await this.httpClient.send("/v1/search/autocomplete", "post", { body });
3893
- return response.body;
3894
- }
3895
- /**
3896
- * Get just the suggestion texts
3897
- */
3898
- async texts() {
3899
- return readPayload(await this.execute()).map((suggestion) => suggestion.text);
3900
- }
3901
- };
3902
- __name(_AutocompleteBuilder, "AutocompleteBuilder");
3903
- var AutocompleteBuilder = _AutocompleteBuilder;
3904
- var _SimilarBuilder = class _SimilarBuilder {
3905
- /**
3906
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent when
3907
- * `.locale()` names none: the function `TypedRelyIOClient` hands over, or a locale fixed for it
3908
- */
3909
- constructor(httpClient, sourceId, locale) {
3910
- this.httpClient = httpClient;
3911
- __publicField(this, "sourceId");
3912
- __publicField(this, "similarOptions", {});
3913
- __publicField(this, "requestHeaders");
3914
- /** The client's locale, asked when the read is sent rather than copied when it was built. */
3915
- __publicField(this, "clientLocale");
3916
- this.sourceId = sourceId;
3917
- this.clientLocale = readClientLocale(locale);
3918
- }
3919
- /**
3920
- * Headers this read adds to the client's own, e.g. `X-RelyIO-Dataset` to read another dataset
3921
- * the key can see. A name the client already sends is replaced for this read only.
3922
- */
3923
- headers(headers) {
3924
- this.requestHeaders = headers;
3925
- return this;
3926
- }
3927
- /**
3928
- * Find similar content within a content type
3929
- * @param contentType - Content type to search
3930
- */
3931
- in(contentType) {
3932
- this.similarOptions.contentType = contentType;
3933
- this.similarOptions.contentTypes = void 0;
3934
- return this;
3935
- }
3936
- /**
3937
- * Find similar content across several content types, or `'*'` for every type
3938
- * @param contentTypes - Array of content types or '*' for all
3939
- */
3940
- across(contentTypes) {
3941
- this.similarOptions.contentTypes = contentTypes;
3942
- this.similarOptions.contentType = void 0;
3943
- return this;
3944
- }
3945
- /*
3946
- * No `where()` (REL-1452). Similar ranks from the source entry's stored vector, and the vector
3947
- * index can pre-filter by content type and locale only — never by an entry field. The API used to
3948
- * accept `where` here and apply nothing; it now refuses the property, so the builder does not
3949
- * offer a filter that cannot be honoured. Narrow with `.in()`, `.across()` and `.locale()`.
3950
- */
3951
- /**
3952
- * Limit number of results
3953
- * @param count - Maximum results
3954
- */
3955
- limit(count) {
3956
- this.similarOptions.limit = count;
3957
- return this;
3958
- }
3959
- /**
3960
- * Set locale for localized content
3961
- * @param locale - Locale code
3962
- */
3963
- locale(locale) {
3964
- this.similarOptions.locale = locale;
3965
- return this;
3966
- }
3967
- /**
3968
- * Execute the similar query
3969
- */
3970
- async execute() {
3971
- const { contentType, contentTypes } = this.similarOptions;
3972
- if ((contentType == null || contentType === "") && contentTypes == null) {
3973
- throw new Error(
3974
- 'Content type is required for similar search. Use .in("contentType") or .across("*")'
3975
- );
3976
- }
3977
- const body = { source: this.sourceId };
3978
- if (contentType != null && contentType !== "") {
3979
- body.contentType = contentType;
3980
- }
3981
- if (contentTypes != null) {
3982
- body.contentTypes = contentTypes;
3983
- }
3984
- if (this.similarOptions.limit !== void 0) {
3985
- body.limit = this.similarOptions.limit;
3986
- }
3987
- const locale = this.similarOptions.locale ?? this.clientLocale();
3988
- if (locale != null && locale !== "") {
3989
- body.locale = locale;
3990
- }
3991
- const response = await this.httpClient.send(
3992
- "/v1/search/similar",
3993
- "post",
3994
- { body, headers: this.requestHeaders }
3995
- );
3996
- return response.body;
3997
- }
3998
- /**
3999
- * Get just the similar items
4000
- */
4001
- async items() {
4002
- return readPayload(await this.execute());
4003
- }
4004
- /**
4005
- * Get the most similar item
4006
- */
4007
- async first() {
4008
- return readPayload(await this.limit(1).execute())[0] ?? null;
4009
- }
4010
- };
4011
- __name(_SimilarBuilder, "SimilarBuilder");
4012
- var SimilarBuilder = _SimilarBuilder;
4013
- var _SearchClient = class _SearchClient {
4014
- /**
4015
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`): every builder
4016
- * here sends it when the query names none, as `content()`'s reads do — the function
4017
- * `TypedRelyIOClient` hands over, or a locale fixed for this client
4018
- */
4019
- constructor(httpClient, locale) {
4020
- this.httpClient = httpClient;
4021
- /** The client's locale, handed to every builder here to ask when it sends. */
4022
- __publicField(this, "clientLocale");
4023
- this.clientLocale = readClientLocale(locale);
4024
- }
4025
- /**
4026
- * Start a search query
4027
- * @param query - Search query string
4028
- */
4029
- search(query) {
4030
- return new SearchBuilder(this.httpClient, query, this.clientLocale);
4031
- }
4032
- /**
4033
- * Start an autocomplete query
4034
- * @param query - Partial query to autocomplete
4035
- */
4036
- autocomplete(query) {
4037
- return new AutocompleteBuilder(this.httpClient, query, this.clientLocale);
4038
- }
4039
- /**
4040
- * Find content similar to a given entry
4041
- * @param sourceId - Entry ID to find similar content for
4042
- */
4043
- similar(sourceId) {
4044
- return new SimilarBuilder(this.httpClient, sourceId, this.clientLocale);
4045
- }
4046
- };
4047
- __name(_SearchClient, "SearchClient");
4048
- var SearchClient = _SearchClient;
4049
-
4050
- // src/batch/batch-client.ts
4051
- var _BatchBuilder = class _BatchBuilder {
4052
- /**
4053
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), each
4054
- * operation's when it names none: the function `TypedRelyIOClient` hands over, or a locale fixed
4055
- * for this batch
4056
- */
4057
- constructor(httpClient, locale) {
4058
- this.httpClient = httpClient;
4059
- __publicField(this, "operations", []);
4060
- __publicField(this, "defaultOptions", {
4061
- atomic: false,
4062
- dryRun: false,
4063
- returnData: true,
4064
- continueOnError: true
4065
- });
4066
- __publicField(this, "requestHeaders");
4067
- /** The client's locale, asked as each operation is added rather than copied when this was built. */
4068
- __publicField(this, "clientLocale");
4069
- this.clientLocale = readClientLocale(locale);
4070
- }
4071
- /**
4072
- * An operation's body with its locale: the one it names, else the client's as it is when the
4073
- * operation is added.
4074
- */
4075
- localized(data) {
4076
- const locale = callLocale(data.locale, this.clientLocale());
4077
- return locale === void 0 ? data : { ...data, locale };
4078
- }
4079
- // ==========================================================================
4080
- // ENTRY OPERATIONS
4081
- // ==========================================================================
4082
- /**
4083
- * Add a create operation
4084
- * @param contentType - Content type to create
4085
- * @param data - Entry data with content field
4086
- * @param id - Optional operation ID for tracking
4087
- */
4088
- create(contentType, data, id) {
4089
- this.operations.push({
4090
- id,
4091
- method: "POST",
4092
- path: `/${contentType}`,
4093
- body: this.localized(data)
4094
- });
4095
- return this;
4096
- }
4097
- /**
4098
- * Add an update operation (partial update).
4099
- *
4100
- * The submitted fields are merged into the entry and the rest are left as they are. The merge is
4101
- * field-level rather than deep: sending an object-typed field replaces that field's whole value.
4102
- *
4103
- * @param contentType - Content type
4104
- * @param entryId - Entry ID to update
4105
- * @param data - Fields to update
4106
- * @param id - Optional operation ID for tracking
4107
- */
4108
- update(contentType, entryId, data, id) {
4109
- this.operations.push({
4110
- id,
4111
- method: "PATCH",
4112
- path: `/${contentType}/${entryId}`,
4113
- body: this.localized(data)
4114
- });
4115
- return this;
4116
- }
4117
- /**
4118
- * Add a replace operation (full replacement).
4119
- *
4120
- * The payload becomes the entry's content for the addressed locale: fields you do not send are
4121
- * cleared. Send the whole entry, or use {@link BatchClient.update} to change part of one.
4122
- *
4123
- * @param contentType - Content type
4124
- * @param entryId - Entry ID to replace
4125
- * @param data - Complete entry data
4126
- * @param id - Optional operation ID for tracking
4127
- */
4128
- replace(contentType, entryId, data, id) {
4129
- this.operations.push({
4130
- id,
4131
- method: "PUT",
4132
- path: `/${contentType}/${entryId}`,
4133
- body: this.localized(data)
4134
- });
4135
- return this;
4136
- }
4137
- /**
4138
- * Add a delete operation
4139
- * @param contentType - Content type
4140
- * @param entryId - Entry ID to delete
4141
- * @param id - Optional operation ID for tracking
4142
- */
4143
- delete(contentType, entryId, id) {
4144
- this.operations.push({
4145
- id,
4146
- method: "DELETE",
4147
- path: `/${contentType}/${entryId}`
4148
- });
4149
- return this;
4150
- }
4151
- // ==========================================================================
4152
- // SINGLETON OPERATIONS
4153
- // ==========================================================================
4154
- /**
4155
- * Add a singleton upsert operation
4156
- * @param singletonKey - Singleton key
4157
- * @param data - Singleton content
4158
- * @param id - Optional operation ID for tracking
4159
- */
4160
- upsertSingleton(singletonKey, data, id) {
4161
- this.operations.push({
4162
- id,
4163
- method: "PATCH",
4164
- path: `/_singletons/${singletonKey}`,
4165
- body: this.localized(data)
4166
- });
4167
- return this;
4168
- }
4169
- /**
4170
- * Add a singleton create operation (alias for upsert with POST)
4171
- * @param singletonKey - Singleton key
4172
- * @param data - Singleton content
4173
- * @param id - Optional operation ID for tracking
4174
- */
4175
- createSingleton(singletonKey, data, id) {
4176
- this.operations.push({
4177
- id,
4178
- method: "POST",
4179
- path: `/_singletons/${singletonKey}`,
4180
- body: this.localized(data)
4181
- });
4182
- return this;
4183
- }
4184
- // ==========================================================================
4185
- // RAW OPERATIONS
4186
- // ==========================================================================
4187
- /**
4188
- * Add a raw operation (for advanced use cases). It is sent exactly as written: the client's
4189
- * locale is not added to it.
4190
- * @param operation - The operation to add
4191
- */
4192
- raw(operation) {
4193
- this.operations.push(operation);
4194
- return this;
4195
- }
4196
- /**
4197
- * Add multiple raw operations
4198
- * @param operations - Operations to add
4199
- */
4200
- rawMany(operations) {
4201
- this.operations.push(...operations);
4202
- return this;
4203
- }
4204
- // ==========================================================================
4205
- // BULK HELPERS
4206
- // ==========================================================================
4207
- /**
4208
- * Bulk create multiple entries of the same content type
4209
- * @param contentType - Content type
4210
- * @param items - Array of entry data
4211
- */
4212
- bulkCreate(contentType, items) {
4213
- for (const item of items) {
4214
- const { id, ...data } = item;
4215
- this.create(contentType, data, id);
4216
- }
4217
- return this;
4218
- }
4219
- /**
4220
- * Bulk update multiple entries
4221
- * @param contentType - Content type
4222
- * @param updates - Array of { entryId, data } pairs
4223
- */
4224
- bulkUpdate(contentType, updates) {
4225
- for (const update of updates) {
4226
- this.update(contentType, update.entryId, update.data, update.id);
4227
- }
4228
- return this;
4229
- }
4230
- /**
4231
- * Bulk delete multiple entries
4232
- * @param contentType - Content type
4233
- * @param entryIds - Entry IDs to delete
4234
- */
4235
- bulkDelete(contentType, entryIds) {
4236
- for (const entryId of entryIds) {
4237
- this.delete(contentType, entryId);
4238
- }
4239
- return this;
4240
- }
4241
- // ==========================================================================
4242
- // CONFIGURATION
4243
- // ==========================================================================
4244
- /**
4245
- * Configure default options for execution
4246
- * @param options - Batch options
4247
- */
4248
- configure(options) {
4249
- this.defaultOptions = { ...this.defaultOptions, ...options };
4250
- return this;
4251
- }
4252
- /**
4253
- * Enable atomic mode (all-or-nothing)
4254
- */
4255
- atomic() {
4256
- this.defaultOptions.atomic = true;
4257
- return this;
4258
- }
4259
- /**
4260
- * Enable dry-run mode (validate without executing)
4261
- */
4262
- dryRun() {
4263
- this.defaultOptions.dryRun = true;
4264
- return this;
4265
- }
4266
- /**
4267
- * Disable returning full data in response
4268
- */
4269
- noData() {
4270
- this.defaultOptions.returnData = false;
4271
- return this;
4272
- }
4273
- /**
4274
- * Stop on first error (non-atomic mode)
4275
- */
4276
- stopOnError() {
4277
- this.defaultOptions.continueOnError = false;
4278
- return this;
4279
- }
4280
- /**
4281
- * Headers the batch request adds — e.g. `{ 'X-RelyIO-Dataset': 'staging' }` to write a dataset
4282
- * other than the client's. They replace the client's own header of the same name for this
4283
- * request alone, and apply to every operation in it: a batch is one request.
4284
- */
4285
- headers(headers) {
4286
- this.requestHeaders = { ...this.requestHeaders, ...headers };
4287
- return this;
4288
- }
4289
- // ==========================================================================
4290
- // EXECUTION
4291
- // ==========================================================================
4292
- /**
4293
- * Get the current list of operations
4294
- */
4295
- getOperations() {
4296
- return [...this.operations];
4297
- }
4298
- /**
4299
- * Get the number of operations
4300
- */
4301
- size() {
4302
- return this.operations.length;
4303
- }
4304
- /**
4305
- * Clear all operations
4306
- */
4307
- clear() {
4308
- this.operations = [];
4309
- return this;
4310
- }
4311
- /**
4312
- * Clone the builder
4313
- */
4314
- clone() {
4315
- const cloned = new _BatchBuilder(this.httpClient, this.clientLocale);
4316
- cloned.operations = [...this.operations];
4317
- cloned.defaultOptions = { ...this.defaultOptions };
4318
- cloned.requestHeaders = this.requestHeaders === void 0 ? void 0 : { ...this.requestHeaders };
4319
- return cloned;
4320
- }
4321
- /**
4322
- * Execute the batch operations
4323
- * @param options - Override default options
4324
- */
4325
- async execute(options) {
4326
- if (this.operations.length === 0) {
4327
- throw new Error(
4328
- "No operations to execute. Add operations using .create(), .update(), .delete(), etc."
4329
- );
4330
- }
4331
- if (this.operations.length > 100) {
4332
- throw new Error("Maximum 100 operations per batch. Split into multiple batches.");
4333
- }
4334
- const finalOptions = { ...this.defaultOptions, ...options };
4335
- return this.httpClient.fetchPayload("/v1/batch", "post", {
4336
- body: { operations: this.operations, options: finalOptions },
4337
- headers: this.requestHeaders
4338
- });
4339
- }
4340
- /**
4341
- * Validate operations without executing (convenience for dry-run)
4342
- */
4343
- async validate() {
4344
- return this.execute({ dryRun: true });
4345
- }
4346
- /**
4347
- * Execute and throw if any operation failed
4348
- */
4349
- async executeOrThrow(options) {
4350
- const response = await this.execute(options);
4351
- if (response.summary.failed > 0) {
4352
- const failedOps = response.results.filter(
4353
- (result) => "error" in result
4354
- );
4355
- const errorMessages = failedOps.map(
4356
- (op) => `Operation ${op.index}${op.id != null && op.id !== "" ? ` (${op.id})` : ""}: ${op.error.code} \u2014 ${op.error.messages.join(" ")}`
4357
- ).join("; ");
4358
- throw new Error(
4359
- `Batch execution failed: ${response.summary.failed} of ${response.summary.total} operations failed. ${errorMessages}`
4360
- );
4361
- }
4362
- return response;
4363
- }
4364
- };
4365
- __name(_BatchBuilder, "BatchBuilder");
4366
- var BatchBuilder = _BatchBuilder;
4367
- var _BatchClient = class _BatchClient {
4368
- /**
4369
- * @param locale - The client's locale: the function `TypedRelyIOClient` hands over, or a locale
4370
- * fixed for this client
4371
- */
4372
- constructor(httpClient, locale) {
4373
- this.httpClient = httpClient;
4374
- /** The client's locale, handed to every batch this builds to ask as operations are added. */
4375
- __publicField(this, "clientLocale");
4376
- this.clientLocale = readClientLocale(locale);
4377
- }
4378
- /**
4379
- * Create a new batch builder, whose operations default to this client's locale
4380
- */
4381
- create() {
4382
- return new BatchBuilder(this.httpClient, this.clientLocale);
4383
- }
4384
- /**
4385
- * Quick bulk create entries
4386
- * @param contentType - Content type
4387
- * @param items - Array of entry data
4388
- * @param options - Batch options
4389
- */
4390
- async bulkCreate(contentType, items, options) {
4391
- return this.create().bulkCreate(contentType, items).execute(options);
4392
- }
4393
- /**
4394
- * Quick bulk update entries
4395
- * @param contentType - Content type
4396
- * @param updates - Array of updates
4397
- * @param options - Batch options
4398
- */
4399
- async bulkUpdate(contentType, updates, options) {
4400
- return this.create().bulkUpdate(contentType, updates).execute(options);
4401
- }
4402
- /**
4403
- * Quick bulk delete entries
4404
- * @param contentType - Content type
4405
- * @param entryIds - Entry IDs to delete
4406
- * @param options - Batch options
4407
- */
4408
- async bulkDelete(contentType, entryIds, options) {
4409
- return this.create().bulkDelete(contentType, entryIds).execute(options);
4410
- }
4411
- /**
4412
- * Execute raw batch operations
4413
- * @param operations - Array of operations
4414
- * @param options - Batch options
4415
- */
4416
- async execute(operations, options) {
4417
- return this.create().rawMany(operations).execute(options);
4418
- }
4419
- };
4420
- __name(_BatchClient, "BatchClient");
4421
- var BatchClient = _BatchClient;
4422
-
4423
- // src/queries/adhoc-query-client.ts
4424
- function withClientLocale(parameters, clientLocale) {
4425
- if (clientLocale === void 0 || clientLocale === "" || parameters?.locale != null) {
4426
- return parameters;
4427
- }
4428
- return { ...parameters, locale: clientLocale };
4429
- }
4430
- __name(withClientLocale, "withClientLocale");
4431
- var _AdhocQueryBuilder = class _AdhocQueryBuilder {
4432
- /**
4433
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent as the
4434
- * `locale` parameter when `.param('locale', …)` binds none: the function `TypedRelyIOClient`
4435
- * hands over, or a locale fixed for this builder
4436
- */
4437
- constructor(httpClient, locale) {
4438
- this.httpClient = httpClient;
4439
- __publicField(this, "queryDef", {});
4440
- __publicField(this, "parameters", {});
4441
- __publicField(this, "options", {});
4442
- /** The client's locale, asked when the query is sent rather than copied when it was built. */
4443
- __publicField(this, "clientLocale");
4444
- this.clientLocale = readClientLocale(locale);
4445
- }
4446
- // ==========================================================================
4447
- // QUERY BLOCKS
4448
- // ==========================================================================
4449
- /**
4450
- * Add a fetch block to retrieve content
4451
- * @param config - Fetch configuration
4452
- */
4453
- fetch(config) {
4454
- this.queryDef.fetch = config;
4455
- return this;
4456
- }
4457
- /**
4458
- * Fetch from a content type
4459
- * @param contentType - Content type to fetch
4460
- */
4461
- from(contentType) {
4462
- this.queryDef.fetch = { ...this.queryDef.fetch, contentType };
4463
- return this;
4464
- }
4465
- /**
4466
- * Fetch a singleton
4467
- * @param singletonKey - Singleton key
4468
- */
4469
- singleton(singletonKey) {
4470
- this.queryDef.fetch = { ...this.queryDef.fetch, singleton: singletonKey };
4471
- return this;
4472
- }
4473
- /**
4474
- * Add aggregate block
4475
- * @param config - Aggregate configuration
4476
- */
4477
- aggregate(config) {
4478
- this.queryDef.aggregate = config;
4479
- return this;
4480
- }
4481
- /**
4482
- * Add search block
4483
- * @param config - Search configuration
4484
- */
4485
- search(config) {
4486
- this.queryDef.search = config;
4487
- return this;
4488
- }
4489
- // ==========================================================================
4490
- // FETCH MODIFIERS
4491
- // ==========================================================================
4492
- /**
4493
- * Add where conditions to fetch
4494
- * @param conditions - Filter conditions
4495
- */
4496
- where(conditions) {
4497
- this.queryDef.fetch = {
4498
- ...this.queryDef.fetch,
4499
- where: { ...this.queryDef.fetch?.where, ...conditions }
4500
- };
4501
- return this;
4502
- }
4503
- /**
4504
- * Add include for reference population
4505
- * @param fields - Reference fields to include
4506
- */
4507
- include(fields) {
4508
- this.queryDef.fetch = {
4509
- ...this.queryDef.fetch,
4510
- include: fields
4511
- };
4512
- return this;
4513
- }
4514
- /**
4515
- * Add sort specification
4516
- * @param sort - Sort configuration
4517
- */
4518
- sort(sort) {
4519
- this.queryDef.fetch = {
4520
- ...this.queryDef.fetch,
4521
- sort: { ...this.queryDef.fetch?.sort, ...sort }
4522
- };
4523
- return this;
4524
- }
4525
- /**
4526
- * Sort by field ascending
4527
- * @param field - Field to sort by
4528
- */
4529
- sortAsc(field) {
4530
- return this.sort({ [field]: "asc" });
4531
- }
4532
- /**
4533
- * Sort by field descending
4534
- * @param field - Field to sort by
4535
- */
4536
- sortDesc(field) {
4537
- return this.sort({ [field]: "desc" });
4538
- }
4539
- /**
4540
- * Limit results
4541
- * @param count - Maximum results
4542
- */
4543
- limit(count) {
4544
- this.queryDef.fetch = {
4545
- ...this.queryDef.fetch,
4546
- limit: count
4547
- };
4548
- return this;
4549
- }
4550
- /**
4551
- * Skip results
4552
- * @param count - Number to skip
4553
- */
4554
- offset(count) {
4555
- this.queryDef.fetch = {
4556
- ...this.queryDef.fetch,
4557
- offset: count
4558
- };
4559
- return this;
4560
- }
4561
- // ==========================================================================
4562
- // PROJECTIONS & FILTERS
4563
- // ==========================================================================
4564
- /**
4565
- * Select and transform fields in output
4566
- * @param projection - Field mapping (outputField: sourceField)
4567
- */
4568
- select(projection) {
4569
- this.queryDef.select = { ...this.queryDef.select, ...projection };
4570
- return this;
4571
- }
4572
- /**
4573
- * Add a post-fetch filter (supports ${param} syntax)
4574
- * @param field - Field path to filter
4575
- * @param condition - Filter condition
4576
- */
4577
- filter(field, condition) {
4578
- this.queryDef.filters = { ...this.queryDef.filters, [field]: condition };
4579
- return this;
4580
- }
4581
- /**
4582
- * Add full-text search
4583
- * @param config - Full-text configuration
4584
- */
4585
- fullText(config) {
4586
- this.queryDef.fullText = config;
4587
- return this;
4588
- }
4589
- // ==========================================================================
4590
- // PARAMETERS
4591
- // ==========================================================================
4592
- /**
4593
- * Set query parameters
4594
- * @param params - Parameter values
4595
- */
4596
- params(params) {
4597
- this.parameters = { ...this.parameters, ...params };
4598
- return this;
4599
- }
4600
- /**
4601
- * Set a single parameter
4602
- * @param name - Parameter name
4603
- * @param value - Parameter value
4604
- */
4605
- param(name, value) {
4606
- this.parameters[name] = value;
4607
- return this;
4608
- }
4609
- // ==========================================================================
4610
- // OPTIONS
4611
- // ==========================================================================
4612
- /**
4613
- * Enable debug mode
4614
- */
4615
- debug() {
4616
- this.options.debug = true;
4617
- return this;
4618
- }
4619
- /**
4620
- * Skip cache for this request
4621
- */
4622
- skipCache() {
4623
- this.options.skipCache = true;
4624
- return this;
4625
- }
4626
- /**
4627
- * Set custom timeout
4628
- * @param ms - Timeout in milliseconds (1000-60000)
4629
- */
4630
- timeout(ms) {
4631
- if (ms < 1e3 || ms > 6e4) {
4632
- throw new Error("Timeout must be between 1000 and 60000 milliseconds");
4633
- }
4634
- this.options.timeout = ms;
4635
- return this;
4636
- }
4637
- /**
4638
- * Set cache policy
4639
- * @param ttl - Cache TTL in seconds
4640
- * @param strategy - Cache strategy
4641
- */
4642
- cache(ttl, strategy) {
4643
- this.queryDef.cache = { ttl, strategy };
4644
- return this;
4645
- }
4646
- // ==========================================================================
4647
- // EXECUTION
4648
- // ==========================================================================
4649
- /**
4650
- * Get the query definition (for debugging)
4651
- */
4652
- getDefinition() {
4653
- return { ...this.queryDef };
4654
- }
4655
- /**
4656
- * Get the parameters (for debugging)
4657
- */
4658
- getParameters() {
4659
- return { ...this.parameters };
4660
- }
2762
+ // src/content/singleton-client.ts
2763
+ var _SingletonClient = class _SingletonClient extends DocumentHandle {
4661
2764
  /**
4662
- * Execute the query
2765
+ * The singleton, or `null` when nobody has written it yet (REL-2419, REL-2409 Q18).
2766
+ *
2767
+ * `null` only for a singleton with no content: one the schema does not declare, or a dataset with
2768
+ * no schema deployed, throws `ResourceNotFoundError` naming which (`context.resourceType`
2769
+ * `'singleton'` or `'schema'`), as a content type's `get` does.
2770
+ *
2771
+ * It takes a content read's options where the route declares them — `include`, `locale` (one
2772
+ * code), `dataset` and `fresh` (`DocumentReadOptions`).
2773
+ *
2774
+ * @example
2775
+ * ```typescript
2776
+ * const home = await relyio.singleton('homepage').get({ include: ['hero'], locale: 'fr-FR' })
2777
+ * if (home) await relyio.singleton('homepage').update(home, { headline: 'Bonjour' })
2778
+ * ```
4663
2779
  */
4664
- async execute() {
4665
- if (!this.queryDef.fetch && !this.queryDef.aggregate && !this.queryDef.search) {
4666
- throw new Error(
4667
- "Query must have at least one of: fetch, aggregate or search. Use .from(), .aggregate() or .search()"
4668
- );
4669
- }
4670
- const body = {
4671
- query: this.queryDef
4672
- };
4673
- const parameters = withClientLocale(this.parameters, this.clientLocale());
4674
- if (parameters !== void 0 && Object.keys(parameters).length > 0) {
4675
- body.parameters = parameters;
4676
- }
4677
- if (Object.keys(this.options).length > 0) {
4678
- body.options = this.options;
2780
+ async get(options = {}) {
2781
+ try {
2782
+ return await this.httpClient.fetchPayload("/v1/singletons/{key}", "get", {
2783
+ path: { key: this.name },
2784
+ query: documentQuery(options, this.clientLocale()),
2785
+ headers: readHeaders(options)
2786
+ });
2787
+ } catch (error) {
2788
+ if (isMissingEntry(error)) return null;
2789
+ throw error;
4679
2790
  }
2791
+ }
2792
+ /** The API publishes on PATCH: there is no separate publish route. */
2793
+ patch(write, options) {
4680
2794
  return this.httpClient.fetchPayload(
4681
- "/v1/query",
4682
- "post",
4683
- { body }
2795
+ "/v1/singletons/{key}",
2796
+ "patch",
2797
+ {
2798
+ path: { key: this.name },
2799
+ body: DocumentHandle.bodyOf(write),
2800
+ headers: DocumentHandle.headersOf(write, options)
2801
+ }
4684
2802
  );
4685
2803
  }
4686
- /**
4687
- * Execute and return the records as an array (for list queries).
4688
- */
4689
- async items() {
4690
- const { result } = await this.execute();
4691
- if (result === void 0) return [];
4692
- return Array.isArray(result) ? result : [result];
4693
- }
4694
- /**
4695
- * Execute and return the single record (for singleton queries).
4696
- */
4697
- async data() {
4698
- const { result } = await this.execute();
4699
- if (Array.isArray(result)) return result[0];
4700
- return result;
2804
+ async readVersions(query) {
2805
+ return this.httpClient.fetchPayload("/v1/singletons/{key}/versions", "get", { path: { key: this.name }, query });
4701
2806
  }
4702
- /**
4703
- * Clone the builder
4704
- */
4705
- clone() {
4706
- const cloned = new _AdhocQueryBuilder(this.httpClient, this.clientLocale);
4707
- cloned.queryDef = JSON.parse(JSON.stringify(this.queryDef));
4708
- cloned.parameters = { ...this.parameters };
4709
- cloned.options = { ...this.options };
4710
- return cloned;
2807
+ readVersion(versionNumber, query) {
2808
+ return this.httpClient.fetchPayload(
2809
+ "/v1/singletons/{key}/versions/{versionNumber}",
2810
+ "get",
2811
+ {
2812
+ path: { key: this.name, versionNumber },
2813
+ query
2814
+ }
2815
+ );
4711
2816
  }
4712
2817
  };
4713
- __name(_AdhocQueryBuilder, "AdhocQueryBuilder");
4714
- var AdhocQueryBuilder = _AdhocQueryBuilder;
4715
- var _AdhocQueryClient = class _AdhocQueryClient {
4716
- /**
4717
- * @param locale - The client's locale (`withLocale()`, `updateConfig({ locale })`), sent as the
4718
- * `locale` parameter of every query that binds none: the function `TypedRelyIOClient` hands
4719
- * over, or a locale fixed for this client
4720
- */
4721
- constructor(httpClient, locale) {
4722
- this.httpClient = httpClient;
4723
- /** The client's locale, asked on every query rather than copied when this client was taken. */
4724
- __publicField(this, "clientLocale");
4725
- this.clientLocale = readClientLocale(locale);
4726
- }
2818
+ __name(_SingletonClient, "SingletonClient");
2819
+ var SingletonClient = _SingletonClient;
2820
+
2821
+ // src/content/settings-client.ts
2822
+ var _SettingsClient = class _SettingsClient extends DocumentHandle {
4727
2823
  /**
4728
- * Create a new query builder
2824
+ * The settings group (REL-2419, REL-2409 Q18).
2825
+ *
2826
+ * Never `null`: the API answers a declared group that nobody has written yet with its declared
2827
+ * defaults (it initializes the group on that first read), so there is no missing group to report.
2828
+ * A group the schema does not declare, or a dataset with no schema deployed, throws
2829
+ * `ResourceNotFoundError` naming which (`context.resourceType` `'settingsGroup'` or `'schema'`) —
2830
+ * the not-found rule every handle's `get` follows.
2831
+ *
2832
+ * It takes a content read's options where the route declares them — `include`, `locale` (one
2833
+ * code), `dataset` and `fresh` (`DocumentReadOptions`).
2834
+ *
2835
+ * @example
2836
+ * ```typescript
2837
+ * const site = await relyio.settings('site').get({ include: ['logo'] })
2838
+ * await relyio.settings('site').update(site, { title: 'New title' })
2839
+ * ```
4729
2840
  */
4730
- build() {
4731
- return new AdhocQueryBuilder(this.httpClient, this.clientLocale);
2841
+ async get(options = {}) {
2842
+ return this.httpClient.fetchPayload(
2843
+ "/v1/settings/{groupId}",
2844
+ "get",
2845
+ {
2846
+ path: { groupId: this.name },
2847
+ query: documentQuery(options, this.clientLocale()),
2848
+ headers: readHeaders(options)
2849
+ }
2850
+ );
4732
2851
  }
4733
- /**
4734
- * Execute a query definition directly
4735
- * @param definition - Query definition
4736
- * @param parameters - Parameter values
4737
- * @param options - Execution options
4738
- * @param request - `headers` this one request adds to the client's own, e.g. `X-RelyIO-Dataset`
4739
- * to query another dataset the key can see. A name the client already sends is replaced for
4740
- * this request only.
4741
- */
4742
- async execute(definition, parameters, options, request) {
4743
- const body = {
4744
- query: definition
4745
- };
4746
- const sent = withClientLocale(parameters, this.clientLocale());
4747
- if (sent !== void 0 && Object.keys(sent).length > 0) {
4748
- body.parameters = sent;
4749
- }
4750
- if (options && Object.keys(options).length > 0) {
4751
- body.options = options;
4752
- }
2852
+ async reset(...args) {
2853
+ const [first, second] = args;
2854
+ const write = first !== void 0 && isRead(first) ? { ...versionCheckOf(first), options: second } : { locale: this.localeOf(first?.locale), ifMatch: void 0, options: first };
4753
2855
  return this.httpClient.fetchPayload(
4754
- "/v1/query",
2856
+ "/v1/settings/{groupId}/reset",
4755
2857
  "post",
4756
- { body, headers: request?.headers }
2858
+ {
2859
+ path: { groupId: this.name },
2860
+ query: write.locale === void 0 ? void 0 : { locale: write.locale },
2861
+ headers: DocumentHandle.headersOf(write, write.options)
2862
+ }
4757
2863
  );
4758
2864
  }
4759
- /**
4760
- * Quick fetch helper
4761
- * @param contentType - Content type
4762
- * @param options - Fetch options
4763
- */
4764
- async fetch(contentType, options) {
4765
- const { result } = await this.execute({ fetch: { contentType, ...options } });
4766
- if (result === void 0) return [];
4767
- return Array.isArray(result) ? result : [result];
2865
+ /** The group's default values, as the schema declares them. */
2866
+ async getDefaults() {
2867
+ return this.httpClient.fetchPayload(
2868
+ "/v1/settings/{groupId}/defaults",
2869
+ "get",
2870
+ { path: { groupId: this.name } }
2871
+ );
4768
2872
  }
4769
- /**
4770
- * Quick singleton fetch helper
4771
- * @param singletonKey - Singleton key
4772
- */
4773
- async fetchSingleton(singletonKey) {
4774
- const { result } = await this.execute({ fetch: { singleton: singletonKey } });
4775
- if (Array.isArray(result)) return result[0];
4776
- return result;
2873
+ patch(write, options) {
2874
+ return this.httpClient.fetchPayload(
2875
+ "/v1/settings/{groupId}",
2876
+ "patch",
2877
+ {
2878
+ path: { groupId: this.name },
2879
+ body: DocumentHandle.bodyOf(write),
2880
+ headers: DocumentHandle.headersOf(write, options)
2881
+ }
2882
+ );
4777
2883
  }
4778
- /**
4779
- * Quick aggregate helper
4780
- * @param source - Source content type
4781
- * @param metrics - Metrics to compute
4782
- * @param groupBy - Optional grouping field
4783
- */
4784
- async aggregate(source, metrics, groupBy) {
4785
- const { result } = await this.execute({ aggregate: { source, metrics, by: groupBy } });
4786
- if (result === void 0) return [];
4787
- return Array.isArray(result) ? result : [result];
2884
+ async readVersions(query) {
2885
+ return this.httpClient.fetchPayload("/v1/settings/{groupId}/versions", "get", { path: { groupId: this.name }, query });
2886
+ }
2887
+ readVersion(versionNumber, query) {
2888
+ return this.httpClient.fetchPayload("/v1/settings/{groupId}/versions/{versionNumber}", "get", {
2889
+ path: { groupId: this.name, versionNumber },
2890
+ query
2891
+ });
4788
2892
  }
4789
2893
  };
4790
- __name(_AdhocQueryClient, "AdhocQueryClient");
4791
- var AdhocQueryClient = _AdhocQueryClient;
2894
+ __name(_SettingsClient, "SettingsClient");
2895
+ var SettingsClient = _SettingsClient;
4792
2896
 
4793
2897
  // src/changes/changes.ts
4794
2898
  var CHANGES_POLL_TIMEOUT_MS = 25e3 + 5e3;
@@ -5425,6 +3529,264 @@ function hasOwn(object, key) {
5425
3529
  }
5426
3530
  __name(hasOwn, "hasOwn");
5427
3531
 
3532
+ // src/search/search-options.ts
3533
+ function scopeOf(contentType) {
3534
+ if (contentType === void 0) return { contentTypes: "*" };
3535
+ if (typeof contentType === "string") return { contentType };
3536
+ return { contentTypes: [...contentType] };
3537
+ }
3538
+ __name(scopeOf, "scopeOf");
3539
+ function selectedFields(select) {
3540
+ if (select === void 0 || select.length === 0) return {};
3541
+ return { fields: Object.fromEntries(select.map((field) => [field, field])) };
3542
+ }
3543
+ __name(selectedFields, "selectedFields");
3544
+ function localeOf(own, client) {
3545
+ const locale = own ?? client;
3546
+ return locale === void 0 || locale === "" ? {} : { locale };
3547
+ }
3548
+ __name(localeOf, "localeOf");
3549
+ function whereOf(where) {
3550
+ if (where === void 0) return {};
3551
+ refuseMetadataConditions(where);
3552
+ return Object.keys(where).length === 0 ? {} : { where };
3553
+ }
3554
+ __name(whereOf, "whereOf");
3555
+ function given(options) {
3556
+ return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0));
3557
+ }
3558
+ __name(given, "given");
3559
+ function transportOf(options) {
3560
+ const headers = readHeaders(options);
3561
+ return {
3562
+ ...headers === void 0 ? {} : { headers },
3563
+ ...typeof options.fresh === "string" ? { query: { [FRESH_PARAMETER]: options.fresh } } : {}
3564
+ };
3565
+ }
3566
+ __name(transportOf, "transportOf");
3567
+ async function runSearch(http, q, options, clientLocale) {
3568
+ const sort = options.sort === void 0 ? [] : Object.entries(options.sort).flatMap(
3569
+ ([field, direction]) => direction === void 0 ? [] : [{ field, direction }]
3570
+ );
3571
+ const body = {
3572
+ q,
3573
+ ...scopeOf(options.contentType),
3574
+ ...whereOf(options.where),
3575
+ ...given({
3576
+ searchFields: options.searchFields === void 0 ? void 0 : [...options.searchFields]
3577
+ }),
3578
+ ...selectedFields(options.select),
3579
+ ...sort.length === 0 ? {} : { sort },
3580
+ ...given({
3581
+ page: options.page,
3582
+ limit: options.limit,
3583
+ includeScore: options.includeScore,
3584
+ explain: options.explain,
3585
+ highlight: options.highlight,
3586
+ facets: options.facets
3587
+ }),
3588
+ ...localeOf(options.locale, clientLocale)
3589
+ };
3590
+ const response = await http.send(
3591
+ "/v1/search",
3592
+ "post",
3593
+ {
3594
+ body,
3595
+ ...transportOf(options)
3596
+ }
3597
+ );
3598
+ return response.body;
3599
+ }
3600
+ __name(runSearch, "runSearch");
3601
+ async function runAutocomplete(http, q, options, clientLocale) {
3602
+ const body = {
3603
+ q,
3604
+ contentType: options.contentType,
3605
+ field: options.field,
3606
+ ...given({ fuzzy: options.fuzzy }),
3607
+ ...whereOf(options.where),
3608
+ ...given({ limit: options.limit }),
3609
+ ...localeOf(options.locale, clientLocale)
3610
+ };
3611
+ const response = await http.send(
3612
+ "/v1/search/autocomplete",
3613
+ "post",
3614
+ { body, ...transportOf(options) }
3615
+ );
3616
+ return response.body;
3617
+ }
3618
+ __name(runAutocomplete, "runAutocomplete");
3619
+ async function runSimilar(http, source, options, clientLocale) {
3620
+ const body = {
3621
+ source,
3622
+ ...scopeOf(options.contentType),
3623
+ ...given({ limit: options.limit }),
3624
+ ...localeOf(options.locale, clientLocale),
3625
+ ...selectedFields(options.select)
3626
+ };
3627
+ const response = await http.send(
3628
+ "/v1/search/similar",
3629
+ "post",
3630
+ { body, ...transportOf(options) }
3631
+ );
3632
+ return response.body;
3633
+ }
3634
+ __name(runSimilar, "runSimilar");
3635
+
3636
+ // src/batch/batch-operations.ts
3637
+ var VERBS = ["create", "update", "replace", "delete", "singleton"];
3638
+ async function runBatch(http, operations, options, clientLocale) {
3639
+ const { atomic, dryRun, stopOnError, returnData, dataset } = options;
3640
+ const runOptions = {
3641
+ ...atomic === void 0 ? {} : { atomic },
3642
+ ...dryRun === void 0 ? {} : { dryRun },
3643
+ ...stopOnError === void 0 ? {} : { continueOnError: !stopOnError },
3644
+ ...returnData === void 0 ? {} : { returnData }
3645
+ };
3646
+ const headers = readHeaders({ ...dataset === void 0 ? {} : { dataset } });
3647
+ const response = await http.send("/v1/batch", "post", {
3648
+ body: {
3649
+ operations: operations.map((operation, index) => operationOf(operation, index, clientLocale)),
3650
+ ...Object.keys(runOptions).length === 0 ? {} : { options: runOptions }
3651
+ },
3652
+ ...headers === void 0 ? {} : { headers }
3653
+ });
3654
+ return response.body;
3655
+ }
3656
+ __name(runBatch, "runBatch");
3657
+ function operationOf(operation, index, clientLocale) {
3658
+ const named = VERBS.filter((verb2) => operation[verb2] !== void 0);
3659
+ const verb = named[0];
3660
+ if (verb === void 0 || named.length > 1) {
3661
+ throw new ValidationError(
3662
+ `Batch operation ${index} must name exactly one of ${VERBS.join(", ")}; it names ${named.length === 0 ? "none" : named.join(" and ")}.`,
3663
+ [{ field: `operations[${index}]`, code: "ONE_VERB", message: "name one verb" }]
3664
+ );
3665
+ }
3666
+ const { slug, parentId, sortOrder } = operation;
3667
+ const placement = {
3668
+ ...slug === void 0 ? {} : { slug },
3669
+ ...parentId === void 0 ? {} : { parentId },
3670
+ ...sortOrder === void 0 ? {} : { sortOrder }
3671
+ };
3672
+ const located = /* @__PURE__ */ __name((locale) => locale === void 0 ? {} : { locale }, "located");
3673
+ switch (verb) {
3674
+ case "create": {
3675
+ return {
3676
+ method: "POST",
3677
+ path: `/${operation.create}`,
3678
+ body: {
3679
+ content: operation.data,
3680
+ ...placement,
3681
+ ...located(callLocale(operation.locale, clientLocale))
3682
+ }
3683
+ };
3684
+ }
3685
+ case "update":
3686
+ case "replace": {
3687
+ const target = targetOf(operation, clientLocale);
3688
+ return {
3689
+ method: verb === "update" ? "PATCH" : "PUT",
3690
+ path: `/${operation[verb]}/${target.id}`,
3691
+ ...target.ifMatch === void 0 ? {} : { ifMatch: target.ifMatch },
3692
+ body: { content: operation.data, ...placement, ...located(target.locale) }
3693
+ };
3694
+ }
3695
+ case "delete": {
3696
+ const target = targetOf(operation, void 0);
3697
+ return {
3698
+ method: "DELETE",
3699
+ path: `/${operation.delete}/${target.id}`,
3700
+ ...target.ifMatch === void 0 ? {} : { ifMatch: target.ifMatch }
3701
+ };
3702
+ }
3703
+ case "singleton": {
3704
+ return {
3705
+ method: "PATCH",
3706
+ path: `/_singletons/${operation.singleton}`,
3707
+ body: { content: operation.data, ...located(callLocale(operation.locale, clientLocale)) }
3708
+ };
3709
+ }
3710
+ }
3711
+ }
3712
+ __name(operationOf, "operationOf");
3713
+ function targetOf(operation, clientLocale) {
3714
+ if (operation.entry !== void 0) return versionCheckOf(operation.entry);
3715
+ if (operation.id === void 0) {
3716
+ throw new ValidationError("A batch update, replace or delete names an `entry` or an `id`.", [
3717
+ { field: "id", code: "MISSING_TARGET", message: "name an entry or an id" }
3718
+ ]);
3719
+ }
3720
+ const locale = callLocale(operation.locale, clientLocale);
3721
+ return { id: operation.id, ...locale === void 0 ? {} : { locale } };
3722
+ }
3723
+ __name(targetOf, "targetOf");
3724
+
3725
+ // src/queries/query-call.ts
3726
+ async function runAdhocQuery(http, query, clientLocale) {
3727
+ const { where, include, select, sort, limit, page, aggregate, fullText } = query;
3728
+ if (where !== void 0) refuseMetadataConditions(where);
3729
+ const order = sort === void 0 ? [] : Object.entries(sort).flatMap(
3730
+ ([field, direction]) => direction === void 0 ? [] : [{ [field]: direction }]
3731
+ );
3732
+ const fetch2 = {
3733
+ contentType: query.from,
3734
+ ...where === void 0 || Object.keys(where).length === 0 ? {} : { where },
3735
+ ...include === void 0 || include.length === 0 ? {} : { include: [...include] },
3736
+ ...order.length === 0 ? {} : { sort: order },
3737
+ ...limit === void 0 ? {} : { limit },
3738
+ ...page === void 0 ? {} : { offset: offsetOf(page, limit) }
3739
+ };
3740
+ const locale = query.locale ?? clientLocale;
3741
+ const parameters = {
3742
+ ...query.params,
3743
+ ...locale === void 0 || locale === "" ? {} : { locale }
3744
+ };
3745
+ const body = {
3746
+ query: {
3747
+ fetch: fetch2,
3748
+ ...aggregate === void 0 ? {} : { aggregate },
3749
+ ...select === void 0 || select.length === 0 ? {} : { select: Object.fromEntries(select.map((field) => [field, field])) },
3750
+ ...fullText === void 0 ? {} : { fullText }
3751
+ },
3752
+ ...Object.keys(parameters).length === 0 ? {} : { parameters }
3753
+ };
3754
+ const headers = readHeaders(query);
3755
+ const response = await http.send("/v1/query", "post", {
3756
+ body,
3757
+ ...headers === void 0 ? {} : { headers },
3758
+ ...typeof query.fresh === "string" ? { query: { [FRESH_PARAMETER]: query.fresh } } : {}
3759
+ });
3760
+ return response.body;
3761
+ }
3762
+ __name(runAdhocQuery, "runAdhocQuery");
3763
+ function offsetOf(page, limit) {
3764
+ if (limit === void 0 || !Number.isInteger(page) || page < 1) {
3765
+ throw new ValidationError(
3766
+ "`page` is a whole number from 1, beside the `limit` that sizes it.",
3767
+ [{ field: "page", code: "INVALID_PAGE", message: `page ${page}, limit ${String(limit)}` }]
3768
+ );
3769
+ }
3770
+ return (page - 1) * limit;
3771
+ }
3772
+ __name(offsetOf, "offsetOf");
3773
+ async function runNamedQuery(http, name, options, clientLocale) {
3774
+ const locale = options.locale ?? clientLocale;
3775
+ const headers = readHeaders(options);
3776
+ const response = await http.send(
3777
+ "/v1/queries/{name}",
3778
+ "post",
3779
+ {
3780
+ path: { name },
3781
+ body: options.params === void 0 ? {} : { params: options.params },
3782
+ ...locale === void 0 || locale === "" ? {} : { query: { locale } },
3783
+ ...headers === void 0 ? {} : { headers }
3784
+ }
3785
+ );
3786
+ return response.body;
3787
+ }
3788
+ __name(runNamedQuery, "runNamedQuery");
3789
+
5428
3790
  // src/config/dev-detection.ts
5429
3791
  function sandboxStateOf(resolution) {
5430
3792
  return resolution.state === "active" ? resolution.sandbox : resolution;
@@ -5629,9 +3991,9 @@ function withHandshake(configured) {
5629
3991
  return { config: merged, sandbox: sandboxStateOf(dev), configured };
5630
3992
  }
5631
3993
  __name(withHandshake, "withHandshake");
5632
- function withDefaults(base, given, defaults) {
3994
+ function withDefaults(base, given2, defaults) {
5633
3995
  const merged = new Map(Object.entries(base));
5634
- const givenValues = new Map(Object.entries(given ?? {}));
3996
+ const givenValues = new Map(Object.entries(given2 ?? {}));
5635
3997
  const defaultValues = new Map(Object.entries(defaults));
5636
3998
  for (const key of /* @__PURE__ */ new Set([...merged.keys(), ...givenValues.keys()])) {
5637
3999
  const fallback = merged.get(key);
@@ -5658,7 +4020,6 @@ function isOptionBag(value) {
5658
4020
  __name(isOptionBag, "isOptionBag");
5659
4021
 
5660
4022
  // src/client/create-client.ts
5661
- var API_VERSION_SEGMENT = "v1";
5662
4023
  var _TypedRelyIOClient = class _TypedRelyIOClient {
5663
4024
  constructor(config) {
5664
4025
  /**
@@ -5669,7 +4030,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5669
4030
  __publicField(this, "config");
5670
4031
  /**
5671
4032
  * The configuration as `createClient()`, `setApiKey()` and `updateConfig()` gave it, before the
5672
- * `relyio dev` handshake: what the next update is laid over, and what `withLocale()` starts from.
4033
+ * `relyio dev` handshake: what the next update is laid over, and what `with()` starts from.
5673
4034
  */
5674
4035
  __publicField(this, "configured");
5675
4036
  __publicField(this, "_sandbox");
@@ -5679,7 +4040,15 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5679
4040
  * rather than a copy of the locale, so one taken before `updateConfig({ locale })` sends the new
5680
4041
  * locale, or none after `locale: null` (REL-1453).
5681
4042
  */
5682
- __publicField(this, "currentLocale", /* @__PURE__ */ __name(() => this.config.locale, "currentLocale"));
4043
+ __publicField(this, "currentLocale", /* @__PURE__ */ __name(() => this.defaults.locale ?? (this.parent === void 0 ? this.config.locale : this.parent.currentLocale()), "currentLocale"));
4044
+ /**
4045
+ * The client `with()` was called on, for a client it made: whose key, base URL and configuration
4046
+ * this one reads with as they are when each request is sent. `undefined` for a client
4047
+ * `createClient()` made, which reads its own.
4048
+ */
4049
+ __publicField(this, "parent");
4050
+ /** What `with()` gave this client over its parent's: the locale and dataset it names, and no other. */
4051
+ __publicField(this, "defaults", {});
5683
4052
  /** The live edge's poll client id: chosen once, when first needed, and kept for this client's life. */
5684
4053
  __publicField(this, "_liveClientId");
5685
4054
  const { schema, ...clientConfig } = config;
@@ -5693,12 +4062,6 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5693
4062
  // ============================================================================
5694
4063
  // CORE CLIENTS
5695
4064
  // ============================================================================
5696
- /**
5697
- * Get the schema definition
5698
- */
5699
- get schema() {
5700
- return this._schema;
5701
- }
5702
4065
  /**
5703
4066
  * The `relyio dev` sandbox this client resolved at construction, as the preview toolbar displays
5704
4067
  * it (`sdk-surfaces-spec.md` decision 22).
@@ -5714,13 +4077,23 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5714
4077
  * ```
5715
4078
  */
5716
4079
  get sandbox() {
5717
- return this._sandbox;
4080
+ return this.parent === void 0 ? this._sandbox : this.parent.sandbox;
5718
4081
  }
5719
4082
  /**
5720
- * Get the ad-hoc query client. Every query it sends is in the client's locale as it is then.
4083
+ * Run a query in one call (REL-2421, REL-2409 Q22):
4084
+ *
4085
+ * - `query({ from, … })` runs one inline, with `list`'s option names — `where` (the query
4086
+ * route's dialect), `include`, `select`, `sort`, `limit`, `page`, `locale`, `dataset`, `fresh` —
4087
+ * plus `aggregate`, `params` and `fullText`;
4088
+ * - `query(name, { params, … })` runs the saved query the schema declares under `name`, its
4089
+ * `params` typed from that declaration.
4090
+ *
4091
+ * Both answer the API's body, `{ data: { result, metadata } }`. See {@link QueryCall}. Every query
4092
+ * is sent in the client's locale as it is then, unless it names its own.
5721
4093
  */
5722
4094
  get query() {
5723
- return new AdhocQueryClient(this.httpClient, this.currentLocale);
4095
+ const call = /* @__PURE__ */ __name((target, options = {}) => typeof target === "string" ? runNamedQuery(this.httpClient, target, options, this.currentLocale()) : runAdhocQuery(this.httpClient, target, this.currentLocale()), "call");
4096
+ return call;
5724
4097
  }
5725
4098
  // ============================================================================
5726
4099
  // CONTENT OPERATIONS
@@ -5731,12 +4104,11 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5731
4104
  *
5732
4105
  * @example
5733
4106
  * ```typescript
5734
- * const products = await relyio.content('product')
5735
- * .query()
5736
- * .where({ status: 'active' }) // ← Field names autocomplete with schema!
5737
- * .locale('en-US')
5738
- * .limit(20)
5739
- * .execute()
4107
+ * const { data: products } = await relyio.content('product').list({
4108
+ * where: { status: 'active' }, // ← Field names autocomplete with schema!
4109
+ * locale: 'en-US',
4110
+ * limit: 20,
4111
+ * })
5740
4112
  * ```
5741
4113
  */
5742
4114
  content(contentType) {
@@ -5745,9 +4117,9 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5745
4117
  /**
5746
4118
  * Get an asset client for a specific asset type.
5747
4119
  *
5748
- * Mirrors `content()` but targets `entryType: 'asset'` entries on the same
5749
- * dynamic `/{assetTypeId}` routes, and adds the `file(entryUid)` sub-resource
5750
- * builder + a high-level `upload()` helper. Type-safe when a schema is
4120
+ * Reads and writes as `content()` does — `list`, `get`, `listAll`, `update`, `delete` — over
4121
+ * `entryType: 'asset'` entries on the same dynamic `/{assetTypeId}` routes, and adds `create`,
4122
+ * the `file(entryUid)` sub-resource builder and a high-level `upload()` helper. Type-safe when a schema is
5751
4123
  * provided: autocompletes asset type names AND metadata field names.
5752
4124
  *
5753
4125
  * @example
@@ -5769,10 +4141,10 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5769
4141
  *
5770
4142
  * @example
5771
4143
  * ```typescript
5772
- * const homepage = await relyio.singleton('homepage')
5773
- * .include(['featuredProducts'])
5774
- * .locale('en')
5775
- * .fetch()
4144
+ * const homepage = await relyio.singleton('homepage').get({
4145
+ * include: ['featuredProducts'],
4146
+ * locale: 'en',
4147
+ * })
5776
4148
  * ```
5777
4149
  */
5778
4150
  singleton(key) {
@@ -5784,101 +4156,54 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5784
4156
  *
5785
4157
  * @example
5786
4158
  * ```typescript
5787
- * const emailConfig = await relyio.settings('email-config')
5788
- * .include(['defaultTemplate'])
5789
- * .fetch()
4159
+ * const emailConfig = await relyio.settings('email-config').get({
4160
+ * include: ['defaultTemplate'],
4161
+ * })
5790
4162
  * ```
5791
4163
  */
5792
4164
  settings(groupId) {
5793
4165
  return new SettingsClient(this.httpClient, groupId, this.currentLocale);
5794
4166
  }
5795
- // ============================================================================
5796
- // SEARCH OPERATIONS
5797
- // ============================================================================
5798
- /**
5799
- * Start a search query with full-text, semantic, or hybrid search.
5800
- *
5801
- * Where a schema types the client, the results are its entries — every content type's until
5802
- * `in()` or `across()` narrows them (`INV-SS-TYPES-INFERRED`).
5803
- *
5804
- * @example
5805
- * ```typescript
5806
- * const results = await relyio.search('wireless headphones')
5807
- * .in('product')
5808
- * .where({ status: 'active' })
5809
- * .limit(20)
5810
- * .includeScore()
5811
- * .execute()
5812
- * ```
5813
- */
5814
- search(query) {
5815
- return this.searchClient().search(query);
4167
+ search(query, options) {
4168
+ return runSearch(this.httpClient, query, options, this.currentLocale());
5816
4169
  }
5817
- /**
5818
- * Start an autocomplete query for search suggestions
5819
- *
5820
- * @example
5821
- * ```typescript
5822
- * const suggestions = await relyio.autocomplete('wire')
5823
- * .in('product')
5824
- * .field('title')
5825
- * .fuzzy()
5826
- * .limit(10)
5827
- * .execute()
5828
- * ```
5829
- */
5830
- autocomplete(query) {
5831
- return this.searchClient().autocomplete(query);
4170
+ autocomplete(query, options) {
4171
+ return runAutocomplete(this.httpClient, query, options, this.currentLocale());
5832
4172
  }
5833
- /**
5834
- * Find content similar to a given entry using vector search
5835
- *
5836
- * @example
5837
- * ```typescript
5838
- * const similar = await relyio.similar('entry_abc123')
5839
- * .in('product')
5840
- * .locale('fr-FR')
5841
- * .limit(5)
5842
- * .execute()
5843
- * ```
5844
- */
5845
- similar(sourceId) {
5846
- return this.searchClient().similar(sourceId);
4173
+ similar(sourceId, options) {
4174
+ return runSimilar(this.httpClient, sourceId, options, this.currentLocale());
5847
4175
  }
5848
4176
  // ============================================================================
5849
4177
  // BATCH OPERATIONS
5850
4178
  // ============================================================================
5851
4179
  /**
5852
- * Start a batch operation for bulk create/update/delete.
4180
+ * Write a list of operations in one request (REL-2421, REL-2409 Q22): each a create, update,
4181
+ * replace or delete of an entry, or a singleton write.
4182
+ *
4183
+ * An update, replace or delete takes the **entry you read** — checked against the version it
4184
+ * carries, in the locale it was read in, as `update(entry, data)` is — or an **id**, which writes
4185
+ * unchecked, on purpose. A stale entry fails its operation with `RESOURCE_CONFLICT` naming the
4186
+ * versions that disagreed: re-read it with `fresh: true` and retry. With `atomic: true` nothing
4187
+ * in the batch is written then — and the API takes an atomic batch only when every operation is
4188
+ * the same kind of write.
5853
4189
  *
5854
- * By default each operation lands or fails on its own. `atomic: true` makes the batch one
5855
- * transaction, which the API accepts only when every operation is the same kind of write and none
5856
- * writes a singleton that does not exist yet.
4190
+ * Answers the API's body, `{ data: { results, summary } }`: one result per operation, in order,
4191
+ * each an `outcome` or an `error`. An operation that failed is not thrown.
5857
4192
  *
5858
4193
  * @example
5859
4194
  * ```typescript
5860
- * const result = await relyio.batch()
5861
- * .create('product', { content: { title: 'iPhone', price: 999 } })
5862
- * .update('product', 'entry_abc', { content: { price: 899 } })
5863
- * .delete('product', 'entry_xyz')
5864
- * .upsertSingleton('homepage', { content: { hero: 'Welcome!' } })
5865
- * .execute()
5866
- *
5867
- * console.log(result.summary.succeeded)
5868
- *
5869
- * // All or nothing: one kind of write
5870
- * await relyio.batch()
5871
- * .update('product', 'entry_abc', { content: { price: 899 } })
5872
- * .update('product', 'entry_def', { content: { price: 799 } })
5873
- * .execute({ atomic: true })
4195
+ * const post = await relyio.content('post').get('hello-world')
4196
+ * const { data } = await relyio.batch([
4197
+ * { create: 'post', data: { title: 'New' } },
4198
+ * ...(post ? [{ update: 'post' as const, entry: post, data: { title: 'Changed' } }] : []),
4199
+ * { delete: 'post', id: 'entry_xyz' },
4200
+ * { singleton: 'homepage', data: { hero: 'Welcome!' } },
4201
+ * ])
4202
+ * console.log(data.summary.succeeded)
5874
4203
  * ```
5875
4204
  */
5876
- batch() {
5877
- return new BatchClient(this.httpClient, this.currentLocale).create();
5878
- }
5879
- /** The search client, whose builders send the client's locale as it is when each one is sent. */
5880
- searchClient() {
5881
- return new SearchClient(this.httpClient, this.currentLocale);
4205
+ async batch(operations, options = {}) {
4206
+ return runBatch(this.httpClient, operations, options, this.currentLocale());
5882
4207
  }
5883
4208
  // ============================================================================
5884
4209
  // CHANGES FEED
@@ -5898,7 +4223,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5898
4223
  * const controller = new AbortController()
5899
4224
  * for await (const change of relyio.changes({ since: cursor, types: ['post'], signal: controller.signal })) {
5900
4225
  * // { entryId, contentType, locale, kind, cursor, fresh }
5901
- * await relyio.content(change.contentType).findById(change.entryId).fresh(change.fresh).execute()
4226
+ * await relyio.content(change.contentType).get(change.entryId, { fresh: change.fresh })
5902
4227
  * }
5903
4228
  * ```
5904
4229
  *
@@ -5940,7 +4265,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5940
4265
  * signal: controller.signal,
5941
4266
  * // `fresh` names a position no cache holds a body for from before the change.
5942
4267
  * onChange: change =>
5943
- * relyio.content(change.contentType).findById(change.entryId).fresh(change.fresh).execute(),
4268
+ * relyio.content(change.contentType).get(change.entryId, { fresh: change.fresh }),
5944
4269
  * onResync: resync => refetchEverything(resync.cause === 'expired' ? resync.expired.fresh : undefined),
5945
4270
  * })
5946
4271
  * ```
@@ -5949,7 +4274,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5949
4274
  * edge's URL. On a server, follow `changes()` with it instead.
5950
4275
  */
5951
4276
  liveChanges(options = {}) {
5952
- const { apiKey, dataset, baseUrl, liveUrl, fetch: fetch2, webSocket, timeout } = this.config;
4277
+ const { apiKey, dataset, baseUrl, liveUrl, fetch: fetch2, webSocket, timeout } = this.getConfig();
5953
4278
  this._liveClientId ?? (this._liveClientId = randomClientId());
5954
4279
  return subscribeLiveEdge(
5955
4280
  {
@@ -5977,60 +4302,13 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5977
4302
  * @example
5978
4303
  * ```typescript
5979
4304
  * const since = await relyio.changesHead()
5980
- * const post = await relyio.content('post').findById(id).execute()
4305
+ * const post = await relyio.content('post').get(id)
5981
4306
  * for await (const change of relyio.changes({ since, ids: [id] })) { … }
5982
4307
  * ```
5983
4308
  */
5984
4309
  changesHead(options = {}) {
5985
4310
  return readChangesHead(this.httpClient, options);
5986
4311
  }
5987
- // ============================================================================
5988
- // QUERY OPERATIONS
5989
- // ============================================================================
5990
- /**
5991
- * Build and execute an ad-hoc query dynamically
5992
- *
5993
- * @example
5994
- * ```typescript
5995
- * const result = await relyio.adhoc()
5996
- * .from('product')
5997
- * .where({ status: 'active' })
5998
- * .include(['brand', 'categories'])
5999
- * .select({
6000
- * id: 'id',
6001
- * title: 'title',
6002
- * price: 'pricing.basePrice'
6003
- * })
6004
- * .limit(20)
6005
- * .execute()
6006
- * ```
6007
- */
6008
- adhoc() {
6009
- return this.query.build();
6010
- }
6011
- /**
6012
- * Execute a predefined query by name (from schema)
6013
- * Type-safe when schema is provided: autocompletes query names
6014
- *
6015
- * @example
6016
- * ```typescript
6017
- * const featured = await relyio.executeQuery('featured-products', {
6018
- * limit: 10,
6019
- * category: 'electronics'
6020
- * })
6021
- * ```
6022
- */
6023
- async executeQuery(queryName, params) {
6024
- const clientLocale = this.config.locale;
6025
- const namesLocale = params?.locale != null || params?.locales != null;
6026
- const response = await this.httpClient.request({
6027
- method: "GET",
6028
- url: `/${API_VERSION_SEGMENT}/${String(queryName)}`,
6029
- params: namesLocale || clientLocale === void 0 || clientLocale === "" ? params ?? {} : { ...params, locale: clientLocale }
6030
- });
6031
- const payload = readPayload(response.body);
6032
- return Array.isArray(payload) ? payload : [payload];
6033
- }
6034
4312
  /**
6035
4313
  * Describe the project this key resolves to — `GET /v1/project`.
6036
4314
  *
@@ -6049,46 +4327,61 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6049
4327
  return this.httpClient.fetchPayload("/v1/project", "get", {});
6050
4328
  }
6051
4329
  /**
6052
- * Get schema information from the API
4330
+ * The schema definition the key's branch has deployed, as stored — `GET /v1/meta/schema` — or,
4331
+ * given a content type or singleton id, that one type's definition — `GET /v1/meta/schema/{id}`.
4332
+ *
4333
+ * It answers what the deployed schema declares; `project()` answers where the key points
4334
+ * (organization, project, dataset, branch, Studio link). The two share no field.
4335
+ *
4336
+ * @example
4337
+ * ```typescript
4338
+ * const definition = await relyio.schema('post')
4339
+ * ```
6053
4340
  */
6054
- async getSchemaInfo(contentType) {
4341
+ async schema(contentType) {
6055
4342
  return contentType == null ? this.httpClient.fetchPayload("/v1/meta/schema", "get", {}) : this.httpClient.fetchPayload("/v1/meta/schema/{contentType}", "get", {
6056
4343
  path: { contentType }
6057
4344
  });
6058
4345
  }
6059
4346
  /**
6060
- * List all content types from the API
4347
+ * The content types and singletons the key's branch has deployed — `GET /v1/meta/content-types`.
4348
+ *
4349
+ * Each is named by its `id` (what `content()` and `singleton()` take), its `name` (the schema's
4350
+ * `displayName`) and its `type`, content types first, each group in the order the schema declares it.
4351
+ *
4352
+ * @example
4353
+ * ```typescript
4354
+ * const types = await relyio.contentTypes()
4355
+ * const singletons = types.filter(type => type.type === 'singleton').map(type => type.id)
4356
+ * ```
6061
4357
  */
6062
- async listContentTypes() {
6063
- return this.httpClient.fetchPayload("/v1/meta/content-types", "get", {});
4358
+ async contentTypes() {
4359
+ return this.httpClient.fetchPayload(
4360
+ "/v1/meta/content-types",
4361
+ "get",
4362
+ {}
4363
+ );
6064
4364
  }
6065
4365
  /**
6066
- * Get API health status
4366
+ * Whether the API can serve requests now — `GET /health/ready`.
4367
+ *
4368
+ * Resolves `{ status: 'ok', timestamp }` when the API answers and reaches every store it reads.
4369
+ * Rejects otherwise, with the error the request met: a `503` naming the store that did not answer,
4370
+ * or a network error when the API could not be reached at all. So there is no `status` to check:
4371
+ * a call that resolves is the healthy answer.
4372
+ *
4373
+ * @example
4374
+ * ```typescript
4375
+ * try {
4376
+ * await relyio.health()
4377
+ * } catch (error) {
4378
+ * console.error('RelyIO cannot serve now', error)
4379
+ * }
4380
+ * ```
6067
4381
  */
6068
4382
  async health() {
6069
- return this.httpClient.fetchPayload("/health", "get", {});
6070
- }
6071
- /**
6072
- * Check if the API is ready
6073
- */
6074
- async ready() {
6075
- try {
6076
- const payload = await this.httpClient.fetchPayload("/health/ready", "get", {});
6077
- return payload.status === "ok";
6078
- } catch {
6079
- return false;
6080
- }
6081
- }
6082
- /**
6083
- * Test the connection to the API
6084
- */
6085
- async testConnection() {
6086
- try {
6087
- await this.health();
6088
- return true;
6089
- } catch {
6090
- return false;
6091
- }
4383
+ const { status, timestamp } = await this.httpClient.fetchPayload("/health/ready", "get", {});
4384
+ return { status, timestamp };
6092
4385
  }
6093
4386
  /**
6094
4387
  * Change some of the client's options and keep the rest.
@@ -6116,11 +4409,10 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6116
4409
  *
6117
4410
  * The client's one HTTP client is changed in place, so every request from now on is sent as the
6118
4411
  * update says — including one from a `content()`, `asset()`, `singleton()` or `settings()`
6119
- * sub-client, a `query` client, or a builder such as `search()` or `batch()`, taken before the
6120
- * call. The locale reaches them too: each reads the client's locale when it sends, so a new
6121
- * `locale` is the default of its next request and `locale: null` leaves that request with none. A
6122
- * locale the call names, and a sub-client's own `withLocale()`, still win over it. A client made
6123
- * by `withLocale()` is a client of its own: an update of this one does not reach it.
4412
+ * sub-client taken before the call. The locale reaches them too: each reads the client's locale
4413
+ * when it sends, so a new `locale` is the default of its next request and `locale: null` leaves
4414
+ * that request with none. A locale the call names still wins over it, and so does the locale of a
4415
+ * client `with({ locale })` made from this one.
6124
4416
  *
6125
4417
  * @example
6126
4418
  * ```typescript
@@ -6133,6 +4425,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6133
4425
  * ```
6134
4426
  */
6135
4427
  updateConfig(update) {
4428
+ if (this.parent !== void 0) return this.parent.updateConfig(update);
6136
4429
  const resolved = resolveConfigUpdate(this.configured, update);
6137
4430
  this.config = resolved.config;
6138
4431
  this.configured = resolved.configured;
@@ -6143,7 +4436,8 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6143
4436
  * Get the current configuration
6144
4437
  */
6145
4438
  getConfig() {
6146
- return { ...this.config };
4439
+ if (this.parent === void 0) return { ...this.config };
4440
+ return { ...this.parent.getConfig(), ...this.defaults };
6147
4441
  }
6148
4442
  /**
6149
4443
  * Replace the API key every later request sends as `X-API-Key`.
@@ -6151,8 +4445,8 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6151
4445
  * It reaches every request this client makes from now on, including those of a `content()`,
6152
4446
  * `asset()` or other sub-client taken before the call, and `getConfig().apiKey` reports it. A key
6153
4447
  * given in `headers`, under any spelling, is replaced with it and does not come back on a later
6154
- * `updateConfig()`. A client already derived with `withLocale()` is a client of its own and keeps
6155
- * its key.
4448
+ * `updateConfig()`. A client `with()` made from this one sends the new key too: the two share one
4449
+ * connection.
6156
4450
  *
6157
4451
  * An empty or blank key is no key, as it is when passed to `createClient`: the next request
6158
4452
  * rejects with `MissingApiKeyError` and nothing is sent.
@@ -6168,6 +4462,7 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6168
4462
  * ```
6169
4463
  */
6170
4464
  setApiKey(apiKey) {
4465
+ if (this.parent !== void 0) return this.parent.setApiKey(apiKey);
6171
4466
  this.configured = withConfiguredKey(this.configured, apiKey);
6172
4467
  if (this._sandbox.state === "active") return;
6173
4468
  this.httpClient.setApiKey(apiKey);
@@ -6182,73 +4477,76 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
6182
4477
  // LOCALE OPERATIONS
6183
4478
  // ============================================================================
6184
4479
  /**
6185
- * Create a locale-scoped client
6186
- *
6187
- * Every call the returned client builds is in this locale unless the call names one of its own,
6188
- * which wins: every read — `content()`, `asset()`, `singleton()`, `settings()`, `search()`,
6189
- * `similar()`, `autocomplete()`, `executeQuery()` and the ad-hoc queries — and every write and
6190
- * version-history read — `create()` and `update()`, the singleton and settings writes, the asset
6191
- * file writes, `versions()` and `version()`, and each operation `batch()` builds. `restore()`
6192
- * always names its locale; a delete, and a `batch().raw()` operation, carry none of the client's.
4480
+ * Get the current default locale
4481
+ */
4482
+ getLocale() {
4483
+ return this.currentLocale();
4484
+ }
4485
+ /**
4486
+ * A client whose reads and writes are in `locale` and `dataset` unless a call names its own, and
4487
+ * which otherwise **follows this one** (REL-2417, Q9): it sends this client's key, to this
4488
+ * client's base URL, under this client's configuration as it is when each request is sent — so a
4489
+ * later `setApiKey()` or `updateConfig()` here reaches it. A default it does not name is this
4490
+ * client's, as this client changes it.
6193
4491
  *
6194
- * Type-safe when schema is provided: autocompletes valid locale codes!
4492
+ * The two share one connection, so a `setApiKey()` or `updateConfig()` called on the client made
4493
+ * here changes this one too. A call's own `locale` or `dataset` wins over the defaults.
6195
4494
  *
6196
4495
  * @example
6197
4496
  * ```typescript
6198
- * const spanish = relyio.withLocale('es-ES') // ← Autocompletes with schema!
6199
- *
6200
- * // Reads and writes use Spanish
6201
- * const products = await spanish.content('product').query().execute()
6202
- * const homepage = await spanish.singleton('homepage').fetch()
6203
- * const results = await spanish.search('zapatos').execute()
6204
- * await spanish.content('product').update(id, { title: 'Zapatos' })
4497
+ * const staging = relyio.with({ dataset: 'staging' })
4498
+ * const { data } = await staging.content('post').list({ limit: 10 })
6205
4499
  *
6206
- * // Original client unchanged
6207
- * const englishProducts = await relyio.content('product').query().execute()
4500
+ * const french = relyio.with({ locale: 'fr-FR' }) // ← autocompletes the schema's locales
6208
4501
  * ```
6209
4502
  */
6210
- withLocale(locale) {
6211
- const newConfig = {
6212
- ...this.configured,
6213
- locale,
4503
+ with(defaults) {
4504
+ const child = new _TypedRelyIOClient({
4505
+ ...this.configuredNow(),
4506
+ dev: false,
6214
4507
  schema: this._schema
4508
+ });
4509
+ child.follow(this, defaults);
4510
+ return child;
4511
+ }
4512
+ /** Make this client one `with()` made from `parent`: see {@link with}. */
4513
+ follow(parent, defaults) {
4514
+ const { locale, dataset } = defaults;
4515
+ this.parent = parent;
4516
+ this.defaults = {
4517
+ ...locale === void 0 ? {} : { locale },
4518
+ ...dataset === void 0 ? {} : { dataset }
6215
4519
  };
6216
- return new _TypedRelyIOClient(newConfig);
4520
+ this.httpClient = parent.httpClient.withHeaders(
4521
+ dataset === void 0 ? {} : { [DATASET_HEADER]: dataset }
4522
+ );
6217
4523
  }
6218
4524
  /**
6219
- * Get the current default locale
4525
+ * The configuration as given, before the `relyio dev` handshake — this client's own, or for a
4526
+ * client `with()` made, its parent's with its defaults laid over it.
6220
4527
  */
6221
- getLocale() {
6222
- return this.config.locale;
4528
+ configuredNow() {
4529
+ return this.parent === void 0 ? this.configured : { ...this.parent.configuredNow(), ...this.defaults };
6223
4530
  }
6224
4531
  /**
6225
- * Get available locales from the API
4532
+ * Every locale the key's branch has deployed, the default marked — `GET /v1/meta/locales`.
4533
+ *
4534
+ * In the order the schema declares them. Exactly one has `default: true`, the locale a read or
4535
+ * write that names none is in; every other has `default: false`. `fallback`, `direction` and
4536
+ * `active` are as the schema declares them, absent where it does not.
6226
4537
  *
6227
4538
  * @example
6228
4539
  * ```typescript
6229
- * const { locales, defaultLocale } = await relyio.getLocales()
4540
+ * const locales = await relyio.locales()
4541
+ * const defaultLocale = locales.find(locale => locale.default)?.code
6230
4542
  *
6231
- * // Build language switcher
6232
- * const options = locales.map(l => ({
6233
- * code: l.code,
6234
- * label: l.displayName,
6235
- * isDefault: l.default,
6236
- * }))
4543
+ * // Build a language switcher
4544
+ * const options = locales.map(locale => ({ code: locale.code, label: locale.displayName }))
6237
4545
  * ```
6238
4546
  */
6239
- async getLocales(search) {
6240
- const params = {};
6241
- if (search !== void 0 && search !== "") {
6242
- params.search = search;
6243
- }
6244
- return this.httpClient.fetchPayload("/v1/meta/locales", "get", { query: params });
6245
- }
6246
- /**
6247
- * Get the default locale from the API
6248
- */
6249
- async getDefaultLocale() {
6250
- const { defaultLocale } = await this.getLocales();
6251
- return defaultLocale;
4547
+ async locales() {
4548
+ const { locales, defaultLocale } = await this.httpClient.fetchPayload("/v1/meta/locales", "get", {});
4549
+ return locales.map((locale) => ({ ...locale, default: locale.code === defaultLocale }));
6252
4550
  }
6253
4551
  };
6254
4552
  __name(_TypedRelyIOClient, "TypedRelyIOClient");
@@ -6271,6 +4569,6 @@ function randomClientId() {
6271
4569
  }
6272
4570
  __name(randomClientId, "randomClientId");
6273
4571
 
6274
- export { AdhocQueryBuilder, AdhocQueryClient, AssetClient, AssetFileBuilder, AssetUploadBuilder, AuthorizationError, AutocompleteBuilder, BaseValidationError, BatchBuilder, BatchClient, ChangesExpiredError, ConnectionError, ContentByIdBuilder, ContentClient, ContentQueryBuilder, ErrorMapper, FileUploadError, FileValidationError, HttpClient, InvalidApiKeyError, InvalidPayloadError, LIVE_KEEPALIVE_INTERVAL_MS, LIVE_SOCKET_OPEN_TIMEOUT_MS, LiveEdgeError, MethodNotAllowedError, MissingApiKeyError, NetworkError, PUBLISHABLE_KEY_PREFIX, PayloadTooLargeError, PlanFeatureUnavailableError, RateLimitError, ReadOnlyKeyError, ResourceConflictError, ResourceExpiredError, ResourceNotFoundError, SDKError, SearchBuilder, SearchClient, ServerError, ServiceIndeterminateError, SettingsClient, SimilarBuilder, SingletonClient, TimeoutError, TransactionRolledBackError, TypedRelyIOClient, UnknownContractError, UsageQuotaExceededError, VISITOR_ADMISSION_RETRY_AFTER_SECONDS, ValidationError, createClient, entityTagOf, isAborted, isAssetEntry, isPublishableKey, isResourceNotFound, matchRoute, serviceInstructedDelayMs, sleep, validateFile };
6275
- //# sourceMappingURL=chunk-FRJEUAAF.js.map
6276
- //# sourceMappingURL=chunk-FRJEUAAF.js.map
4572
+ export { AssetClient, AssetFileBuilder, AssetUploadBuilder, AuthorizationError, BaseValidationError, ChangesExpiredError, ConnectionError, ContentClient, ErrorMapper, FileUploadError, FileValidationError, HttpClient, InvalidApiKeyError, InvalidPayloadError, LIVE_KEEPALIVE_INTERVAL_MS, LIVE_SOCKET_OPEN_TIMEOUT_MS, LiveEdgeError, MethodNotAllowedError, MissingApiKeyError, NetworkError, PUBLISHABLE_KEY_PREFIX, PayloadTooLargeError, PlanFeatureUnavailableError, RateLimitError, ReadOnlyKeyError, ResourceConflictError, ResourceExpiredError, ResourceNotFoundError, SDKError, ServerError, ServiceIndeterminateError, SettingsClient, SingletonClient, TimeoutError, TransactionRolledBackError, TypedRelyIOClient, UnknownContractError, UsageQuotaExceededError, VISITOR_ADMISSION_RETRY_AFTER_SECONDS, ValidationError, createClient, isAborted, isAssetEntry, isMissingEntry, isPublishableKey, isResourceNotFound, matchRoute, serviceInstructedDelayMs, sleep, validateFile, versionCheckOf };
4573
+ //# sourceMappingURL=chunk-DBBZVZOS.js.map
4574
+ //# sourceMappingURL=chunk-DBBZVZOS.js.map