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

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,514 +1,125 @@
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";
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-D-18nBUU.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-DD58W3in.js";
3
+ import { t as createResourceClient } from "./resources-BhOgbxg5.js";
3
4
  import * as Context from "effect/Context";
4
5
  import * as Effect from "effect/Effect";
5
6
  import * as FetchHttpClient from "effect/http/FetchHttpClient";
6
7
  import * as Layer from "effect/Layer";
7
8
  import * as Random from "effect/Random";
8
9
  import * as Clock from "effect/Clock";
10
+ import * as ManagedRuntime from "effect/ManagedRuntime";
9
11
  import * as Duration from "effect/Duration";
10
12
  import * as Fiber from "effect/Fiber";
11
13
  import { constVoid } from "effect/Function";
12
- import * as ManagedRuntime from "effect/ManagedRuntime";
13
- const base64Url = (bytes) => {
14
- let binary = "";
15
- for (const byte of bytes) binary += String.fromCodePoint(byte);
16
- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/[=]+$/u, "");
17
- };
18
- const createOauthRandomValue = (crypto = globalThis.crypto) => base64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
19
- const createPkcePair = async (crypto = globalThis.crypto) => {
20
- const verifier = createOauthRandomValue(crypto);
21
- const challengeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
22
- return {
23
- challenge: base64Url(challengeBytes),
24
- method: "S256",
25
- verifier
26
- };
27
- };
28
- const transactionLifetimeMs = 6e5;
29
- const maxReturnTargetLength = 2048;
30
- const asUrl = (value, field) => {
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) => {
31
22
  try {
32
- const url = new URL(value);
33
- if (url.username !== "" || url.password !== "") throw new Error("credentials");
34
- return url;
35
- } catch {
36
- 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;
37
27
  }
38
28
  };
