@collective-intelligence/external-apps-client-sdk 0.1.35 → 0.1.37
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/README.md +190 -0
- package/dist/effect.d.ts +132 -0
- package/dist/effect.js +32 -0
- package/dist/index-BqdhzpcZ.d.ts +1029 -0
- package/dist/index.d.ts +3 -925
- package/dist/index.js +323 -1233
- package/dist/resources-DT-KqPTd.js +109 -0
- package/dist/{resources-GSZWfWkN.d.ts → resources-tBGn1Exi.d.ts} +208 -10
- package/dist/resources.d.ts +1 -1
- package/dist/resources.js +2 -1
- package/dist/{resources-DVME85iC.js → service-C7kswu6e.js} +560 -277
- package/dist/service-CxUyG8yF.js +1439 -0
- package/package.json +20 -4
package/dist/index.js
CHANGED
|
@@ -1,511 +1,125 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
this.code = code;
|
|
23
|
-
}
|
|
24
|
-
};
|
|
25
|
-
const transactionLifetimeMs = 6e5;
|
|
26
|
-
const maxReturnTargetLength = 2048;
|
|
27
|
-
const asUrl = (value, field) => {
|
|
1
|
+
import { E as FederatedAuthError, O as errors_exports, S as toCiResult, T as CiTransportError, _ as makeHttpExecute, d as createEntityHttpTransport, g as directHttpOptions, m as isEntityReadLimitError, p as createEntityProtocol, v as proxyHttpOptions, x as isClientOperationId, y as clientOperationIds } from "./service-C7kswu6e.js";
|
|
2
|
+
import { A as layerFromFactory, E as makeConnection, M as currentLink, N as createFetchEventSourceFactory, O as realtimeTopicKey, S as make, a as layer$2, c as layerFederated, f as DEFAULT_FOLLOW_RUN_DEADLINE_MS, g as CiClient, h as layer, i as FixedWorkflows, j as layerBrowser, k as layer$3, m as followSource, n as layer$1, p as Runs, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, y as layerFromExecutor } from "./service-CxUyG8yF.js";
|
|
3
|
+
import { t as createResourceClient } from "./resources-DT-KqPTd.js";
|
|
4
|
+
import * as Context from "effect/Context";
|
|
5
|
+
import * as Effect from "effect/Effect";
|
|
6
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
|
|
7
|
+
import * as Layer from "effect/Layer";
|
|
8
|
+
import * as Random from "effect/Random";
|
|
9
|
+
import * as Clock from "effect/Clock";
|
|
10
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
11
|
+
import * as Duration from "effect/Duration";
|
|
12
|
+
import * as Fiber from "effect/Fiber";
|
|
13
|
+
import { constVoid } from "effect/Function";
|
|
14
|
+
/**
|
|
15
|
+
* Internal; no entrypoint exports it. Runs one facade method:
|
|
16
|
+
* `runtime.runPromise(effect, { signal })`. A failure rejects with its tagged
|
|
17
|
+
* class; when the caller aborts, the call rejects with `signal.reason`, the
|
|
18
|
+
* `AbortError` that `fetch` uses (Q84); any other interruption is a Defect.
|
|
19
|
+
* A function without a client of its own passes `Effect` as `runtime`.
|
|
20
|
+
*/
|
|
21
|
+
const runPromise = async (runtime, effect, signal) => {
|
|
28
22
|
try {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
throw new FederatedAuthError("configuration_error", `${field} must be an absolute URL without credentials`);
|
|
23
|
+
return await runtime.runPromise(effect, signal === void 0 ? void 0 : { signal });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (signal?.aborted === true) throw signal.reason;
|
|
26
|
+
throw error;
|
|
34
27
|
}
|
|
35
28
|
};
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
const parseTransaction = (serialized) => {
|
|
49
|
-
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");
|
|
51
|
-
return {
|
|
52
|
-
expiresAt: value.expiresAt,
|
|
53
|
-
returnTo: value.returnTo,
|
|
54
|
-
state: value.state,
|
|
55
|
-
verifier: value.verifier
|
|
56
|
-
};
|
|
57
|
-
};
|
|
58
|
-
const parseToken = (value, now) => {
|
|
59
|
-
const accessToken = value.access_token;
|
|
60
|
-
const expiresIn = value.expires_in;
|
|
61
|
-
if (typeof accessToken !== "string" || accessToken.length === 0 || typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0 || value.token_type !== "Bearer") throw new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token");
|
|
29
|
+
/**
|
|
30
|
+
* The `.` facade of sign-in: `createFederatedAuth` keeps its options and
|
|
31
|
+
* methods over the `FederatedAuth` service (`./service`), in a runtime of
|
|
32
|
+
* its own.
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* Internal. The facade of the `FederatedAuth` service in `runtime`;
|
|
36
|
+
* `getState` and `subscribe` stay synchronous. A configuration error throws
|
|
37
|
+
* its `FederatedAuthError` here.
|
|
38
|
+
*/
|
|
39
|
+
const authFacade = (runtime) => {
|
|
40
|
+
const session = runtime.runSync(FederatedAuth);
|
|
62
41
|
return {
|
|
63
|
-
|
|
64
|
-
|
|
42
|
+
beginLogin: (options) => runPromise(runtime, session.beginLogin(options)),
|
|
43
|
+
completeLogin: (callbackUrl) => runPromise(runtime, session.completeLogin(callbackUrl)),
|
|
44
|
+
getAccessToken: () => runPromise(runtime, session.getAccessToken),
|
|
45
|
+
getState: session.getState,
|
|
46
|
+
logout: () => runPromise(runtime, session.logout),
|
|
47
|
+
reauthorize: (options) => runPromise(runtime, session.reauthorize(options)),
|
|
48
|
+
subscribe: session.subscribe
|
|
65
49
|
};
|
|
66
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* Browser federated sign-in with PKCE; the access token stays in memory. A
|
|
53
|
+
* bad option throws `FederatedAuthError` `configuration_error`. Methods
|
|
54
|
+
* reject with `FederatedAuthError`, or with `CiTransportError` when the
|
|
55
|
+
* tenant cannot be reached. `close` disposes the runtime of the client.
|
|
56
|
+
*/
|
|
67
57
|
const createFederatedAuth = (options) => {
|
|
68
|
-
const
|
|
69
|
-
const redirectUri = asUrl(options.redirectUri, "redirectUri");
|
|
70
|
-
const crypto = options.crypto ?? globalThis.crypto;
|
|
71
|
-
const fetch = options.fetch ?? globalThis.fetch;
|
|
72
|
-
const now = options.now ?? Date.now;
|
|
73
|
-
const storage = options.sessionStorage ?? globalThis.sessionStorage;
|
|
74
|
-
const navigate = options.navigate ?? ((url) => {
|
|
75
|
-
const { location } = globalThis;
|
|
76
|
-
if (!location || !("assign" in location) || typeof location.assign !== "function") throw new FederatedAuthError("configuration_error", "Provide navigate when browser navigation is unavailable");
|
|
77
|
-
location.assign(url);
|
|
78
|
-
});
|
|
79
|
-
const storageKey = `ci:federated-auth:${redirectUri.origin}:${options.clientId}`;
|
|
80
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
81
|
-
let state = { status: "anonymous" };
|
|
82
|
-
let token;
|
|
83
|
-
let completion;
|
|
84
|
-
let rememberedReturnTo;
|
|
85
|
-
if (options.clientId.length === 0 || options.scopes.length === 0) throw new FederatedAuthError("configuration_error", "clientId and at least one scope are required");
|
|
86
|
-
if (crypto === void 0 || storage === void 0 || fetch === void 0) throw new FederatedAuthError("configuration_error", "Browser crypto, fetch, and sessionStorage are required");
|
|
87
|
-
const transition = (next) => {
|
|
88
|
-
state = next;
|
|
89
|
-
for (const listener of listeners) listener(next);
|
|
90
|
-
};
|
|
91
|
-
const fail = (error) => {
|
|
92
|
-
token = void 0;
|
|
93
|
-
transition({
|
|
94
|
-
error,
|
|
95
|
-
status: "error"
|
|
96
|
-
});
|
|
97
|
-
throw error;
|
|
98
|
-
};
|
|
99
|
-
const beginLogin = async ({ returnTo }) => {
|
|
100
|
-
const normalizedReturnTo = normalizedReturnTarget(returnTo, redirectUri.origin);
|
|
101
|
-
rememberedReturnTo = normalizedReturnTo;
|
|
102
|
-
const pkce = await createPkcePair(crypto);
|
|
103
|
-
const transaction = {
|
|
104
|
-
expiresAt: now() + transactionLifetimeMs,
|
|
105
|
-
returnTo: normalizedReturnTo,
|
|
106
|
-
state: createOauthRandomValue(crypto),
|
|
107
|
-
verifier: pkce.verifier
|
|
108
|
-
};
|
|
109
|
-
storage.setItem(storageKey, JSON.stringify(transaction));
|
|
110
|
-
const authorizationUrl = new URL("/oauth/authorize", tenantUrl);
|
|
111
|
-
authorizationUrl.searchParams.set("client_id", options.clientId);
|
|
112
|
-
authorizationUrl.searchParams.set("redirect_uri", redirectUri.href);
|
|
113
|
-
authorizationUrl.searchParams.set("response_type", "code");
|
|
114
|
-
authorizationUrl.searchParams.set("scope", options.scopes.join(" "));
|
|
115
|
-
authorizationUrl.searchParams.set("state", transaction.state);
|
|
116
|
-
authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
|
|
117
|
-
authorizationUrl.searchParams.set("code_challenge_method", pkce.method);
|
|
118
|
-
token = void 0;
|
|
119
|
-
completion = void 0;
|
|
120
|
-
transition({ status: "redirecting" });
|
|
121
|
-
navigate(authorizationUrl.href);
|
|
122
|
-
return authorizationUrl.href;
|
|
123
|
-
};
|
|
124
|
-
const complete = async (callbackUrl) => {
|
|
125
|
-
let callback;
|
|
126
|
-
try {
|
|
127
|
-
callback = asUrl(callbackUrl, "callbackUrl");
|
|
128
|
-
} catch {
|
|
129
|
-
storage.removeItem(storageKey);
|
|
130
|
-
return fail(new FederatedAuthError("invalid_callback", "The callback URL is invalid"));
|
|
131
|
-
}
|
|
132
|
-
if (callback.origin !== redirectUri.origin || callback.pathname !== redirectUri.pathname) {
|
|
133
|
-
storage.removeItem(storageKey);
|
|
134
|
-
return fail(new FederatedAuthError("invalid_callback", "The callback URL does not match redirectUri"));
|
|
135
|
-
}
|
|
136
|
-
const serialized = storage.getItem(storageKey);
|
|
137
|
-
storage.removeItem(storageKey);
|
|
138
|
-
if (serialized === null) return fail(new FederatedAuthError("invalid_state", "No login transaction exists"));
|
|
139
|
-
let transaction;
|
|
140
|
-
try {
|
|
141
|
-
transaction = parseTransaction(serialized);
|
|
142
|
-
} catch (error) {
|
|
143
|
-
return fail(error instanceof FederatedAuthError ? error : new FederatedAuthError("invalid_state", "Invalid login transaction"));
|
|
144
|
-
}
|
|
145
|
-
if (transaction.expiresAt <= now()) return fail(new FederatedAuthError("transaction_expired", "The login transaction expired"));
|
|
146
|
-
if (callback.searchParams.get("state") !== transaction.state) return fail(new FederatedAuthError("invalid_state", "OAuth state mismatch"));
|
|
147
|
-
const authorizationError = callback.searchParams.get("error");
|
|
148
|
-
const code = callback.searchParams.get("code");
|
|
149
|
-
if (authorizationError !== null || code === null || code.length === 0) return fail(new FederatedAuthError("authorization_failed", authorizationError ?? "The callback did not include a code"));
|
|
150
|
-
const body = new URLSearchParams({
|
|
151
|
-
client_id: options.clientId,
|
|
152
|
-
code,
|
|
153
|
-
code_verifier: transaction.verifier,
|
|
154
|
-
grant_type: "authorization_code",
|
|
155
|
-
redirect_uri: redirectUri.href
|
|
156
|
-
});
|
|
157
|
-
const response = await fetch(new URL("/oauth/token", tenantUrl), {
|
|
158
|
-
body,
|
|
159
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
160
|
-
method: "POST"
|
|
161
|
-
});
|
|
162
|
-
if (!response.ok) return fail(new FederatedAuthError("token_exchange_failed", "The authorization code exchange failed"));
|
|
163
|
-
try {
|
|
164
|
-
const tokenResponse = await response.json();
|
|
165
|
-
if (!(tokenResponse instanceof Object)) throw new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token");
|
|
166
|
-
const payload = {
|
|
167
|
-
access_token: Object.entries(tokenResponse).find(([key]) => key === "access_token")?.[1],
|
|
168
|
-
expires_in: Object.entries(tokenResponse).find(([key]) => key === "expires_in")?.[1],
|
|
169
|
-
token_type: Object.entries(tokenResponse).find(([key]) => key === "token_type")?.[1]
|
|
170
|
-
};
|
|
171
|
-
token = parseToken(payload, now());
|
|
172
|
-
} catch (error) {
|
|
173
|
-
return fail(error instanceof FederatedAuthError ? error : new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token"));
|
|
174
|
-
}
|
|
175
|
-
transition({
|
|
176
|
-
expiresAt: token.expiresAt,
|
|
177
|
-
status: "authenticated"
|
|
178
|
-
});
|
|
179
|
-
rememberedReturnTo = transaction.returnTo;
|
|
180
|
-
return { returnTo: transaction.returnTo };
|
|
181
|
-
};
|
|
182
|
-
const reauthorize = async (input) => {
|
|
183
|
-
const returnTo = input?.returnTo ?? rememberedReturnTo;
|
|
184
|
-
if (returnTo === void 0) throw new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login");
|
|
185
|
-
return await beginLogin({ returnTo });
|
|
186
|
-
};
|
|
58
|
+
const runtime = ManagedRuntime.make(layerFederated(options));
|
|
187
59
|
return {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
if (completion !== void 0) return await completion;
|
|
191
|
-
const current = complete(callbackUrl);
|
|
192
|
-
completion = current;
|
|
193
|
-
const retire = async () => {
|
|
194
|
-
try {
|
|
195
|
-
await current;
|
|
196
|
-
} catch {} finally {
|
|
197
|
-
if (completion === current) completion = void 0;
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
retire();
|
|
201
|
-
return await current;
|
|
202
|
-
},
|
|
203
|
-
getAccessToken: async () => {
|
|
204
|
-
if (token !== void 0 && token.expiresAt <= now()) {
|
|
205
|
-
token = void 0;
|
|
206
|
-
transition({ status: "expired" });
|
|
207
|
-
await reauthorize();
|
|
208
|
-
throw new FederatedAuthError("reauthorization_required", "A new CI login is required");
|
|
209
|
-
}
|
|
210
|
-
if (token === void 0) throw new FederatedAuthError("reauthorization_required", "A new CI login is required");
|
|
211
|
-
return token.accessToken;
|
|
212
|
-
},
|
|
213
|
-
getState: () => state,
|
|
214
|
-
logout: async () => {
|
|
215
|
-
const accessToken = token?.accessToken;
|
|
216
|
-
token = void 0;
|
|
217
|
-
completion = void 0;
|
|
218
|
-
rememberedReturnTo = void 0;
|
|
219
|
-
storage.removeItem(storageKey);
|
|
220
|
-
transition({ status: "anonymous" });
|
|
221
|
-
if (accessToken !== void 0) try {
|
|
222
|
-
await fetch(new URL("/oauth/logout", tenantUrl), {
|
|
223
|
-
headers: { authorization: `Bearer ${accessToken}` },
|
|
224
|
-
method: "POST"
|
|
225
|
-
});
|
|
226
|
-
} catch {}
|
|
227
|
-
},
|
|
228
|
-
reauthorize,
|
|
229
|
-
subscribe: (listener) => {
|
|
230
|
-
listeners.add(listener);
|
|
231
|
-
return () => {
|
|
232
|
-
listeners.delete(listener);
|
|
233
|
-
};
|
|
234
|
-
}
|
|
60
|
+
...authFacade(runtime),
|
|
61
|
+
close: () => runtime.dispose()
|
|
235
62
|
};
|
|
236
63
|
};
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
};
|
|
245
|
-
const asRecord$2 = (value) => {
|
|
246
|
-
if (typeof value !== "object" || value === null) return null;
|
|
247
|
-
return value;
|
|
248
|
-
};
|
|
249
|
-
const readString$1 = (record, key) => {
|
|
250
|
-
const candidate = record[key];
|
|
251
|
-
return typeof candidate === "string" ? candidate : null;
|
|
252
|
-
};
|
|
253
|
-
const readStrings = (record, key) => {
|
|
254
|
-
const candidate = record[key];
|
|
255
|
-
if (!Array.isArray(candidate)) return null;
|
|
256
|
-
const items = candidate;
|
|
257
|
-
return items.every((item) => typeof item === "string") ? items : null;
|
|
258
|
-
};
|
|
259
|
-
const readKind = (record) => {
|
|
260
|
-
const { kind } = record;
|
|
261
|
-
return kind === "member" || kind === "external_app_user" ? kind : null;
|
|
262
|
-
};
|
|
263
|
-
const parseIdentity = (value) => {
|
|
264
|
-
const identity = asRecord$2(asRecord$2(value)?.identity);
|
|
265
|
-
if (identity === null) return null;
|
|
266
|
-
const appId = readString$1(identity, "appId");
|
|
267
|
-
const appPermissions = readStrings(identity, "appPermissions");
|
|
268
|
-
const kind = readKind(identity);
|
|
269
|
-
const organizationId = readString$1(identity, "organizationId");
|
|
270
|
-
const roles = readStrings(identity, "roles");
|
|
271
|
-
const userId = readString$1(identity, "userId");
|
|
272
|
-
if (appId === null || appPermissions === null || kind === null || organizationId === null || roles === null || userId === null) return null;
|
|
64
|
+
/**
|
|
65
|
+
* Browser session client for a sealed-cookie BFF. The access token never
|
|
66
|
+
* leaves the server. A bad option throws `FederatedAuthError`
|
|
67
|
+
* `configuration_error`. `close` disposes the runtime of the client.
|
|
68
|
+
*/
|
|
69
|
+
const createServerSessionAuth = (options) => {
|
|
70
|
+
const runtime = ManagedRuntime.make(layerServerSession(options));
|
|
273
71
|
return {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
email: readString$1(identity, "email"),
|
|
277
|
-
kind,
|
|
278
|
-
name: readString$1(identity, "name"),
|
|
279
|
-
organizationId,
|
|
280
|
-
roles,
|
|
281
|
-
userId
|
|
72
|
+
...authFacade(runtime),
|
|
73
|
+
close: () => runtime.dispose()
|
|
282
74
|
};
|
|
283
75
|
};
|
|
284
|
-
/**
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
for (const listener of listeners) listener(next);
|
|
303
|
-
};
|
|
304
|
-
const refresh = async () => {
|
|
305
|
-
const response = await fetch(`${origin}${basePath}/session`, {
|
|
306
|
-
credentials: "same-origin",
|
|
307
|
-
headers: { accept: "application/json" }
|
|
308
|
-
});
|
|
309
|
-
if (response.status === 401) {
|
|
310
|
-
transition({ status: "anonymous" });
|
|
311
|
-
return state;
|
|
312
|
-
}
|
|
313
|
-
if (!response.ok) {
|
|
314
|
-
const error = new FederatedAuthError("authorization_failed", "The application session could not be read");
|
|
315
|
-
transition({
|
|
316
|
-
error,
|
|
317
|
-
status: "error"
|
|
318
|
-
});
|
|
319
|
-
return state;
|
|
320
|
-
}
|
|
321
|
-
const payload = await response.json();
|
|
322
|
-
const record = asRecord$2(payload);
|
|
323
|
-
const expiresAt = record === null ? null : parseExpiresAt(record.expiresAt);
|
|
324
|
-
const identity = parseIdentity(payload);
|
|
325
|
-
if (expiresAt === null || identity === null) {
|
|
326
|
-
const error = new FederatedAuthError("authorization_failed", "The application session is invalid");
|
|
327
|
-
transition({
|
|
328
|
-
error,
|
|
329
|
-
status: "error"
|
|
330
|
-
});
|
|
331
|
-
return state;
|
|
332
|
-
}
|
|
333
|
-
if (expiresAt <= now()) {
|
|
334
|
-
transition({ status: "expired" });
|
|
335
|
-
return state;
|
|
336
|
-
}
|
|
337
|
-
transition({
|
|
338
|
-
expiresAt,
|
|
339
|
-
identity,
|
|
340
|
-
status: "authenticated"
|
|
341
|
-
});
|
|
342
|
-
return state;
|
|
343
|
-
};
|
|
344
|
-
const beginLogin = ({ returnTo }) => {
|
|
345
|
-
rememberedReturnTo = returnTo;
|
|
346
|
-
const url = `${origin}${basePath}/login?returnTo=${encodeURIComponent(returnTo)}`;
|
|
347
|
-
transition({ status: "redirecting" });
|
|
348
|
-
navigate(url);
|
|
349
|
-
return Promise.resolve(url);
|
|
350
|
-
};
|
|
351
|
-
const complete = async () => {
|
|
352
|
-
await refresh();
|
|
353
|
-
if (state.status === "error") throw state.error;
|
|
354
|
-
return { returnTo: rememberedReturnTo ?? "/" };
|
|
355
|
-
};
|
|
356
|
-
const reauthorize = async (input) => {
|
|
357
|
-
const returnTo = input?.returnTo ?? rememberedReturnTo;
|
|
358
|
-
if (returnTo === void 0) throw new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login");
|
|
359
|
-
return await beginLogin({ returnTo });
|
|
360
|
-
};
|
|
76
|
+
/**
|
|
77
|
+
* The `.` facade of run follow (`./service`). The source and the options
|
|
78
|
+
* keep their Promise forms; `now` and `sleep` become the `Clock` of the
|
|
79
|
+
* follow.
|
|
80
|
+
*/
|
|
81
|
+
/** A read of the source; a rejection is a transport failure. */
|
|
82
|
+
const read = (call) => Effect.tryPromise({
|
|
83
|
+
catch: (cause) => cause instanceof CiTransportError ? cause : new CiTransportError({ cause }),
|
|
84
|
+
try: call
|
|
85
|
+
}).pipe(Effect.map(toCiResult));
|
|
86
|
+
const sourceOf = (runs) => ({
|
|
87
|
+
get: (input) => read(() => runs.get(input)),
|
|
88
|
+
stream: (input) => read(() => runs.stream(input))
|
|
89
|
+
});
|
|
90
|
+
/** Internal. The live `Clock`, except that it reads `now` and sleeps on `sleep`. */
|
|
91
|
+
const clockOf$1 = (options) => {
|
|
92
|
+
const live = Clock.Clock.defaultValue();
|
|
93
|
+
const { now, sleep } = options;
|
|
361
94
|
return {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
await current;
|
|
370
|
-
} catch {} finally {
|
|
371
|
-
if (completion === current) completion = void 0;
|
|
372
|
-
}
|
|
373
|
-
};
|
|
374
|
-
retire();
|
|
375
|
-
return await current;
|
|
376
|
-
},
|
|
377
|
-
getAccessToken: () => Promise.reject(new FederatedAuthError("reauthorization_required", "The CI access token stays on the application server")),
|
|
378
|
-
getState: () => state,
|
|
379
|
-
logout: async () => {
|
|
380
|
-
rememberedReturnTo = void 0;
|
|
381
|
-
completion = void 0;
|
|
382
|
-
try {
|
|
383
|
-
await fetch(`${origin}${basePath}/logout`, {
|
|
384
|
-
credentials: "same-origin",
|
|
385
|
-
method: "POST"
|
|
386
|
-
});
|
|
387
|
-
} catch {}
|
|
388
|
-
transition({ status: "anonymous" });
|
|
389
|
-
},
|
|
390
|
-
reauthorize,
|
|
391
|
-
subscribe: (listener) => {
|
|
392
|
-
listeners.add(listener);
|
|
393
|
-
return () => {
|
|
394
|
-
listeners.delete(listener);
|
|
395
|
-
};
|
|
396
|
-
}
|
|
95
|
+
currentTimeMillis: now === void 0 ? live.currentTimeMillis : Effect.sync(now),
|
|
96
|
+
currentTimeMillisUnsafe: now ?? (() => live.currentTimeMillisUnsafe()),
|
|
97
|
+
currentTimeNanos: live.currentTimeNanos,
|
|
98
|
+
currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe(),
|
|
99
|
+
monotonicTimeNanos: live.monotonicTimeNanos,
|
|
100
|
+
monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(),
|
|
101
|
+
sleep: (duration) => sleep === void 0 ? live.sleep(duration) : Effect.promise(() => sleep(Duration.toMillis(duration)))
|
|
397
102
|
};
|
|
398
103
|
};
|
|
399
104
|
/**
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
105
|
+
* Follows dedicated run events until a terminal event or snapshot status.
|
|
106
|
+
* Resolves with the last event page read. A failed read rejects with its
|
|
107
|
+
* `CiError`; a source that rejects gives `CiTransportError`; an abort
|
|
108
|
+
* rejects with `signal.reason`.
|
|
403
109
|
*/
|
|
404
|
-
const
|
|
405
|
-
const DEFAULT_IDLE_MS = 50;
|
|
406
|
-
const MAX_BACKOFF_IDLE_MS = 1e3;
|
|
407
|
-
const terminalEventKinds = /* @__PURE__ */ new Set([
|
|
408
|
-
"cancelled",
|
|
409
|
-
"completed",
|
|
410
|
-
"failed"
|
|
411
|
-
]);
|
|
412
|
-
const terminalSnapshotStatuses = /* @__PURE__ */ new Set([
|
|
413
|
-
"cancelled",
|
|
414
|
-
"failed",
|
|
415
|
-
"succeeded"
|
|
416
|
-
]);
|
|
417
|
-
const asRecord$1 = (value) => {
|
|
418
|
-
if (typeof value !== "object" || value === null) return null;
|
|
419
|
-
return value;
|
|
420
|
-
};
|
|
421
|
-
const readString = (record, key) => {
|
|
422
|
-
const candidate = record[key];
|
|
423
|
-
return typeof candidate === "string" ? candidate : null;
|
|
424
|
-
};
|
|
425
|
-
const snapshotStatus = (value) => {
|
|
426
|
-
const record = asRecord$1(value);
|
|
427
|
-
if (record === null) return null;
|
|
428
|
-
const nested = asRecord$1(record.result);
|
|
429
|
-
return readString(record, "status") ?? (nested === null ? null : readString(nested, "status"));
|
|
430
|
-
};
|
|
431
|
-
const eventKind = (event) => {
|
|
432
|
-
const record = asRecord$1(event);
|
|
433
|
-
return record === null ? null : readString(record, "kind");
|
|
434
|
-
};
|
|
435
|
-
const idle$1 = async (ms, sleep, signal) => {
|
|
436
|
-
if (ms <= 0 || signal?.aborted === true) return;
|
|
437
|
-
if (sleep !== void 0) {
|
|
438
|
-
await sleep(ms);
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
const cleanup = new AbortController();
|
|
442
|
-
try {
|
|
443
|
-
await new Promise((resolve) => {
|
|
444
|
-
const timeout = setTimeout(resolve, ms);
|
|
445
|
-
signal?.addEventListener("abort", () => {
|
|
446
|
-
clearTimeout(timeout);
|
|
447
|
-
resolve();
|
|
448
|
-
}, {
|
|
449
|
-
once: true,
|
|
450
|
-
signal: cleanup.signal
|
|
451
|
-
});
|
|
452
|
-
});
|
|
453
|
-
} finally {
|
|
454
|
-
cleanup.abort();
|
|
455
|
-
}
|
|
456
|
-
};
|
|
457
|
-
const isTerminalEvent = (event) => {
|
|
458
|
-
const kind = eventKind(event);
|
|
459
|
-
return kind !== null && terminalEventKinds.has(kind);
|
|
460
|
-
};
|
|
110
|
+
const followRun = (runs, options) => runPromise(Effect, followSource(sourceOf(runs), options).pipe(Effect.provideService(Clock.Clock, clockOf$1(options))), options.signal);
|
|
461
111
|
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
112
|
+
* Internal. The Vanilla Facade of `CiClient.executeResult`: a
|
|
113
|
+
* `TypedOperationExecutor` whose calls run in `runtime`. A CI error answer
|
|
114
|
+
* resolves `{ ok: false, error }` with a `CiError`; a transport failure
|
|
115
|
+
* rejects with `CiTransportError`; an abort rejects with `signal.reason`.
|
|
464
116
|
*/
|
|
465
|
-
const
|
|
466
|
-
let last = page;
|
|
467
|
-
while (last.nextCursor !== null && !last.events.some(isTerminalEvent)) {
|
|
468
|
-
options.signal?.throwIfAborted();
|
|
469
|
-
const next = await runs.stream({
|
|
470
|
-
afterCursor: last.nextCursor,
|
|
471
|
-
runId: options.runId
|
|
472
|
-
});
|
|
473
|
-
if (!next.ok) throw new Error(next.error.message);
|
|
474
|
-
if (next.value.events.length === 0) return last;
|
|
475
|
-
last = next.value;
|
|
476
|
-
}
|
|
477
|
-
return last;
|
|
478
|
-
};
|
|
117
|
+
const executorFacade = (runtime) => ({ execute: (operationId, input, options) => runPromise(runtime, CiClient.use((client) => client.executeResult(operationId, input, options ?? { organizationId: "" })), options?.signal) });
|
|
479
118
|
/**
|
|
480
|
-
*
|
|
481
|
-
*
|
|
119
|
+
* The `.` facade of the CI client: `createClient` keeps its domains and
|
|
120
|
+
* types over `CiClient` and `Runs` (`./transports/service`,
|
|
121
|
+
* `./runs/service`), in a runtime of its own.
|
|
482
122
|
*/
|
|
483
|
-
const followRun = async (runs, options) => {
|
|
484
|
-
const deadlineMs = options.deadlineMs ?? 6e5;
|
|
485
|
-
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
486
|
-
const maxIdleMs = Math.max(idleMs, MAX_BACKOFF_IDLE_MS);
|
|
487
|
-
const now = options.now ?? Date.now;
|
|
488
|
-
const deadline = now() + deadlineMs;
|
|
489
|
-
let afterCursor;
|
|
490
|
-
let emptyPolls = 0;
|
|
491
|
-
while (now() < deadline) {
|
|
492
|
-
options.signal?.throwIfAborted();
|
|
493
|
-
const snapshot = await runs.get({ runId: options.runId });
|
|
494
|
-
if (!snapshot.ok) throw new Error(snapshot.error.message);
|
|
495
|
-
const page = await runs.stream(afterCursor === void 0 ? { runId: options.runId } : {
|
|
496
|
-
afterCursor,
|
|
497
|
-
runId: options.runId
|
|
498
|
-
});
|
|
499
|
-
if (!page.ok) throw new Error(page.error.message);
|
|
500
|
-
if (page.value.events.some(isTerminalEvent)) return page.value;
|
|
501
|
-
const status = snapshotStatus(snapshot.value);
|
|
502
|
-
if (status !== null && terminalSnapshotStatuses.has(status)) return await readRemainingPages(runs, options, page.value);
|
|
503
|
-
if (page.value.nextCursor !== null) afterCursor = page.value.nextCursor;
|
|
504
|
-
emptyPolls = page.value.events.length === 0 ? emptyPolls + 1 : 0;
|
|
505
|
-
await idle$1(Math.min(idleMs * 2 ** emptyPolls, maxIdleMs), options.sleep, options.signal);
|
|
506
|
-
}
|
|
507
|
-
throw new Error("Run did not finish");
|
|
508
|
-
};
|
|
509
123
|
const clientSdkProtocolVersion = "v1";
|
|
510
124
|
const executionOptions = (organizationId, options) => options?.signal === void 0 ? { organizationId } : {
|
|
511
125
|
organizationId,
|
|
@@ -516,7 +130,8 @@ const rootOperation = (transport, operationId) => async (input, options) => {
|
|
|
516
130
|
const { organizationId, ...wireInput } = input;
|
|
517
131
|
return await transport.execute(operationId, wireInput, executionOptions(organizationId, options));
|
|
518
132
|
};
|
|
519
|
-
const domains = (
|
|
133
|
+
const domains = (runtime, organizationId) => {
|
|
134
|
+
const transport = executorFacade(runtime);
|
|
520
135
|
const operation = (operationId) => organizationId === void 0 ? rootOperation(transport, operationId) : scopedOperation(transport, organizationId, operationId);
|
|
521
136
|
return {
|
|
522
137
|
agents: {
|
|
@@ -546,10 +161,10 @@ const domains = (transport, organizationId) => {
|
|
|
546
161
|
follow: (async (options) => {
|
|
547
162
|
const orgId = organizationId ?? options.organizationId;
|
|
548
163
|
if (orgId === void 0 || orgId.length === 0) throw new TypeError("organizationId is required");
|
|
549
|
-
return await
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
}, options);
|
|
164
|
+
return await runPromise(runtime, Runs.use((runs) => runs.follow({
|
|
165
|
+
...options,
|
|
166
|
+
organizationId: orgId
|
|
167
|
+
})).pipe(Effect.provideService(Clock.Clock, clockOf$1(options))), options.signal);
|
|
553
168
|
}),
|
|
554
169
|
get: operation("runs_get"),
|
|
555
170
|
stream: operation("runs_stream")
|
|
@@ -564,12 +179,16 @@ const domains = (transport, organizationId) => {
|
|
|
564
179
|
}
|
|
565
180
|
};
|
|
566
181
|
};
|
|
567
|
-
|
|
568
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Internal. The client facade of the `CiClient` and `Runs` in `runtime`;
|
|
184
|
+
* the delegated runtime shares its own runtime with it.
|
|
185
|
+
*/
|
|
186
|
+
const clientFacade = (runtime) => {
|
|
187
|
+
const publicDomains = domains(runtime);
|
|
569
188
|
const forOrganization = (organizationId) => {
|
|
570
189
|
if (organizationId.length === 0) throw new TypeError("organizationId is required");
|
|
571
190
|
return {
|
|
572
|
-
...domains(
|
|
191
|
+
...domains(runtime, organizationId),
|
|
573
192
|
organizationId
|
|
574
193
|
};
|
|
575
194
|
};
|
|
@@ -579,511 +198,98 @@ const createClient = (options) => {
|
|
|
579
198
|
...publicDomains.context,
|
|
580
199
|
forOrganization
|
|
581
200
|
},
|
|
582
|
-
execute:
|
|
201
|
+
execute: executorFacade(runtime).execute,
|
|
583
202
|
forOrganization,
|
|
584
203
|
protocolVersion: "v1"
|
|
585
204
|
};
|
|
586
205
|
};
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
case "authenticated":
|
|
601
|
-
if (state.identity === void 0) return {
|
|
602
|
-
message: "The application session is invalid",
|
|
603
|
-
status: "unavailable"
|
|
604
|
-
};
|
|
605
|
-
return {
|
|
606
|
-
expiresAt: new Date(state.expiresAt).toISOString(),
|
|
607
|
-
identity: state.identity,
|
|
608
|
-
status: "authenticated"
|
|
609
|
-
};
|
|
610
|
-
case "expired": return { status: "expired" };
|
|
611
|
-
case "error": return {
|
|
612
|
-
message: state.error.message,
|
|
613
|
-
status: "unavailable"
|
|
614
|
-
};
|
|
615
|
-
default: return { status: "anonymous" };
|
|
616
|
-
}
|
|
206
|
+
/**
|
|
207
|
+
* The Vanilla Facade of `CiClient` and `Runs` over `transport`, in one
|
|
208
|
+
* runtime; `close` disposes it. A CI error answer resolves
|
|
209
|
+
* `{ ok: false, error }` with a `CiError`; `runs.follow` rejects with it. A
|
|
210
|
+
* transport failure rejects with `CiTransportError`, an abort with
|
|
211
|
+
* `signal.reason`.
|
|
212
|
+
*/
|
|
213
|
+
const createClient = (options) => {
|
|
214
|
+
const runtime = ManagedRuntime.make(layer.pipe(Layer.provideMerge(layerFromExecutor(options.transport))));
|
|
215
|
+
return {
|
|
216
|
+
...clientFacade(runtime),
|
|
217
|
+
close: () => runtime.dispose()
|
|
218
|
+
};
|
|
617
219
|
};
|
|
618
|
-
/**
|
|
220
|
+
/**
|
|
221
|
+
* The `.` facade of the delegated runtime (`./service`). Its `client`,
|
|
222
|
+
* `auth` and `sessionAuth` are facades over the same runtime.
|
|
223
|
+
*/
|
|
224
|
+
/**
|
|
225
|
+
* Browser runtime for a sealed-cookie BFF: session identity, proxy client,
|
|
226
|
+
* and run follow, in one runtime; `close` disposes it, also for `client` and
|
|
227
|
+
* `auth`. `followRun` rejects with the `CiError` of a failed read, and with
|
|
228
|
+
* `FederatedAuthError` `reauthorization_required` without a session.
|
|
229
|
+
*/
|
|
619
230
|
const createDelegatedApplicationRuntime = (options) => {
|
|
620
|
-
const
|
|
621
|
-
const
|
|
622
|
-
const
|
|
623
|
-
const
|
|
624
|
-
basePath: authBasePath,
|
|
625
|
-
fetch,
|
|
626
|
-
...options.navigate && { navigate: options.navigate },
|
|
627
|
-
origin: options.origin
|
|
628
|
-
});
|
|
629
|
-
const client = createClient({ transport: createProxyTransport({
|
|
630
|
-
authentication: {
|
|
631
|
-
credentials: "same-origin",
|
|
632
|
-
mode: "server_delegated"
|
|
633
|
-
},
|
|
634
|
-
fetch,
|
|
635
|
-
path: proxyPath,
|
|
636
|
-
serverUrl: options.origin
|
|
637
|
-
}) });
|
|
638
|
-
let state = { status: "checking" };
|
|
639
|
-
let generation = 0;
|
|
640
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
641
|
-
const publish = (next) => {
|
|
642
|
-
state = next;
|
|
643
|
-
for (const notify of listeners) notify();
|
|
644
|
-
};
|
|
645
|
-
const subscribe = (notify) => {
|
|
646
|
-
listeners.add(notify);
|
|
647
|
-
return () => {
|
|
648
|
-
listeners.delete(notify);
|
|
649
|
-
};
|
|
650
|
-
};
|
|
651
|
-
const refresh = async () => {
|
|
652
|
-
generation += 1;
|
|
653
|
-
const current = generation;
|
|
654
|
-
publish({ status: "checking" });
|
|
655
|
-
try {
|
|
656
|
-
await sessionAuth.completeLogin(`${options.origin}${authBasePath}/callback`);
|
|
657
|
-
if (current !== generation) return;
|
|
658
|
-
publish(mapAuthState(sessionAuth.getState()));
|
|
659
|
-
} catch (error) {
|
|
660
|
-
if (current === generation) publish({
|
|
661
|
-
message: error instanceof Error ? error.message : "CI session verification is unavailable",
|
|
662
|
-
status: "unavailable"
|
|
663
|
-
});
|
|
664
|
-
}
|
|
665
|
-
};
|
|
666
|
-
const login = async (returnTo) => {
|
|
667
|
-
generation += 1;
|
|
668
|
-
publish({ status: "anonymous" });
|
|
669
|
-
await sessionAuth.beginLogin({ returnTo });
|
|
670
|
-
};
|
|
671
|
-
const initialize = async (url) => {
|
|
672
|
-
await refresh();
|
|
673
|
-
if (state.status === "authenticated") return;
|
|
674
|
-
if (state.status === "anonymous" || state.status === "expired") await login(url);
|
|
675
|
-
};
|
|
676
|
-
const logout = async () => {
|
|
677
|
-
generation += 1;
|
|
678
|
-
await sessionAuth.logout();
|
|
679
|
-
publish({ status: "anonymous" });
|
|
680
|
-
};
|
|
681
|
-
const followRun = async (runId) => {
|
|
682
|
-
if (state.status !== "authenticated") throw new Error("A CI session is required to follow a run");
|
|
683
|
-
return await client.forOrganization(state.identity.organizationId).runs.follow({ runId });
|
|
684
|
-
};
|
|
231
|
+
const runtime = ManagedRuntime.make(layer$1(options));
|
|
232
|
+
const session = runtime.runSync(DelegatedRuntime);
|
|
233
|
+
const sessionAuth = authFacade(runtime);
|
|
234
|
+
const client = clientFacade(runtime);
|
|
685
235
|
const auth = sessionAuth;
|
|
686
236
|
return {
|
|
687
237
|
applicationId: options.applicationId,
|
|
688
238
|
auth,
|
|
689
239
|
client,
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
240
|
+
close: () => runtime.dispose(),
|
|
241
|
+
followRun: (runId) => runPromise(runtime, session.followRun(runId)),
|
|
242
|
+
getSnapshot: session.getSnapshot,
|
|
243
|
+
initialize: (url) => runPromise(runtime, session.initialize(url)),
|
|
244
|
+
login: (returnTo) => runPromise(runtime, session.login(returnTo)),
|
|
245
|
+
logout: () => runPromise(runtime, session.logout),
|
|
246
|
+
refresh: () => runPromise(runtime, session.refresh),
|
|
696
247
|
sessionAuth,
|
|
697
|
-
subscribe
|
|
248
|
+
subscribe: session.subscribe
|
|
698
249
|
};
|
|
699
250
|
};
|
|
700
|
-
const asRecord = (value) => {
|
|
701
|
-
if (typeof value !== "object" || value === null) return null;
|
|
702
|
-
return value;
|
|
703
|
-
};
|
|
704
|
-
const readRunId = (value) => {
|
|
705
|
-
const payload = asRecord(value);
|
|
706
|
-
const runId = payload === null ? null : payload.runId;
|
|
707
|
-
return typeof runId === "string" ? runId : null;
|
|
708
|
-
};
|
|
709
|
-
/** Posts a Fixed workflow BFF route and returns the admitted run id. */
|
|
710
|
-
const createFixedWorkflowClient = (options) => {
|
|
711
|
-
const fetch = options.fetch ?? globalThis.fetch;
|
|
712
|
-
return { invoke: async (input) => {
|
|
713
|
-
const response = await fetch(options.url(input), {
|
|
714
|
-
body: JSON.stringify(options.body === void 0 ? input : options.body(input)),
|
|
715
|
-
credentials: "same-origin",
|
|
716
|
-
headers: {
|
|
717
|
-
"content-type": "application/json",
|
|
718
|
-
"x-idempotency-key": crypto.randomUUID()
|
|
719
|
-
},
|
|
720
|
-
method: "POST"
|
|
721
|
-
});
|
|
722
|
-
const payload = await response.json();
|
|
723
|
-
const runId = readRunId(payload);
|
|
724
|
-
if (!response.ok || runId === null) throw new Error("Fixed workflow did not return a run id");
|
|
725
|
-
return { runId };
|
|
726
|
-
} };
|
|
727
|
-
};
|
|
728
|
-
const nextStreamCursor = (page) => page.nextCursor;
|
|
729
|
-
const createDirectTransport = (options) => {
|
|
730
|
-
const tenantUrl = parseOriginUrl(options.tenantUrl, "tenantUrl");
|
|
731
|
-
return createHttpOperationTransport({
|
|
732
|
-
authorization: options.auth.getAccessToken,
|
|
733
|
-
basePath: "/application/v1",
|
|
734
|
-
fetch: options.fetch ?? globalThis.fetch,
|
|
735
|
-
origin: tenantUrl
|
|
736
|
-
});
|
|
737
|
-
};
|
|
738
|
-
const emptyBlock = () => ({
|
|
739
|
-
comment: false,
|
|
740
|
-
data: [],
|
|
741
|
-
id: void 0,
|
|
742
|
-
type: ""
|
|
743
|
-
});
|
|
744
251
|
/**
|
|
745
|
-
*
|
|
746
|
-
* the server's pings are comments, and the client's watchdog needs them.
|
|
252
|
+
* The `.` facade of `FixedWorkflows` (`./service`), in a runtime of its own.
|
|
747
253
|
*/
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
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
|
-
};
|
|
254
|
+
/**
|
|
255
|
+
* Posts a Fixed workflow BFF route and returns the admitted run id. A
|
|
256
|
+
* refused invocation rejects with `CiError`; a route that cannot be reached
|
|
257
|
+
* rejects with `CiTransportError`. `close` disposes the runtime of the
|
|
258
|
+
* client.
|
|
259
|
+
*/
|
|
260
|
+
const createFixedWorkflowClient = (options) => {
|
|
261
|
+
const runtime = ManagedRuntime.make(layer$2(options.fetch === void 0 ? {} : { fetch: options.fetch }));
|
|
780
262
|
return {
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
},
|
|
787
|
-
/** The last `retry:` the stream sent, in milliseconds. */
|
|
788
|
-
retry: () => retry
|
|
263
|
+
close: () => runtime.dispose(),
|
|
264
|
+
invoke: (input) => runPromise(runtime, FixedWorkflows.use((workflows) => workflows.invoke({
|
|
265
|
+
body: options.body === void 0 ? input : options.body(input),
|
|
266
|
+
url: options.url(input)
|
|
267
|
+
})))
|
|
789
268
|
};
|
|
790
269
|
};
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
const
|
|
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
|
-
};
|
|
270
|
+
const nextStreamCursor = (page) => page.nextCursor;
|
|
271
|
+
/**
|
|
272
|
+
* The Vanilla Facade of `CiClient.layerDirect`, in a runtime of its own;
|
|
273
|
+
* `close` disposes it. A bad `tenantUrl` throws `TypeError`.
|
|
274
|
+
*/
|
|
275
|
+
const createDirectTransport = (options) => {
|
|
276
|
+
const runtime = ManagedRuntime.make(Layer.succeed(CiClient, make(makeHttpExecute(directHttpOptions(options)))));
|
|
921
277
|
return {
|
|
922
|
-
|
|
923
|
-
|
|
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
|
-
}
|
|
278
|
+
...executorFacade(runtime),
|
|
279
|
+
close: () => runtime.dispose()
|
|
936
280
|
};
|
|
937
281
|
};
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
282
|
+
/**
|
|
283
|
+
* The Vanilla Facade of `CiClient.layerProxy`, in a runtime of its own;
|
|
284
|
+
* `close` disposes it. A bad `serverUrl` or `path` throws `TypeError`.
|
|
285
|
+
*/
|
|
286
|
+
const createProxyTransport = (options) => {
|
|
287
|
+
const runtime = ManagedRuntime.make(Layer.succeed(CiClient, make(makeHttpExecute(proxyHttpOptions(options)))));
|
|
943
288
|
return {
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
retryMilliseconds,
|
|
947
|
-
type: "backoff"
|
|
948
|
-
}],
|
|
949
|
-
state: {
|
|
950
|
-
...shared(state),
|
|
951
|
-
attempt: state.attempt + 1,
|
|
952
|
-
phase: "backoff"
|
|
953
|
-
}
|
|
289
|
+
...executorFacade(runtime),
|
|
290
|
+
close: () => runtime.dispose()
|
|
954
291
|
};
|
|
955
292
|
};
|
|
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
293
|
/** Surfaces a listener's error without stopping the other listeners. */
|
|
1088
294
|
const report = (error) => {
|
|
1089
295
|
if ("reportError" in globalThis) {
|
|
@@ -1101,282 +307,166 @@ const notify = (listener) => {
|
|
|
1101
307
|
report(error);
|
|
1102
308
|
}
|
|
1103
309
|
};
|
|
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
310
|
const defaultTimers = { schedule: (callback, milliseconds) => {
|
|
1109
311
|
const handle = globalThis.setTimeout(callback, milliseconds);
|
|
1110
312
|
return () => globalThis.clearTimeout(handle);
|
|
1111
313
|
} };
|
|
314
|
+
/** The connection of one facade client, as its runtime holds it. */
|
|
315
|
+
var FacadeConnection = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/FacadeConnection") {};
|
|
1112
316
|
/**
|
|
1113
|
-
*
|
|
1114
|
-
*
|
|
1115
|
-
*
|
|
1116
|
-
*
|
|
1117
|
-
*
|
|
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.
|
|
317
|
+
* A scheduler that runs fiber tasks in the call stack of the facade. A task
|
|
318
|
+
* that a callback schedules outside every fiber runs at once; a task that a
|
|
319
|
+
* fiber schedules runs after it, when `flush` runs or in a microtask. Thus a
|
|
320
|
+
* facade call, a page event or a stream handler has its whole effect before
|
|
321
|
+
* it returns, as in the event loop that the service replaced.
|
|
1122
322
|
*/
|
|
1123
|
-
const
|
|
1124
|
-
const
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
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
|
-
});
|
|
323
|
+
const makeSyncScheduler = () => {
|
|
324
|
+
const tasks = [];
|
|
325
|
+
let flushing = false;
|
|
326
|
+
let flushQueued = false;
|
|
327
|
+
const flush = () => {
|
|
328
|
+
if (flushing) return;
|
|
329
|
+
flushing = true;
|
|
1197
330
|
try {
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
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
|
-
});
|
|
331
|
+
for (let next = tasks.shift(); next !== void 0; next = tasks.shift()) next[0]();
|
|
332
|
+
} finally {
|
|
333
|
+
flushing = false;
|
|
1264
334
|
}
|
|
1265
|
-
}).close;
|
|
1266
|
-
const cancelTimer = (timer) => {
|
|
1267
|
-
pendingTimers.get(timer)?.();
|
|
1268
|
-
pendingTimers.delete(timer);
|
|
1269
335
|
};
|
|
1270
|
-
const
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
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)
|
|
336
|
+
const dispatcher = {
|
|
337
|
+
flush,
|
|
338
|
+
scheduleTask: (task, priority) => {
|
|
339
|
+
const later = tasks.findIndex(([, queued]) => queued > priority);
|
|
340
|
+
tasks.splice(later === -1 ? tasks.length : later, 0, [task, priority]);
|
|
341
|
+
if (flushing) return;
|
|
342
|
+
if (Fiber.getCurrent() === void 0) flush();
|
|
343
|
+
else if (!flushQueued) {
|
|
344
|
+
flushQueued = true;
|
|
345
|
+
queueMicrotask(() => {
|
|
346
|
+
flushQueued = false;
|
|
347
|
+
flush();
|
|
1302
348
|
});
|
|
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
349
|
}
|
|
1312
|
-
case "resync":
|
|
1313
|
-
resync();
|
|
1314
|
-
return;
|
|
1315
350
|
}
|
|
1316
351
|
};
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
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
|
-
});
|
|
352
|
+
return {
|
|
353
|
+
flush,
|
|
354
|
+
scheduler: {
|
|
355
|
+
executionMode: "sync",
|
|
356
|
+
makeDispatcher: () => dispatcher,
|
|
357
|
+
shouldYield: (fiber) => fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield
|
|
358
|
+
}
|
|
1337
359
|
};
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
360
|
+
};
|
|
361
|
+
/** The live `Clock`, except that it sleeps on `timers`. */
|
|
362
|
+
const clockOf = (timers, flush) => {
|
|
363
|
+
const live = Clock.Clock.defaultValue();
|
|
364
|
+
return {
|
|
365
|
+
currentTimeMillis: live.currentTimeMillis,
|
|
366
|
+
currentTimeMillisUnsafe: () => live.currentTimeMillisUnsafe(),
|
|
367
|
+
currentTimeNanos: live.currentTimeNanos,
|
|
368
|
+
currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe(),
|
|
369
|
+
monotonicTimeNanos: live.monotonicTimeNanos,
|
|
370
|
+
monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(),
|
|
371
|
+
sleep: (duration) => Effect.callback((resume) => {
|
|
372
|
+
const cancel = timers.schedule(() => {
|
|
373
|
+
resume(Effect.void);
|
|
374
|
+
flush();
|
|
375
|
+
}, Duration.toMillis(duration));
|
|
376
|
+
return Effect.sync(cancel);
|
|
377
|
+
})
|
|
378
|
+
};
|
|
379
|
+
};
|
|
380
|
+
const randomOf = (random) => ({
|
|
381
|
+
nextDoubleUnsafe: random,
|
|
382
|
+
nextIntUnsafe: () => Math.floor(random() * Number.MAX_SAFE_INTEGER)
|
|
383
|
+
});
|
|
384
|
+
/**
|
|
385
|
+
* The origin on which the service requests the ticket. `HttpClient` resolves
|
|
386
|
+
* a relative URL against `location`, and fails without one. But `fetch` got
|
|
387
|
+
* `ticketUrl` as the app gave it before the service, and a custom `fetch` can
|
|
388
|
+
* resolve it on a base of its own. So the service requests `ticketUrl` on this
|
|
389
|
+
* origin, and `fetchOf` gives `fetch` the `ticketUrl` of the app in its place.
|
|
390
|
+
*/
|
|
391
|
+
const ticketOrigin = "http://realtime-ticket.invalid/";
|
|
392
|
+
/** `ticketUrl` on `ticketOrigin`; `ticketOrigin` itself for a string that is not a URL. */
|
|
393
|
+
const ticketRequestUrl = (ticketUrl) => {
|
|
394
|
+
try {
|
|
395
|
+
return new URL(ticketUrl, ticketOrigin).href;
|
|
396
|
+
} catch {
|
|
397
|
+
return ticketOrigin;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
/**
|
|
401
|
+
* The `fetch` of the client as `FetchHttpClient.Fetch`, called as before the
|
|
402
|
+
* service: with a string URL, `ticketUrl` for the ticket request, and without
|
|
403
|
+
* the `duplex: undefined` that `FetchHttpClient` adds for a body that is not
|
|
404
|
+
* a stream. `preconnect` only completes the type of `fetch` under Bun's
|
|
405
|
+
* types; nothing here preconnects.
|
|
406
|
+
*/
|
|
407
|
+
const fetchOf = (fetch, ticketUrl) => {
|
|
408
|
+
const requestUrl = ticketRequestUrl(ticketUrl);
|
|
409
|
+
return Object.assign((input, init) => {
|
|
410
|
+
const href = input instanceof URL ? input.href : input;
|
|
411
|
+
const url = href === requestUrl ? ticketUrl : href;
|
|
412
|
+
if (init === void 0 || !("duplex" in init)) return fetch(url, init);
|
|
413
|
+
const { duplex, ...rest } = init;
|
|
414
|
+
return duplex === void 0 ? fetch(url, rest) : fetch(url, init);
|
|
415
|
+
}, { preconnect: constVoid });
|
|
416
|
+
};
|
|
417
|
+
/**
|
|
418
|
+
* One realtime connection per tab for every subscribed topic. The connection
|
|
419
|
+
* opens while the page is visible and a topic has a listener; a topic set
|
|
420
|
+
* change reconnects after a short debounce, and every reconnect resumes after
|
|
421
|
+
* the last received event; a stream that opens without one resets instead.
|
|
422
|
+
* Changes and resets reach the listeners in one delivery per tab, 250 to
|
|
423
|
+
* 1000 ms after the first of them: a burst of changes refetches once, and
|
|
424
|
+
* tabs that reset together refetch apart.
|
|
425
|
+
* The client runs on the realtime service (`./service`) in a runtime of its
|
|
426
|
+
* own; `close` disposes of it.
|
|
427
|
+
*/
|
|
428
|
+
const createRealtimeClient = (options) => {
|
|
429
|
+
const { flush, scheduler } = makeSyncScheduler();
|
|
430
|
+
const runtime = ManagedRuntime.make(Layer.effect(FacadeConnection, makeConnection({
|
|
431
|
+
resyncOnAccessChange: false,
|
|
432
|
+
ticketUrl: ticketRequestUrl(options.ticketUrl)
|
|
433
|
+
})).pipe(Layer.provide([
|
|
434
|
+
FetchHttpClient.layer,
|
|
435
|
+
layerBrowser({
|
|
436
|
+
document: options.document,
|
|
437
|
+
window: options.window
|
|
438
|
+
}),
|
|
439
|
+
options.eventSourceFactory === void 0 ? layer$3 : layerFromFactory(options.eventSourceFactory)
|
|
440
|
+
]), Layer.provide([
|
|
441
|
+
Layer.succeed(FetchHttpClient.Fetch, fetchOf(options.fetch ?? globalThis.fetch, options.ticketUrl)),
|
|
442
|
+
Layer.succeed(Clock.Clock, clockOf(options.timers ?? defaultTimers, flush)),
|
|
443
|
+
Layer.succeed(Random.Random, randomOf(options.random ?? Math.random))
|
|
444
|
+
])));
|
|
445
|
+
const started = runtime.runFork(FacadeConnection, { scheduler });
|
|
446
|
+
flush();
|
|
447
|
+
const exit = started.pollUnsafe();
|
|
448
|
+
if (exit?._tag !== "Success") throw new Error("The realtime client did not start.", { cause: exit });
|
|
449
|
+
const connection = exit.value;
|
|
450
|
+
const { onAccessChanged, onReset } = options;
|
|
451
|
+
if (onReset !== void 0) connection.listenResyncs(() => notify(onReset));
|
|
452
|
+
if (onAccessChanged !== void 0) connection.listenAccessChanges(() => notify(onAccessChanged));
|
|
1341
453
|
return {
|
|
1342
454
|
close: () => {
|
|
1343
|
-
|
|
1344
|
-
|
|
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);
|
|
455
|
+
Effect.runFork(runtime.disposeEffect, { scheduler });
|
|
456
|
+
flush();
|
|
1351
457
|
},
|
|
1352
|
-
getState: () =>
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
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
|
-
}
|
|
458
|
+
getState: () => {
|
|
459
|
+
const { machine, topics } = connection.state();
|
|
460
|
+
return {
|
|
461
|
+
connections: currentLink(machine) === void 0 ? 0 : 1,
|
|
462
|
+
lastEventId: machine.lastEventId,
|
|
463
|
+
status: machine.phase === "closed" ? "idle" : machine.phase,
|
|
464
|
+
topics
|
|
1377
465
|
};
|
|
1378
|
-
|
|
1379
|
-
|
|
466
|
+
},
|
|
467
|
+
subscribe: (topic, onChanges) => connection.listen(topic, (changes) => notify(() => onChanges(changes)))
|
|
1380
468
|
};
|
|
1381
469
|
};
|
|
1382
|
-
|
|
470
|
+
/** The class of an Expected Error that CI returns. */
|
|
471
|
+
const { CiError } = errors_exports;
|
|
472
|
+
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 };
|