@composable-os/client 0.0.0-stage → 0.1.0-beta.8

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/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ > This licence covers the repository except the directories listed in NOTICE. In particular, the
4
+ > assistant packages `packages/agent-*` (agent-core, agent-a2ui, agent-voice, agent-plugins) are
5
+ > licensed under the MIT License; see the LICENSE file in each of those directories (ADR 0350).
6
+
7
+ ## Abbreviation
8
+
9
+ FSL-1.1-ALv2
10
+
11
+ ## Notice
12
+
13
+ Copyright 2026 Tim O'Connell
14
+
15
+ ## Terms and Conditions
16
+
17
+ ### Licensor ("We")
18
+
19
+ The party offering the Software under these Terms and Conditions.
20
+
21
+ ### The Software
22
+
23
+ The "Software" is each version of the software that we make available under
24
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
25
+ Conditions with the Software.
26
+
27
+ ### License Grant
28
+
29
+ Subject to your compliance with this License Grant and the Patents,
30
+ Redistribution and Trademark clauses below, we hereby grant you the right to
31
+ use, copy, modify, create derivative works, publicly perform, publicly display
32
+ and redistribute the Software for any Permitted Purpose identified below.
33
+
34
+ ### Permitted Purpose
35
+
36
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
37
+ means making the Software available to others in a commercial product or
38
+ service that:
39
+
40
+ 1. substitutes for the Software;
41
+
42
+ 2. substitutes for any other product or service we offer using the Software
43
+ that exists as of the date we make the Software available; or
44
+
45
+ 3. offers the same or substantially similar functionality as the Software.
46
+
47
+ Permitted Purposes specifically include using the Software:
48
+
49
+ 1. for your internal use and access;
50
+
51
+ 2. for non-commercial education;
52
+
53
+ 3. for non-commercial research; and
54
+
55
+ 4. in connection with professional services that you provide to a licensee
56
+ using the Software in accordance with these Terms and Conditions.
57
+
58
+ ### Patents
59
+
60
+ To the extent your use for a Permitted Purpose would necessarily infringe our
61
+ patents, the license grant above includes a license under our patents. If you
62
+ make a claim against any party that the Software infringes or contributes to
63
+ the infringement of any patent, then your patent license to the Software ends
64
+ immediately.
65
+
66
+ ### Redistribution
67
+
68
+ The Terms and Conditions apply to all copies, modifications and derivatives of
69
+ the Software.
70
+
71
+ If you redistribute any copies, modifications or derivatives of the Software,
72
+ you must include a copy of or a link to these Terms and Conditions and not
73
+ remove any copyright notices provided in or with the Software.
74
+
75
+ ### Disclaimer
76
+
77
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
78
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
79
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
80
+
81
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
82
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
83
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
84
+
85
+ ### Trademarks
86
+
87
+ Except for displaying the License Details and identifying us as the origin of
88
+ the Software, you have no right under these Terms and Conditions to use our
89
+ trademarks, trade names, service marks or product names.
90
+
91
+ ## Grant of Future License
92
+
93
+ We hereby irrevocably grant you an additional license to use the Software under
94
+ the Apache License, Version 2.0 that is effective on the second anniversary of
95
+ the date we make the Software available. On or after that date, you may use the
96
+ Software under the Apache License, Version 2.0, in which case the following
97
+ will apply:
98
+
99
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
100
+ this file except in compliance with the License.
101
+
102
+ You may obtain a copy of the License at
103
+
104
+ http://www.apache.org/licenses/LICENSE-2.0
105
+
106
+ Unless required by applicable law or agreed to in writing, software distributed
107
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
108
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
109
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,32 @@
1
+ import type { FetchLike } from "./types.ts";
2
+ /** Customer session cookies are `cos-customer.*`, `__Secure-` prefixed on https (the host's). */
3
+ export declare const CUSTOMER_COOKIE_PREFIX = "cos-customer";
4
+ /** Customer sign-in, served by the host and reached over the binding: forward these paths. */
5
+ export declare const CUSTOMER_AUTH_PATH = "/api/customer-auth";
6
+ /** The customer cookies in a `Cookie` header, as one header value ("" when there are none). */
7
+ export declare function customerCookies(cookieHeader: string | null | undefined): string;
8
+ /** Headers for a call made for the browser's customer: their session cookie, if any. */
9
+ export declare function customerSession(cookieHeader: string | null | undefined): Record<string, string>;
10
+ /** The web app's own marker: when it last checked the customer's session (not a credential). */
11
+ export declare const SESSION_CHECKED_COOKIE = "cos-session-checked";
12
+ /** At most this often, the session is checked and its cookie given a fresh lifetime. */
13
+ export declare const SESSION_CHECK_INTERVAL_MS: number;
14
+ export interface KeepSignedInOptions {
15
+ /** The browser's `Cookie` header. */
16
+ cookieHeader: string | null | undefined;
17
+ /** The binding's fetch: `(url, init) => env.HOST.fetch(url, init)`. */
18
+ fetch: FetchLike;
19
+ /** Any origin: a binding ignores it. */
20
+ baseUrl: string;
21
+ /** Default: now. */
22
+ now?: Date;
23
+ }
24
+ /**
25
+ * Keeps a signed-in customer signed in on the web app's hostname (stage 24, ADR 0421). The host
26
+ * extends a session in its database while it is used, but the browser keeps the cookie's
27
+ * lifetime from sign-in. Once a day at most, on a request that carries the customer's cookie,
28
+ * this asks the host for the session over the binding and returns `Set-Cookie` values for the
29
+ * web app's response: the same cookie with a lifetime to the session's current expiry, and the
30
+ * web app's marker of when it checked. A session that has ended clears both. Nothing to do: [].
31
+ */
32
+ export declare function keepCustomerSignedIn(options: KeepSignedInOptions): Promise<string[]>;
@@ -0,0 +1,84 @@
1
+ // A company's web app calling the host over its service binding (stage 24, ADR 0421).
2
+ //
3
+ // The web app holds no credential of its own. It forwards the customer's session cookie, which
4
+ // the host set on the web app's hostname at sign-in and verifies on every call, and nothing else:
5
+ // `customerSession` picks that cookie out of the browser's request, so the web app's other
6
+ // cookies never reach the host.
7
+ //
8
+ // const api = createCustomerClient({
9
+ // baseUrl: "https://host", // any origin: a binding ignores it
10
+ // fetch: (url, init) => env.HOST.fetch(url, init),
11
+ // headers: () => customerSession(request.headers.get("cookie")),
12
+ // });
13
+ /** Customer session cookies are `cos-customer.*`, `__Secure-` prefixed on https (the host's). */
14
+ export const CUSTOMER_COOKIE_PREFIX = "cos-customer";
15
+ /** Customer sign-in, served by the host and reached over the binding: forward these paths. */
16
+ export const CUSTOMER_AUTH_PATH = "/api/customer-auth";
17
+ function isCustomerCookie(pair) {
18
+ return pair.replace(/^__(Secure|Host)-/, "").startsWith(`${CUSTOMER_COOKIE_PREFIX}.`);
19
+ }
20
+ /** The customer cookies in a `Cookie` header, as one header value ("" when there are none). */
21
+ export function customerCookies(cookieHeader) {
22
+ return (cookieHeader ?? "")
23
+ .split(/;\s*/)
24
+ .filter((pair) => pair && isCustomerCookie(pair))
25
+ .join("; ");
26
+ }
27
+ /** Headers for a call made for the browser's customer: their session cookie, if any. */
28
+ export function customerSession(cookieHeader) {
29
+ const cookie = customerCookies(cookieHeader);
30
+ return cookie ? { cookie } : {};
31
+ }
32
+ /** The web app's own marker: when it last checked the customer's session (not a credential). */
33
+ export const SESSION_CHECKED_COOKIE = "cos-session-checked";
34
+ /** At most this often, the session is checked and its cookie given a fresh lifetime. */
35
+ export const SESSION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
36
+ function cookiePairs(header) {
37
+ return (header ?? "")
38
+ .split(/;\s*/)
39
+ .map((pair) => [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)])
40
+ .filter(([name]) => Boolean(name));
41
+ }
42
+ /**
43
+ * Keeps a signed-in customer signed in on the web app's hostname (stage 24, ADR 0421). The host
44
+ * extends a session in its database while it is used, but the browser keeps the cookie's
45
+ * lifetime from sign-in. Once a day at most, on a request that carries the customer's cookie,
46
+ * this asks the host for the session over the binding and returns `Set-Cookie` values for the
47
+ * web app's response: the same cookie with a lifetime to the session's current expiry, and the
48
+ * web app's marker of when it checked. A session that has ended clears both. Nothing to do: [].
49
+ */
50
+ export async function keepCustomerSignedIn(options) {
51
+ const pairs = cookiePairs(options.cookieHeader);
52
+ const session = pairs.find(([name]) => name.replace(/^__(Secure|Host)-/, "") === `${CUSTOMER_COOKIE_PREFIX}.session_token`);
53
+ if (!session)
54
+ return [];
55
+ const now = (options.now ?? new Date()).getTime();
56
+ const checked = Number(pairs.find(([name]) => name === SESSION_CHECKED_COOKIE)?.[1]);
57
+ if (checked > 0 && now - checked >= 0 && now - checked < SESSION_CHECK_INTERVAL_MS)
58
+ return [];
59
+ const [name, value] = session;
60
+ const attributes = `; Path=/; HttpOnly; SameSite=Lax${name.startsWith("__Secure-") ? "; Secure" : ""}`;
61
+ const response = await options.fetch(`${options.baseUrl.replace(/\/+$/, "")}${CUSTOMER_AUTH_PATH}/get-session`, { method: "GET", headers: { cookie: customerCookies(options.cookieHeader) } });
62
+ // The host could not answer: leave the cookie as it is, and try again on a later request.
63
+ if (response.status >= 500)
64
+ return [];
65
+ let expiresAt = Number.NaN;
66
+ if (response.status === 200) {
67
+ try {
68
+ const body = JSON.parse(await response.text());
69
+ expiresAt = Date.parse(body?.session?.expiresAt ?? "");
70
+ }
71
+ catch { }
72
+ }
73
+ if (!(expiresAt > now)) {
74
+ return [
75
+ `${name}=${attributes}; Max-Age=0`,
76
+ `${SESSION_CHECKED_COOKIE}=${attributes}; Max-Age=0`,
77
+ ];
78
+ }
79
+ const maxAge = Math.floor((expiresAt - now) / 1000);
80
+ return [
81
+ `${name}=${value}${attributes}; Max-Age=${maxAge}`,
82
+ `${SESSION_CHECKED_COOKIE}=${now}${attributes}; Max-Age=${maxAge}`,
83
+ ];
84
+ }
@@ -0,0 +1,74 @@
1
+ import { UpgradeRequiredError } from "./errors.ts";
2
+ import type { FetchLike, Json } from "./types.ts";
3
+ /** What the generated file says about each operation at run time. */
4
+ export interface OperationSpec {
5
+ readonly kind: "query" | "mutation";
6
+ readonly invalidates: readonly string[];
7
+ }
8
+ /** What the generated file says about each operation's types. */
9
+ export type OperationTypes = Record<string, {
10
+ kind: "query" | "mutation";
11
+ input: unknown;
12
+ output: unknown;
13
+ }>;
14
+ export type QueryName<T extends OperationTypes> = {
15
+ [K in keyof T & string]: T[K]["kind"] extends "query" ? K : never;
16
+ }[keyof T & string];
17
+ export type MutationName<T extends OperationTypes> = {
18
+ [K in keyof T & string]: T[K]["kind"] extends "mutation" ? K : never;
19
+ }[keyof T & string];
20
+ export interface ClientOptions {
21
+ /** The host, e.g. `https://crm.example.com`. For a service binding, any origin will do. */
22
+ baseUrl: string;
23
+ /** `fetch`, or a Worker's service binding's `fetch`. Default: the global `fetch`. */
24
+ fetch?: FetchLike;
25
+ /** Headers for every call: a bearer token, say. May be async (a token that refreshes). */
26
+ headers?: () => Record<string, string> | Promise<Record<string, string>>;
27
+ /** Times a call is retried, with the same key, after a network failure or 429/503. Default 2. */
28
+ retries?: number;
29
+ /** Makes an idempotency key. Default: `crypto.randomUUID`, or 32 random hex digits. */
30
+ randomKey?: () => string;
31
+ /** Called before an UpgradeRequiredError is thrown, so an app can show its update screen. */
32
+ onUpgradeRequired?: (error: UpgradeRequiredError) => void;
33
+ /** Waits between retries. Default: a short backoff. Tests pass one that does not wait. */
34
+ sleep?: (ms: number) => Promise<void>;
35
+ }
36
+ export interface CallOptions {
37
+ /** The key to send with a mutation; default one made for this call. */
38
+ idempotencyKey?: string;
39
+ }
40
+ /** The API version this runtime speaks. A host that no longer serves it says upgrade_required. */
41
+ export declare const CLIENT_API_VERSION = "v1";
42
+ /** A key with 128 random bits, from whatever the platform has. */
43
+ export declare function defaultRandomKey(): string;
44
+ export declare function createClient<T extends OperationTypes>(specs: {
45
+ readonly [K in keyof T & string]: OperationSpec;
46
+ }, options: ClientOptions): {
47
+ call: <N extends keyof T & string>(name: N, input: T[N]["input"], callOptions?: CallOptions) => Promise<T[N]["output"]>;
48
+ query: <N extends QueryName<T>>(name: N, input: T[N]["input"]) => {
49
+ queryKey: readonly [N, T[N]["input"]];
50
+ queryFn: () => Promise<T[N]["output"]>;
51
+ };
52
+ mutation: <N extends MutationName<T>>(name: N) => {
53
+ mutationKey: readonly [N];
54
+ mutationFn: (input: T[N]["input"]) => Promise<T[N]["output"]>;
55
+ meta: {
56
+ invalidates: (readonly [string])[];
57
+ };
58
+ };
59
+ invalidates: (name: MutationName<T>) => (readonly [string])[];
60
+ operations: { readonly [K in keyof T & string]: OperationSpec; };
61
+ };
62
+ export type Client<T extends OperationTypes> = ReturnType<typeof createClient<T>>;
63
+ /**
64
+ * For a MutationCache's `onSuccess`: invalidates what a mutation made by this client lists in
65
+ * `meta.invalidates`. `new MutationCache({ onSuccess: invalidateFromMeta(queryClient) })`.
66
+ */
67
+ export declare function invalidateFromMeta(queryClient: {
68
+ invalidateQueries(filters: {
69
+ queryKey: readonly unknown[];
70
+ }): unknown;
71
+ }): (_data: unknown, _variables: unknown, _context: unknown, mutation: {
72
+ meta?: Record<string, unknown> | undefined;
73
+ }) => Promise<unknown[]>;
74
+ export type { Json };
package/dist/client.js ADDED
@@ -0,0 +1,139 @@
1
+ // The typed client (stage 23, ADR 0403, ADR 0418). A product's generated file supplies the
2
+ // operation types and their specs; this calls them over the HTTP surface and gives TanStack Query
3
+ // option objects for each. It imports no TanStack package: the objects are plain, shaped as
4
+ // `queryOptions` and `mutationOptions` take them, so any version of the library fits.
5
+ //
6
+ // - Query keys follow one rule: `[operation, input]`.
7
+ // - A mutation's key is `[operation]`, and its `meta.invalidates` lists the query key prefixes it
8
+ // makes stale (`[operation]` for each), taken from the contract.
9
+ // - Every mutation sends an Idempotency-Key, made once per call and kept across its retries:
10
+ // the client's own retries, and TanStack Query's (keyed by the variables object it passes back).
11
+ import { ApiError, isRetryable, NetworkError, UpgradeRequiredError } from "./errors.js";
12
+ /** The API version this runtime speaks. A host that no longer serves it says upgrade_required. */
13
+ export const CLIENT_API_VERSION = "v1";
14
+ /** A key with 128 random bits, from whatever the platform has. */
15
+ export function defaultRandomKey() {
16
+ const crypto = globalThis.crypto;
17
+ if (crypto?.randomUUID)
18
+ return crypto.randomUUID();
19
+ if (crypto?.getRandomValues) {
20
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
21
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
22
+ }
23
+ throw new Error("No secure random source: pass randomKey to the client (in React Native, from expo-crypto)");
24
+ }
25
+ const defaultSleep = (ms) => new Promise((resolve) => {
26
+ // Every platform this runs on has setTimeout; ECMAScript itself does not declare it.
27
+ globalThis.setTimeout(resolve, ms);
28
+ });
29
+ function globalFetch() {
30
+ const f = globalThis.fetch;
31
+ if (!f)
32
+ throw new Error("No fetch: pass one to the client");
33
+ return f.bind(globalThis);
34
+ }
35
+ /** Reads one response as the surface's envelope: the data, or the error it describes. */
36
+ async function readEnvelope(response) {
37
+ let body;
38
+ try {
39
+ body = JSON.parse(await response.text());
40
+ }
41
+ catch {
42
+ throw new ApiError("internal", `The host answered ${response.status} without JSON`, response.status);
43
+ }
44
+ if (response.status === 200 && body && "data" in body)
45
+ return body.data;
46
+ const error = body?.error ?? {};
47
+ const message = error.message ?? `The host answered ${response.status}`;
48
+ if (error.code === "upgrade_required")
49
+ throw new UpgradeRequiredError(message, error.details);
50
+ throw new ApiError(error.code ?? "internal", message, response.status, error.details);
51
+ }
52
+ export function createClient(specs, options) {
53
+ const base = options.baseUrl.replace(/\/+$/, "");
54
+ const fetcher = options.fetch ?? globalFetch();
55
+ const retries = options.retries ?? 2;
56
+ const randomKey = options.randomKey ?? defaultRandomKey;
57
+ const sleep = options.sleep ?? defaultSleep;
58
+ // TanStack Query passes the same variables object to each retry of one mutation.
59
+ const keys = new WeakMap();
60
+ async function send(name, input, key) {
61
+ const headers = {
62
+ "content-type": "application/json",
63
+ ...(await options.headers?.()),
64
+ ...(key ? { "idempotency-key": key } : {}),
65
+ };
66
+ let response;
67
+ try {
68
+ response = await fetcher(`${base}/api/${CLIENT_API_VERSION}/op/${encodeURIComponent(name)}`, {
69
+ method: "POST",
70
+ headers,
71
+ body: JSON.stringify(input ?? {}),
72
+ });
73
+ }
74
+ catch (error) {
75
+ throw new NetworkError(`Could not reach the host for ${name}`, error);
76
+ }
77
+ return readEnvelope(response);
78
+ }
79
+ async function call(name, input, callOptions = {}) {
80
+ const spec = specs[name];
81
+ if (!spec)
82
+ throw new ApiError("unknown_operation", `No operation named "${name}"`, 404);
83
+ const key = spec.kind === "mutation" ? (callOptions.idempotencyKey ?? randomKey()) : null;
84
+ for (let attempt = 0;; attempt += 1) {
85
+ try {
86
+ return (await send(name, input, key));
87
+ }
88
+ catch (error) {
89
+ if (error instanceof UpgradeRequiredError)
90
+ options.onUpgradeRequired?.(error);
91
+ if (attempt >= retries || !isRetryable(error))
92
+ throw error;
93
+ await sleep(200 * 2 ** attempt);
94
+ }
95
+ }
96
+ }
97
+ /** `queryOptions` for a read: key `[name, input]`. */
98
+ function query(name, input) {
99
+ return {
100
+ queryKey: [name, input],
101
+ queryFn: () => call(name, input),
102
+ };
103
+ }
104
+ /** `mutationOptions` for a write: one idempotency key per mutation, kept across its retries. */
105
+ function mutation(name) {
106
+ const spec = specs[name];
107
+ return {
108
+ mutationKey: [name],
109
+ mutationFn: (input) => {
110
+ const holder = input !== null && typeof input === "object" ? input : null;
111
+ let key = holder ? keys.get(holder) : undefined;
112
+ if (!key) {
113
+ key = randomKey();
114
+ if (holder)
115
+ keys.set(holder, key);
116
+ }
117
+ return call(name, input, { idempotencyKey: key });
118
+ },
119
+ meta: { invalidates: (spec?.invalidates ?? []).map((q) => [q]) },
120
+ };
121
+ }
122
+ /** The query key prefixes a mutation makes stale, for `queryClient.invalidateQueries`. */
123
+ function invalidates(name) {
124
+ return (specs[name]?.invalidates ?? []).map((q) => [q]);
125
+ }
126
+ // `operations`: which operations this client holds, so a pack's hooks can offer exactly the
127
+ // ones it can back (ADR 0453).
128
+ return { call, query, mutation, invalidates, operations: specs };
129
+ }
130
+ /**
131
+ * For a MutationCache's `onSuccess`: invalidates what a mutation made by this client lists in
132
+ * `meta.invalidates`. `new MutationCache({ onSuccess: invalidateFromMeta(queryClient) })`.
133
+ */
134
+ export function invalidateFromMeta(queryClient) {
135
+ return (_data, _variables, _context, mutation) => {
136
+ const stale = (mutation.meta?.invalidates ?? []);
137
+ return Promise.all(stale.map((queryKey) => queryClient.invalidateQueries({ queryKey })));
138
+ };
139
+ }
@@ -0,0 +1,23 @@
1
+ export declare class ApiError extends Error {
2
+ /** The surface's code: `invalid_input`, `unknown_operation`, `rate_limited`, … */
3
+ readonly code: string;
4
+ readonly status: number;
5
+ readonly details?: unknown | undefined;
6
+ name: string;
7
+ constructor(
8
+ /** The surface's code: `invalid_input`, `unknown_operation`, `rate_limited`, … */
9
+ code: string, message: string, status: number, details?: unknown | undefined);
10
+ }
11
+ /** The host no longer serves the version this app was built against: update the app. */
12
+ export declare class UpgradeRequiredError extends ApiError {
13
+ name: string;
14
+ constructor(message: string, details?: unknown);
15
+ }
16
+ /** The request did not reach the host, or no answer came back. Safe to retry with the same key. */
17
+ export declare class NetworkError extends Error {
18
+ readonly cause?: unknown | undefined;
19
+ name: string;
20
+ constructor(message: string, cause?: unknown | undefined);
21
+ }
22
+ /** Whether a failure is worth retrying with the same idempotency key. */
23
+ export declare function isRetryable(error: unknown): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,46 @@
1
+ // What a failed call raises (ADR 0418): the surface's envelope as an error, with its code,
2
+ // message, details and HTTP status. `upgrade_required` is its own type, so an app can show an
3
+ // "update the app" screen; a network failure is `NetworkError`.
4
+ export class ApiError extends Error {
5
+ code;
6
+ status;
7
+ details;
8
+ name = "ApiError";
9
+ constructor(
10
+ /** The surface's code: `invalid_input`, `unknown_operation`, `rate_limited`, … */
11
+ code, message, status, details) {
12
+ super(message);
13
+ this.code = code;
14
+ this.status = status;
15
+ this.details = details;
16
+ }
17
+ }
18
+ /** The host no longer serves the version this app was built against: update the app. */
19
+ export class UpgradeRequiredError extends ApiError {
20
+ name = "UpgradeRequiredError";
21
+ constructor(message, details) {
22
+ super("upgrade_required", message, 426, details);
23
+ }
24
+ }
25
+ /** The request did not reach the host, or no answer came back. Safe to retry with the same key. */
26
+ export class NetworkError extends Error {
27
+ cause;
28
+ name = "NetworkError";
29
+ constructor(message, cause) {
30
+ super(message);
31
+ this.cause = cause;
32
+ }
33
+ }
34
+ /** Whether a failure is worth retrying with the same idempotency key. */
35
+ export function isRetryable(error) {
36
+ if (error instanceof NetworkError)
37
+ return true;
38
+ if (error instanceof ApiError) {
39
+ return (error.status === 429 ||
40
+ error.status === 503 ||
41
+ error.status === 504 ||
42
+ (error.status === 409 &&
43
+ error.details?.reason === "idempotency_key_in_flight"));
44
+ }
45
+ return false;
46
+ }
@@ -0,0 +1,39 @@
1
+ import type { MutationName, OperationTypes, QueryName } from "./client.ts";
2
+ /** Any generated client: it says which operations it holds (`operations`, ADR 0453). */
3
+ export interface ClientHolding {
4
+ readonly operations: object;
5
+ }
6
+ /** The names of the operations a client holds. */
7
+ export type OperationsOf<C> = C extends {
8
+ readonly operations: infer O;
9
+ } ? keyof O & string : never;
10
+ /**
11
+ * The part of a generated client a pack's hooks use, over the pack's operations `T`: what the
12
+ * hooks are written against. Every generated client that holds them fits it.
13
+ */
14
+ export interface PackClient<T extends OperationTypes> {
15
+ query<N extends QueryName<T>>(name: N, input: T[N]["input"]): {
16
+ queryKey: readonly unknown[];
17
+ queryFn: () => Promise<T[N]["output"]>;
18
+ };
19
+ mutation<N extends MutationName<T>>(name: N): {
20
+ mutationKey: readonly unknown[];
21
+ mutationFn: (input: T[N]["input"]) => Promise<T[N]["output"]>;
22
+ };
23
+ }
24
+ /** The hooks of `H` a client holding `Names` can back: those all of whose operations it holds. */
25
+ export type HooksFor<H, Calls extends {
26
+ readonly [K in keyof H]: readonly string[];
27
+ }, Names extends string> = {
28
+ [K in keyof H as Calls[K][number] extends Names ? K : never]: H[K];
29
+ };
30
+ /**
31
+ * The hooks `make` writes, keeping only those whose operations (`calls`, one list per hook, an
32
+ * empty list for a hook that calls none) the client holds: in the type and at run time.
33
+ *
34
+ * `make` is given the client typed over all the pack's operations; a hook it writes over an
35
+ * operation the client lacks is never returned, so it is never called.
36
+ */
37
+ export declare function packHooks<T extends OperationTypes, H extends object, const Calls extends {
38
+ readonly [K in keyof H]: readonly (keyof T & string)[];
39
+ }, C extends ClientHolding>(api: C, calls: Calls, make: (api: PackClient<T>) => H): HooksFor<H, Calls, OperationsOf<C>>;
package/dist/hooks.js ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The hooks `make` writes, keeping only those whose operations (`calls`, one list per hook, an
3
+ * empty list for a hook that calls none) the client holds: in the type and at run time.
4
+ *
5
+ * `make` is given the client typed over all the pack's operations; a hook it writes over an
6
+ * operation the client lacks is never returned, so it is never called.
7
+ */
8
+ export function packHooks(api, calls, make) {
9
+ const held = new Set(Object.keys(api.operations));
10
+ // The one place the client is used as the client of every operation: only the hooks whose
11
+ // operations it holds leave this function.
12
+ const hooks = make(api);
13
+ const out = {};
14
+ for (const [name, hook] of Object.entries(hooks)) {
15
+ const needs = calls[name];
16
+ if (!needs)
17
+ throw new Error(`packHooks: ${name} does not say which operations it calls`);
18
+ if (needs.every((op) => held.has(op)))
19
+ out[name] = hook;
20
+ }
21
+ return out;
22
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./binding.ts";
2
+ export * from "./client.ts";
3
+ export * from "./errors.ts";
4
+ export * from "./hooks.ts";
5
+ export * from "./session.ts";
6
+ export type * from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // @composable-os/client: the typed client's runtime (stage 23, ADR 0403, ADR 0418).
2
+ export * from "./binding.js";
3
+ export * from "./client.js";
4
+ export * from "./errors.js";
5
+ export * from "./hooks.js";
6
+ export * from "./session.js";
@@ -0,0 +1,84 @@
1
+ import type { FetchLike } from "./types.ts";
2
+ export interface Tokens {
3
+ accessToken: string;
4
+ refreshToken: string;
5
+ /** When the access token stops working (ISO time). */
6
+ accessExpiresAt: string;
7
+ sessionId: string;
8
+ }
9
+ /** Where the tokens live between launches: expo-secure-store, the keychain, a test's memory. */
10
+ export interface TokenStore {
11
+ load(): Promise<Tokens | null>;
12
+ save(tokens: Tokens | null): Promise<void>;
13
+ }
14
+ /** Whose sign-in: a customer's (the default) or a staff member's. */
15
+ export type SignInAudience = "customer" | "staff";
16
+ /** A customer's tokens also say whether the account is ready or waits for staff to merge people. */
17
+ export interface SignedIn extends Tokens {
18
+ account?: "ready" | "needs_attention";
19
+ }
20
+ export interface TokenSessionOptions {
21
+ baseUrl: string;
22
+ store: TokenStore;
23
+ fetch?: FetchLike;
24
+ /** Refresh this long before the access token runs out. Default 30 seconds. */
25
+ refreshEarlyMs?: number;
26
+ now?: () => number;
27
+ }
28
+ export declare function tokenSession(options: TokenSessionOptions): {
29
+ /**
30
+ * Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
31
+ * cookie the sign-in answered with.
32
+ */
33
+ exchange(deviceName: string, credentials: Record<string, string>): Promise<Tokens>;
34
+ /**
35
+ * Asks the host to email a sign-in code (ADR 0455). The answer is the same whoever the
36
+ * address is; it throws only when the host refuses to send any (`rate_limited`, or sign-in
37
+ * not set up).
38
+ */
39
+ requestCode(email: string, audience?: SignInAudience): Promise<void>;
40
+ /**
41
+ * Signs in with the emailed code and keeps the device session the host answers with. A wrong,
42
+ * used or expired code throws `forbidden` (`invalid_code`). No cookie is involved.
43
+ */
44
+ signInWithCode(email: string, code: string, deviceName: string, audience?: SignInAudience): Promise<SignedIn>;
45
+ /**
46
+ * Finishes a staff sign-in in the system browser (`startBrowserSignIn`): checks the state it
47
+ * was sent back with and exchanges the code, with the verifier, for a device session.
48
+ */
49
+ finishBrowserSignIn(input: {
50
+ callbackUrl: string;
51
+ state: string;
52
+ verifier: string;
53
+ redirectUri: string;
54
+ deviceName: string;
55
+ }): Promise<Tokens>;
56
+ /** The headers for a call: a current access token, refreshed first when it is about to end. */
57
+ headers(): Promise<Record<string, string>>;
58
+ /**
59
+ * Ends this device's session on the host (ADR 0455) with its refresh token, which any account
60
+ * may do whatever it may call, then forgets the tokens, even when the host could not be
61
+ * reached.
62
+ */
63
+ signOut(): Promise<void>;
64
+ };
65
+ export interface BrowserSignInOptions {
66
+ /** The host's address. */
67
+ hostUrl: string;
68
+ /** The app's own address the host sends the code to, listed in the host's NATIVE_REDIRECT_URIS. */
69
+ redirectUri: string;
70
+ /** Random characters (React Native has no `crypto`: the app passes expo-crypto's). */
71
+ randomKey: () => string;
72
+ /** SHA-256 of a string, as bytes (expo-crypto's digest). */
73
+ sha256: (text: string) => Promise<Uint8Array>;
74
+ }
75
+ /**
76
+ * Starts a staff sign-in in the system browser (ADR 0455): the URL to open in an ephemeral
77
+ * `ASWebAuthenticationSession` or Custom Tab (never a web view), and the state and verifier to
78
+ * keep until `finishBrowserSignIn`. The verifier never leaves the app.
79
+ */
80
+ export declare function startBrowserSignIn(options: BrowserSignInOptions): Promise<{
81
+ url: string;
82
+ state: string;
83
+ verifier: string;
84
+ }>;
@@ -0,0 +1,194 @@
1
+ // Sessions for native apps (stage 23, ADR 0419; signing in for tokens, ADR 0455). A phone signs
2
+ // in with a code emailed to the person and gets a short-lived access token and a refresh token in
3
+ // the answer's body (no cookie is ever set), keeps both in its secure store, and refreshes before
4
+ // the access token runs out. Every refresh rotates the refresh token; the host ends the session
5
+ // when an old one is used again, so two copies of one session cannot both live.
6
+ //
7
+ // const session = tokenSession({ baseUrl, store: secureStore });
8
+ // await session.requestCode(email);
9
+ // await session.signInWithCode(email, code, "Ada's phone");
10
+ // const api = createCustomerClient({ baseUrl, headers: session.headers });
11
+ //
12
+ // Staff whose sign-in is browser-based (Google, Cloudflare Access) use `startBrowserSignIn` and
13
+ // `finishBrowserSignIn` instead: the system browser signs them in, never a web view.
14
+ import { ApiError, NetworkError } from "./errors.js";
15
+ async function post(fetcher, url, body, headers = {}) {
16
+ let response;
17
+ try {
18
+ response = await fetcher(url, {
19
+ method: "POST",
20
+ headers: { "content-type": "application/json", ...headers },
21
+ body: JSON.stringify(body),
22
+ });
23
+ }
24
+ catch (error) {
25
+ throw new NetworkError("Could not reach the host to sign in", error);
26
+ }
27
+ const parsed = JSON.parse(await response.text());
28
+ if (response.status === 200 && parsed.data)
29
+ return parsed.data;
30
+ throw new ApiError(parsed.error?.code ?? "internal", parsed.error?.message ?? `The host answered ${response.status}`, response.status, parsed.error?.details);
31
+ }
32
+ export function tokenSession(options) {
33
+ const base = options.baseUrl.replace(/\/+$/, "");
34
+ const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
35
+ const early = options.refreshEarlyMs ?? 30_000;
36
+ const now = options.now ?? (() => Date.now());
37
+ // One refresh at a time: two at once would present one refresh token twice and end the session.
38
+ let refreshing = null;
39
+ async function refresh(tokens) {
40
+ try {
41
+ const next = await post(fetcher, `${base}/api/v1/auth/refresh`, {
42
+ refreshToken: tokens.refreshToken,
43
+ });
44
+ await options.store.save(next);
45
+ return next;
46
+ }
47
+ catch (error) {
48
+ // The session ended (signed out, unused too long, a reused token): forget it.
49
+ if (error instanceof ApiError)
50
+ await options.store.save(null);
51
+ throw error;
52
+ }
53
+ }
54
+ return {
55
+ /**
56
+ * Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
57
+ * cookie the sign-in answered with.
58
+ */
59
+ async exchange(deviceName, credentials) {
60
+ const tokens = await post(fetcher, `${base}/api/v1/auth/token`, { deviceName }, credentials);
61
+ await options.store.save(tokens);
62
+ return tokens;
63
+ },
64
+ /**
65
+ * Asks the host to email a sign-in code (ADR 0455). The answer is the same whoever the
66
+ * address is; it throws only when the host refuses to send any (`rate_limited`, or sign-in
67
+ * not set up).
68
+ */
69
+ async requestCode(email, audience = "customer") {
70
+ await post(fetcher, `${base}/api/v1/auth/${audience}/code`, { email });
71
+ },
72
+ /**
73
+ * Signs in with the emailed code and keeps the device session the host answers with. A wrong,
74
+ * used or expired code throws `forbidden` (`invalid_code`). No cookie is involved.
75
+ */
76
+ async signInWithCode(email, code, deviceName, audience = "customer") {
77
+ const signedIn = await post(fetcher, `${base}/api/v1/auth/${audience}/sign-in`, {
78
+ email,
79
+ code,
80
+ deviceName,
81
+ });
82
+ const { account: _account, ...tokens } = signedIn;
83
+ await options.store.save(tokens);
84
+ return signedIn;
85
+ },
86
+ /**
87
+ * Finishes a staff sign-in in the system browser (`startBrowserSignIn`): checks the state it
88
+ * was sent back with and exchanges the code, with the verifier, for a device session.
89
+ */
90
+ async finishBrowserSignIn(input) {
91
+ const query = input.callbackUrl.includes("?") ? (input.callbackUrl.split("?")[1] ?? "") : "";
92
+ const params = new Map(query
93
+ .split("&")
94
+ .filter(Boolean)
95
+ .map((pair) => {
96
+ const [key = "", value = ""] = pair.split("=");
97
+ return [decodeURIComponent(key), decodeURIComponent(value.replace(/\+/g, " "))];
98
+ }));
99
+ const code = params.get("code");
100
+ if (!code || params.get("state") !== input.state) {
101
+ throw new ApiError("forbidden", "The sign-in did not come back from this app's request", 401, {
102
+ reason: "invalid_code",
103
+ });
104
+ }
105
+ const tokens = await post(fetcher, `${base}/api/v1/auth/staff/exchange`, {
106
+ code,
107
+ codeVerifier: input.verifier,
108
+ redirectUri: input.redirectUri,
109
+ deviceName: input.deviceName,
110
+ });
111
+ await options.store.save(tokens);
112
+ return tokens;
113
+ },
114
+ /** The headers for a call: a current access token, refreshed first when it is about to end. */
115
+ async headers() {
116
+ let tokens = await options.store.load();
117
+ if (!tokens)
118
+ return {};
119
+ if (Date.parse(tokens.accessExpiresAt) - early <= now()) {
120
+ refreshing ??= refresh(tokens).finally(() => {
121
+ refreshing = null;
122
+ });
123
+ tokens = await refreshing;
124
+ if (!tokens)
125
+ return {};
126
+ }
127
+ return { authorization: `Bearer ${tokens.accessToken}` };
128
+ },
129
+ /**
130
+ * Ends this device's session on the host (ADR 0455) with its refresh token, which any account
131
+ * may do whatever it may call, then forgets the tokens, even when the host could not be
132
+ * reached.
133
+ */
134
+ async signOut() {
135
+ const tokens = await options.store.load();
136
+ try {
137
+ if (tokens) {
138
+ await post(fetcher, `${base}/api/v1/auth/sign-out`, {
139
+ refreshToken: tokens.refreshToken,
140
+ });
141
+ }
142
+ }
143
+ catch {
144
+ // Forgotten here either way; the host ends an unused session after the idle setting.
145
+ }
146
+ finally {
147
+ await options.store.save(null);
148
+ }
149
+ },
150
+ };
151
+ }
152
+ function base64url(bytes) {
153
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
154
+ let out = "";
155
+ for (let i = 0; i < bytes.length; i += 3) {
156
+ const a = bytes[i] ?? 0;
157
+ const b = bytes[i + 1];
158
+ const c = bytes[i + 2];
159
+ out += alphabet[a >> 2];
160
+ out += alphabet[((a & 3) << 4) | ((b ?? 0) >> 4)];
161
+ if (b !== undefined)
162
+ out += alphabet[((b & 15) << 2) | ((c ?? 0) >> 6)];
163
+ if (c !== undefined)
164
+ out += alphabet[c & 63];
165
+ }
166
+ return out;
167
+ }
168
+ /**
169
+ * Starts a staff sign-in in the system browser (ADR 0455): the URL to open in an ephemeral
170
+ * `ASWebAuthenticationSession` or Custom Tab (never a web view), and the state and verifier to
171
+ * keep until `finishBrowserSignIn`. The verifier never leaves the app.
172
+ */
173
+ export async function startBrowserSignIn(options) {
174
+ const verifier = `${options.randomKey()}${options.randomKey()}`
175
+ .replace(/[^A-Za-z0-9._~-]/g, "")
176
+ .slice(0, 128);
177
+ if (verifier.length < 43)
178
+ throw new Error("randomKey must give at least 22 characters");
179
+ const state = options.randomKey().replace(/[^A-Za-z0-9._~-]/g, "");
180
+ const challenge = base64url(await options.sha256(verifier));
181
+ const query = [
182
+ ["redirect_uri", options.redirectUri],
183
+ ["code_challenge", challenge],
184
+ ["code_challenge_method", "S256"],
185
+ ["state", state],
186
+ ]
187
+ .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
188
+ .join("&");
189
+ return {
190
+ url: `${options.hostUrl.replace(/\/+$/, "")}/native/staff-sign-in?${query}`,
191
+ state,
192
+ verifier,
193
+ };
194
+ }
@@ -0,0 +1,17 @@
1
+ export interface ResponseLike {
2
+ readonly status: number;
3
+ readonly headers: {
4
+ get(name: string): string | null;
5
+ };
6
+ text(): Promise<string>;
7
+ }
8
+ export interface RequestInitLike {
9
+ method: string;
10
+ headers: Record<string, string>;
11
+ body?: string;
12
+ }
13
+ export type FetchLike = (url: string, init: RequestInitLike) => Promise<ResponseLike>;
14
+ /** Plain JSON, as the surface sends it. */
15
+ export type Json = string | number | boolean | null | Json[] | {
16
+ [key: string]: Json;
17
+ };
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // The little of the Fetch API the client uses, declared here so the runtime depends on no
2
+ // platform's types (ADR 0418). The global `fetch` of a browser, a Worker, Node and React Native
3
+ // all fit `FetchLike`, and so does a Worker's service binding (`env.HOST.fetch`).
4
+ export {};
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@composable-os/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.8",
4
+ "license": "FSL-1.1-ALv2",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/timoconnellaus/composable-os.git"
9
+ },
10
+ "homepage": "https://composableos.dev",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "description": "The typed client's runtime (stage 23, ADR 0403): the transport, the error types, idempotency keys and the TanStack Query option helpers. No DOM, Node or Workers dependency: it runs in TanStack Start, a Worker and React Native alike. A product's typed operations are generated by `cos client generate`.",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ]
25
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.