39
- const tenantOrigin = (value) => {
40
- const url = asUrl(value, "tenantUrl");
41
- if (url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new FederatedAuthError("configuration_error", "tenantUrl must contain only the tenant origin");
42
- return url.origin;
43
- };
44
- const normalizedReturnTarget = (value, applicationOrigin) => {
45
- if (value.length > maxReturnTargetLength) throw new FederatedAuthError("invalid_return_target", "The return target is too long");
46
- const target = new URL(value, applicationOrigin);
47
- if (target.origin !== applicationOrigin) throw new FederatedAuthError("invalid_return_target", "The return target must share the callback origin");
48
- return target.href;
49
- };
50
- const isRecord = (value) => value !== null && Object(value) === value && !Array.isArray(value);
51
- const parseTransaction = (serialized) => {
52
- const value = JSON.parse(serialized);
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");
54
- return {
55
- expiresAt: value.expiresAt,
56
- returnTo: value.returnTo,
57
- state: value.state,
58
- verifier: value.verifier
59
- };
60
- };
61
- const parseToken = (value, now) => {
62
- const accessToken = value.access_token;
63
- const expiresIn = value.expires_in;
64
- 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);
65
41
  return {
66
- accessToken,
67
- expiresAt: now + expiresIn * 1e3
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
68
49
  };
69
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
+ */
70
57
  const createFederatedAuth = (options) => {
71
- const tenantUrl = tenantOrigin(options.tenantUrl);
72
- const redirectUri = asUrl(options.redirectUri, "redirectUri");
73
- const crypto = options.crypto ?? globalThis.crypto;
74
- const fetch = options.fetch ?? globalThis.fetch;
75
- const now = options.now ?? Date.now;
76
- const storage = options.sessionStorage ?? globalThis.sessionStorage;
77
- const navigate = options.navigate ?? ((url) => {
78
- const { location } = globalThis;
79
- if (!location || !("assign" in location) || typeof location.assign !== "function") throw new FederatedAuthError("configuration_error", "Provide navigate when browser navigation is unavailable");
80
- location.assign(url);
81
- });
82
- const storageKey = `ci:federated-auth:${redirectUri.origin}:${options.clientId}`;
83
- const listeners = /* @__PURE__ */ new Set();
84
- let state = { status: "anonymous" };
85
- let token;
86
- let completion;
87
- let rememberedReturnTo;
88
- if (options.clientId.length === 0 || options.scopes.length === 0) throw new FederatedAuthError("configuration_error", "clientId and at least one scope are required");
89
- if (crypto === void 0 || storage === void 0 || fetch === void 0) throw new FederatedAuthError("configuration_error", "Browser crypto, fetch, and sessionStorage are required");
90
- const transition = (next) => {
91
- state = next;
92
- for (const listener of listeners) listener(next);
93
- };
94
- const fail = (error) => {
95
- token = void 0;
96
- transition({
97
- error,
98
- status: "error"
99
- });
100
- throw error;
101
- };
102
- const beginLogin = async ({ returnTo }) => {
103
- const normalizedReturnTo = normalizedReturnTarget(returnTo, redirectUri.origin);
104
- rememberedReturnTo = normalizedReturnTo;
105
- const pkce = await createPkcePair(crypto);
106
- const transaction = {
107
- expiresAt: now() + transactionLifetimeMs,
108
- returnTo: normalizedReturnTo,
109
- state: createOauthRandomValue(crypto),
110
- verifier: pkce.verifier
111
- };
112
- storage.setItem(storageKey, JSON.stringify(transaction));
113
- const authorizationUrl = new URL("/oauth/authorize", tenantUrl);
114
- authorizationUrl.searchParams.set("client_id", options.clientId);
115
- authorizationUrl.searchParams.set("redirect_uri", redirectUri.href);
116
- authorizationUrl.searchParams.set("response_type", "code");
117
- authorizationUrl.searchParams.set("scope", options.scopes.join(" "));
118
- authorizationUrl.searchParams.set("state", transaction.state);
119
- authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
120
- authorizationUrl.searchParams.set("code_challenge_method", pkce.method);
121
- token = void 0;
122
- completion = void 0;
123
- transition({ status: "redirecting" });
124
- navigate(authorizationUrl.href);
125
- return authorizationUrl.href;
126
- };
127
- const complete = async (callbackUrl) => {
128
- let callback;
129
- try {
130
- callback = asUrl(callbackUrl, "callbackUrl");
131
- } catch {
132
- storage.removeItem(storageKey);
133
- return fail(new FederatedAuthError("invalid_callback", "The callback URL is invalid"));
134
- }
135
- if (callback.origin !== redirectUri.origin || callback.pathname !== redirectUri.pathname) {
136
- storage.removeItem(storageKey);
137
- return fail(new FederatedAuthError("invalid_callback", "The callback URL does not match redirectUri"));
138
- }
139
- const serialized = storage.getItem(storageKey);
140
- storage.removeItem(storageKey);
141
- if (serialized === null) return fail(new FederatedAuthError("invalid_state", "No login transaction exists"));
142
- let transaction;
143
- try {
144
- transaction = parseTransaction(serialized);
145
- } catch (error) {
146
- return fail(error instanceof FederatedAuthError ? error : new FederatedAuthError("invalid_state", "Invalid login transaction"));
147
- }
148
- if (transaction.expiresAt <= now()) return fail(new FederatedAuthError("transaction_expired", "The login transaction expired"));
149
- if (callback.searchParams.get("state") !== transaction.state) return fail(new FederatedAuthError("invalid_state", "OAuth state mismatch"));
150
- const authorizationError = callback.searchParams.get("error");
151
- const code = callback.searchParams.get("code");
152
- if (authorizationError !== null || code === null || code.length === 0) return fail(new FederatedAuthError("authorization_failed", authorizationError ?? "The callback did not include a code"));
153
- const body = new URLSearchParams({
154
- client_id: options.clientId,
155
- code,
156
- code_verifier: transaction.verifier,
157
- grant_type: "authorization_code",
158
- redirect_uri: redirectUri.href
159
- });
160
- const response = await fetch(new URL("/oauth/token", tenantUrl), {
161
- body,
162
- headers: { "content-type": "application/x-www-form-urlencoded" },
163
- method: "POST"
164
- });
165
- if (!response.ok) return fail(new FederatedAuthError("token_exchange_failed", "The authorization code exchange failed"));
166
- try {
167
- const tokenResponse = await response.json();
168
- if (!(tokenResponse instanceof Object)) throw new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token");
169
- const payload = {
170
- access_token: Object.entries(tokenResponse).find(([key]) => key === "access_token")?.[1],
171
- expires_in: Object.entries(tokenResponse).find(([key]) => key === "expires_in")?.[1],
172
- token_type: Object.entries(tokenResponse).find(([key]) => key === "token_type")?.[1]
173
- };
174
- token = parseToken(payload, now());
175
- } catch (error) {
176
- return fail(error instanceof FederatedAuthError ? error : new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token"));
177
- }
178
- transition({
179
- expiresAt: token.expiresAt,
180
- status: "authenticated"
181
- });
182
- rememberedReturnTo = transaction.returnTo;
183
- return { returnTo: transaction.returnTo };
184
- };
185
- const reauthorize = async (input) => {
186
- const returnTo = input?.returnTo ?? rememberedReturnTo;
187
- if (returnTo === void 0) throw new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login");
188
- return await beginLogin({ returnTo });
189
- };
58
+ const runtime = ManagedRuntime.make(layerFederated(options));
190
59
  return {
191
- beginLogin,
192
- completeLogin: async (callbackUrl) => {
193
- if (completion !== void 0) return await completion;
194
- const current = complete(callbackUrl);
195
- completion = current;
196
- const retire = async () => {
197
- try {
198
- await current;
199
- } catch {} finally {
200
- if (completion === current) completion = void 0;
201
- }
202
- };
203
- retire();
204
- return await current;
205
- },
206
- getAccessToken: async () => {
207
- if (token !== void 0 && token.expiresAt <= now()) {
208
- token = void 0;
209
- transition({ status: "expired" });
210
- await reauthorize();
211
- throw new FederatedAuthError("reauthorization_required", "A new CI login is required");
212
- }
213
- if (token === void 0) throw new FederatedAuthError("reauthorization_required", "A new CI login is required");
214
- return token.accessToken;
215
- },
216
- getState: () => state,
217
- logout: async () => {
218
- const accessToken = token?.accessToken;
219
- token = void 0;
220
- completion = void 0;
221
- rememberedReturnTo = void 0;
222
- storage.removeItem(storageKey);
223
- transition({ status: "anonymous" });
224
- if (accessToken !== void 0) try {
225
- await fetch(new URL("/oauth/logout", tenantUrl), {
226
- headers: { authorization: `Bearer ${accessToken}` },
227
- method: "POST"
228
- });
229
- } catch {}
230
- },
231
- reauthorize,
232
- subscribe: (listener) => {
233
- listeners.add(listener);
234
- return () => {
235
- listeners.delete(listener);
236
- };
237
- }
60
+ ...authFacade(runtime),
61
+ close: () => runtime.dispose()
238
62
  };
239
63
  };
240
- const parseExpiresAt = (value) => {
241
- if (typeof value === "string") {
242
- const parsed = Date.parse(value);
243
- return Number.isFinite(parsed) ? parsed : null;
244
- }
245
- if (typeof value === "number" && Number.isFinite(value)) return value;
246
- return null;
247
- };
248
- const asRecord$2 = (value) => {
249
- if (typeof value !== "object" || value === null) return null;
250
- return value;
251
- };
252
- const readString$1 = (record, key) => {
253
- const candidate = record[key];
254
- return typeof candidate === "string" ? candidate : null;
255
- };
256
- const readStrings = (record, key) => {
257
- const candidate = record[key];
258
- if (!Array.isArray(candidate)) return null;
259
- const items = candidate;
260
- return items.every((item) => typeof item === "string") ? items : null;
261
- };
262
- const readKind = (record) => {
263
- const { kind } = record;
264
- return kind === "member" || kind === "external_app_user" ? kind : null;
265
- };
266
- const parseIdentity = (value) => {
267
- const identity = asRecord$2(asRecord$2(value)?.identity);
268
- if (identity === null) return null;
269
- const appId = readString$1(identity, "appId");
270
- const appPermissions = readStrings(identity, "appPermissions");
271
- const kind = readKind(identity);
272
- const organizationId = readString$1(identity, "organizationId");
273
- const roles = readStrings(identity, "roles");
274
- const userId = readString$1(identity, "userId");
275
- 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));
276
71
  return {
277
- appId,
278
- appPermissions,
279
- email: readString$1(identity, "email"),
280
- kind,
281
- name: readString$1(identity, "name"),
282
- organizationId,
283
- roles,
284
- userId
72
+ ...authFacade(runtime),
73
+ close: () => runtime.dispose()
285
74
  };
286
75
  };
