@relyio/sdk 0.7.0 → 0.8.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.
@@ -412,6 +412,45 @@ var _InvalidPayloadError = class _InvalidPayloadError extends BaseValidationErro
412
412
  chunkMWMSFIWN_cjs.__name(_InvalidPayloadError, "InvalidPayloadError");
413
413
  var InvalidPayloadError = _InvalidPayloadError;
414
414
 
415
+ // ../../platform/api-contract/dist/chunk-PYZCLRXR.js
416
+ function defineRoute(route) {
417
+ if (route.kind === "raw" && route.standardShape === void 0) {
418
+ throw new Error("kind 'raw' requires a named StandardShape");
419
+ }
420
+ if (route.kind === "raw" && route.success === 302 && !route.headers.some((header) => header.name === "Location")) {
421
+ throw new Error("a raw route declaring success 302 must declare its 'Location' header");
422
+ }
423
+ if (route.kind === "stream" && route.stream === void 0) {
424
+ throw new Error("kind 'stream' requires a StreamDeclaration");
425
+ }
426
+ if (route.kind === "collection" && route.page === void 0) {
427
+ throw new Error("kind 'collection' requires a page dialect");
428
+ }
429
+ if ((route.kind === "object" || route.kind === "collection") && route.negotiated !== void 0) {
430
+ refuseMismatchedAlternate(route, route.negotiated["text/event-stream"]);
431
+ }
432
+ return route;
433
+ }
434
+ chunkMWMSFIWN_cjs.__name(defineRoute, "defineRoute");
435
+ function refuseMismatchedAlternate(route, stream) {
436
+ if (stream.kind !== "stream") {
437
+ throw new Error("a negotiated 'text/event-stream' alternate must be kind 'stream'");
438
+ }
439
+ if (stream.stream.mediaType !== "text/event-stream") {
440
+ throw new Error(
441
+ `a negotiated 'text/event-stream' alternate declares media type "${stream.stream.mediaType}"`
442
+ );
443
+ }
444
+ const own = [...new Set(route.codes)].sort();
445
+ const alternate = [...new Set(stream.codes)].sort();
446
+ if (own.length !== alternate.length || own.some((code, index) => code !== alternate[index])) {
447
+ throw new Error(
448
+ `a negotiated alternate refuses with [${alternate.join(", ")}] while its route refuses with [${own.join(", ")}]; one route refuses with one set of codes on every transport`
449
+ );
450
+ }
451
+ }
452
+ chunkMWMSFIWN_cjs.__name(refuseMismatchedAlternate, "refuseMismatchedAlternate");
453
+
415
454
  // ../../platform/api-contract/dist/index.js
416
455
  var HEADER_RETRY_AFTER = { name: "Retry-After" };
417
456
  var HEADER_ENTITY_TAG = { name: "X-Entity-Tag" };
@@ -419,6 +458,169 @@ var HEADER_IF_MATCH = {
419
458
  name: "If-Match"};
420
459
  var HEADER_IDEMPOTENCY_KEY = {
421
460
  name: "Idempotency-Key"};
461
+ var FRESH_PARAMETER = "_fresh";
462
+ var VISITOR_LIVE_PATH = "/visitor/changes";
463
+ var VISITOR_QUERY = {
464
+ /** The publishable key. */
465
+ key: "key",
466
+ /** A dataset id or name the key reaches; absent, the key's default dataset. */
467
+ dataset: "dataset",
468
+ /** The cursor to continue from; absent, the socket starts now. */
469
+ since: "since",
470
+ /** Comma-separated content types to keep; absent keeps every type. */
471
+ types: "types",
472
+ /** Comma-separated entry ids to keep; absent keeps every entry. */
473
+ ids: "ids",
474
+ /** The poll's client id. Required on a poll, and not read on a socket. */
475
+ client: "client"
476
+ };
477
+ var VISITOR_CURSOR = /^[\w.~-]{1,256}$/;
478
+ var VISITOR_POLL_INTERVAL_MS = 15e3;
479
+ var VISITOR_KEEPALIVE = { request: "ping", response: "pong" };
480
+ var VISITOR_FRAMES = {
481
+ opened: "feed.opened",
482
+ changes: "feed.changes",
483
+ resync: "feed.resync"
484
+ };
485
+ defineRoute({
486
+ kind: "object",
487
+ headers: [HEADER_RETRY_AFTER],
488
+ codes: [
489
+ "REQUEST_INVALID",
490
+ "MISSING_API_KEY",
491
+ "INVALID_API_KEY",
492
+ "ACCESS_DENIED",
493
+ "METHOD_NOT_ALLOWED",
494
+ "SERVICE_INDETERMINATE",
495
+ "USAGE_QUOTA_EXCEEDED",
496
+ "RATE_LIMIT_EXCEEDED"
497
+ ]
498
+ });
499
+ var VISITOR_CLOSE_CODES = {
500
+ /** A query the door cannot read: a malformed `since`, filter, `dataset` or `client`. */
501
+ requestInvalid: 4400,
502
+ /** No publishable key, or one that is unknown, revoked, expired, a secret key or a preview key. */
503
+ keyRefused: 4401,
504
+ /** The page's `Origin` is absent, or not on the key's allowed origins. */
505
+ originRefused: 4403,
506
+ /** `dataset` names nothing the key reaches. */
507
+ datasetRefused: 4404,
508
+ /** The key's scope, the project's counter or the feed could not be reached just now. */
509
+ unavailable: 1013,
510
+ /**
511
+ * The project holds as many visitor connections as its plan allows — Starter's 100 — or its
512
+ * Organization is suspended. As HTTP's 402: more needs a bigger plan, or visitors leaving.
513
+ */
514
+ allowanceReached: 4402,
515
+ /** This client's address holds as many connections to the project as one address may. */
516
+ addressLimitReached: 4429,
517
+ /** The project is at its per-project safety ceiling — Pro's 50,000 — whatever it would pay for. */
518
+ ceilingReached: 4503
519
+ };
520
+ var VISITOR_CLOSE_RETRY = {
521
+ 4400: "stop",
522
+ 4401: "stop",
523
+ 4403: "stop",
524
+ 4404: "stop",
525
+ 1013: "retry",
526
+ 4402: "back-off",
527
+ 4429: "back-off",
528
+ 4503: "back-off"
529
+ };
530
+ var VISITOR_POLL_RETRY = {
531
+ REQUEST_INVALID: "stop",
532
+ MISSING_API_KEY: "stop",
533
+ INVALID_API_KEY: "stop",
534
+ ACCESS_DENIED: "stop",
535
+ METHOD_NOT_ALLOWED: "stop",
536
+ SERVICE_INDETERMINATE: "retry",
537
+ USAGE_QUOTA_EXCEEDED: "back-off",
538
+ RATE_LIMIT_EXCEEDED: "back-off"
539
+ };
540
+ var VISITOR_ADMISSION_RETRY_AFTER_SECONDS = 60;
541
+ function parseVisitorFrame(text) {
542
+ let value;
543
+ try {
544
+ value = JSON.parse(text);
545
+ } catch {
546
+ return null;
547
+ }
548
+ if (!isRecord2(value) || !isCursor(value.cursor)) return null;
549
+ switch (value.type) {
550
+ case VISITOR_FRAMES.opened: {
551
+ return hasOnly(value, ["type", "cursor"]) ? { type: VISITOR_FRAMES.opened, cursor: value.cursor } : null;
552
+ }
553
+ case VISITOR_FRAMES.changes: {
554
+ const changes = hasOnly(value, ["type", "changes", "cursor"]) ? readVisitorChanges(value.changes) : null;
555
+ return changes === null ? null : { type: VISITOR_FRAMES.changes, changes, cursor: value.cursor };
556
+ }
557
+ case VISITOR_FRAMES.resync: {
558
+ return hasOnly(value, ["type", "reason", "cursor"]) && isResyncReason(value.reason) ? { type: VISITOR_FRAMES.resync, reason: value.reason, cursor: value.cursor } : null;
559
+ }
560
+ default: {
561
+ return null;
562
+ }
563
+ }
564
+ }
565
+ chunkMWMSFIWN_cjs.__name(parseVisitorFrame, "parseVisitorFrame");
566
+ function readVisitorPollAnswer(value) {
567
+ if (!isRecord2(value) || !isCursor(value.cursor)) return null;
568
+ if (value.kind === "resync") {
569
+ return hasOnly(value, ["kind", "reason", "cursor"]) && isResyncReason(value.reason) ? { kind: "resync", reason: value.reason, cursor: value.cursor } : null;
570
+ }
571
+ if (value.kind !== "changes" || !hasOnly(value, ["kind", "changes", "cursor"])) return null;
572
+ const changes = readVisitorChanges(value.changes);
573
+ return changes === null ? null : { kind: "changes", changes, cursor: value.cursor };
574
+ }
575
+ chunkMWMSFIWN_cjs.__name(readVisitorPollAnswer, "readVisitorPollAnswer");
576
+ var CHANGE_KINDS = /* @__PURE__ */ new Set([
577
+ "published",
578
+ "updated",
579
+ "unpublished",
580
+ "deleted"
581
+ ]);
582
+ var RESYNC_REASONS = /* @__PURE__ */ new Set([
583
+ "retention",
584
+ "dataset-replaced",
585
+ "ahead-of-head",
586
+ "foreign-cursor",
587
+ "too-far-behind"
588
+ ]);
589
+ function isResyncReason(value) {
590
+ return typeof value === "string" && RESYNC_REASONS.has(value);
591
+ }
592
+ chunkMWMSFIWN_cjs.__name(isResyncReason, "isResyncReason");
593
+ function readVisitorChanges(value) {
594
+ if (!Array.isArray(value)) return null;
595
+ const changes = [];
596
+ for (const item of value) {
597
+ if (!isRecord2(item) || !hasOnly(item, ["entryId", "contentType", "locale", "kind"])) return null;
598
+ const { entryId, contentType, locale, kind } = item;
599
+ if (!isNonEmptyString2(entryId) || !isNonEmptyString2(contentType)) return null;
600
+ if (locale !== null && typeof locale !== "string") return null;
601
+ if (typeof kind !== "string" || !CHANGE_KINDS.has(kind)) return null;
602
+ changes.push({ entryId, contentType, locale, kind });
603
+ }
604
+ return changes;
605
+ }
606
+ chunkMWMSFIWN_cjs.__name(readVisitorChanges, "readVisitorChanges");
607
+ function isCursor(value) {
608
+ return typeof value === "string" && VISITOR_CURSOR.test(value);
609
+ }
610
+ chunkMWMSFIWN_cjs.__name(isCursor, "isCursor");
611
+ function isRecord2(value) {
612
+ return typeof value === "object" && value !== null && !Array.isArray(value);
613
+ }
614
+ chunkMWMSFIWN_cjs.__name(isRecord2, "isRecord2");
615
+ function isNonEmptyString2(value) {
616
+ return typeof value === "string" && value.length > 0;
617
+ }
618
+ chunkMWMSFIWN_cjs.__name(isNonEmptyString2, "isNonEmptyString2");
619
+ function hasOnly(value, keys) {
620
+ const present = Object.keys(value);
621
+ return present.length === keys.length && present.every((key) => keys.includes(key));
622
+ }
623
+ chunkMWMSFIWN_cjs.__name(hasOnly, "hasOnly");
422
624
 
