@collective-intelligence/external-apps-client-sdk 0.1.34 → 0.1.36

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.
package/dist/index.js CHANGED
@@ -1,4 +1,15 @@
1
- import { a as createHttpOperationTransport, c as clientOperationIds, i as isEntityReadLimitError, l as isClientOperationId, n as createResourceClient, o as parseMountPath, r as createEntityProtocol, s as parseOriginUrl, t as createEntityHttpTransport } from "./resources-DVME85iC.js";
1
+ import { a as realtimeTopicKey, c as layerBrowser, g as errors_exports, l as currentLink, m as FederatedAuthError, o as layer, p as CiTransportError, r as makeConnection, s as layerFromFactory, u as createFetchEventSourceFactory } from "./service-4l3X16iR.js";
2
+ import { a as createHttpOperationTransport, c as clientOperationIds, i as isEntityReadLimitError, l as isClientOperationId, n as createResourceClient, o as parseMountPath, r as createEntityProtocol, s as parseOriginUrl, t as createEntityHttpTransport } from "./resources-BFJrm_N2.js";
3
+ import * as Context from "effect/Context";
4
+ import * as Effect from "effect/Effect";
5
+ import * as FetchHttpClient from "effect/http/FetchHttpClient";
6
+ import * as Layer from "effect/Layer";
7
+ import * as Random from "effect/Random";
8
+ import * as Clock from "effect/Clock";
9
+ import * as Duration from "effect/Duration";
10
+ import * as Fiber from "effect/Fiber";
11
+ import { constVoid } from "effect/Function";
12
+ import * as ManagedRuntime from "effect/ManagedRuntime";
2
13
  const base64Url = (bytes) => {
3
14
  let binary = "";
4
15
  for (const byte of bytes) binary += String.fromCodePoint(byte);
@@ -14,14 +25,6 @@ const createPkcePair = async (crypto = globalThis.crypto) => {
14
25
  verifier
15
26
  };
16
27
  };
17
- var FederatedAuthError = class extends Error {
18
- code;
19
- constructor(code, message) {
20
- super(message);
21
- this.name = "FederatedAuthError";
22
- this.code = code;
23
- }
24
- };
25
28
  const transactionLifetimeMs = 6e5;
26
29
  const maxReturnTargetLength = 2048;