287
- /** Browser session client for a sealed-cookie BFF. The access token never leaves the server. */
288
- const createServerSessionAuth = (options) => {
289
- const { basePath } = options;
290
- if (!/^\/[\w/-]+$/u.test(basePath) || basePath.endsWith("/")) throw new FederatedAuthError("configuration_error", "basePath must be an absolute path without a trailing slash");
291
- const fetch = options.fetch ?? globalThis.fetch;
292
- const origin = options.origin ?? "";
293
- const now = options.now ?? Date.now;
294
- const navigate = options.navigate ?? ((url) => {
295
- const { location } = globalThis;
296
- if (!location || !("assign" in location) || typeof location.assign !== "function") throw new FederatedAuthError("configuration_error", "Provide navigate when browser navigation is unavailable");
297
- location.assign(url);
298
- });
299
- const listeners = /* @__PURE__ */ new Set();
300
- let state = { status: "anonymous" };
301
- let rememberedReturnTo;
302
- let completion;
303
- const transition = (next) => {
304
- state = next;
305
- for (const listener of listeners) listener(next);
306
- };
307
- const refresh = async () => {
308
- const response = await fetch(`${origin}${basePath}/session`, {
309
- credentials: "same-origin",
310
- headers: { accept: "application/json" }
311
- });
312
- if (response.status === 401) {
313
- transition({ status: "anonymous" });
314
- return state;
315
- }
316
- if (!response.ok) {
317
- const error = new FederatedAuthError("authorization_failed", "The application session could not be read");
318
- transition({
319
- error,
320
- status: "error"
321
- });
322
- return state;
323
- }
324
- const payload = await response.json();
325
- const record = asRecord$2(payload);
326
- const expiresAt = record === null ? null : parseExpiresAt(record.expiresAt);
327
- const identity = parseIdentity(payload);
328
- if (expiresAt === null || identity === null) {
329
- const error = new FederatedAuthError("authorization_failed", "The application session is invalid");
330
- transition({
331
- error,
332
- status: "error"
333
- });
334
- return state;
335
- }
336
- if (expiresAt <= now()) {
337
- transition({ status: "expired" });
338
- return state;
339
- }
340
- transition({
341
- expiresAt,
342
- identity,
343
- status: "authenticated"
344
- });
345
- return state;
346
- };
347
- const beginLogin = ({ returnTo }) => {
348
- rememberedReturnTo = returnTo;
349
- const url = `${origin}${basePath}/login?returnTo=${encodeURIComponent(returnTo)}`;
350
- transition({ status: "redirecting" });
351
- navigate(url);
352
- return Promise.resolve(url);
353
- };
354
- const complete = async () => {
355
- await refresh();
356
- if (state.status === "error") throw state.error;
357
- return { returnTo: rememberedReturnTo ?? "/" };
358
- };
359
- const reauthorize = async (input) => {
360
- const returnTo = input?.returnTo ?? rememberedReturnTo;
361
- if (returnTo === void 0) throw new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login");
362
- return await beginLogin({ returnTo });
363
- };
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;
364
94
  return {
365
- beginLogin,
366
- completeLogin: async () => {
367
- if (completion !== void 0) return await completion;
368
- const current = complete();
369
- completion = current;
370
- const retire = async () => {
371
- try {
372
- await current;
373
- } catch {} finally {
374
- if (completion === current) completion = void 0;
375
- }
376
- };
377
- retire();
378
- return await current;
379
- },
380
- getAccessToken: () => Promise.reject(new FederatedAuthError("reauthorization_required", "The CI access token stays on the application server")),
381
- getState: () => state,
382
- logout: async () => {
383
- rememberedReturnTo = void 0;
384
- completion = void 0;
385
- try {
386
- await fetch(`${origin}${basePath}/logout`, {
387
- credentials: "same-origin",
388
- method: "POST"
389
- });
390
- } catch {}
391
- transition({ status: "anonymous" });
392
- },
393
- reauthorize,
394
- subscribe: (listener) => {
395
- listeners.add(listener);
396
- return () => {
397
- listeners.delete(listener);
398
- };
399
- }
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)))
400
102
  };