423
625
  // ../../platform/api-contract/dist/client/index.js
424
626
  var _a;
@@ -687,6 +889,8 @@ var DECLARED_PATHS = {
687
889
  "/health/cache": true,
688
890
  "/health/live": true,
689
891
  "/health/ready": true,
892
+ "/internal/live/visitor-feed/{projectId}/{datasetId}/changes": true,
893
+ "/internal/live/visitor-key": true,
690
894
  "/internal/media/claim": true,
691
895
  "/internal/media/file-complete": true,
692
896
  "/internal/media/progress": true,
@@ -1425,8 +1629,20 @@ var _ContentQueryBuilder = class _ContentQueryBuilder {
1425
1629
  chunkMWMSFIWN_cjs.__publicField(this, "requestHeaders");
1426
1630
  /** The client's locale, asked when the query is sent rather than copied when it was built. */
1427
1631
  chunkMWMSFIWN_cjs.__publicField(this, "clientLocale");
1632
+ chunkMWMSFIWN_cjs.__publicField(this, "freshValue");
1428
1633
  this.clientLocale = readClientLocale(locale);
1429
1634
  }
1635
+ /**
1636
+ * The feed position this read follows — a change's `fresh` (`FeedChange`), or a resync's. Sent as
1637
+ * `?_fresh`, the one term the API declares for it: no cache — the Content API's edge or the
1638
+ * browser's own — holds an answer for that position from before it, so the read is answered after
1639
+ * the change, and every read naming the same position shares that answer. The answer is the
1640
+ * read's own; omit it for a read no change prompted.
1641
+ */
1642
+ fresh(position) {
1643
+ this.freshValue = position;
1644
+ return this;
1645
+ }
1430
1646
  /**
1431
1647
  * Headers this query adds to the client's own, e.g. `X-RelyIO-Dataset` to list another dataset
1432
1648
  * the key can see. A name the client already sends is replaced for this query only; the client
@@ -1711,6 +1927,7 @@ var _ContentQueryBuilder = class _ContentQueryBuilder {
1711
1927
  cloned.pageNumber = this.pageNumber;
1712
1928
  cloned.pageSizeValue = this.pageSizeValue;
1713
1929
  cloned.requestHeaders = this.requestHeaders ? { ...this.requestHeaders } : void 0;
1930
+ cloned.freshValue = this.freshValue;
1714
1931
  return cloned;
1715
1932
  }
1716
1933
  /**
@@ -1803,6 +2020,9 @@ var _ContentQueryBuilder = class _ContentQueryBuilder {
1803
2020
  params.childrenLimit = this.childrenOptions.limit;
1804
2021
  }
1805
2022
  }
2023
+ if (this.freshValue !== void 0) {
2024
+ params[FRESH_PARAMETER] = this.freshValue;
2025
+ }
1806
2026
  return params;
1807
2027
  }
1808
2028
  };
@@ -1825,8 +2045,20 @@ var _ContentByIdBuilder = class _ContentByIdBuilder {
1825
2045
  chunkMWMSFIWN_cjs.__publicField(this, "requestHeaders");
1826
2046
  /** The client's locale, asked when the read is sent rather than copied when it was built. */
1827
2047
  chunkMWMSFIWN_cjs.__publicField(this, "clientLocale");
2048
+ chunkMWMSFIWN_cjs.__publicField(this, "freshValue");
1828
2049
  this.clientLocale = readClientLocale(locale);
1829
2050
  }