27
30
  const asUrl = (value, field) => {
@@ -44,10 +47,10 @@ const normalizedReturnTarget = (value, applicationOrigin) => {
44
47
  if (target.origin !== applicationOrigin) throw new FederatedAuthError("invalid_return_target", "The return target must share the callback origin");
45
48
  return target.href;
46
49
  };
47
- const isRecord$1 = (value) => value !== null && Object(value) === value && !Array.isArray(value);
50
+ const isRecord = (value) => value !== null && Object(value) === value && !Array.isArray(value);
48
51
  const parseTransaction = (serialized) => {
49
52
  const value = JSON.parse(serialized);
50
- if (!isRecord$1(value) || typeof value.expiresAt !== "number" || typeof value.returnTo !== "string" || typeof value.state !== "string" || typeof value.verifier !== "string") throw new FederatedAuthError("invalid_state", "Invalid login transaction");
53
+ if (!isRecord(value) || typeof value.expiresAt !== "number" || typeof value.returnTo !== "string" || typeof value.state !== "string" || typeof value.verifier !== "string") throw new FederatedAuthError("invalid_state", "Invalid login transaction");
51
54
  return {
52
55
  expiresAt: value.expiresAt,
53
56
  returnTo: value.returnTo,
@@ -432,7 +435,7 @@ const eventKind = (event) => {
432
435
  const record = asRecord$1(event);
433
436
  return record === null ? null : readString(record, "kind");
434
437
  };
435
- const idle$1 = async (ms, sleep, signal) => {
438
+ const idle = async (ms, sleep, signal) => {
436
439
  if (ms <= 0 || signal?.aborted === true) return;
437
440
  if (sleep !== void 0) {
438
441
  await sleep(ms);
@@ -502,7 +505,7 @@ const followRun = async (runs, options) => {
502
505
  if (status !== null && terminalSnapshotStatuses.has(status)) return await readRemainingPages(runs, options, page.value);
503
506
  if (page.value.nextCursor !== null) afterCursor = page.value.nextCursor;
504
507
  emptyPolls = page.value.events.length === 0 ? emptyPolls + 1 : 0;
505
- await idle$1(Math.min(idleMs * 2 ** emptyPolls, maxIdleMs), options.sleep, options.signal);
508
+ await idle(Math.min(idleMs * 2 ** emptyPolls, maxIdleMs), options.sleep, options.signal);
506
509
  }
507
510
  throw new Error("Run did not finish");
508
511
  };
@@ -735,355 +738,6 @@ const createDirectTransport = (options) => {
735
738
  origin: tenantUrl
736
739
  });
737
740
  };
738
- const emptyBlock = () => ({
739
- comment: false,
740
- data: [],
741
- id: void 0,
742
- type: ""
743
- });
744
- /**
745
- * A Server-Sent Events parser that, unlike `EventSource`, reports comments:
746
- * the server's pings are comments, and the client's watchdog needs them.
747
- */
748
- const createEventStreamParser = (handlers) => {
749
- let buffer = "";
750
- let block = emptyBlock();
751
- let retry;
752
- const dispatch = () => {
753
- const ended = block;
754
- block = emptyBlock();
755
- if (ended.data.length > 0) handlers.onEvent({
756
- data: ended.data.join("\n"),
757
- id: ended.id,
758
- type: ended.type === "" ? "message" : ended.type
759
- });
760
- else if (ended.comment || ended.id !== void 0) handlers.onPing(ended.id);
761
- };
762
- const line = (text) => {
763
- if (text === "") {
764
- dispatch();
765
- return;
766
- }
767
- if (text.startsWith(":")) {
768
- block.comment = true;
769
- return;
770
- }
771
- const colon = text.indexOf(":");
772
- const field = colon === -1 ? text : text.slice(0, colon);
773
- const raw = colon === -1 ? "" : text.slice(colon + 1);
774
- const value = raw.startsWith(" ") ? raw.slice(1) : raw;
775
- if (field === "data") block.data.push(value);
776
- else if (field === "event") block.type = value;
777
- else if (field === "id" && !value.includes("\0")) block.id = value;
778
- else if (field === "retry" && /^\d+$/u.test(value)) retry = Number(value);
779
- };
780
- return {
781
- push: (chunk) => {
782
- buffer += chunk;
783
- const lines = buffer.split("\n");
784
- buffer = lines.pop() ?? "";
785
- for (const text of lines) line(text.endsWith("\r") ? text.slice(0, -1) : text);
786
- },
787
- /** The last `retry:` the stream sent, in milliseconds. */
788
- retry: () => retry
789
- };
790
- };
791
- /** `Retry-After` in milliseconds, seconds form only. */
792
- const retryAfterMilliseconds = (response) => {
793
- const value = response.headers.get("retry-after");
794
- return value !== null && /^\d+$/u.test(value) ? Number(value) * 1e3 : void 0;
795
- };
796
- /** Reads `text/event-stream` with `fetch`, so pings and refusals are visible. */
797
- const createFetchEventSourceFactory = (fetch) => (url, handlers) => {
798
- const abort = new AbortController();
799
- const live = () => !abort.signal.aborted;
800
- const parser = createEventStreamParser({
801
- onEvent: (event) => {
802
- if (live()) handlers.onEvent(event);
803
- },
804
- onPing: (id) => {
805
- if (live()) handlers.onPing(id);
806
- }
807
- });
808
- const read = async () => {
809
- try {
810
- const response = await fetch(url, {
811
- cache: "no-store",
812
- headers: { accept: "text/event-stream" },
813
- signal: abort.signal
814
- });
815
- if (!response.ok || response.body === null) {
816
- parser.push(`${await response.text()}\n\n`);
817
- if (live()) handlers.onEnd({
818
- retryMilliseconds: retryAfterMilliseconds(response) ?? parser.retry(),
819
- status: response.status
820
- });
821
- return;
822
- }
823
- if (live()) handlers.onOpen();
824
- const decoder = new TextDecoder();
825
- const reader = response.body.getReader();
826
- for (;;) {
827
- const { done, value } = await reader.read();
828
- if (done) break;
829
- parser.push(decoder.decode(value, { stream: true }));
830
- }
831
- } catch {}
832
- if (live()) handlers.onEnd({
833
- retryMilliseconds: parser.retry(),
834
- status: void 0
835
- });
836
- };
837
- read();
838
- return { close: () => abort.abort() };
839
- };
840
- const topicSetDebounceMilliseconds = 300;
841
- const pingTimeoutMilliseconds = 45e3;
842
- const backoffBaseMilliseconds = 1e3;
843
- const backoffCapMilliseconds = 3e4;
844
- const initialMachineState = (documentVisible) => ({
845
- attempt: 0,
846
- documentVisible,
847
- lastEventId: void 0,
848
- nextLinkId: 1,
849
- pageShown: true,
850
- phase: "idle",
851
- topics: []
852
- });
853
- /** Full jitter over an exponential cap; a server hint is a lower bound. */
854
- const backoffDelay = (attempt, retryMilliseconds, jitter) => {
855
- const cap = Math.min(backoffCapMilliseconds, backoffBaseMilliseconds * 2 ** attempt);
856
- return Math.max(retryMilliseconds ?? 0, Math.floor(jitter * cap));
857
- };
858
- const currentLink = (state) => "link" in state ? state.link : void 0;
859
- const shared = (state) => ({
860
- attempt: state.attempt,
861
- documentVisible: state.documentVisible,
862
- lastEventId: state.lastEventId,
863
- nextLinkId: state.nextLinkId,
864
- pageShown: state.pageShown,
865
- topics: state.topics
866
- });
867
- const visible = (state) => state.documentVisible && state.pageShown;
868
- const wanted = (state) => state.phase !== "closed" && visible(state) && state.topics.length > 0;
869
- const sameTopics = (left, right) => left.length === right.length && left.every((key) => right.includes(key));
870
- const unchanged = (state) => ({
871
- commands: [],
872
- state
873
- });
874
- /** Commands that end the current link, if any. */
875
- const unlink = (state) => {
876
- const link = currentLink(state);
877
- return link === void 0 ? [] : [{
878
- linkId: link.id,
879
- type: "disconnect"
880
- }, {
881
- timer: "watchdog",
882
- type: "cancel"
883
- }];
884
- };
885
- const watchdog = (linkId) => ({
886
- event: {
887
- linkId,
888
- type: "watchdogElapsed"
889
- },
890
- milliseconds: pingTimeoutMilliseconds,
891
- timer: "watchdog",
892
- type: "schedule"
893
- });
894
- const idle = (state) => ({
895
- ...shared(state),
896
- phase: state.phase === "closed" ? "closed" : "idle"
897
- });
898
- const stop = (state) => ({
899
- commands: [
900
- {
901
- timer: "debounce",
902
- type: "cancel"
903
- },
904
- {
905
- timer: "backoff",
906
- type: "cancel"
907
- },
908
- ...unlink(state)
909
- ],
910
- state: idle(state)
911
- });
912
- const connect = (state) => {
913
- if (!wanted(state)) return {
914
- commands: unlink(state),
915
- state: idle(state)
916
- };
917
- const link = {
918
- id: state.nextLinkId,
919
- topics: state.topics
920
- };
921
- return {
922
- commands: [
923
- ...unlink(state),
924
- watchdog(link.id),
925
- {
926
- link,
927
- type: "mint"
928
- }
929
- ],
930
- state: {
931
- ...shared(state),
932
- link,
933
- nextLinkId: state.nextLinkId + 1,
934
- phase: "connecting"
935
- }
936
- };
937
- };
938
- const retry = (state, retryMilliseconds) => {
939
- if (!wanted(state)) return {
940
- commands: unlink(state),
941
- state: idle(state)
942
- };
943
- return {
944
- commands: [...unlink(state), {
945
- attempt: state.attempt,
946
- retryMilliseconds,
947
- type: "backoff"
948
- }],
949
- state: {
950
- ...shared(state),
951
- attempt: state.attempt + 1,
952
- phase: "backoff"
953
- }
954
- };
955
- };
956
- /** Brings the connection in line with the page and the topic set. */
957
- const sync = (state) => {
958
- if (!wanted(state)) return stop(state);
959
- const link = currentLink(state);
960
- if (state.phase === "backoff" || link !== void 0 && sameTopics(link.topics, state.topics)) return {
961
- commands: [{
962
- timer: "debounce",
963
- type: "cancel"
964
- }],
965
- state
966
- };
967
- return connect(state);
968
- };
969
- const reactToPage = (state) => {
970
- if (!visible(state)) return stop(state);
971
- return currentLink(state) === void 0 && state.phase !== "backoff" ? sync(state) : unchanged(state);
972
- };
973
- const streamUrlAfter = (streamUrl, lastEventId) => {
974
- const url = new URL(streamUrl);
975
- if (lastEventId !== void 0) url.searchParams.set("lastEventId", lastEventId);
976
- return url.href;
977
- };
978
- /** Events of the client, the page and its timers. */
979
- const clientTransition = (state, event) => {
980
- switch (event.type) {
981
- case "topicsChanged": {
982
- const next = {
983
- ...state,
984
- topics: event.topics
985
- };
986
- return next.phase === "closed" ? unchanged(next) : {
987
- commands: [{
988
- event: { type: "debounceElapsed" },
989
- milliseconds: topicSetDebounceMilliseconds,
990
- timer: "debounce",
991
- type: "schedule"
992
- }],
993
- state: next
994
- };
995
- }
996
- case "debounceElapsed": return sync(state);
997
- case "visibilityChanged": return reactToPage({
998
- ...state,
999
- documentVisible: event.visible
1000
- });
1001
- case "pageHidden": return stop({
1002
- ...state,
1003
- pageShown: false
1004
- });
1005
- case "pageShown": return reactToPage({
1006
- ...state,
1007
- documentVisible: event.visible,
1008
- pageShown: true
1009
- });
1010
- case "backoffElapsed": return state.phase === "backoff" ? connect(state) : unchanged(state);
1011
- case "close": return {
1012
- ...stop(state),
1013
- state: {
1014
- ...shared(state),
1015
- phase: "closed"
1016
- }
1017
- };
1018
- default: return unchanged(state);
1019
- }
1020
- };
1021
- /** Events of one link; an event of an earlier link changes nothing. */
1022
- const linkTransition = (state, event) => {
1023
- const link = currentLink(state);
1024
- if (link?.id !== event.linkId) return unchanged(state);
1025
- switch (event.type) {
1026
- case "ticketMinted": return {
1027
- commands: [{
1028
- linkId: link.id,
1029
- type: "openStream",
1030
- url: streamUrlAfter(event.streamUrl, state.lastEventId)
1031
- }],
1032
- state
1033
- };
1034
- case "ticketFailed":
1035
- case "streamEnded": return retry(state, event.retryMilliseconds);
1036
- case "streamOpened": return {
1037
- commands: state.lastEventId === void 0 ? [watchdog(link.id), { type: "resync" }] : [watchdog(link.id)],
1038
- state: {
1039
- ...shared(state),
1040
- link,
1041
- phase: "open"
1042
- }
1043
- };
1044
- case "received": {
1045
- const { eventId } = event;
1046
- return {
1047
- commands: [watchdog(link.id)],
1048
- state: {
1049
- ...state,
1050
- attempt: 0,
1051
- lastEventId: eventId === void 0 || eventId === "" ? state.lastEventId : eventId
1052
- }
1053
- };
1054
- }
1055
- case "watchdogElapsed": return retry(state);
1056
- default: return unchanged(state);
1057
- }
1058
- };
1059
- const transition = (state, event) => "linkId" in event ? linkTransition(state, event) : clientTransition(state, event);
1060
- /** One stable key per topic, whatever the key order of the object. */
1061
- const realtimeTopicKey = ({ filter, schema }) => JSON.stringify(filter === void 0 ? [schema] : [
1062
- schema,
1063
- filter.field,
1064
- filter.eq
1065
- ]);
1066
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1067
- const isFilterValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1068
- const isTopic = (value) => isRecord(value) && typeof value.schema === "string" && (value.filter === void 0 || isRecord(value.filter) && typeof value.filter.field === "string" && isFilterValue(value.filter.eq));
1069
- const isOp = (value) => value === "create" || value === "update" || value === "delete";
1070
- /** The `data` of a `change` event, or undefined when it is malformed. */
1071
- const parseRealtimeChange = (data) => {
1072
- let value;
1073
- try {
1074
- value = JSON.parse(data);
1075
- } catch {
1076
- return;
1077
- }
1078
- return isRecord(value) && typeof value.id === "string" && isOp(value.op) && typeof value.revision === "string" && isTopic(value.topic) ? {
1079
- id: value.id,
1080
- op: value.op,
1081
- revision: value.revision,
1082
- topic: value.topic
1083
- } : void 0;
1084
- };
1085
- /** The stream URL of a ticket route answer, or undefined when it is malformed. */
1086
- const readStreamUrl = (value) => isRecord(value) && typeof value.streamUrl === "string" ? value.streamUrl : void 0;
1087
741
  /** Surfaces a listener's error without stopping the other listeners. */
1088
742
  const report = (error) => {
1089
743
  if ("reportError" in globalThis) {
@@ -1101,282 +755,166 @@ const notify = (listener) => {
1101
755
  report(error);
1102
756
  }
1103
757
  };
1104
- /** The least wait before a delivery: a burst of changes joins one delivery. */
1105
- const changeWindowMilliseconds = 250;
1106
- /** The random extra wait, so that the tabs of many users refetch apart. */
1107
- const changeJitterMilliseconds = 750;
1108
758
  const defaultTimers = { schedule: (callback, milliseconds) => {
1109
759
  const handle = globalThis.setTimeout(callback, milliseconds);
1110
760
  return () => globalThis.clearTimeout(handle);
1111
761
  } };
762
+ /** The connection of one facade client, as its runtime holds it. */
763
+ var FacadeConnection = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/FacadeConnection") {};
1112
764
  /**
1113
- * One realtime connection per tab for every subscribed topic. The connection
1114
- * opens while the page is visible and a topic has a listener; a topic set
1115
- * change reconnects after a short debounce, and every reconnect resumes after
1116
- * the last received event; a stream that opens without one resets instead.
1117
- * Changes and resets reach the listeners in one delivery per tab, 250 to
1118
- * 1000 ms after the first of them: a burst of changes refetches once, and
1119
- * tabs that reset together refetch apart.
1120
- * Connection decisions live in the pure state machine (`./machine`); this
1121
- * client only runs its commands.
765
+ * A scheduler that runs fiber tasks in the call stack of the facade. A task
766
+ * that a callback schedules outside every fiber runs at once; a task that a
767
+ * fiber schedules runs after it, when `flush` runs or in a microtask. Thus a
768
+ * facade call, a page event or a stream handler has its whole effect before
769
+ * it returns, as in the event loop that the service replaced.
1122
770
  */
1123
- const createRealtimeClient = (options) => {
1124
- const fetch = options.fetch ?? globalThis.fetch;
1125
- const openStream = options.eventSourceFactory ?? createFetchEventSourceFactory(fetch);
1126
- const timers = options.timers ?? defaultTimers;
1127
- const random = options.random ?? Math.random;
1128
- const page = options.document;
1129
- const view = options.window;
1130
- const documentVisible = () => page === void 0 || page.visibilityState !== "hidden";
1131
- const registrations = /* @__PURE__ */ new Map();
1132
- const pendingTimers = /* @__PURE__ */ new Map();
1133
- const links = /* @__PURE__ */ new Map();
1134
- const queue = [];
1135
- /** Per topic key, the latest change of each record, by last arrival. */
1136
- const pending = /* @__PURE__ */ new Map();
1137
- let resetPending = false;
1138
- let cancelDelivery;
1139
- let state = initialMachineState(documentVisible());
1140
- /** Runs events one at a time; events sent by a command wait in the queue. */
1141
- const dispatch = (event) => {
1142
- queue.push(event);
1143
- if (queue.length > 1) return;
1144
- for (let next = queue.at(0); next !== void 0; next = queue.at(0)) try {
1145
- const { commands, state: nextState } = transition(state, next);
1146
- state = nextState;
1147
- for (const command of commands) run(command);
1148
- } finally {
1149
- queue.shift();
1150
- }
1151
- };
1152
- /** Delivers the pending changes, or the pending reset, to the current listeners. */
1153
- const deliver = () => {
1154
- cancelDelivery = void 0;
1155
- const batches = [...pending];
1156
- pending.clear();
1157
- if (resetPending) {
1158
- resetPending = false;
1159
- notify(() => options.onReset?.());
1160
- return;
1161
- }
1162
- for (const [key, changes] of batches) {
1163
- const batch = [...changes.values()];
1164
- for (const listener of registrations.get(key)?.listeners ?? []) notify(() => listener(batch));
1165
- }
1166
- };
1167
- /**
1168
- * The first change or reset after a delivery schedules the next one; later
1169
- * ones join it without delaying it.
1170
- */
1171
- const scheduleDelivery = () => {
1172
- cancelDelivery ??= timers.schedule(deliver, changeWindowMilliseconds + Math.floor(random() * changeJitterMilliseconds));
1173
- };
1174
- /**
1175
- * Replaces the pending changes with one `onReset` at the next delivery.
1176
- * Without `onReset` no refetch covers them, so they stay.
1177
- */
1178
- const resync = () => {
1179
- if (options.onReset === void 0) return;
1180
- resetPending = true;
1181
- scheduleDelivery();
1182
- };
1183
- const route = (change) => {
1184
- const key = realtimeTopicKey(change.topic);
1185
- if (!registrations.has(key)) return;
1186
- const changes = pending.get(key) ?? /* @__PURE__ */ new Map();
1187
- changes.delete(change.id);
1188
- changes.set(change.id, change);
1189
- pending.set(key, changes);
1190
- scheduleDelivery();
1191
- };
1192
- const ticketEvent = async (link, signal) => {
1193
- const topics = link.topics.flatMap((key) => {
1194
- const registration = registrations.get(key);
1195
- return registration === void 0 ? [] : [registration.topic];
1196
- });
771
+ const makeSyncScheduler = () => {
772
+ const tasks = [];
773
+ let flushing = false;
774
+ let flushQueued = false;
775
+ const flush = () => {
776
+ if (flushing) return;
777
+ flushing = true;
1197
778
  try {
1198
- const response = await fetch(options.ticketUrl, {
1199
- body: JSON.stringify({ topics }),
1200
- credentials: "same-origin",
1201
- headers: { "content-type": "application/json" },
1202
- method: "POST",
1203
- signal
1204
- });
1205
- if (!response.ok) return {
1206
- linkId: link.id,
1207
- retryMilliseconds: retryAfterMilliseconds(response),
1208
- type: "ticketFailed"
1209
- };
1210
- const streamUrl = readStreamUrl(await response.json());
1211
- return streamUrl === void 0 ? {
1212
- linkId: link.id,
1213
- retryMilliseconds: void 0,
1214
- type: "ticketFailed"
1215
- } : {
1216
- linkId: link.id,
1217
- streamUrl,
1218
- type: "ticketMinted"
1219
- };
1220
- } catch {
1221
- return {
1222
- linkId: link.id,
1223
- retryMilliseconds: void 0,
1224
- type: "ticketFailed"
1225
- };
1226
- }
1227
- };
1228
- const mint = async (link, signal) => {
1229
- dispatch(await ticketEvent(link, signal));
1230
- };
1231
- const openEvents = (linkId, url) => openStream(url, {
1232
- onEnd: (end) => {
1233
- dispatch({
1234
- linkId,
1235
- retryMilliseconds: end.retryMilliseconds,
1236
- type: "streamEnded"
1237
- });
1238
- },
1239
- onEvent: (event) => {
1240
- if (currentLink(state)?.id !== linkId) return;
1241
- dispatch({
1242
- eventId: event.id,
1243
- linkId,
1244
- type: "received"
1245
- });
1246
- if (event.type === "change") {
1247
- const change = parseRealtimeChange(event.data);
1248
- if (change !== void 0) route(change);
1249
- } else if (event.type === "reset") resync();
1250
- else if (event.type === "access-changed") options.onAccessChanged?.();
1251
- },
1252
- onOpen: () => {
1253
- dispatch({
1254
- linkId,
1255
- type: "streamOpened"
1256
- });
1257
- },
1258
- onPing: (id) => {
1259
- dispatch({
1260
- eventId: id,
1261
- linkId,
1262
- type: "received"
1263
- });
779
+ for (let next = tasks.shift(); next !== void 0; next = tasks.shift()) next[0]();
780
+ } finally {
781
+ flushing = false;
1264
782
  }
1265
- }).close;
1266
- const cancelTimer = (timer) => {
1267
- pendingTimers.get(timer)?.();
1268
- pendingTimers.delete(timer);
1269
783
  };
1270
- const scheduleTimer = (timer, milliseconds, event) => {
1271
- cancelTimer(timer);
1272
- pendingTimers.set(timer, timers.schedule(() => {
1273
- pendingTimers.delete(timer);
1274
- dispatch(event);
1275
- }, milliseconds));
1276
- };
1277
- const run = (command) => {
1278
- switch (command.type) {
1279
- case "schedule":
1280
- scheduleTimer(command.timer, command.milliseconds, command.event);
1281
- return;
1282
- case "cancel":
1283
- cancelTimer(command.timer);
1284
- return;
1285
- case "backoff":
1286
- scheduleTimer("backoff", backoffDelay(command.attempt, command.retryMilliseconds, random()), { type: "backoffElapsed" });
1287
- return;
1288
- case "mint": {
1289
- const abort = new AbortController();
1290
- links.set(command.link.id, {
1291
- abort,
1292
- close: void 0
1293
- });
1294
- mint(command.link, abort.signal);
1295
- return;
1296
- }
1297
- case "openStream": {
1298
- const resources = links.get(command.linkId);
1299
- if (resources !== void 0) links.set(command.linkId, {
1300
- ...resources,
1301
- close: openEvents(command.linkId, command.url)
784
+ const dispatcher = {
785
+ flush,
786
+ scheduleTask: (task, priority) => {
787
+ const later = tasks.findIndex(([, queued]) => queued > priority);
788
+ tasks.splice(later === -1 ? tasks.length : later, 0, [task, priority]);
789
+ if (flushing) return;
790
+ if (Fiber.getCurrent() === void 0) flush();
791
+ else if (!flushQueued) {
792
+ flushQueued = true;
793
+ queueMicrotask(() => {
794
+ flushQueued = false;
795
+ flush();
1302
796
  });
1303
- return;
1304
- }
1305
- case "disconnect": {
1306
- const resources = links.get(command.linkId);
1307
- links.delete(command.linkId);
1308
- resources?.abort.abort();
1309
- resources?.close?.();
1310
- return;
1311
797
  }
1312
- case "resync":
1313
- resync();
1314
- return;
1315
798
  }
1316
799
  };
1317
- const topicsChanged = () => {
1318
- dispatch({
1319
- topics: [...registrations.keys()],
1320
- type: "topicsChanged"
1321
- });
1322
- };
1323
- const onVisibility = () => {
1324
- dispatch({
1325
- type: "visibilityChanged",
1326
- visible: documentVisible()
1327
- });
1328
- };
1329
- const onPageHide = () => {
1330
- dispatch({ type: "pageHidden" });
1331
- };
1332
- const onPageShow = () => {
1333
- dispatch({
1334
- type: "pageShown",
1335
- visible: documentVisible()
1336
- });
800
+ return {
801
+ flush,
802
+ scheduler: {
803
+ executionMode: "sync",
804
+ makeDispatcher: () => dispatcher,
805
+ shouldYield: (fiber) => fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield
806
+ }
1337
807
  };
1338
- page?.addEventListener("visibilitychange", onVisibility);
1339
- view?.addEventListener("pagehide", onPageHide);
1340
- view?.addEventListener("pageshow", onPageShow);
808
+ };
809
+ /** The live `Clock`, except that it sleeps on `timers`. */
810
+ const clockOf = (timers, flush) => {
811
+ const live = Clock.Clock.defaultValue();
812
+ return {
813
+ currentTimeMillis: live.currentTimeMillis,
814
+ currentTimeMillisUnsafe: () => live.currentTimeMillisUnsafe(),
815
+ currentTimeNanos: live.currentTimeNanos,
816
+ currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe(),
817
+ monotonicTimeNanos: live.monotonicTimeNanos,
818
+ monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(),
819
+ sleep: (duration) => Effect.callback((resume) => {
820
+ const cancel = timers.schedule(() => {
821
+ resume(Effect.void);
822
+ flush();
823
+ }, Duration.toMillis(duration));
824
+ return Effect.sync(cancel);
825
+ })
826
+ };
827
+ };
828
+ const randomOf = (random) => ({
829
+ nextDoubleUnsafe: random,
830
+ nextIntUnsafe: () => Math.floor(random() * Number.MAX_SAFE_INTEGER)
831
+ });
832
+ /**
833
+ * The origin on which the service requests the ticket. `HttpClient` resolves
834
+ * a relative URL against `location`, and fails without one. But `fetch` got
835
+ * `ticketUrl` as the app gave it before the service, and a custom `fetch` can
836
+ * resolve it on a base of its own. So the service requests `ticketUrl` on this
837
+ * origin, and `fetchOf` gives `fetch` the `ticketUrl` of the app in its place.
838
+ */
839
+ const ticketOrigin = "http://realtime-ticket.invalid/";
840
+ /** `ticketUrl` on `ticketOrigin`; `ticketOrigin` itself for a string that is not a URL. */
841
+ const ticketRequestUrl = (ticketUrl) => {
842
+ try {
843
+ return new URL(ticketUrl, ticketOrigin).href;
844
+ } catch {
845
+ return ticketOrigin;
846
+ }
847
+ };
848
+ /**
849
+ * The `fetch` of the client as `FetchHttpClient.Fetch`, called as before the
850
+ * service: with a string URL, `ticketUrl` for the ticket request, and without
851
+ * the `duplex: undefined` that `FetchHttpClient` adds for a body that is not
852
+ * a stream. `preconnect` only completes the type of `fetch` under Bun's
853
+ * types; nothing here preconnects.
854
+ */
855
+ const fetchOf = (fetch, ticketUrl) => {
856
+ const requestUrl = ticketRequestUrl(ticketUrl);
857
+ return Object.assign((input, init) => {
858
+ const href = input instanceof URL ? input.href : input;
859
+ const url = href === requestUrl ? ticketUrl : href;
860
+ if (init === void 0 || !("duplex" in init)) return fetch(url, init);
861
+ const { duplex, ...rest } = init;
862
+ return duplex === void 0 ? fetch(url, rest) : fetch(url, init);
863
+ }, { preconnect: constVoid });
864
+ };
865
+ /**
866
+ * One realtime connection per tab for every subscribed topic. The connection
867
+ * opens while the page is visible and a topic has a listener; a topic set
868
+ * change reconnects after a short debounce, and every reconnect resumes after
869
+ * the last received event; a stream that opens without one resets instead.
870
+ * Changes and resets reach the listeners in one delivery per tab, 250 to
871
+ * 1000 ms after the first of them: a burst of changes refetches once, and
872
+ * tabs that reset together refetch apart.
873
+ * The client runs on the realtime service (`./service`) in a runtime of its
874
+ * own; `close` disposes of it.
875
+ */
876
+ const createRealtimeClient = (options) => {
877
+ const { flush, scheduler } = makeSyncScheduler();
878
+ const runtime = ManagedRuntime.make(Layer.effect(FacadeConnection, makeConnection({
879
+ resyncOnAccessChange: false,
880
+ ticketUrl: ticketRequestUrl(options.ticketUrl)
881
+ })).pipe(Layer.provide([
882
+ FetchHttpClient.layer,
883
+ layerBrowser({
884
+ document: options.document,
885
+ window: options.window
886
+ }),
887
+ options.eventSourceFactory === void 0 ? layer : layerFromFactory(options.eventSourceFactory)
888
+ ]), Layer.provide([
889
+ Layer.succeed(FetchHttpClient.Fetch, fetchOf(options.fetch ?? globalThis.fetch, options.ticketUrl)),
890
+ Layer.succeed(Clock.Clock, clockOf(options.timers ?? defaultTimers, flush)),
891
+ Layer.succeed(Random.Random, randomOf(options.random ?? Math.random))
892
+ ])));
893
+ const started = runtime.runFork(FacadeConnection, { scheduler });
894
+ flush();
895
+ const exit = started.pollUnsafe();
896
+ if (exit?._tag !== "Success") throw new Error("The realtime client did not start.", { cause: exit });
897
+ const connection = exit.value;
898
+ const { onAccessChanged, onReset } = options;
899
+ if (onReset !== void 0) connection.listenResyncs(() => notify(onReset));
900
+ if (onAccessChanged !== void 0) connection.listenAccessChanges(() => notify(onAccessChanged));
1341
901
  return {
1342
902
  close: () => {
1343
- dispatch({ type: "close" });
1344
- cancelDelivery?.();
1345
- cancelDelivery = void 0;
1346
- pending.clear();
1347
- resetPending = false;
1348
- page?.removeEventListener("visibilitychange", onVisibility);
1349
- view?.removeEventListener("pagehide", onPageHide);
1350
- view?.removeEventListener("pageshow", onPageShow);
903
+ Effect.runFork(runtime.disposeEffect, { scheduler });
904
+ flush();
1351
905
  },
1352
- getState: () => ({
1353
- connections: currentLink(state) === void 0 ? 0 : 1,
1354
- lastEventId: state.lastEventId,
1355
- status: state.phase === "closed" ? "idle" : state.phase,
1356
- topics: [...registrations.values()].map(({ topic }) => topic)
1357
- }),
1358
- subscribe: (topic, onChanges) => {
1359
- const key = realtimeTopicKey(topic);
1360
- const registration = registrations.get(key) ?? {
1361
- listeners: /* @__PURE__ */ new Set(),
1362
- topic
1363
- };
1364
- const listener = (changes) => onChanges(changes);
1365
- registration.listeners.add(listener);
1366
- if (!registrations.has(key)) {
1367
- registrations.set(key, registration);
1368
- topicsChanged();
1369
- }
1370
- const unsubscribe = () => {
1371
- if (!registration.listeners.delete(listener)) return;
1372
- if (registration.listeners.size === 0) {
1373
- registrations.delete(key);
1374
- pending.delete(key);
1375
- topicsChanged();
1376
- }
906
+ getState: () => {
907
+ const { machine, topics } = connection.state();
908
+ return {
909
+ connections: currentLink(machine) === void 0 ? 0 : 1,
910
+ lastEventId: machine.lastEventId,
911
+ status: machine.phase === "closed" ? "idle" : machine.phase,
912
+ topics
1377
913
  };
1378
- return unsubscribe;
1379
- }
914
+ },
915
+ subscribe: (topic, onChanges) => connection.listen(topic, (changes) => notify(() => onChanges(changes)))
1380
916
  };
1381
917
  };
1382
- export { DEFAULT_FOLLOW_RUN_DEADLINE_MS, FederatedAuthError, clientOperationIds, clientSdkProtocolVersion, createClient, createDelegatedApplicationRuntime, createDirectTransport, createEntityHttpTransport, createEntityProtocol, createFederatedAuth, createFetchEventSourceFactory, createFixedWorkflowClient, createProxyTransport, createRealtimeClient, createResourceClient, createServerSessionAuth, followRun, isClientOperationId, isEntityReadLimitError, nextStreamCursor, realtimeTopicKey };
918
+ /** The class of an Expected Error that CI returns. */
919
+ const { CiError } = errors_exports;
920
+ export { CiError, CiTransportError, DEFAULT_FOLLOW_RUN_DEADLINE_MS, FederatedAuthError, clientOperationIds, clientSdkProtocolVersion, createClient, createDelegatedApplicationRuntime, createDirectTransport, createEntityHttpTransport, createEntityProtocol, createFederatedAuth, createFetchEventSourceFactory, createFixedWorkflowClient, createProxyTransport, createRealtimeClient, createResourceClient, createServerSessionAuth, followRun, isClientOperationId, isEntityReadLimitError, nextStreamCursor, realtimeTopicKey };