401
103
  };
402
104
  /**
403
- * Ten minutes: a skill run's five-minute AI deadline plus queueing and
404
- * delivery slack. Long runs return a `runId` immediately; follow is how
405
- * callers wait for their outcome.
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`.
406
109
  */
407
- const DEFAULT_FOLLOW_RUN_DEADLINE_MS = 6e5;
408
- const DEFAULT_IDLE_MS = 50;
409
- const MAX_BACKOFF_IDLE_MS = 1e3;
410
- const terminalEventKinds = /* @__PURE__ */ new Set([
411
- "cancelled",
412
- "completed",
413
- "failed"
414
- ]);
415
- const terminalSnapshotStatuses = /* @__PURE__ */ new Set([
416
- "cancelled",
417
- "failed",
418
- "succeeded"
419
- ]);
420
- const asRecord$1 = (value) => {
421
- if (typeof value !== "object" || value === null) return null;
422
- return value;
423
- };
424
- const readString = (record, key) => {
425
- const candidate = record[key];
426
- return typeof candidate === "string" ? candidate : null;
427
- };
428
- const snapshotStatus = (value) => {
429
- const record = asRecord$1(value);
430
- if (record === null) return null;
431
- const nested = asRecord$1(record.result);
432
- return readString(record, "status") ?? (nested === null ? null : readString(nested, "status"));
433
- };
434
- const eventKind = (event) => {
435
- const record = asRecord$1(event);
436
- return record === null ? null : readString(record, "kind");
437
- };
438
- const idle = async (ms, sleep, signal) => {
439
- if (ms <= 0 || signal?.aborted === true) return;
440
- if (sleep !== void 0) {
441
- await sleep(ms);
442
- return;
443
- }
444
- const cleanup = new AbortController();
445
- try {
446
- await new Promise((resolve) => {
447
- const timeout = setTimeout(resolve, ms);
448
- signal?.addEventListener("abort", () => {
449
- clearTimeout(timeout);
450
- resolve();
451
- }, {
452
- once: true,
453
- signal: cleanup.signal
454
- });
455
- });
456
- } finally {
457
- cleanup.abort();
458
- }
459
- };
460
- const isTerminalEvent = (event) => {
461
- const kind = eventKind(event);
462
- return kind !== null && terminalEventKinds.has(kind);
463
- };
110
+ const followRun = (runs, options) => runPromise(Effect, followSource(sourceOf(runs), options).pipe(Effect.provideService(Clock.Clock, clockOf$1(options))), options.signal);
464
111
  /**
465
- * Reads the pages after `page` of a run that has already finished and
466
- * returns the last non-empty one. Stops at the first terminal event.
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`.
467
116
  */