2051
+ /**
2052
+ * The feed position this read follows — a change's `fresh` (`FeedChange`), or a resync's. Sent as
2053
+ * `?_fresh`, the one term the API declares for it: no cache — the Content API's edge or the
2054
+ * browser's own — holds an answer for that position from before it, so the read is answered after
2055
+ * the change, and every read naming the same position shares that answer. The answer is the
2056
+ * read's own; omit it for a read no change prompted.
2057
+ */
2058
+ fresh(position) {
2059
+ this.freshValue = position;
2060
+ return this;
2061
+ }
1830
2062
  /**
1831
2063
  * Include related content in the response
1832
2064
  */
@@ -1915,6 +2147,9 @@ var _ContentByIdBuilder = class _ContentByIdBuilder {
1915
2147
  params.childrenLimit = this.childrenOptions.limit;
1916
2148
  }
1917
2149
  }
2150
+ if (this.freshValue !== void 0) {
2151
+ params[FRESH_PARAMETER] = this.freshValue;
2152
+ }
1918
2153
  try {
1919
2154
  return await this.httpClient.fetchPayload(
1920
2155
  "/v1/{contentType}/{id}",
@@ -3081,6 +3316,7 @@ var _SingletonClient = class _SingletonClient {
3081
3316
  const localeValueFinal = options?.locale ?? this.localeValue ?? this.clientLocale();
3082
3317
  if (includeValue) query.include = includeValue.join(",");
3083
3318
  if (localeValueFinal != null && localeValueFinal !== "") query.locale = localeValueFinal;
3319
+ if (options?.fresh !== void 0) query[FRESH_PARAMETER] = options.fresh;
3084
3320
  const response = await this.httpClient.send(
3085
3321
  "/v1/singletons/{key}",
3086
3322
  "get",
@@ -3376,6 +3612,7 @@ var _SearchBuilder = class _SearchBuilder {
3376
3612
  chunkMWMSFIWN_cjs.__publicField(this, "query");
3377
3613
  chunkMWMSFIWN_cjs.__publicField(this, "searchOptions", {});
3378
3614
  chunkMWMSFIWN_cjs.__publicField(this, "requestHeaders");
3615
+ chunkMWMSFIWN_cjs.__publicField(this, "freshValue");
3379
3616
  /** The client's locale, asked when the query is sent rather than copied when it was built. */
3380
3617
  chunkMWMSFIWN_cjs.__publicField(this, "clientLocale");
3381
3618
  this.query = query;
@@ -3389,6 +3626,15 @@ var _SearchBuilder = class _SearchBuilder {
3389
3626
  this.requestHeaders = headers;
3390
3627
  return this;
3391
3628
  }
3629
+ /**
3630
+ * The feed position this search follows — a change's `fresh` (`FeedChange`), or a resync's. Sent
3631
+ * as `?_fresh` on the query string beside the body: the edge keys a search on both, so no answer
3632
+ * it holds from before that position can answer it. The answer is the search's own.
3633
+ */
3634
+ fresh(position) {
3635
+ this.freshValue = position;
3636
+ return this;
3637
+ }
3392
3638
  /**
3393
3639
  * Search within a single content type. Where a schema types the client, the name is one of its
3394
3640
  * content types and the results are that type's entries.
@@ -3530,7 +3776,11 @@ var _SearchBuilder = class _SearchBuilder {
3530
3776
  const response = await this.httpClient.send(
3531
3777
  "/v1/search",
3532
3778
  "post",
3533
- { body, headers: this.requestHeaders }
3779
+ {
3780
+ body,
3781
+ headers: this.requestHeaders,
3782
+ ...this.freshValue === void 0 ? {} : { query: { [FRESH_PARAMETER]: this.freshValue } }
3783
+ }
3534
3784
  );
3535
3785
  return response.body;
3536
3786
  }
@@ -4546,23 +4796,67 @@ var AdhocQueryClient = _AdhocQueryClient;
4546
4796
 
4547
4797
  // src/changes/changes.ts
4548
4798
  var CHANGES_POLL_TIMEOUT_MS = 25e3 + 5e3;
4799
+ var EXPIRED_REASONS = {
4800
+ retention: "retention",
4801
+ "dataset-replaced": "dataset-replaced",
4802
+ "ahead-of-head": "ahead-of-head",
4803
+ "foreign-cursor": "foreign-cursor",
4804
+ "too-far-behind": "too-far-behind"
4805
+ };
4549
4806
  var _ChangesExpiredError = class _ChangesExpiredError extends ResourceExpiredError {
4550
- /** The base class's signature, so `withContext` can rebuild one. */
4551
- constructor(message, statusCode = 410, cause, context) {
4807
+ /** The base class's signature, so `withContext` can rebuild one; then the position resynced to. */
4808
+ constructor(message, statusCode = 410, cause, context, fresh) {
4552
4809
  super(message, statusCode, cause, context);
4553
4810
  chunkMWMSFIWN_cjs.__publicField(this, "reason");
4811
+ /**
4812
+ * The position the feed resynced to, which a refetch of everything names as `?_fresh`, as a
4813
+ * change's {@link FeedChange.fresh} is named: the head a `/v1/changes` resync took, or the cursor
4814
+ * the edge's `feed.resync` sent. `undefined` when there was no resync to take one — the error was
4815
+ * thrown (`onExpired: 'throw'`) — and on an error a caller built itself.
4816
+ */
4817
+ chunkMWMSFIWN_cjs.__publicField(this, "fresh");
4554
4818
  this.name = "ChangesExpiredError";
4555
4819
  this.reason = expiredReasonOf(message);
4820
+ this.fresh = fresh;
4821
+ }
4822
+ /** The base class rebuilds from its four arguments, which would drop the position resynced to. */
4823
+ withContext(context) {
4824
+ const Constructor = this.constructor;
4825
+ return new Constructor(
4826
+ this.message,
4827
+ this.statusCode,
4828
+ this.cause,
4829
+ { ...this.context, ...context },
4830
+ this.fresh
4831
+ );
4832
+ }
4833
+ /** `/v1/changes`' refusal, with the head the feed resynced to when it did. */
4834
+ static of(expired, fresh) {
4835
+ return new _ChangesExpiredError(
4836
+ expired.message,
4837
+ expired.statusCode,
4838
+ expired,
4839
+ expired.context,
4840
+ fresh
4841
+ );
4556
4842
  }
4557
- static of(expired) {
4558
- return new _ChangesExpiredError(expired.message, expired.statusCode, expired, expired.context);
4843
+ /** The live edge's `feed.resync`: refetch everything, then continue from the cursor it sent. */
4844
+ static resync(reason, cursor) {
4845
+ return new _ChangesExpiredError(
4846
+ `The live edge cannot list the changes since this cursor (${reason}). Refetch everything derived from the feed; it continues from the position it sent.`,
4847
+ 410,
4848
+ void 0,
4849
+ { transport: "live-edge" },
4850
+ cursor
4851
+ );
4559
4852
  }
4560
4853
  };
4561
4854
  chunkMWMSFIWN_cjs.__name(_ChangesExpiredError, "ChangesExpiredError");
4562
4855
  var ChangesExpiredError = _ChangesExpiredError;
4563
4856
  function expiredReasonOf(message) {
4564
- if (message.includes("(retention)")) return "retention";
4565
- if (message.includes("(dataset-replaced)")) return "dataset-replaced";
4857
+ for (const reason of Object.values(EXPIRED_REASONS)) {
4858
+ if (message.includes(`(${reason})`)) return reason;
4859
+ }
4566
4860
  return "unknown";
4567
4861
  }
4568
4862
  chunkMWMSFIWN_cjs.__name(expiredReasonOf, "expiredReasonOf");
@@ -4582,7 +4876,7 @@ async function* pollChanges(http, options = {}) {
4582
4876
  const onExpired = options.onExpired ?? "throw";
4583
4877
  if (onExpired === "throw") throw expired;
4584
4878
  since = void 0;
4585
- resynced = typeof onExpired === "function" ? expired : void 0;
4879
+ resynced = typeof onExpired === "function" ? error : void 0;
4586
4880
  continue;
4587
4881
  }
4588
4882
  const { data, page } = response.body;
@@ -4591,13 +4885,13 @@ async function* pollChanges(http, options = {}) {
4591
4885
  }
4592
4886
  since = page.nextCursor;
4593
4887
  if (resynced !== void 0 && typeof options.onExpired === "function") {
4594
- const expired = resynced;
4888
+ const expired = ChangesExpiredError.of(resynced, page.nextCursor);
4595
4889
  resynced = void 0;
4596
4890
  await options.onExpired(expired);
4597
4891
  if (isAborted(signal)) return;
4598
4892
  }
4599
4893
  for (const change of data) {
4600
- yield change;
4894
+ yield { ...change, fresh: change.cursor };
4601
4895
  if (isAborted(signal)) return;
4602
4896
  }
4603
4897
  if (data.length === 0) {
@@ -4636,6 +4930,477 @@ async function pollOnce(http, since, options) {
4636
4930
  }
4637
4931
  chunkMWMSFIWN_cjs.__name(pollOnce, "pollOnce");
4638
4932
 
4933
+ // src/config/key-kind.ts
4934
+ var PUBLISHABLE_KEY_PREFIX = "rly_pub_";
4935
+ var isPublishableKey = /* @__PURE__ */ chunkMWMSFIWN_cjs.__name((apiKey) => apiKey?.startsWith(PUBLISHABLE_KEY_PREFIX) === true, "isPublishableKey");
4936
+
4937
+ // src/errors/live-errors.ts
4938
+ var _LiveEdgeError = class _LiveEdgeError extends SDKError {
4939
+ constructor(message, end, retry, options = {}) {
4940
+ super(message, options.statusCode, options.cause, options.context);
4941
+ chunkMWMSFIWN_cjs.__publicField(this, "code", "LIVE_EDGE_ENDED");
4942
+ chunkMWMSFIWN_cjs.__publicField(this, "retryable");
4943
+ chunkMWMSFIWN_cjs.__publicField(this, "end");
4944
+ chunkMWMSFIWN_cjs.__publicField(this, "retry");
4945
+ /** A refused poll's `Retry-After`, in milliseconds, where it carried a readable one. */
4946
+ chunkMWMSFIWN_cjs.__publicField(this, "retryAfterMs");
4947
+ this.end = end;
4948
+ this.retry = retry;
4949
+ this.retryable = retry !== "stop";
4950
+ this.retryAfterMs = options.retryAfterMs;
4951
+ }
4952
+ /**
4953
+ * The base class rebuilds an error through its own four-argument constructor, which this class
4954
+ * does not have; rebuilt that way, `end` would be a string and `retry` a number.
4955
+ */
4956
+ withContext(context) {
4957
+ const rebuilt = new _LiveEdgeError(this.message, this.end, this.retry, {
4958
+ ...this.statusCode === void 0 ? {} : { statusCode: this.statusCode },
4959
+ ...this.cause === void 0 ? {} : { cause: this.cause },
4960
+ ...this.retryAfterMs === void 0 ? {} : { retryAfterMs: this.retryAfterMs },
4961
+ context: { ...this.context, ...context }
4962
+ });
4963
+ return rebuilt;
4964
+ }
4965
+ getUserMessage() {
4966
+ return this.message;
4967
+ }
4968
+ };
4969
+ chunkMWMSFIWN_cjs.__name(_LiveEdgeError, "LiveEdgeError");
4970
+ var LiveEdgeError = _LiveEdgeError;
4971
+
4972
+ // src/config/live-url.ts
4973
+ var LIVE_EDGE_OF_API = {
4974
+ "https://api.relyio.com": "https://live.relyio.com"
4975
+ };
4976
+ var HTTP_SCHEME_OF = {
4977
+ "http:": "http:",
4978
+ "https:": "https:",
4979
+ "ws:": "http:",
4980
+ "wss:": "https:"
4981
+ };
4982
+ function liveEdgeAddress(config) {
4983
+ if (config.liveUrl !== void 0) return readLiveUrl(config.liveUrl);
4984
+ const derived = originOf(config.baseUrl);
4985
+ const edge = derived === void 0 ? void 0 : LIVE_EDGE_OF_API[derived];
4986
+ if (edge !== void 0) return { ok: true, url: new URL(edge) };
4987
+ return {
4988
+ ok: false,
4989
+ message: `Live updates need the address of RelyIO\u2019s live edge, and this client cannot derive it: \`baseUrl\` is not RelyIO\u2019s API (${Object.keys(LIVE_EDGE_OF_API).join(", ")}). Set \`liveUrl\` in createClient() to the live edge this API belongs with. Nothing was sent.`
4990
+ };
4991
+ }
4992
+ chunkMWMSFIWN_cjs.__name(liveEdgeAddress, "liveEdgeAddress");
4993
+ function readLiveUrl(liveUrl) {
4994
+ let url;
4995
+ try {
4996
+ url = new URL(liveUrl);
4997
+ } catch {
4998
+ return { ok: false, message: `\`liveUrl\` is not a URL: "${liveUrl}". Nothing was sent.` };
4999
+ }
5000
+ const scheme = HTTP_SCHEME_OF[url.protocol];
5001
+ if (scheme === void 0) {
5002
+ return {
5003
+ ok: false,
5004
+ message: `\`liveUrl\` must be an https:, wss:, http: or ws: URL, not ${url.protocol}. Nothing was sent.`
5005
+ };
5006
+ }
5007
+ url.protocol = scheme;
5008
+ url.search = "";
5009
+ url.hash = "";
5010
+ return { ok: true, url };
5011
+ }
5012
+ chunkMWMSFIWN_cjs.__name(readLiveUrl, "readLiveUrl");
5013
+ function originOf(baseUrl) {
5014
+ try {
5015
+ return new URL(baseUrl).origin;
5016
+ } catch {
5017
+ return void 0;
5018
+ }
5019
+ }
5020
+ chunkMWMSFIWN_cjs.__name(originOf, "originOf");
5021
+
5022
+ // src/changes/live-edge.ts
5023
+ var LIVE_KEEPALIVE_INTERVAL_MS = 3e4;
5024
+ var LIVE_POLLS_BEFORE_SOCKET = 4;
5025
+ async function* subscribeLiveEdge(client, options = {}) {
5026
+ const { signal } = options;
5027
+ if (isAborted(signal)) return;
5028
+ const key = client.apiKey;
5029
+ if (key === void 0 || !isPublishableKey(key)) {
5030
+ throw new LiveEdgeError(NEEDS_PUBLISHABLE_KEY, { kind: "needs-publishable-key" }, "stop");
5031
+ }
5032
+ const address = liveEdgeAddress(client);
5033
+ if (!address.ok) throw new LiveEdgeError(address.message, { kind: "needs-live-url" }, "stop");
5034
+ const request = {
5035
+ base: address.url,
5036
+ key,
5037
+ dataset: client.dataset,
5038
+ types: options.types,
5039
+ ids: options.ids
5040
+ };
5041
+ const reach = { position: options.since };
5042
+ for (; ; ) {
5043
+ const socket = openSocket(client, edgeUrl(request, reach.position, "socket"));
5044
+ if (socket !== void 0) {
5045
+ const ended = yield* followSocket(socket, reach, options);
5046
+ if (ended === "aborted") return;
5047
+ }
5048
+ const polled = yield* followPolls(client, request, reach, options);
5049
+ if (polled === "aborted") return;
5050
+ }
5051
+ }
5052
+ chunkMWMSFIWN_cjs.__name(subscribeLiveEdge, "subscribeLiveEdge");
5053
+ var SOCKET_CONNECTING = 0;
5054
+ var SOCKET_OPEN = 1;
5055
+ function runtimeWebSocket() {
5056
+ const candidate = globalThis.WebSocket;
5057
+ return typeof candidate === "function" ? candidate : void 0;
5058
+ }
5059
+ chunkMWMSFIWN_cjs.__name(runtimeWebSocket, "runtimeWebSocket");
5060
+ function openSocket(client, url) {
5061
+ const Socket = client.webSocket ?? runtimeWebSocket();
5062
+ if (Socket === void 0) return void 0;
5063
+ try {
5064
+ return new Socket(url);
5065
+ } catch {
5066
+ return void 0;
5067
+ }
5068
+ }
5069
+ chunkMWMSFIWN_cjs.__name(openSocket, "openSocket");
5070
+ async function* followSocket(socket, reach, options) {
5071
+ const { signal } = options;
5072
+ const inbox = socketInbox(socket, signal);
5073
+ let open = false;
5074
+ try {
5075
+ for (; ; ) {
5076
+ const event = await inbox.next();
5077
+ if (event === void 0) return "aborted";
5078
+ switch (event.kind) {
5079
+ case "open": {
5080
+ open = true;
5081
+ inbox.keepAlive();
5082
+ continue;
5083
+ }
5084
+ case "error": {
5085
+ if (!open) return "unopened";
5086
+ continue;
5087
+ }
5088
+ case "close": {
5089
+ if (!open) return "unopened";
5090
+ throw closedBy(event.code, event.reason);
5091
+ }
5092
+ case "silent": {
5093
+ throw new LiveEdgeError(
5094
+ "The live edge\u2019s socket stopped answering its keepalive, so the connection is presumed dead; reconnecting from the last cursor.",
5095
+ { kind: "lost" },
5096
+ "retry"
5097
+ );
5098
+ }
5099
+ case "message": {
5100
+ if (event.data === VISITOR_KEEPALIVE.response) continue;
5101
+ const frame = typeof event.data === "string" ? parseVisitorFrame(event.data) : null;
5102
+ if (frame === null)
5103
+ throw unreadable(`a frame the wire does not declare: ${sample(event.data)}`);
5104
+ switch (frame.type) {
5105
+ case VISITOR_FRAMES.opened: {
5106
+ reach.position = frame.cursor;
5107
+ options.opened?.();
5108
+ options.reached?.(frame.cursor);
5109
+ continue;
5110
+ }
5111
+ case VISITOR_FRAMES.changes: {
5112
+ const prior = reach.position;
5113
+ if (prior === void 0) throw unreadable("changes before the socket had a position");
5114
+ for (const change of changesOf(frame.changes, frame.cursor, prior)) {
5115
+ yield change;
5116
+ if (isAborted(signal)) return "aborted";
5117
+ }
5118
+ reach.position = frame.cursor;
5119
+ if (frame.changes.length === 0) options.reached?.(frame.cursor);
5120
+ continue;
5121
+ }
5122
+ case VISITOR_FRAMES.resync: {
5123
+ await expire(frame.reason, frame.cursor, options);
5124
+ if (isAborted(signal)) return "aborted";
5125
+ reach.position = frame.cursor;
5126
+ options.reached?.(frame.cursor);
5127
+ continue;
5128
+ }
5129
+ }
5130
+ }
5131
+ }
5132
+ }
5133
+ } finally {
5134
+ inbox.dispose();
5135
+ }
5136
+ }
5137
+ chunkMWMSFIWN_cjs.__name(followSocket, "followSocket");
5138
+ function socketInbox(socket, signal) {
5139
+ const events = [];
5140
+ let wake;
5141
+ let disposed = false;
5142
+ let heard = true;
5143
+ let keepalive;
5144
+ const rouse = /* @__PURE__ */ chunkMWMSFIWN_cjs.__name(() => {
5145
+ const waking = wake;
5146
+ wake = void 0;
5147
+ waking?.();
5148
+ }, "rouse");
5149
+ const push = /* @__PURE__ */ chunkMWMSFIWN_cjs.__name((event) => {
5150
+ if (disposed) return;
5151
+ events.push(event);
5152
+ rouse();
5153
+ }, "push");
5154
+ socket.addEventListener("open", () => push({ kind: "open" }));
5155
+ socket.addEventListener("message", (event) => {
5156
+ heard = true;
5157
+ push({ kind: "message", data: isRecord(event) ? event["data"] : void 0 });
5158
+ });
5159
+ socket.addEventListener("close", (event) => {
5160
+ const code = isRecord(event) ? event["code"] : void 0;
5161
+ const reason = isRecord(event) ? event["reason"] : void 0;
5162
+ push({
5163
+ kind: "close",
5164
+ // A close event always carries both; a socket that somehow raised one without them closed
5165
+ // abnormally, which is what 1006 says.
5166
+ code: typeof code === "number" ? code : 1006,
5167
+ reason: typeof reason === "string" ? reason : ""
5168
+ });
5169
+ });
5170
+ socket.addEventListener("error", () => push({ kind: "error" }));
5171
+ signal?.addEventListener("abort", rouse, { once: true });
5172
+ return {
5173
+ async next() {
5174
+ for (; ; ) {
5175
+ if (isAborted(signal)) return void 0;
5176
+ const event = events.shift();
5177
+ if (event !== void 0) return event;
5178
+ await new Promise((resolve) => {
5179
+ wake = resolve;
5180
+ });
5181
+ }
5182
+ },
5183
+ keepAlive() {
5184
+ keepalive = setInterval(() => {
5185
+ if (!heard) {
5186
+ push({ kind: "silent" });
5187
+ return;
5188
+ }
5189
+ heard = false;
5190
+ if (socket.readyState === SOCKET_OPEN) socket.send(VISITOR_KEEPALIVE.request);
5191
+ }, LIVE_KEEPALIVE_INTERVAL_MS);
5192
+ },
5193
+ dispose() {
5194
+ disposed = true;
5195
+ if (keepalive !== void 0) clearInterval(keepalive);
5196
+ signal?.removeEventListener("abort", rouse);
5197
+ if (socket.readyState === SOCKET_CONNECTING || socket.readyState === SOCKET_OPEN) {
5198
+ socket.close(1e3);
5199
+ }
5200
+ }
5201
+ };
5202
+ }
5203
+ chunkMWMSFIWN_cjs.__name(socketInbox, "socketInbox");
5204
+ function closedBy(code, reason) {
5205
+ const retry = closeRetryOf(code);
5206
+ const meaning = hasOwn(CLOSE_MEANING, code) ? CLOSE_MEANING[code] : code < 4e3 ? "the connection dropped" : "a refusal this version of the SDK does not know";
5207
+ const said = `close ${code}${reason === "" ? "" : ` ${reason}`}`;
5208
+ return new LiveEdgeError(
5209
+ `The live edge ended this subscription (${said}): ${meaning}. ${AFTER_A_CLOSE[retry]}`,
5210
+ { kind: "closed", code, reason },
5211
+ retry
5212
+ );
5213
+ }
5214
+ chunkMWMSFIWN_cjs.__name(closedBy, "closedBy");
5215
+ var AFTER_A_CLOSE = {
5216
+ stop: "The same request would be refused again, so it was not retried.",
5217
+ retry: "Reconnecting from the last cursor after a short back-off.",
5218
+ "back-off": "Retrying after a back-off of at least a minute, without polling, which the same admission refuses."
5219
+ };
5220
+ function closeRetryOf(code) {
5221
+ if (hasOwn(VISITOR_CLOSE_RETRY, code)) return VISITOR_CLOSE_RETRY[code];
5222
+ return code < 4e3 ? "retry" : "stop";
5223
+ }
5224
+ chunkMWMSFIWN_cjs.__name(closeRetryOf, "closeRetryOf");
5225
+ var CLOSE_MEANING = {
5226
+ [VISITOR_CLOSE_CODES.requestInvalid]: "the edge could not read the request \u2014 a malformed cursor or filter",
5227
+ [VISITOR_CLOSE_CODES.keyRefused]: "the key is not a publishable key the edge accepts \u2014 unknown, revoked or expired",
5228
+ [VISITOR_CLOSE_CODES.originRefused]: "this page\u2019s origin is not on the publishable key\u2019s allowed origins",
5229
+ [VISITOR_CLOSE_CODES.datasetRefused]: "`dataset` names no dataset the key reaches",
5230
+ [VISITOR_CLOSE_CODES.unavailable]: "the edge could not reach what it needed to decide just now",
5231
+ [VISITOR_CLOSE_CODES.allowanceReached]: "the project holds as many live connections as its plan allows",
5232
+ [VISITOR_CLOSE_CODES.addressLimitReached]: "this address holds as many live connections to the project as one address may",
5233
+ [VISITOR_CLOSE_CODES.ceilingReached]: "the project is at its safety ceiling of live connections"
5234
+ };
5235
+ async function* followPolls(client, request, reach, options) {
5236
+ const { signal } = options;
5237
+ for (let poll = 0; poll < LIVE_POLLS_BEFORE_SOCKET; poll += 1) {
5238
+ if (isAborted(signal)) return "aborted";
5239
+ const answer = await pollOnce2(client, request, reach.position, signal);
5240
+ if (answer === void 0) return "aborted";
5241
+ options.opened?.();
5242
+ if (answer.kind === "resync") {
5243
+ await expire(answer.reason, answer.cursor, options);
5244
+ if (isAborted(signal)) return "aborted";
5245
+ reach.position = answer.cursor;
5246
+ options.reached?.(answer.cursor);
5247
+ } else {
5248
+ const prior = reach.position;
5249
+ if (answer.changes.length > 0 && prior === void 0) {
5250
+ throw unreadable("a poll without a cursor answered changes");
5251
+ }
5252
+ for (const change of changesOf(answer.changes, answer.cursor, prior ?? answer.cursor)) {
5253
+ yield change;
5254
+ if (isAborted(signal)) return "aborted";
5255
+ }
5256
+ reach.position = answer.cursor;
5257
+ if (answer.changes.length === 0) options.reached?.(answer.cursor);
5258
+ }
5259
+ await sleep(VISITOR_POLL_INTERVAL_MS, signal);
5260
+ }
5261
+ return isAborted(signal) ? "aborted" : "socket";
5262
+ }
5263
+ chunkMWMSFIWN_cjs.__name(followPolls, "followPolls");
5264
+ async function pollOnce2(client, request, since, signal) {
5265
+ if (isAborted(signal)) return void 0;
5266
+ const url = edgeUrl(request, since, "poll", client.clientId);
5267
+ const context = { url: edgeUrl({ ...request, key: void 0 }, since, "poll", client.clientId) };
5268
+ const controller = new AbortController();
5269
+ let timedOut = false;
5270
+ const timer = setTimeout(() => {
5271
+ timedOut = true;
5272
+ controller.abort();
5273
+ }, client.timeout);
5274
+ const onAbort = /* @__PURE__ */ chunkMWMSFIWN_cjs.__name(() => controller.abort(), "onAbort");
5275
+ signal?.addEventListener("abort", onAbort, { once: true });
5276
+ try {
5277
+ let response;
5278
+ let text;
5279
+ try {
5280
+ const send = client.fetch ?? globalThis.fetch;
5281
+ response = await send(url, { method: "GET", signal: controller.signal });
5282
+ text = await response.text();
5283
+ } catch (error) {
5284
+ if (isAborted(signal)) return void 0;
5285
+ if (timedOut) {
5286
+ throw new TimeoutError(
5287
+ `The live edge did not answer a poll within ${client.timeout}ms`,
5288
+ client.timeout,
5289
+ void 0,
5290
+ void 0,
5291
+ context
5292
+ );
5293
+ }
5294
+ throw ErrorMapper.mapGenericError(
5295
+ error instanceof Error ? error : new Error(String(error)),
5296
+ context
5297
+ );
5298
+ }
5299
+ const body = parseJson(text);
5300
+ if (!response.ok) throw refusedPoll(response, body, context);
5301
+ const answer = readVisitorPollAnswer(isRecord(body) ? body["data"] : void 0);
5302
+ if (answer === null)
5303
+ throw unreadable(`a poll answer the wire does not declare: ${sample(text)}`);
5304
+ return answer;
5305
+ } finally {
5306
+ clearTimeout(timer);
5307
+ signal?.removeEventListener("abort", onAbort);
5308
+ }
5309
+ }
5310
+ chunkMWMSFIWN_cjs.__name(pollOnce2, "pollOnce");
5311
+ function refusedPoll(response, body, context) {
5312
+ const headers = {};
5313
+ response.headers.forEach((value, name) => {
5314
+ headers[name] = value;
5315
+ });
5316
+ const mapped = ErrorMapper.mapHttpError(
5317
+ { status: response.status, statusText: response.statusText, body, headers },
5318
+ { ...context, method: "GET" }
5319
+ );
5320
+ const refusal = readError(body);
5321
+ if (refusal === void 0 || !hasOwn(VISITOR_POLL_RETRY, refusal.code)) return mapped;
5322
+ const code = refusal.code;
5323
+ const retryAfterMs = parseRetryAfterMs(headerValue(headers, "Retry-After"), Date.now());
5324
+ return new LiveEdgeError(
5325
+ `The live edge refused a poll (${code}): ${refusal.messages[0] ?? mapped.message}`,
5326
+ { kind: "refused", code },
5327
+ VISITOR_POLL_RETRY[code],
5328
+ {
5329
+ statusCode: response.status,
5330
+ cause: mapped,
5331
+ ...retryAfterMs === void 0 ? {} : { retryAfterMs },
5332
+ context
5333
+ }
5334
+ );
5335
+ }
5336
+ chunkMWMSFIWN_cjs.__name(refusedPoll, "refusedPoll");
5337
+ function edgeUrl(request, since, transport, clientId) {
5338
+ const url = new URL(request.base.href);
5339
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}${VISITOR_LIVE_PATH}`;
5340
+ if (transport === "socket") url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
5341
+ const query = new URLSearchParams();
5342
+ if (request.key !== void 0) query.set(VISITOR_QUERY.key, request.key);
5343
+ if (request.dataset !== void 0 && request.dataset !== "") {
5344
+ query.set(VISITOR_QUERY.dataset, request.dataset);
5345
+ }
5346
+ if (since !== void 0) query.set(VISITOR_QUERY.since, since);
5347
+ if (request.types !== void 0) query.set(VISITOR_QUERY.types, request.types.join(","));
5348
+ if (request.ids !== void 0) query.set(VISITOR_QUERY.ids, request.ids.join(","));
5349
+ if (transport === "poll" && clientId !== void 0) query.set(VISITOR_QUERY.client, clientId);
5350
+ url.search = query.toString();
5351
+ return url.href;
5352
+ }
5353
+ chunkMWMSFIWN_cjs.__name(edgeUrl, "edgeUrl");
5354
+ function changesOf(changes, cursor, prior) {
5355
+ const last = changes.length - 1;
5356
+ return changes.map((change, index) => ({
5357
+ entryId: change.entryId,
5358
+ contentType: change.contentType,
5359
+ locale: change.locale,
5360
+ kind: change.kind,
5361
+ cursor: index === last ? cursor : prior,
5362
+ fresh: cursor
5363
+ }));
5364
+ }
5365
+ chunkMWMSFIWN_cjs.__name(changesOf, "changesOf");
5366
+ async function expire(reason, cursor, options) {
5367
+ const expired = ChangesExpiredError.resync(reason, cursor);
5368
+ const onExpired = options.onExpired ?? "throw";
5369
+ if (onExpired === "throw") throw expired;
5370
+ if (typeof onExpired === "function") await onExpired(expired);
5371
+ }
5372
+ chunkMWMSFIWN_cjs.__name(expire, "expire");
5373
+ function unreadable(what) {
5374
+ return new LiveEdgeError(
5375
+ `The live edge sent ${what}. This version of the SDK cannot follow it, so it stopped.`,
5376
+ { kind: "unreadable", what },
5377
+ "stop"
5378
+ );
5379
+ }
5380
+ chunkMWMSFIWN_cjs.__name(unreadable, "unreadable");
5381
+ var NEEDS_PUBLISHABLE_KEY = `Live updates at RelyIO\u2019s edge need a publishable key (\`${PUBLISHABLE_KEY_PREFIX}\u2026\`), and this client holds none. A secret or preview key is never sent to the edge; on a server, follow \`changes()\` with it instead. Nothing was sent.`;
5382
+ function sample(value) {
5383
+ const text = typeof value === "string" ? value : `(${typeof value})`;
5384
+ return text.length > 200 ? `${text.slice(0, 200)}\u2026` : text;
5385
+ }
5386
+ chunkMWMSFIWN_cjs.__name(sample, "sample");
5387
+ function parseJson(text) {
5388
+ try {
5389
+ return JSON.parse(text);
5390
+ } catch {
5391
+ return void 0;
5392
+ }
5393
+ }
5394
+ chunkMWMSFIWN_cjs.__name(parseJson, "parseJson");
5395
+ function isRecord(value) {
5396
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5397
+ }
5398
+ chunkMWMSFIWN_cjs.__name(isRecord, "isRecord");
5399
+ function hasOwn(object, key) {
5400
+ return Object.prototype.hasOwnProperty.call(object, key);
5401
+ }
5402
+ chunkMWMSFIWN_cjs.__name(hasOwn, "hasOwn");
5403
+
4639
5404
  // src/config/dev-detection.ts
4640
5405
  function sandboxStateOf(resolution) {
4641
5406
  return resolution.state === "active" ? resolution.sandbox : resolution;
@@ -4778,6 +5543,12 @@ function validateConfig(config) {
4778
5543
  if (config.baseUrl != null && typeof config.baseUrl !== "string") {
4779
5544
  throw new Error("Base URL must be a string");
4780
5545
  }
5546
+ if (config.liveUrl != null && typeof config.liveUrl !== "string") {
5547
+ throw new Error("liveUrl must be a string");
5548
+ }
5549
+ if (config.webSocket != null && typeof config.webSocket !== "function") {
5550
+ throw new Error("webSocket must be a WebSocket class");
5551
+ }
4781
5552
  if (config.timeout != null) assertRequestTimeout(config.timeout);
4782
5553
  if (config.retryAttempts != null && !(Number.isInteger(config.retryAttempts) && config.retryAttempts >= 1)) {
4783
5554
  throw new Error(
@@ -4885,6 +5656,8 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
4885
5656
  * locale, or none after `locale: null` (REL-1453).
4886
5657
  */
4887
5658
  chunkMWMSFIWN_cjs.__publicField(this, "currentLocale", /* @__PURE__ */ chunkMWMSFIWN_cjs.__name(() => this.config.locale, "currentLocale"));
5659
+ /** The live edge's poll client id: chosen once, when first needed, and kept for this client's life. */
5660
+ chunkMWMSFIWN_cjs.__publicField(this, "_liveClientId");
4888
5661
  const { schema, ...clientConfig } = config;
4889
5662
  this._schema = schema;
4890
5663
  const resolved = resolveConfig(clientConfig);
@@ -5093,13 +5866,15 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5093
5866
  * Lazy — nothing is requested until the first `next()`. It runs until
5094
5867
  * `signal` aborts, which ends the `for await` cleanly rather than throwing.
5095
5868
  * A change names what changed; refetch it through the ordinary read path
5096
- * (`INV-SS-CHANGE-IS-IDS`).
5869
+ * (`INV-SS-CHANGE-IS-IDS`), naming its `fresh` so no cache answers with the
5870
+ * body from before it (`FeedChange`).
5097
5871
  *
5098
5872
  * @example
5099
5873
  * ```typescript
5100
5874
  * const controller = new AbortController()
5101
5875
  * for await (const change of relyio.changes({ since: cursor, types: ['post'], signal: controller.signal })) {
5102
- * // { entryId, contentType, locale, kind, cursor }
5876
+ * // { entryId, contentType, locale, kind, cursor, fresh }
5877
+ * await relyio.content(change.contentType).findById(change.entryId).fresh(change.fresh).execute()
5103
5878
  * }
5104
5879
  * ```
5105
5880
  *
@@ -5107,13 +5882,60 @@ var _TypedRelyIOClient = class _TypedRelyIOClient {
5107
5882
  * ```typescript
5108
5883
  * for await (const change of relyio.changes({
5109
5884
  * since: cursor,
5110
- * onExpired: async () => invalidateEverything(),
5885
+ * onExpired: async expired => refetchEverything(expired.fresh),
5111
5886
  * })) { … }
5112
5887
  * ```
5113
5888
  */
5114
5889
  changes(options = {}) {
5115
5890
  return pollChanges(this.httpClient, options);
5116
5891
  }
5892
+ /**
5893
+ * Follow the dataset's **published** changes at RelyIO's live edge, with a publishable key
5894
+ * (`rly_pub_…`): each change as ids, in order — the transport a browser follows changes with.
5895
+ *
5896
+ * A WebSocket to the edge, from `since` or the dataset's current position; where a socket cannot
5897
+ * open — the runtime has none, or the network refuses it — it polls the edge instead, about every
5898
+ * fifteen seconds, from the same cursor. The edge is `liveUrl`, or derived from the default
5899
+ * `baseUrl` (see `RelyIOConfig.liveUrl`).
5900
+ *
5901
+ * One subscription ends only when `signal` aborts, which ends the `for await` cleanly; every other
5902
+ * end — a socket a deploy dropped, a refusal, a refused poll — is thrown as a `LiveEdgeError`
5903
+ * that says whether to stop, retry or back off. Hand it to `followChanges()`, the one loop that
5904
+ * reconnects from the last cursor with jittered back-off and honours those answers:
5905
+ *
5906
+ * @example
5907
+ * ```typescript
5908
+ * const relyio = createClient({ apiKey: 'rly_pub_…' })
5909
+ * const controller = new AbortController()
5910
+ * await followChanges(from => relyio.liveChanges({ ...from, types: ['post'] }), {
5911
+ * signal: controller.signal,
5912
+ * // `fresh` names a position no cache holds a body for from before the change.
5913
+ * onChange: change =>
5914
+ * relyio.content(change.contentType).findById(change.entryId).fresh(change.fresh).execute(),
5915
+ * onResync: resync => refetchEverything(resync.cause === 'expired' ? resync.expired.fresh : undefined),
5916
+ * })
5917
+ * ```
5918
+ *
5919
+ * A client without a publishable key sends nothing: a secret or preview key is never put in the
5920
+ * edge's URL. On a server, follow `changes()` with it instead.
5921
+ */
5922
+ liveChanges(options = {}) {
5923
+ const { apiKey, dataset, baseUrl, liveUrl, fetch: fetch2, webSocket, timeout } = this.config;
5924
+ this._liveClientId ?? (this._liveClientId = randomClientId());
5925
+ return subscribeLiveEdge(
5926
+ {
5927
+ apiKey,
5928
+ dataset,
5929
+ baseUrl,
5930
+ liveUrl,
5931
+ fetch: fetch2,
5932
+ webSocket,
5933
+ timeout,
5934
+ clientId: this._liveClientId
5935
+ },
5936
+ options
5937
+ );
5938
+ }
5117
5939
  /**
5118
5940
  * The dataset's current position in the changes feed, as a cursor to start
5119
5941
  * `changes({ since })` or `followChanges(…, { since })` from. One
@@ -5406,6 +6228,19 @@ function createClient(config) {
5406
6228
  return new TypedRelyIOClient(config);
5407
6229
  }
5408
6230
  chunkMWMSFIWN_cjs.__name(createClient, "createClient");
6231
+ function randomClientId() {
6232
+ const bytes = new Uint8Array(16);
6233
+ const random = globalThis.crypto;
6234
+ if (typeof random?.getRandomValues === "function") {
6235
+ random.getRandomValues.call(random, bytes);
6236
+ } else {
6237
+ for (let index = 0; index < bytes.length; index += 1) {
6238
+ bytes[index] = Math.floor(Math.random() * 256);
6239
+ }
6240
+ }
6241
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
6242
+ }
6243
+ chunkMWMSFIWN_cjs.__name(randomClientId, "randomClientId");
5409
6244
 
5410
6245
  exports.AdhocQueryBuilder = AdhocQueryBuilder;
5411
6246
  exports.AdhocQueryClient = AdhocQueryClient;
@@ -5428,9 +6263,12 @@ exports.FileValidationError = FileValidationError;
5428
6263
  exports.HttpClient = HttpClient;
5429
6264
  exports.InvalidApiKeyError = InvalidApiKeyError;
5430
6265
  exports.InvalidPayloadError = InvalidPayloadError;
6266
+ exports.LIVE_KEEPALIVE_INTERVAL_MS = LIVE_KEEPALIVE_INTERVAL_MS;
6267
+ exports.LiveEdgeError = LiveEdgeError;
5431
6268
  exports.MethodNotAllowedError = MethodNotAllowedError;
5432
6269
  exports.MissingApiKeyError = MissingApiKeyError;
5433
6270
  exports.NetworkError = NetworkError;
6271
+ exports.PUBLISHABLE_KEY_PREFIX = PUBLISHABLE_KEY_PREFIX;
5434
6272
  exports.PayloadTooLargeError = PayloadTooLargeError;
5435
6273
  exports.PlanFeatureUnavailableError = PlanFeatureUnavailableError;
5436
6274
  exports.RateLimitError = RateLimitError;
@@ -5451,15 +6289,17 @@ exports.TransactionRolledBackError = TransactionRolledBackError;
5451
6289
  exports.TypedRelyIOClient = TypedRelyIOClient;
5452
6290
  exports.UnknownContractError = UnknownContractError;
5453
6291
  exports.UsageQuotaExceededError = UsageQuotaExceededError;
6292
+ exports.VISITOR_ADMISSION_RETRY_AFTER_SECONDS = VISITOR_ADMISSION_RETRY_AFTER_SECONDS;
5454
6293
  exports.ValidationError = ValidationError;
5455
6294
  exports.createClient = createClient;
5456
6295
  exports.entityTagOf = entityTagOf;
5457
6296
  exports.isAborted = isAborted;
5458
6297
  exports.isAssetEntry = isAssetEntry;
6298
+ exports.isPublishableKey = isPublishableKey;
5459
6299
  exports.isResourceNotFound = isResourceNotFound;
5460
6300
  exports.matchRoute = matchRoute;
5461
6301
  exports.serviceInstructedDelayMs = serviceInstructedDelayMs;
5462
6302
  exports.sleep = sleep;
5463
6303
  exports.validateFile = validateFile;
5464
- //# sourceMappingURL=chunk-VH2DE7HZ.cjs.map
5465
- //# sourceMappingURL=chunk-VH2DE7HZ.cjs.map
6304
+ //# sourceMappingURL=chunk-XIE7WJV3.cjs.map
6305
+ //# sourceMappingURL=chunk-XIE7WJV3.cjs.map