468
- const readRemainingPages = async (runs, options, page) => {
469
- let last = page;
470
- while (last.nextCursor !== null && !last.events.some(isTerminalEvent)) {
471
- options.signal?.throwIfAborted();
472
- const next = await runs.stream({
473
- afterCursor: last.nextCursor,
474
- runId: options.runId
475
- });
476
- if (!next.ok) throw new Error(next.error.message);
477
- if (next.value.events.length === 0) return last;
478
- last = next.value;
479
- }
480
- return last;
481
- };
117
+ const executorFacade = (runtime) => ({ execute: (operationId, input, options) => runPromise(runtime, CiClient.use((client) => client.executeResult(operationId, input, options ?? { organizationId: "" })), options?.signal) });
482
118
  /**
483
- * Follows dedicated run events until a terminal event or snapshot status.
484
- * Resolves with the last event page read.
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.
485
122
  */
486
- const followRun = async (runs, options) => {
487
- const deadlineMs = options.deadlineMs ?? 6e5;
488
- const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
489
- const maxIdleMs = Math.max(idleMs, MAX_BACKOFF_IDLE_MS);
490
- const now = options.now ?? Date.now;
491
- const deadline = now() + deadlineMs;
492
- let afterCursor;
493
- let emptyPolls = 0;
494
- while (now() < deadline) {
495
- options.signal?.throwIfAborted();
496
- const snapshot = await runs.get({ runId: options.runId });
497
- if (!snapshot.ok) throw new Error(snapshot.error.message);
498
- const page = await runs.stream(afterCursor === void 0 ? { runId: options.runId } : {
499
- afterCursor,
500
- runId: options.runId
501
- });
502
- if (!page.ok) throw new Error(page.error.message);
503
- if (page.value.events.some(isTerminalEvent)) return page.value;
504
- const status = snapshotStatus(snapshot.value);
505
- if (status !== null && terminalSnapshotStatuses.has(status)) return await readRemainingPages(runs, options, page.value);
506
- if (page.value.nextCursor !== null) afterCursor = page.value.nextCursor;
507
- emptyPolls = page.value.events.length === 0 ? emptyPolls + 1 : 0;
508
- await idle(Math.min(idleMs * 2 ** emptyPolls, maxIdleMs), options.sleep, options.signal);
509
- }
510
- throw new Error("Run did not finish");
511
- };
512
123
  const clientSdkProtocolVersion = "v1";
513
124
  const executionOptions = (organizationId, options) => options?.signal === void 0 ? { organizationId } : {
514
125
  organizationId,
@@ -519,7 +130,8 @@ const rootOperation = (transport, operationId) => async (input, options) => {
519
130
  const { organizationId, ...wireInput } = input;
520
131
  return await transport.execute(operationId, wireInput, executionOptions(organizationId, options));
521
132
  };
522
- const domains = (transport, organizationId) => {
133
+ const domains = (runtime, organizationId) => {
134
+ const transport = executorFacade(runtime);
523
135
  const operation = (operationId) => organizationId === void 0 ? rootOperation(transport, operationId) : scopedOperation(transport, organizationId, operationId);
524
136
  return {
525
137
  agents: {
@@ -549,10 +161,10 @@ const domains = (transport, organizationId) => {
549
161
  follow: (async (options) => {
550
162
  const orgId = organizationId ?? options.organizationId;
551
163
  if (orgId === void 0 || orgId.length === 0) throw new TypeError("organizationId is required");
552
- return await followRun({
553
- get: (input) => transport.execute("runs_get", input, executionOptions(orgId, options)),
554
- stream: (input) => transport.execute("runs_stream", input, executionOptions(orgId, options))
555
- }, 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);
556
168
  }),
557
169
  get: operation("runs_get"),
558
170
  stream: operation("runs_stream")
@@ -567,12 +179,16 @@ const domains = (transport, organizationId) => {
567
179
  }
568
180
  };
569
181
  };
570
- const createClient = (options) => {
571
- const publicDomains = domains(options.transport);
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);
572
188
  const forOrganization = (organizationId) => {
573
189
  if (organizationId.length === 0) throw new TypeError("organizationId is required");
574
190
  return {
575
- ...domains(options.transport, organizationId),
191
+ ...domains(runtime, organizationId),
576
192
  organizationId
577
193
  };
578
194
  };
@@ -582,161 +198,97 @@ const createClient = (options) => {
582
198
  ...publicDomains.context,
583
199
  forOrganization
584
200
  },
585
- execute: options.transport.execute,
201
+ execute: executorFacade(runtime).execute,
586
202
  forOrganization,
587
203
  protocolVersion: "v1"
588
204
  };
589
205
  };
590
- const createProxyTransport = (options) => {
591
- const serverUrl = parseOriginUrl(options.serverUrl, "serverUrl");
592
- const path = parseMountPath(options.path);
593
- const { authentication } = options;
594
- return createHttpOperationTransport({
595
- ...authentication.mode === "federated" ? { authorization: authentication.auth.getAccessToken } : { credentials: authentication.credentials ?? "same-origin" },
596
- basePath: path,
597
- fetch: options.fetch ?? globalThis.fetch,
598
- origin: serverUrl
599
- });
600
- };
601
- const mapAuthState = (state) => {
602
- switch (state.status) {
603
- case "authenticated":
604
- if (state.identity === void 0) return {
605
- message: "The application session is invalid",
606
- status: "unavailable"
607
- };
608
- return {
609
- expiresAt: new Date(state.expiresAt).toISOString(),
610
- identity: state.identity,
611
- status: "authenticated"
612
- };
613
- case "expired": return { status: "expired" };
614
- case "error": return {
615
- message: state.error.message,
616
- status: "unavailable"
617
- };
618
- default: return { status: "anonymous" };
619
- }
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
+ };
620
219
  };
621
- /** Browser runtime for a sealed-cookie BFF: session identity, proxy client, and run follow. */
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
+ */
622
230
  const createDelegatedApplicationRuntime = (options) => {
623
- const fetch = options.fetch ?? globalThis.fetch;
624
- const authBasePath = options.authBasePath ?? "/api/auth";
625
- const proxyPath = options.proxyPath ?? "/api";
626
- const sessionAuth = createServerSessionAuth({
627
- basePath: authBasePath,
628
- fetch,
629
- ...options.navigate && { navigate: options.navigate },
630
- origin: options.origin
631
- });
632
- const client = createClient({ transport: createProxyTransport({
633
- authentication: {
634
- credentials: "same-origin",
635
- mode: "server_delegated"
636
- },
637
- fetch,
638
- path: proxyPath,
639
- serverUrl: options.origin
640
- }) });
641
- let state = { status: "checking" };
642
- let generation = 0;
643
- const listeners = /* @__PURE__ */ new Set();
644
- const publish = (next) => {
645
- state = next;
646
- for (const notify of listeners) notify();
647
- };
648
- const subscribe = (notify) => {
649
- listeners.add(notify);
650
- return () => {
651
- listeners.delete(notify);
652
- };
653
- };
654
- const refresh = async () => {
655
- generation += 1;
656
- const current = generation;
657
- publish({ status: "checking" });
658
- try {
659
- await sessionAuth.completeLogin(`${options.origin}${authBasePath}/callback`);
660
- if (current !== generation) return;
661
- publish(mapAuthState(sessionAuth.getState()));
662
- } catch (error) {
663
- if (current === generation) publish({
664
- message: error instanceof Error ? error.message : "CI session verification is unavailable",
665
- status: "unavailable"
666
- });
667
- }
668
- };
669
- const login = async (returnTo) => {
670
- generation += 1;
671
- publish({ status: "anonymous" });
672
- await sessionAuth.beginLogin({ returnTo });
673
- };
674
- const initialize = async (url) => {
675
- await refresh();
676
- if (state.status === "authenticated") return;
677
- if (state.status === "anonymous" || state.status === "expired") await login(url);
678
- };
679
- const logout = async () => {
680
- generation += 1;
681
- await sessionAuth.logout();
682
- publish({ status: "anonymous" });
683
- };
684
- const followRun = async (runId) => {
685
- if (state.status !== "authenticated") throw new Error("A CI session is required to follow a run");
686
- return await client.forOrganization(state.identity.organizationId).runs.follow({ runId });
687
- };
231
+ const runtime = ManagedRuntime.make(layer$1(options));
232
+ const session = runtime.runSync(DelegatedRuntime);
233
+ const sessionAuth = authFacade(runtime);
234
+ const client = clientFacade(runtime);
688
235
  const auth = sessionAuth;
689
236
  return {
690
237
  applicationId: options.applicationId,
691
238
  auth,
692
239
  client,
693
- followRun,
694
- getSnapshot: () => state,
695
- initialize,
696
- login,
697
- logout,
698
- refresh,
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),
699
247
  sessionAuth,
700
- subscribe
248
+ subscribe: session.subscribe
701
249
  };
702
250
  };
703
- const asRecord = (value) => {
704
- if (typeof value !== "object" || value === null) return null;
705
- return value;
706
- };
707
- const readRunId = (value) => {
708
- const payload = asRecord(value);
709
- const runId = payload === null ? null : payload.runId;
710
- return typeof runId === "string" ? runId : null;
711
- };
712
- /** Posts a Fixed workflow BFF route and returns the admitted run id. */
251
+ /**
252
+ * The `.` facade of `FixedWorkflows` (`./service`), in a runtime of its own.
253
+ */
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
+ */
713
260
  const createFixedWorkflowClient = (options) => {
714
- const fetch = options.fetch ?? globalThis.fetch;
715
- return { invoke: async (input) => {
716
- const response = await fetch(options.url(input), {
717
- body: JSON.stringify(options.body === void 0 ? input : options.body(input)),
718
- credentials: "same-origin",
719
- headers: {
720
- "content-type": "application/json",
721
- "x-idempotency-key": crypto.randomUUID()
722
- },
723
- method: "POST"
724
- });
725
- const payload = await response.json();
726
- const runId = readRunId(payload);
727
- if (!response.ok || runId === null) throw new Error("Fixed workflow did not return a run id");
728
- return { runId };
729
- } };
261
+ const runtime = ManagedRuntime.make(layer$2(options.fetch === void 0 ? {} : { fetch: options.fetch }));
262
+ return {
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
+ })))
268
+ };
730
269
  };
731
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
+ */
732
275
  const createDirectTransport = (options) => {
733
- const tenantUrl = parseOriginUrl(options.tenantUrl, "tenantUrl");
734
- return createHttpOperationTransport({
735
- authorization: options.auth.getAccessToken,
736
- basePath: "/application/v1",
737
- fetch: options.fetch ?? globalThis.fetch,
738
- origin: tenantUrl
739
- });
276
+ const runtime = ManagedRuntime.make(Layer.succeed(CiClient, make(makeHttpExecute(directHttpOptions(options)))));
277
+ return {
278
+ ...executorFacade(runtime),
279
+ close: () => runtime.dispose()
280
+ };
281
+ };
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)))));
288
+ return {
289
+ ...executorFacade(runtime),
290
+ close: () => runtime.dispose()
291
+ };
740
292
  };
741
293
  /** Surfaces a listener's error without stopping the other listeners. */
742
294
  const report = (error) => {
@@ -884,7 +436,7 @@ const createRealtimeClient = (options) => {
884
436
  document: options.document,
885
437
  window: options.window
886
438
  }),
887
- options.eventSourceFactory === void 0 ? layer : layerFromFactory(options.eventSourceFactory)
439
+ options.eventSourceFactory === void 0 ? layer$3 : layerFromFactory(options.eventSourceFactory)
888
440
  ]), Layer.provide([
889
441
  Layer.succeed(FetchHttpClient.Fetch, fetchOf(options.fetch ?? globalThis.fetch, options.ticketUrl)),
890
442
  Layer.succeed(Clock.Clock, clockOf(options.timers ?? defaultTimers, flush)),