@rexezuge/web 1.14.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/api.d.ts +18 -2
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +1 -1
- package/dist/api.js.map +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ const api = createApiClient({ baseUrl: '', fetchFn: fetch });
|
|
|
83
83
|
const me = await api.get('/user'); // typed JSON; 204/empty bodies resolve to undefined
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
-
Every rejection is a `ServiceError` with `status` / `type` / `retryable`, decoded from the family `{ Exception: { Type, Message } }` envelope first, then the legacy `{ error, message }` shape; markup bodies are treated as absent and messages truncate at `MAX_ERROR_MESSAGE_LENGTH` (500). `buildQuery` encodes `QueryParams`. Deliberately excluded: the authed-first public fallback, WebDAV `207` handling, and per-app `SUPPORTED_LANGUAGES` — each had exactly one consumer, so each stays with it.
|
|
86
|
+
Every rejection is a `ServiceError` with `status` / `type` / `retryable`, decoded from the family `{ Exception: { Type, Message } }` envelope first, then the legacy `{ error, message }` shape; `type` is the server's `Exception.Type`, verbatim, and the class is chosen by it when the catalog knows it (a `DatabaseError` stays one; `InternalError` and `InternalServerError` both decode to `InternalServerError`), else by status; markup bodies are treated as absent and messages truncate at `MAX_ERROR_MESSAGE_LENGTH` (500). `serviceErrorFromResponse(response, { maxErrorMessageLength })` is the same decoder for a plane the client cannot read (an XML WebDAV multistatus), so one error shape reaches the UI. `buildQuery` encodes `QueryParams`. Deliberately excluded: the authed-first public fallback, WebDAV `207` handling, and per-app `SUPPORTED_LANGUAGES` — each had exactly one consumer, so each stays with it.
|
|
87
87
|
|
|
88
88
|
**D1 session bookmarks** (`x-d1-bookmark`, converged from the CalDAV-Bridge / Mail-Meow / Mail-Otter `apiFetch` copies) are **on by default**, which is safe: the client only echoes a value the server sent, so against a Worker without D1 sessions nothing is ever sent. The store belongs to the client (no module state, no `resetD1Bookmark()` test seam), keeps the **newest** bookmark so a slow response cannot move the session backwards, and is read from error responses too. `bookmarks: false` turns it off; `createBookmarkStore()` passed to several clients shares one session.
|
|
89
89
|
|
package/dist/api.d.ts
CHANGED
|
@@ -134,6 +134,22 @@ declare const MAX_ERROR_MESSAGE_LENGTH = 500;
|
|
|
134
134
|
declare class HttpStatusError extends ServiceError {
|
|
135
135
|
constructor(status: number, message: string, type: string | null);
|
|
136
136
|
}
|
|
137
|
+
interface ServiceErrorFromResponseOptions {
|
|
138
|
+
/**
|
|
139
|
+
Truncation limit for a server-provided message. Defaults to 500.
|
|
140
|
+
*/
|
|
141
|
+
maxErrorMessageLength?: number;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* A failed response as the `ServiceError` {@link createApiClient} throws, for planes the client cannot read
|
|
145
|
+
* itself (an XML WebDAV multistatus, a download). Reads the body once, in any of the three dialects.
|
|
146
|
+
*
|
|
147
|
+
* The server's `Exception.Type` is kept on `error.type` verbatim. The class is chosen by that `Type` when the
|
|
148
|
+
* catalog knows it (so a `DatabaseError` stays a `DatabaseError`), else by status; `error.status` is always
|
|
149
|
+
* the response's. A `DatabaseError` answered with 503 is the server's "transient, retry" verdict, so it
|
|
150
|
+
* comes back `retryable`.
|
|
151
|
+
*/
|
|
152
|
+
declare function serviceErrorFromResponse(response: Response, options?: ServiceErrorFromResponseOptions): Promise<ServiceError>;
|
|
137
153
|
/**
|
|
138
154
|
* Builds a query string, with the leading `?` and without it when empty.
|
|
139
155
|
*
|
|
@@ -157,6 +173,6 @@ declare function buildQuery(params: QueryParams): string;
|
|
|
157
173
|
* instance per render still churns.
|
|
158
174
|
*/
|
|
159
175
|
declare function createApiClient(fetchFn: FetchFn, options?: CreateApiClientOptions): ApiClient;
|
|
160
|
-
export { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH };
|
|
161
|
-
export type { ApiClient, ApiRequestInit, CreateApiClientOptions, FetchFn, QueryParams, QueryValue };
|
|
176
|
+
export { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH, serviceErrorFromResponse };
|
|
177
|
+
export type { ApiClient, ApiRequestInit, CreateApiClientOptions, ServiceErrorFromResponseOptions, FetchFn, QueryParams, QueryValue };
|
|
162
178
|
//# sourceMappingURL=api.d.ts.map
|
package/dist/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAcL,YAAY,EAIb,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AAEH;;EAEE;AACF,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAExE;;EAEE;AACF,KAAK,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;AAE/D,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,UAAU,EAAE,CAAC,CAAC;AAEtE,UAAU,cAAc;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;MAEE;IACF,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,MAAM,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;IAC5B;;;;;;MAME;IACF,K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CAGjE;AA4FD,UAAU,+BAA+B;IACvC;;MAEE;IACF,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,iBAAe,wBAAwB,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,GAAE,+BAAoC,GAAG,OAAO,CAAC,YAAY,CAAC,CAuBhI;AAiBD;;;;;;GAMG;AACH,iBAAS,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAkB/C;AAED;;;;;;;;;;;;;GAaG;AACH,iBAAS,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,sBAA2B,GAAG,SAAS,CA8F1F;AAED,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,eAAe,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,CAAC;AAC5G,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC"}
|
package/dist/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var D=Object.defineProperty;var c=(e,t)=>D(e,"name",{value:t,configurable:!0});import{BadGatewayError as O,BadRequestError as P,ConflictError as C,DatabaseError as N,ForbiddenError as $,InternalServerError as E,MethodNotAllowedError as M,NotFoundError as _,NotImplementedError as k,PayloadTooLargeError as H,PreconditionFailedError as L,RateLimitedError as U,INTERNAL_ERROR_TYPE as z,ServiceError as h,ServiceUnavailableError as x,UnauthorizedError as B,UnsupportedMediaTypeError as F}from"@rexezuge/errors";import{D1_BOOKMARK_HEADER as g,resolveBookmarkStore as K}from"./bookmarks.js";const b=500,j={400:P,401:B,403:$,404:_,405:M,409:C,412:L,413:H,415:F,429:U,500:E,501:k,502:O,503:x},v={BadRequest:P,Unauthorized:B,Forbidden:$,NotFound:_,MethodNotAllowed:M,Conflict:C,PreconditionFailed:L,PayloadTooLarge:H,UnsupportedMediaType:F,RateLimited:U,InternalServerError:E,[z]:E,NotImplemented:k,BadGateway:O,ServiceUnavailable:x,DatabaseError:N};class R extends h{static{c(this,"HttpStatusError")}constructor(t,a,r){super(t,r??`HttpStatus${t}`,a)}}function l(e){return typeof e=="string"&&e.trim()!==""?e:null}c(l,"readString");function S(e,t){return e.length>t?`${e.slice(0,t)}\u2026`:e}c(S,"truncate");const Q=/[\u0000-\u001F\u007F]/;function Y(e,t){return e.length===0||e.length>t||e.includes("<")?!1:!Q.test(e)}c(Y,"isProbablyProse");function X(e,t,a){if(typeof e=="string"){const n=e.trim();return{message:n===""?null:S(n,a),type:null}}if(typeof e!="object"||e===null)return{message:null,type:null};const r=e,o=typeof r.error=="object"&&r.error!==null?r.error:null,u=l(r.Exception?.Type)??(typeof r.error=="string"?l(r.error):null)??l(o?.code)??l(r.code)??null,i=l(r.Exception?.Message)??l(r.message)??(typeof r.error=="string"?l(r.error):null)??l(o?.message)??null;return i!==null?{message:S(i,a),type:u}:u!==null?{message:`${u} (HTTP ${t})`,type:u}:{message:null,type:null}}c(X,"decodeJsonError");function V(e,t,a){const r=e.trim();if(r==="")return{message:null,type:null};try{return X(JSON.parse(r),t,a)}catch{return{message:Y(r,a)?S(r,a):null,type:null}}}c(V,"decodeErrorBody");async function q(e,t={}){let a="";try{a=await e.text()}catch{}const r=V(a,e.status,t.maxErrorMessageLength??b),{status:o}=e,i=(r.type!==null&&Object.hasOwn(v,r.type)?v[r.type]:void 0)??(Object.hasOwn(j,o)?j[o]:void 0);if(i===void 0)return new R(o,r.message??`Request failed with status ${o}.`,r.type);const n=new i(r.message??void 0);return n.status=o,r.type!==null&&(n.type=r.type),n instanceof N&&o===503&&(n.retryable=!0),n}c(q,"serviceErrorFromResponse");function W(e,t){const a=new Headers(e);if(t===void 0)return a;for(const[r,o]of new Headers(t))a.set(r,o);return a}c(W,"mergeHeaders");function Z(e){return Array.isArray(e)}c(Z,"isQueryList");function G(e){const t=new URLSearchParams;for(const[r,o]of Object.entries(e))if(!(o==null||o==="")){if(Z(o)){for(const u of o)u!=null&&u!==""&&t.append(r,String(u));continue}t.set(r,String(o))}const a=t.toString();return a===""?"":`?${a}`}c(G,"buildQuery");function ee(e,t={}){const a=t.baseUrl??"",r=t.maxErrorMessageLength??b,o=K(t.bookmarks);async function u(n,s={}){const f=(s.method??"GET").toUpperCase(),p=`${a}${n}`,T=s.body!==void 0,d=W(t.headers,s.headers);d.has("Accept")||d.set("Accept","application/json"),T&&!d.has("Content-Type")&&d.set("Content-Type","application/json");const w=o?.get()??null;w!==null&&!d.has(g)&&d.set(g,w);const y={method:f,headers:d};t.credentials!==void 0&&(y.credentials=t.credentials),T&&(y.body=JSON.stringify(s.body)),s.signal!==void 0&&s.signal!==null&&(y.signal=s.signal),s.cache!==void 0&&(y.cache=s.cache);const I=`${f} ${p}`;let m;try{m=await e(p,y)}catch(J){throw h.from(J)}const A=m.headers.get(g);if(o!==null&&A!==null&&o.set(A),!m.ok)throw await q(m,{maxErrorMessageLength:r});return i(m,I)}c(u,"request");async function i(n,s){if(n.status===204)return;let f;try{f=await n.text()}catch(p){throw h.from(p)}if(f.trim()!=="")try{return JSON.parse(f)}catch{throw new R(n.status,`Malformed response body: ${s}`,null)}}return c(i,"readJson"),{request:u,get:c(async(n,s)=>u(`${n}${s===void 0?"":G(s)}`),"get"),post:c(async(n,s)=>u(n,{method:"POST",body:s}),"post"),put:c(async(n,s)=>u(n,{method:"PUT",body:s}),"put"),patch:c(async(n,s)=>u(n,{method:"PATCH",body:s}),"patch"),delete:c(async(n,s)=>u(n,{method:"DELETE",body:s}),"delete")}}c(ee,"createApiClient");export{R as HttpStatusError,b as MAX_ERROR_MESSAGE_LENGTH,G as buildQuery,ee as createApiClient,q as serviceErrorFromResponse};
|
package/dist/api.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/api.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n BadGatewayError,\n BadRequestError,\n ConflictError,\n ForbiddenError,\n InternalServerError,\n MethodNotAllowedError,\n NotFoundError,\n NotImplementedError,\n PayloadTooLargeError,\n PreconditionFailedError,\n RateLimitedError,\n ServiceError,\n ServiceUnavailableError,\n UnauthorizedError,\n UnsupportedMediaTypeError,\n} from '@rexezuge/errors';\nimport { D1_BOOKMARK_HEADER, resolveBookmarkStore } from './bookmarks.ts';\nimport type { BookmarkStore } from './bookmarks.ts';\n\n/**\n * The SPA's request path.\n *\n * ## Provenance\n *\n * `lib/api.ts` in **CalDAV-Bridge**, **Durable-DAV**, **Durable-DAV-Router**,\n * **Edge-Git**, **Edge-Sonic**, **Mail-Otter** and **AWS-AccessBridge** — seven\n * copies that all drift on the same three decisions, settled here as follows.\n *\n * **1. Error model.** Six of the seven define a private `BackendError`\n * (`{ message, errorType, status }`) and hand-roll the status→branch mapping at\n * every call site; AWS defines `ApiError` (`{ status, message }`) plus an\n * `ApiResult{ok,status,data,error}` shape that its own guide records as\n * abandoned — every admin tab bypassed it, which is how nine of its seventeen\n * functions ended up with no caller. The kit replaces both with the family\n * taxonomy: every rejection is a `ServiceError`, so `error.status`,\n * `error.type`, `error.retryable` and `instanceof ServiceError` are available\n * without a per-repo error class, and `ServiceError.from` covers the\n * transport-level failures the private classes swallowed.\n *\n * **2. Error body decoding.** Converged from the three variants that exist:\n *\n * - The **AWS envelope** `{ Exception: { Type, Message } }`, read first in all\n * copies.\n * - The **legacy** `{ error, message }` shape, where Durable-DAV also reads a\n * string `error` as the *type* — otherwise a legacy body produced a correct\n * message and a `null` type, which sent it through the generic fallback and\n * lost the specific wording.\n * - **Edge-Sonic's prose test** for a non-JSON body: an Access login page or a\n * proxy's HTML error page is not a message an operator can act on, so markup\n * is reported as absent rather than quoted into a notice bar. Short,\n * single-line, tag-free text *is* surfaced, truncated.\n * - **Truncation** at 500 characters, from every copy that has one: an\n * unbounded error string from a proxy page is a rendering hazard.\n * - **`text()` then `JSON.parse`, never `json()` with a `text()` fallback** —\n * Edge-Sonic's comment records why the old shape cannot work: `json()`\n * consumes the body stream before it fails to parse, so the second read\n * returned `''` and the \"not JSON\" branch was unreachable.\n *\n * **3. Empty bodies.** Durable-DAV's fix is the one kept: a `204`, and an empty\n * body from an edge error page, resolve to `undefined` rather than throwing a\n * `SyntaxError` — which used to report a generic failure for an operation that\n * had actually succeeded (credential revoke). AWS-AccessBridge resolved the same\n * case to `{}`; `undefined` is the honest answer for \"there is no body\".\n *\n * D1 session bookmarks are on by default (`bookmarks`); see `./bookmarks.ts`.\n *\n * ## What is deliberately not here\n *\n * - **`apiAuthedFirst`** (Edge-Git) — a public-fallback policy with\n * fail-closed 401/403/404 handling, specific to that app's two-surface API.\n * - **WebDAV `readDav`** (Durable-DAV, Durable-DAV-Router) — it accepts `207\n * Multi-Status` as success, which is a WebDAV rule, not an HTTP rule. A\n * consumer needing XML calls `client.request` and reads `response.text()`\n * itself.\n * - **The `/user` base path.** Edge-Sonic bakes it in; the others pass full\n * paths. `baseUrl` is an option here, defaulting to empty, so the caller\n * decides.\n */\n\n/**\nThe `fetch` shape a client is built on: same-origin by default, no token in JavaScript.\n*/\ntype FetchFn = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\nA query-string value. `null`/`undefined`/`''` are omitted, as in every copy.\n*/\ntype QueryValue = string | number | boolean | null | undefined;\n\ntype QueryParams = Record<string, QueryValue | readonly QueryValue[]>;\n\ninterface ApiRequestInit {\n method?: string;\n /**\n Serialized as JSON with a matching `Content-Type`.\n */\n body?: unknown;\n headers?: HeadersInit;\n signal?: AbortSignal | null;\n /**\n Passed through to `fetch`; omitted leaves the browser default.\n\n It is a standard `RequestInit` field, so a caller that needs `'no-store'`\n (an auth probe that must never read a cached page) or `'reload'` does not have\n to reach around the client to set it.\n */\n cache?: RequestCache;\n}\n\ninterface CreateApiClientOptions {\n /**\n Prepended to every path; `''` (the default) sends the path as given.\n */\n baseUrl?: string;\n /**\n Headers merged into every request; a per-request header wins over these.\n */\n headers?: HeadersInit;\n /**\n Passed through to `fetch`; omitted leaves the browser default.\n */\n credentials?: RequestCredentials;\n /**\n Truncation limit for a server-provided error message. Defaults to 500.\n */\n maxErrorMessageLength?: number;\n /**\n * D1 session bookmarks: `true` (the default) keeps them in a store private to\n * this client, a `BookmarkStore` shares one, `false` never sends or stores one.\n */\n bookmarks?: boolean | BookmarkStore;\n}\n\ninterface ApiClient {\n /**\n One request. Throws a `ServiceError`; resolves to the parsed JSON body.\n */\n request<T>(path: string, init?: ApiRequestInit): Promise<T>;\n get<T>(path: string, params?: QueryParams): Promise<T>;\n post<T>(path: string, body?: unknown): Promise<T>;\n put<T>(path: string, body?: unknown): Promise<T>;\n patch<T>(path: string, body?: unknown): Promise<T>;\n delete<T>(path: string, body?: unknown): Promise<T>;\n}\n\n/**\nDefault truncation for a server-provided message.\n*/\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\n/**\n * Statuses the family taxonomy has a class for, mapped to it.\n *\n * The map is keyed by status rather than by the server's `Exception.Type`\n * because the status is the fact that survives a rolling deploy: a body from an\n * older Worker build still carries today's status, while a `Type` may be\n * spelled either way.\n */\nconst HTTP_ERROR_CLASSES: Readonly<Record<number, new (message?: string) => ServiceError>> = {\n 400: BadRequestError,\n 401: UnauthorizedError,\n 403: ForbiddenError,\n 404: NotFoundError,\n 405: MethodNotAllowedError,\n 409: ConflictError,\n 412: PreconditionFailedError,\n 413: PayloadTooLargeError,\n 415: UnsupportedMediaTypeError,\n 429: RateLimitedError,\n 500: InternalServerError,\n 501: NotImplementedError,\n 502: BadGatewayError,\n 503: ServiceUnavailableError,\n};\n\n/**\n * A failure whose only fact is its HTTP status: a status the catalog has no\n * class for (451, 418, a proxy's own 5xx), or a 2xx body that is not JSON.\n *\n * It exists so the thrown value is *always* a `ServiceError` — a caller\n * branching on `instanceof ServiceError` does not have to know which statuses\n * the catalog happens to cover.\n */\nclass HttpStatusError extends ServiceError {\n constructor(status: number, message: string, type: string | null) {\n super(status, type ?? `HttpStatus${status}`, message);\n }\n}\n\ninterface DecodedErrorBody {\n /**\n What the server said, or `null` when it said nothing usable.\n */\n message: string | null;\n /**\n The server's machine-readable code, when it sent one.\n */\n type: string | null;\n}\n\nfunction readString(value: unknown): string | null {\n return typeof value === 'string' && value.trim() !== '' ? value : null;\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;\n}\n\n/**\nRejects control characters: that is what separates text from a binary or a document.\n*/\n// eslint-disable-next-line no-control-regex -- rejecting control characters IS the test\nconst CONTROL_CHARACTER = /[\\u0000-\\u001F\\u007F]/;\n\n/**\n * Whether a non-JSON error body is text worth showing rather than markup or a\n * blob. Deliberately conservative: the cost of wrongly refusing is the generic\n * status sentence, and the cost of wrongly accepting is an HTML page in a\n * notice bar.\n */\nfunction isProbablyProse(raw: string, maxLength: number): boolean {\n if (raw.length === 0 || raw.length > maxLength || raw.includes('<')) {\n return false;\n }\n return !CONTROL_CHARACTER.test(raw);\n}\n\nfunction decodeJsonError(payload: unknown, status: number, maxLength: number): DecodedErrorBody {\n if (typeof payload === 'string') {\n const message = payload.trim();\n return { message: message === '' ? null : truncate(message, maxLength), type: null };\n }\n if (typeof payload !== 'object' || payload === null) {\n return { message: null, type: null };\n }\n // Three dialects, newest first: the AWS envelope, the unified `{error:\n // {code,message}}` object, and the legacy flat `{error, message}`.\n const envelope = payload as {\n Exception?: { Type?: unknown; Message?: unknown };\n error?: unknown;\n message?: unknown;\n code?: unknown;\n };\n const nestedError =\n typeof envelope.error === 'object' && envelope.error !== null ? (envelope.error as { message?: unknown; code?: unknown }) : null;\n const type =\n readString(envelope.Exception?.Type) ??\n (typeof envelope.error === 'string' ? readString(envelope.error) : null) ??\n readString(nestedError?.code) ??\n readString(envelope.code) ??\n null;\n const message =\n readString(envelope.Exception?.Message) ??\n readString(envelope.message) ??\n (typeof envelope.error === 'string' ? readString(envelope.error) : null) ??\n readString(nestedError?.message) ??\n null;\n if (message !== null) {\n return { message: truncate(message, maxLength), type };\n }\n if (type !== null) {\n // The server named the failure but gave no sentence for it.\n return { message: `${type} (HTTP ${status})`, type };\n }\n return { message: null, type: null };\n}\n\nfunction decodeErrorBody(text: string, status: number, maxLength: number): DecodedErrorBody {\n const trimmed = text.trim();\n if (trimmed === '') {\n return { message: null, type: null };\n }\n try {\n return decodeJsonError(JSON.parse(trimmed) as unknown, status, maxLength);\n } catch {\n return { message: isProbablyProse(trimmed, maxLength) ? truncate(trimmed, maxLength) : null, type: null };\n }\n}\n\nfunction mergeHeaders(base: HeadersInit | undefined, overrides?: HeadersInit): Headers {\n const headers = new Headers(base);\n if (overrides === undefined) {\n return headers;\n }\n for (const [name, value] of new Headers(overrides)) {\n headers.set(name, value);\n }\n return headers;\n}\n\nfunction isQueryList(value: QueryValue | readonly QueryValue[]): value is readonly QueryValue[] {\n return Array.isArray(value);\n}\n\n/**\n * Builds a query string, with the leading `?` and without it when empty.\n *\n * `null`, `undefined` and `''` are dropped rather than sent as empty\n * parameters, and an array value repeats the key — both as in the copies this\n * replaces.\n */\nfunction buildQuery(params: QueryParams): string {\n const search = new URLSearchParams();\n for (const [name, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === '') {\n continue;\n }\n if (isQueryList(value)) {\n for (const entry of value) {\n if (entry !== undefined && entry !== null && entry !== '') {\n search.append(name, String(entry));\n }\n }\n continue;\n }\n search.set(name, String(value));\n }\n const encoded = search.toString();\n return encoded === '' ? '' : `?${encoded}`;\n}\n\n/**\n * Builds a client over a `fetch` implementation.\n *\n * ```ts\n * const api = createApiClient(fetch, { baseUrl: '/user' });\n * const me = await api.get<CurrentUser>('/me');\n * ```\n *\n * The `fetchFn` parameter is what makes this testable without a network and\n * swappable for an instrumented wrapper; in a browser it is the global `fetch`.\n * Memoize the client (a module constant, or `useMemo`) — `useCurrentUser`\n * deliberately does not re-fetch when a new client instance appears, but a new\n * instance per render still churns.\n */\nfunction createApiClient(fetchFn: FetchFn, options: CreateApiClientOptions = {}): ApiClient {\n const baseUrl = options.baseUrl ?? '';\n const maxErrorMessageLength = options.maxErrorMessageLength ?? MAX_ERROR_MESSAGE_LENGTH;\n const bookmarks = resolveBookmarkStore(options.bookmarks);\n\n async function request<T>(path: string, init: ApiRequestInit = {}): Promise<T> {\n const method = (init.method ?? 'GET').toUpperCase();\n const url = `${baseUrl}${path}`;\n const hasBody = init.body !== undefined;\n const headers = mergeHeaders(options.headers, init.headers);\n // Same-origin only, and no token in JavaScript: the Cloudflare Access\n // session cookie rides along under the default credentials, and there is no\n // place for a token to leak to. Both defaults yield to an explicit header\n // — a consumer that wants XML passes its own `Accept`.\n if (!headers.has('Accept')) {\n headers.set('Accept', 'application/json');\n }\n if (hasBody && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n const bookmark = bookmarks?.get() ?? null;\n if (bookmark !== null && !headers.has(D1_BOOKMARK_HEADER)) {\n headers.set(D1_BOOKMARK_HEADER, bookmark);\n }\n const requestInit: RequestInit = { method, headers };\n if (options.credentials !== undefined) {\n requestInit.credentials = options.credentials;\n }\n if (hasBody) {\n requestInit.body = JSON.stringify(init.body);\n }\n if (init.signal !== undefined && init.signal !== null) {\n requestInit.signal = init.signal;\n }\n if (init.cache !== undefined) {\n requestInit.cache = init.cache;\n }\n\n const context = `${method} ${url}`;\n let response: Response;\n try {\n response = await fetchFn(url, requestInit);\n } catch (cause) {\n // The transport never answered — offline, DNS, CORS, an aborted signal.\n // There is no status to report, so the failure normalizes through\n // `ServiceError.from` like any other unknown throw. A caller that cancels\n // its own request therefore sees a 500-shaped error too; the taxonomy has\n // no \"aborted\" class, and swallowing it here would hide real transport\n // failures. A caller that cancels should not surface the rejection.\n throw ServiceError.from(cause);\n }\n // Read on every status: a failed write still advanced the session.\n const nextBookmark = response.headers.get(D1_BOOKMARK_HEADER);\n if (bookmarks !== null && nextBookmark !== null) {\n bookmarks.set(nextBookmark);\n }\n if (!response.ok) {\n throw await toServiceError(response);\n }\n return readJson<T>(response, context);\n }\n\n async function toServiceError(response: Response): Promise<ServiceError> {\n let text = '';\n try {\n text = await response.text();\n } catch {\n // The body could not be read at all — a reset after the headers. The\n // status is still the one true thing about the request, and the catalog\n // default message says more than anything this could invent.\n }\n const decoded = decodeErrorBody(text, response.status, maxErrorMessageLength);\n if (Object.hasOwn(HTTP_ERROR_CLASSES, response.status)) {\n const ErrorClass = HTTP_ERROR_CLASSES[response.status];\n // A `null` message leaves the catalog's default in place, which is a\n // better sentence than anything the client could invent.\n return new ErrorClass(decoded.message ?? undefined);\n }\n return new HttpStatusError(response.status, decoded.message ?? `Request failed with status ${response.status}.`, decoded.type);\n }\n\n async function readJson<T>(response: Response, context: string): Promise<T> {\n if (response.status === 204) {\n return undefined as T;\n }\n let text: string;\n try {\n text = await response.text();\n } catch (cause) {\n throw ServiceError.from(cause);\n }\n if (text.trim() === '') {\n return undefined as T;\n }\n try {\n return JSON.parse(text) as T;\n } catch {\n // A 2xx body that is not JSON is an HTML error page from a proxy. It must\n // surface as a ServiceError, not a SyntaxError, so the caller's error\n // handling has one shape to recognize.\n throw new HttpStatusError(response.status, `Malformed response body: ${context}`, null);\n }\n }\n\n return {\n request,\n get: async <T>(path: string, params?: QueryParams): Promise<T> =>\n request<T>(`${path}${params === undefined ? '' : buildQuery(params)}`),\n post: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'POST', body }),\n put: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'PUT', body }),\n patch: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'PATCH', body }),\n delete: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'DELETE', body }),\n };\n}\n\nexport { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH };\nexport type { ApiClient, ApiRequestInit, CreateApiClientOptions, FetchFn, QueryParams, QueryValue };\n"],
|
|
5
|
-
"mappings": "+EAAA,OACE,mBAAAA,EACA,mBAAAC,EACA,iBAAAC,EACA,kBAAAC,EACA,uBAAAC,EACA,yBAAAC,EACA,iBAAAC,EACA,uBAAAC,EACA,wBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,gBAAAC,EACA,2BAAAC,EACA,qBAAAC,EACA,6BAAAC,MACK,mBACP,OAAS,sBAAAC,EAAoB,wBAAAC,MAA4B,iBAoIzD,MAAMC,EAA2B,
|
|
6
|
-
"names": ["BadGatewayError", "BadRequestError", "ConflictError", "ForbiddenError", "InternalServerError", "MethodNotAllowedError", "NotFoundError", "NotImplementedError", "PayloadTooLargeError", "PreconditionFailedError", "RateLimitedError", "ServiceError", "ServiceUnavailableError", "UnauthorizedError", "UnsupportedMediaTypeError", "D1_BOOKMARK_HEADER", "resolveBookmarkStore", "MAX_ERROR_MESSAGE_LENGTH", "HTTP_ERROR_CLASSES", "HttpStatusError", "__name", "status", "message", "type", "readString", "value", "truncate", "maxLength", "CONTROL_CHARACTER", "isProbablyProse", "raw", "decodeJsonError", "payload", "envelope", "nestedError", "decodeErrorBody", "text", "trimmed", "mergeHeaders", "base", "overrides", "headers", "name", "isQueryList", "buildQuery", "params", "search", "entry", "encoded", "createApiClient", "fetchFn", "
|
|
4
|
+
"sourcesContent": ["import {\n BadGatewayError,\n BadRequestError,\n ConflictError,\n DatabaseError,\n ForbiddenError,\n InternalServerError,\n MethodNotAllowedError,\n NotFoundError,\n NotImplementedError,\n PayloadTooLargeError,\n PreconditionFailedError,\n RateLimitedError,\n INTERNAL_ERROR_TYPE,\n ServiceError,\n ServiceUnavailableError,\n UnauthorizedError,\n UnsupportedMediaTypeError,\n} from '@rexezuge/errors';\nimport { D1_BOOKMARK_HEADER, resolveBookmarkStore } from './bookmarks.ts';\nimport type { BookmarkStore } from './bookmarks.ts';\n\n/**\n * The SPA's request path.\n *\n * ## Provenance\n *\n * `lib/api.ts` in **CalDAV-Bridge**, **Durable-DAV**, **Durable-DAV-Router**,\n * **Edge-Git**, **Edge-Sonic**, **Mail-Otter** and **AWS-AccessBridge** — seven\n * copies that all drift on the same three decisions, settled here as follows.\n *\n * **1. Error model.** Six of the seven define a private `BackendError`\n * (`{ message, errorType, status }`) and hand-roll the status→branch mapping at\n * every call site; AWS defines `ApiError` (`{ status, message }`) plus an\n * `ApiResult{ok,status,data,error}` shape that its own guide records as\n * abandoned — every admin tab bypassed it, which is how nine of its seventeen\n * functions ended up with no caller. The kit replaces both with the family\n * taxonomy: every rejection is a `ServiceError`, so `error.status`,\n * `error.type`, `error.retryable` and `instanceof ServiceError` are available\n * without a per-repo error class, and `ServiceError.from` covers the\n * transport-level failures the private classes swallowed.\n *\n * **2. Error body decoding.** Converged from the three variants that exist:\n *\n * - The **AWS envelope** `{ Exception: { Type, Message } }`, read first in all\n * copies.\n * - The **legacy** `{ error, message }` shape, where Durable-DAV also reads a\n * string `error` as the *type* — otherwise a legacy body produced a correct\n * message and a `null` type, which sent it through the generic fallback and\n * lost the specific wording.\n * - **Edge-Sonic's prose test** for a non-JSON body: an Access login page or a\n * proxy's HTML error page is not a message an operator can act on, so markup\n * is reported as absent rather than quoted into a notice bar. Short,\n * single-line, tag-free text *is* surfaced, truncated.\n * - **Truncation** at 500 characters, from every copy that has one: an\n * unbounded error string from a proxy page is a rendering hazard.\n * - **`text()` then `JSON.parse`, never `json()` with a `text()` fallback** —\n * Edge-Sonic's comment records why the old shape cannot work: `json()`\n * consumes the body stream before it fails to parse, so the second read\n * returned `''` and the \"not JSON\" branch was unreachable.\n *\n * **3. Empty bodies.** Durable-DAV's fix is the one kept: a `204`, and an empty\n * body from an edge error page, resolve to `undefined` rather than throwing a\n * `SyntaxError` — which used to report a generic failure for an operation that\n * had actually succeeded (credential revoke). AWS-AccessBridge resolved the same\n * case to `{}`; `undefined` is the honest answer for \"there is no body\".\n *\n * D1 session bookmarks are on by default (`bookmarks`); see `./bookmarks.ts`.\n *\n * ## What is deliberately not here\n *\n * - **`apiAuthedFirst`** (Edge-Git) — a public-fallback policy with\n * fail-closed 401/403/404 handling, specific to that app's two-surface API.\n * - **WebDAV `readDav`** (Durable-DAV, Durable-DAV-Router) — it accepts `207\n * Multi-Status` as success, which is a WebDAV rule, not an HTTP rule. A\n * consumer needing XML calls `client.request` and reads `response.text()`\n * itself.\n * - **The `/user` base path.** Edge-Sonic bakes it in; the others pass full\n * paths. `baseUrl` is an option here, defaulting to empty, so the caller\n * decides.\n */\n\n/**\nThe `fetch` shape a client is built on: same-origin by default, no token in JavaScript.\n*/\ntype FetchFn = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\nA query-string value. `null`/`undefined`/`''` are omitted, as in every copy.\n*/\ntype QueryValue = string | number | boolean | null | undefined;\n\ntype QueryParams = Record<string, QueryValue | readonly QueryValue[]>;\n\ninterface ApiRequestInit {\n method?: string;\n /**\n Serialized as JSON with a matching `Content-Type`.\n */\n body?: unknown;\n headers?: HeadersInit;\n signal?: AbortSignal | null;\n /**\n Passed through to `fetch`; omitted leaves the browser default.\n\n It is a standard `RequestInit` field, so a caller that needs `'no-store'`\n (an auth probe that must never read a cached page) or `'reload'` does not have\n to reach around the client to set it.\n */\n cache?: RequestCache;\n}\n\ninterface CreateApiClientOptions {\n /**\n Prepended to every path; `''` (the default) sends the path as given.\n */\n baseUrl?: string;\n /**\n Headers merged into every request; a per-request header wins over these.\n */\n headers?: HeadersInit;\n /**\n Passed through to `fetch`; omitted leaves the browser default.\n */\n credentials?: RequestCredentials;\n /**\n Truncation limit for a server-provided error message. Defaults to 500.\n */\n maxErrorMessageLength?: number;\n /**\n * D1 session bookmarks: `true` (the default) keeps them in a store private to\n * this client, a `BookmarkStore` shares one, `false` never sends or stores one.\n */\n bookmarks?: boolean | BookmarkStore;\n}\n\ninterface ApiClient {\n /**\n One request. Throws a `ServiceError`; resolves to the parsed JSON body.\n */\n request<T>(path: string, init?: ApiRequestInit): Promise<T>;\n get<T>(path: string, params?: QueryParams): Promise<T>;\n post<T>(path: string, body?: unknown): Promise<T>;\n put<T>(path: string, body?: unknown): Promise<T>;\n patch<T>(path: string, body?: unknown): Promise<T>;\n delete<T>(path: string, body?: unknown): Promise<T>;\n}\n\n/**\nDefault truncation for a server-provided message.\n*/\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\ntype ErrorClass = new (message?: string) => ServiceError;\n\n/**\n * Statuses the family taxonomy has a class for, mapped to it. The fallback when the server's `Type` is\n * missing or not one the catalog knows: the status is the fact that survives a rolling deploy.\n */\nconst HTTP_ERROR_CLASSES: Readonly<Record<number, ErrorClass>> = {\n 400: BadRequestError,\n 401: UnauthorizedError,\n 403: ForbiddenError,\n 404: NotFoundError,\n 405: MethodNotAllowedError,\n 409: ConflictError,\n 412: PreconditionFailedError,\n 413: PayloadTooLargeError,\n 415: UnsupportedMediaTypeError,\n 429: RateLimitedError,\n 500: InternalServerError,\n 501: NotImplementedError,\n 502: BadGatewayError,\n 503: ServiceUnavailableError,\n};\n\n/**\n * The server's `Exception.Type` values the catalog has a class for. `InternalError` is the wire type of an\n * untyped throw (`ServiceError.from`) and decodes to the same 500 class as `InternalServerError`.\n */\nconst TYPE_ERROR_CLASSES: Readonly<Record<string, ErrorClass>> = {\n BadRequest: BadRequestError,\n Unauthorized: UnauthorizedError,\n Forbidden: ForbiddenError,\n NotFound: NotFoundError,\n MethodNotAllowed: MethodNotAllowedError,\n Conflict: ConflictError,\n PreconditionFailed: PreconditionFailedError,\n PayloadTooLarge: PayloadTooLargeError,\n UnsupportedMediaType: UnsupportedMediaTypeError,\n RateLimited: RateLimitedError,\n InternalServerError,\n [INTERNAL_ERROR_TYPE]: InternalServerError,\n NotImplemented: NotImplementedError,\n BadGateway: BadGatewayError,\n ServiceUnavailable: ServiceUnavailableError,\n DatabaseError,\n};\n\n/**\n * A failure whose only fact is its HTTP status: a status the catalog has no\n * class for (451, 418, a proxy's own 5xx), or a 2xx body that is not JSON.\n *\n * It exists so the thrown value is *always* a `ServiceError` — a caller\n * branching on `instanceof ServiceError` does not have to know which statuses\n * the catalog happens to cover.\n */\nclass HttpStatusError extends ServiceError {\n constructor(status: number, message: string, type: string | null) {\n super(status, type ?? `HttpStatus${status}`, message);\n }\n}\n\ninterface DecodedErrorBody {\n /**\n What the server said, or `null` when it said nothing usable.\n */\n message: string | null;\n /**\n The server's machine-readable code, when it sent one.\n */\n type: string | null;\n}\n\nfunction readString(value: unknown): string | null {\n return typeof value === 'string' && value.trim() !== '' ? value : null;\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;\n}\n\n/**\nRejects control characters: that is what separates text from a binary or a document.\n*/\n// eslint-disable-next-line no-control-regex -- rejecting control characters IS the test\nconst CONTROL_CHARACTER = /[\\u0000-\\u001F\\u007F]/;\n\n/**\n * Whether a non-JSON error body is text worth showing rather than markup or a\n * blob. Deliberately conservative: the cost of wrongly refusing is the generic\n * status sentence, and the cost of wrongly accepting is an HTML page in a\n * notice bar.\n */\nfunction isProbablyProse(raw: string, maxLength: number): boolean {\n if (raw.length === 0 || raw.length > maxLength || raw.includes('<')) {\n return false;\n }\n return !CONTROL_CHARACTER.test(raw);\n}\n\nfunction decodeJsonError(payload: unknown, status: number, maxLength: number): DecodedErrorBody {\n if (typeof payload === 'string') {\n const message = payload.trim();\n return { message: message === '' ? null : truncate(message, maxLength), type: null };\n }\n if (typeof payload !== 'object' || payload === null) {\n return { message: null, type: null };\n }\n // Three dialects, newest first: the AWS envelope, the unified `{error:\n // {code,message}}` object, and the legacy flat `{error, message}`.\n const envelope = payload as {\n Exception?: { Type?: unknown; Message?: unknown };\n error?: unknown;\n message?: unknown;\n code?: unknown;\n };\n const nestedError =\n typeof envelope.error === 'object' && envelope.error !== null ? (envelope.error as { message?: unknown; code?: unknown }) : null;\n const type =\n readString(envelope.Exception?.Type) ??\n (typeof envelope.error === 'string' ? readString(envelope.error) : null) ??\n readString(nestedError?.code) ??\n readString(envelope.code) ??\n null;\n const message =\n readString(envelope.Exception?.Message) ??\n readString(envelope.message) ??\n (typeof envelope.error === 'string' ? readString(envelope.error) : null) ??\n readString(nestedError?.message) ??\n null;\n if (message !== null) {\n return { message: truncate(message, maxLength), type };\n }\n if (type !== null) {\n // The server named the failure but gave no sentence for it.\n return { message: `${type} (HTTP ${status})`, type };\n }\n return { message: null, type: null };\n}\n\nfunction decodeErrorBody(text: string, status: number, maxLength: number): DecodedErrorBody {\n const trimmed = text.trim();\n if (trimmed === '') {\n return { message: null, type: null };\n }\n try {\n return decodeJsonError(JSON.parse(trimmed) as unknown, status, maxLength);\n } catch {\n return { message: isProbablyProse(trimmed, maxLength) ? truncate(trimmed, maxLength) : null, type: null };\n }\n}\n\ninterface ServiceErrorFromResponseOptions {\n /**\n Truncation limit for a server-provided message. Defaults to 500.\n */\n maxErrorMessageLength?: number;\n}\n\n/**\n * A failed response as the `ServiceError` {@link createApiClient} throws, for planes the client cannot read\n * itself (an XML WebDAV multistatus, a download). Reads the body once, in any of the three dialects.\n *\n * The server's `Exception.Type` is kept on `error.type` verbatim. The class is chosen by that `Type` when the\n * catalog knows it (so a `DatabaseError` stays a `DatabaseError`), else by status; `error.status` is always\n * the response's. A `DatabaseError` answered with 503 is the server's \"transient, retry\" verdict, so it\n * comes back `retryable`.\n */\nasync function serviceErrorFromResponse(response: Response, options: ServiceErrorFromResponseOptions = {}): Promise<ServiceError> {\n let text = '';\n try {\n text = await response.text();\n } catch {\n // The body could not be read at all — a reset after the headers. The\n // status is still the one true thing about the request, and the catalog\n // default message says more than anything this could invent.\n }\n const decoded = decodeErrorBody(text, response.status, options.maxErrorMessageLength ?? MAX_ERROR_MESSAGE_LENGTH);\n const { status } = response;\n const byType = decoded.type !== null && Object.hasOwn(TYPE_ERROR_CLASSES, decoded.type) ? TYPE_ERROR_CLASSES[decoded.type] : undefined;\n const ErrorClass = byType ?? (Object.hasOwn(HTTP_ERROR_CLASSES, status) ? HTTP_ERROR_CLASSES[status] : undefined);\n if (ErrorClass === undefined) {\n return new HttpStatusError(status, decoded.message ?? `Request failed with status ${status}.`, decoded.type);\n }\n // A `null` message leaves the catalog's default in place, which is a\n // better sentence than anything the client could invent.\n const error = new ErrorClass(decoded.message ?? undefined);\n error.status = status;\n if (decoded.type !== null) error.type = decoded.type;\n if (error instanceof DatabaseError && status === 503) error.retryable = true;\n return error;\n}\n\nfunction mergeHeaders(base: HeadersInit | undefined, overrides?: HeadersInit): Headers {\n const headers = new Headers(base);\n if (overrides === undefined) {\n return headers;\n }\n for (const [name, value] of new Headers(overrides)) {\n headers.set(name, value);\n }\n return headers;\n}\n\nfunction isQueryList(value: QueryValue | readonly QueryValue[]): value is readonly QueryValue[] {\n return Array.isArray(value);\n}\n\n/**\n * Builds a query string, with the leading `?` and without it when empty.\n *\n * `null`, `undefined` and `''` are dropped rather than sent as empty\n * parameters, and an array value repeats the key — both as in the copies this\n * replaces.\n */\nfunction buildQuery(params: QueryParams): string {\n const search = new URLSearchParams();\n for (const [name, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === '') {\n continue;\n }\n if (isQueryList(value)) {\n for (const entry of value) {\n if (entry !== undefined && entry !== null && entry !== '') {\n search.append(name, String(entry));\n }\n }\n continue;\n }\n search.set(name, String(value));\n }\n const encoded = search.toString();\n return encoded === '' ? '' : `?${encoded}`;\n}\n\n/**\n * Builds a client over a `fetch` implementation.\n *\n * ```ts\n * const api = createApiClient(fetch, { baseUrl: '/user' });\n * const me = await api.get<CurrentUser>('/me');\n * ```\n *\n * The `fetchFn` parameter is what makes this testable without a network and\n * swappable for an instrumented wrapper; in a browser it is the global `fetch`.\n * Memoize the client (a module constant, or `useMemo`) — `useCurrentUser`\n * deliberately does not re-fetch when a new client instance appears, but a new\n * instance per render still churns.\n */\nfunction createApiClient(fetchFn: FetchFn, options: CreateApiClientOptions = {}): ApiClient {\n const baseUrl = options.baseUrl ?? '';\n const maxErrorMessageLength = options.maxErrorMessageLength ?? MAX_ERROR_MESSAGE_LENGTH;\n const bookmarks = resolveBookmarkStore(options.bookmarks);\n\n async function request<T>(path: string, init: ApiRequestInit = {}): Promise<T> {\n const method = (init.method ?? 'GET').toUpperCase();\n const url = `${baseUrl}${path}`;\n const hasBody = init.body !== undefined;\n const headers = mergeHeaders(options.headers, init.headers);\n // Same-origin only, and no token in JavaScript: the Cloudflare Access\n // session cookie rides along under the default credentials, and there is no\n // place for a token to leak to. Both defaults yield to an explicit header\n // — a consumer that wants XML passes its own `Accept`.\n if (!headers.has('Accept')) {\n headers.set('Accept', 'application/json');\n }\n if (hasBody && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n const bookmark = bookmarks?.get() ?? null;\n if (bookmark !== null && !headers.has(D1_BOOKMARK_HEADER)) {\n headers.set(D1_BOOKMARK_HEADER, bookmark);\n }\n const requestInit: RequestInit = { method, headers };\n if (options.credentials !== undefined) {\n requestInit.credentials = options.credentials;\n }\n if (hasBody) {\n requestInit.body = JSON.stringify(init.body);\n }\n if (init.signal !== undefined && init.signal !== null) {\n requestInit.signal = init.signal;\n }\n if (init.cache !== undefined) {\n requestInit.cache = init.cache;\n }\n\n const context = `${method} ${url}`;\n let response: Response;\n try {\n response = await fetchFn(url, requestInit);\n } catch (cause) {\n // The transport never answered — offline, DNS, CORS, an aborted signal.\n // There is no status to report, so the failure normalizes through\n // `ServiceError.from` like any other unknown throw. A caller that cancels\n // its own request therefore sees a 500-shaped error too; the taxonomy has\n // no \"aborted\" class, and swallowing it here would hide real transport\n // failures. A caller that cancels should not surface the rejection.\n throw ServiceError.from(cause);\n }\n // Read on every status: a failed write still advanced the session.\n const nextBookmark = response.headers.get(D1_BOOKMARK_HEADER);\n if (bookmarks !== null && nextBookmark !== null) {\n bookmarks.set(nextBookmark);\n }\n if (!response.ok) {\n throw await serviceErrorFromResponse(response, { maxErrorMessageLength });\n }\n return readJson<T>(response, context);\n }\n\n async function readJson<T>(response: Response, context: string): Promise<T> {\n if (response.status === 204) {\n return undefined as T;\n }\n let text: string;\n try {\n text = await response.text();\n } catch (cause) {\n throw ServiceError.from(cause);\n }\n if (text.trim() === '') {\n return undefined as T;\n }\n try {\n return JSON.parse(text) as T;\n } catch {\n // A 2xx body that is not JSON is an HTML error page from a proxy. It must\n // surface as a ServiceError, not a SyntaxError, so the caller's error\n // handling has one shape to recognize.\n throw new HttpStatusError(response.status, `Malformed response body: ${context}`, null);\n }\n }\n\n return {\n request,\n get: async <T>(path: string, params?: QueryParams): Promise<T> =>\n request<T>(`${path}${params === undefined ? '' : buildQuery(params)}`),\n post: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'POST', body }),\n put: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'PUT', body }),\n patch: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'PATCH', body }),\n delete: async <T>(path: string, body?: unknown): Promise<T> => request<T>(path, { method: 'DELETE', body }),\n };\n}\n\nexport { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH, serviceErrorFromResponse };\nexport type { ApiClient, ApiRequestInit, CreateApiClientOptions, ServiceErrorFromResponseOptions, FetchFn, QueryParams, QueryValue };\n"],
|
|
5
|
+
"mappings": "+EAAA,OACE,mBAAAA,EACA,mBAAAC,EACA,iBAAAC,EACA,iBAAAC,EACA,kBAAAC,EACA,uBAAAC,EACA,yBAAAC,EACA,iBAAAC,EACA,uBAAAC,EACA,wBAAAC,EACA,2BAAAC,EACA,oBAAAC,EACA,uBAAAC,EACA,gBAAAC,EACA,2BAAAC,EACA,qBAAAC,EACA,6BAAAC,MACK,mBACP,OAAS,sBAAAC,EAAoB,wBAAAC,MAA4B,iBAoIzD,MAAMC,EAA2B,IAQ3BC,EAA2D,CAC/D,IAAKnB,EACL,IAAKc,EACL,IAAKX,EACL,IAAKG,EACL,IAAKD,EACL,IAAKJ,EACL,IAAKQ,EACL,IAAKD,EACL,IAAKO,EACL,IAAKL,EACL,IAAKN,EACL,IAAKG,EACL,IAAKR,EACL,IAAKc,GAODO,EAA2D,CAC/D,WAAYpB,EACZ,aAAcc,EACd,UAAWX,EACX,SAAUG,EACV,iBAAkBD,EAClB,SAAUJ,EACV,mBAAoBQ,EACpB,gBAAiBD,EACjB,qBAAsBO,EACtB,YAAaL,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F,IAAIH,EACJ,GAAI,CACFA,EAAO,MAAMG,EAAS,KAAI,CAC5B,OAAS8B,EAAO,CACd,MAAM3D,EAAa,KAAK2D,CAAK,CAC/B,CACA,GAAIjC,EAAK,KAAI,IAAO,GAGpB,GAAI,CACF,OAAO,KAAK,MAAMA,CAAI,CACxB,MAAQ,CAIN,MAAM,IAAIjB,EAAgBoB,EAAS,OAAQ,4BAA4B6B,CAAO,GAAI,IAAI,CACxF,CACF,CArBe,OAAAhD,EAAAmD,EAAA,YAuBR,CACL,QAAAX,EACA,IAAKxC,EAAA,MAAUyC,EAAcV,IAC3BS,EAAW,GAAGC,CAAI,GAAGV,IAAW,OAAY,GAAKD,EAAWC,CAAM,CAAC,EAAE,EADlE,OAEL,KAAM/B,EAAA,MAAUyC,EAAcW,IAA+BZ,EAAWC,EAAM,CAAE,OAAQ,OAAQ,KAAAW,CAAI,CAAE,EAAhG,QACN,IAAKpD,EAAA,MAAUyC,EAAcW,IAA+BZ,EAAWC,EAAM,CAAE,OAAQ,MAAO,KAAAW,CAAI,CAAE,EAA/F,OACL,MAAOpD,EAAA,MAAUyC,EAAcW,IAA+BZ,EAAWC,EAAM,CAAE,OAAQ,QAAS,KAAAW,CAAI,CAAE,EAAjG,SACP,OAAQpD,EAAA,MAAUyC,EAAcW,IAA+BZ,EAAWC,EAAM,CAAE,OAAQ,SAAU,KAAAW,CAAI,CAAE,EAAlG,UAEZ,CA9FSpD,EAAAmC,GAAA",
|
|
6
|
+
"names": ["BadGatewayError", "BadRequestError", "ConflictError", "DatabaseError", "ForbiddenError", "InternalServerError", "MethodNotAllowedError", "NotFoundError", "NotImplementedError", "PayloadTooLargeError", "PreconditionFailedError", "RateLimitedError", "INTERNAL_ERROR_TYPE", "ServiceError", "ServiceUnavailableError", "UnauthorizedError", "UnsupportedMediaTypeError", "D1_BOOKMARK_HEADER", "resolveBookmarkStore", "MAX_ERROR_MESSAGE_LENGTH", "HTTP_ERROR_CLASSES", "TYPE_ERROR_CLASSES", "HttpStatusError", "__name", "status", "message", "type", "readString", "value", "truncate", "maxLength", "CONTROL_CHARACTER", "isProbablyProse", "raw", "decodeJsonError", "payload", "envelope", "nestedError", "decodeErrorBody", "text", "trimmed", "serviceErrorFromResponse", "response", "options", "decoded", "ErrorClass", "error", "mergeHeaders", "base", "overrides", "headers", "name", "isQueryList", "buildQuery", "params", "search", "entry", "encoded", "createApiClient", "fetchFn", "baseUrl", "maxErrorMessageLength", "bookmarks", "request", "path", "init", "method", "url", "hasBody", "bookmark", "requestInit", "context", "cause", "nextBookmark", "readJson", "body"]
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -103,8 +103,8 @@ export { useMutation, useResource } from './useResource.ts';
|
|
|
103
103
|
export type { MutationState, MutationStatus, ResourceState, ResourceStatus, UseResourceOptions } from './useResource.ts';
|
|
104
104
|
export { CURRENT_USER_PATH, useCurrentUser } from './useCurrentUser.ts';
|
|
105
105
|
export type { CurrentUser, UseCurrentUserOptions, UseCurrentUserResult } from './useCurrentUser.ts';
|
|
106
|
-
export { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH } from './api.ts';
|
|
107
|
-
export type { ApiClient, ApiRequestInit, CreateApiClientOptions, FetchFn, QueryParams, QueryValue } from './api.ts';
|
|
106
|
+
export { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH, serviceErrorFromResponse } from './api.ts';
|
|
107
|
+
export type { ApiClient, ApiRequestInit, CreateApiClientOptions, ServiceErrorFromResponseOptions, FetchFn, QueryParams, QueryValue, } from './api.ts';
|
|
108
108
|
export { createBookmarkStore, D1_BOOKMARK_HEADER } from './bookmarks.ts';
|
|
109
109
|
export type { BookmarkStore } from './bookmarks.ts';
|
|
110
110
|
export { createContractClient } from './contractClient.ts';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA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AC/B,OAAO,EACP,WAAW,EACX,UAAU,GACX,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzE,YAAY,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Badge as o,badgeBaseClass as t,badgeClass as a,badgeVariantClass as n}from"./Badge.js";import{Button as l,buttonBaseClass as s,buttonClass as m,buttonSizeClass as f,buttonVariantClass as C}from"./Button.js";import{Card as
|
|
1
|
+
import{Badge as o,badgeBaseClass as t,badgeClass as a,badgeVariantClass as n}from"./Badge.js";import{Button as l,buttonBaseClass as s,buttonClass as m,buttonSizeClass as f,buttonVariantClass as C}from"./Button.js";import{Card as u,cardClass as x,cardHeaderClass as d,cardTitleClass as S,CardHeader as E,CardTitle as T}from"./Card.js";import{FocusInput as A}from"./FocusInput.js";import{Input as c,Label as b,Select as L,Textarea as R,fieldClass as B}from"./Input.js";import{LoadingButton as y}from"./LoadingButton.js";import{ModalShell as O}from"./ModalShell.js";import{ConfirmDeleteModal as N,EmptyState as F,LoadingSpinner as H}from"./PageState.js";import{AppPage as D}from"./AppPage.js";import{PageHeaderCard as h}from"./PageHeaderCard.js";import{ContextBar as z}from"./ContextBar.js";import{Unauthorized as v}from"./Unauthorized.js";import{NoticeBar as Y}from"./NoticeBar.js";import{LanguageSelector as Q}from"./LanguageSelector.js";import{RefreshButton as X}from"./RefreshButton.js";import{ReadOnlyField as j}from"./ReadOnlyField.js";import{TypeToConfirmModal as J}from"./TypeToConfirmModal.js";import{useCopyToClipboard as ee}from"./useCopyToClipboard.js";import{Pagination as oe,clampPage as te,pageCountFor as ae,pageWindow as ne}from"./Pagination.js";import{Spinner as le}from"./Spinner.js";import{btnBase as me,btnBlueStyle as fe,btnGreenStyle as Ce,btnSmallStyle as ie,buttonColors as ue,cardStyle as xe,inputStyle as de,paginationBtnStyle as Se,tableCardStyle as Ee,tdStyle as Te,theme as ge,thStyle as Ae}from"./theme.js";import{cn as ce,configureClassMerge as be}from"./utils.js";import{COPY_FEEDBACK_TIMEOUT_MS as Re,NOTICE_TIMEOUT_MS as Be,ZERO_TRUST_AUTHENTICATION_PATH as Ue}from"./constants.js";import{useNotice as Me}from"./useNotice.js";import{canonicalizeLanguageTag as Ge,DEFAULT_FALLBACK_LANGUAGE as Ne,DEFAULT_LANGUAGE_STORAGE_KEY as Fe,DEFAULT_SUPPORTED_LANGUAGES as He,resolveLanguageTag as Pe,useSpaLanguage as De}from"./useSpaLanguage.js";import{useMutation as he,useResource as Ke}from"./useResource.js";import{CURRENT_USER_PATH as ke,useCurrentUser as ve}from"./useCurrentUser.js";import{buildQuery as Ye,createApiClient as we,HttpStatusError as Qe,MAX_ERROR_MESSAGE_LENGTH as We,serviceErrorFromResponse as Xe}from"./api.js";import{createBookmarkStore as je,D1_BOOKMARK_HEADER as qe}from"./bookmarks.js";import{createContractClient as $e}from"./contractClient.js";export{D as AppPage,o as Badge,l as Button,Re as COPY_FEEDBACK_TIMEOUT_MS,ke as CURRENT_USER_PATH,u as Card,E as CardHeader,T as CardTitle,N as ConfirmDeleteModal,z as ContextBar,qe as D1_BOOKMARK_HEADER,Ne as DEFAULT_FALLBACK_LANGUAGE,Fe as DEFAULT_LANGUAGE_STORAGE_KEY,He as DEFAULT_SUPPORTED_LANGUAGES,F as EmptyState,A as FocusInput,Qe as HttpStatusError,c as Input,b as Label,Q as LanguageSelector,y as LoadingButton,H as LoadingSpinner,We as MAX_ERROR_MESSAGE_LENGTH,O as ModalShell,Be as NOTICE_TIMEOUT_MS,Y as NoticeBar,h as PageHeaderCard,oe as Pagination,j as ReadOnlyField,X as RefreshButton,L as Select,le as Spinner,R as Textarea,J as TypeToConfirmModal,v as Unauthorized,Ue as ZERO_TRUST_AUTHENTICATION_PATH,t as badgeBaseClass,a as badgeClass,n as badgeVariantClass,me as btnBase,fe as btnBlueStyle,Ce as btnGreenStyle,ie as btnSmallStyle,Ye as buildQuery,s as buttonBaseClass,m as buttonClass,ue as buttonColors,f as buttonSizeClass,C as buttonVariantClass,Ge as canonicalizeLanguageTag,x as cardClass,d as cardHeaderClass,xe as cardStyle,S as cardTitleClass,te as clampPage,ce as cn,be as configureClassMerge,we as createApiClient,je as createBookmarkStore,$e as createContractClient,B as fieldClass,de as inputStyle,ae as pageCountFor,ne as pageWindow,Se as paginationBtnStyle,Pe as resolveLanguageTag,Xe as serviceErrorFromResponse,Ee as tableCardStyle,Te as tdStyle,Ae as thStyle,ge as theme,ee as useCopyToClipboard,ve as useCurrentUser,he as useMutation,Me as useNotice,Ke as useResource,De as useSpaLanguage};
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `@rexezuge/web` — the SPA layer of the kit.\n *\n * React primitives, the hooks every app's shell needs, and the one API client.\n * Every export is the converged form of a framework that lived as copies inside\n * the nine consumer repos; see the `## Provenance` block at the top of each\n * module for what it replaced and which copy won.\n *\n * ```ts\n * import { AppPage, Button, Card, createApiClient, useCurrentUser, useNotice, useSpaLanguage } from '@rexezuge/web';\n * ```\n *\n * ## What a consumer must provide\n *\n * - **The CSS variables the class-based components read.** Import\n * `@rexezuge/web/styles.css` for defaults (and the source scan), or define\n * them yourself:\n * `--color-accent`, `--color-accent-dim`, `--color-border`,\n * `--color-surface-base`, `--color-surface-1..4`,\n * `--color-text-primary`, `--color-text-secondary`, `--color-text-muted`, and\n * `--color-{success,error,warning,info,neutral}-{bg,text}`.\n * - **`animate-spin`**, for `Spinner` (and therefore `Button`'s busy state).\n * Tailwind ships it; a non-Tailwind app defines the keyframes once.\n * - **A dependency on `@rexezuge/errors`**, which `api.ts` imports for\n * `ServiceError` and the status classes.\n *\n * ## Glyphs in, strings out\n *\n * Three components (`RefreshButton`, `ReadOnlyField`, `TypeToConfirmModal`) take\n * their icon from `lucide-react`, which is why it is a peer rather than a\n * dependency. Everything *sayable* is a prop: no component here calls\n * `useTranslation`, because the app rendering a dialog knows what it says and a\n * kit that hard-codes English for it has taken over the app's string catalogue.\n *\n * The dividing line is deliberate. `Button` keeps using this package's own\n * `Spinner` rather than lucide's `Loader2` — chrome is cheap to draw, iconography\n * is not, and vendoring a glyph's path data freezes it at whatever version was\n * current when it was copied.\n *\n * ## Migrating the copies\n *\n * `codemods/` rewrites the family's `../components/…` imports onto this package\n * for every component converged here, and names the ones it has not. Those\n * imports are **relative**, so this is a separate transform from the\n * `@scope/pkg` one — see `codemods/src/web-components.ts`.\n *\n * ## What is deliberately not here\n *\n * Domain badges (`ConnectionBadge`, `TaskRunStatusBadge`, …), the OAuth\n * `?oauth2=` notice seeding, WebDAV `207` handling, the authed-first public\n * fallback, and every app's `SUPPORTED_LANGUAGES`. Each had\n * exactly one consumer, so each stays with it — see `constants.ts` and the\n * per-module provenance notes for the list.\n */\n\nexport { Badge, badgeBaseClass, badgeClass, badgeVariantClass } from './Badge.tsx';\nexport type { BadgeProps, BadgeVariant } from './Badge.tsx';\n\nexport { Button, buttonBaseClass, buttonClass, buttonSizeClass, buttonVariantClass } from './Button.tsx';\nexport type { ButtonProps, ButtonSize, ButtonVariant } from './Button.tsx';\n\nexport { Card, cardClass, cardHeaderClass, cardTitleClass, CardHeader, CardTitle } from './Card.tsx';\nexport type { CardHeaderProps, CardProps, CardTitleProps } from './Card.tsx';\n\nexport { FocusInput } from './FocusInput.tsx';\nexport type { FocusInputProps } from './FocusInput.tsx';\n\nexport { Input, Label, Select, Textarea, fieldClass } from './Input.tsx';\nexport type { InputProps, LabelProps, SelectProps, TextareaProps } from './Input.tsx';\n\nexport { LoadingButton } from './LoadingButton.tsx';\nexport type { LoadingButtonProps } from './LoadingButton.tsx';\n\n// Converged from the `ModalShell` / `ConfirmDeleteModal` / `PageState` copies\n// that Durable-DAV, Durable-DAV-Router, Mail-Otter and Edge-Git each shipped.\n// Deliberately dependency-free — labels are props, not `useTranslation` — so\n// adopting these does not require a translation library or an icon set.\nexport { ModalShell } from './ModalShell.tsx';\nexport type { ModalShellProps } from './ModalShell.tsx';\nexport { ConfirmDeleteModal, EmptyState, LoadingSpinner } from './PageState.tsx';\n\n// The second convergence round: page layout, the notice banner, the access\n// page, the language picker, and the two clipboard-bearing controls. Same rule\n// on labels — the app owns its string catalogue. Three of these need\n// `lucide-react`, which is why it is a peer and not a dependency.\nexport { AppPage } from './AppPage.tsx';\nexport type { AppPageProps, AppPageVariant } from './AppPage.tsx';\nexport { PageHeaderCard } from './PageHeaderCard.tsx';\nexport type { PageHeaderCardProps } from './PageHeaderCard.tsx';\nexport { ContextBar } from './ContextBar.tsx';\nexport type { ContextBarProps } from './ContextBar.tsx';\nexport { Unauthorized } from './Unauthorized.tsx';\nexport type { UnauthorizedProps } from './Unauthorized.tsx';\nexport { NoticeBar } from './NoticeBar.tsx';\nexport type { NoticeBarProps, NoticeStatusLabels } from './NoticeBar.tsx';\nexport { LanguageSelector } from './LanguageSelector.tsx';\nexport type { LanguageSelectorProps } from './LanguageSelector.tsx';\nexport { RefreshButton } from './RefreshButton.tsx';\nexport type { RefreshButtonProps } from './RefreshButton.tsx';\nexport { ReadOnlyField } from './ReadOnlyField.tsx';\nexport type { ReadOnlyFieldProps } from './ReadOnlyField.tsx';\nexport { TypeToConfirmModal } from './TypeToConfirmModal.tsx';\nexport type { TypeToConfirmModalProps } from './TypeToConfirmModal.tsx';\nexport { useCopyToClipboard } from './useCopyToClipboard.ts';\nexport type { UseCopyToClipboardResult } from './useCopyToClipboard.ts';\n\nexport { Pagination, clampPage, pageCountFor, pageWindow } from './Pagination.tsx';\nexport type { PaginationLabels, PaginationProps } from './Pagination.tsx';\n\nexport { Spinner } from './Spinner.tsx';\nexport type { SpinnerProps } from './Spinner.tsx';\n\nexport {\n btnBase,\n btnBlueStyle,\n btnGreenStyle,\n btnSmallStyle,\n buttonColors,\n cardStyle,\n inputStyle,\n paginationBtnStyle,\n tableCardStyle,\n tdStyle,\n theme,\n thStyle,\n} from './theme.ts';\n\nexport { cn, configureClassMerge } from './utils.ts';\nexport type { ClassDictionary, ClassValue } from './utils.ts';\n\nexport { COPY_FEEDBACK_TIMEOUT_MS, NOTICE_TIMEOUT_MS, ZERO_TRUST_AUTHENTICATION_PATH } from './constants.ts';\n\nexport { useNotice } from './useNotice.ts';\nexport type { Notice, NoticeKind, ShowNotice, UseNoticeOptions, UseNoticeResult } from './useNotice.ts';\n\nexport {\n canonicalizeLanguageTag,\n DEFAULT_FALLBACK_LANGUAGE,\n DEFAULT_LANGUAGE_STORAGE_KEY,\n DEFAULT_SUPPORTED_LANGUAGES,\n resolveLanguageTag,\n useSpaLanguage,\n} from './useSpaLanguage.ts';\nexport type { LanguageRuntime, LanguageStatus, LanguageTag, UseSpaLanguageOptions, UseSpaLanguageResult } from './useSpaLanguage.ts';\n\nexport { useMutation, useResource } from './useResource.ts';\nexport type { MutationState, MutationStatus, ResourceState, ResourceStatus, UseResourceOptions } from './useResource.ts';\n\nexport { CURRENT_USER_PATH, useCurrentUser } from './useCurrentUser.ts';\nexport type { CurrentUser, UseCurrentUserOptions, UseCurrentUserResult } from './useCurrentUser.ts';\n\nexport { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH } from './api.ts';\nexport type {
|
|
5
|
-
"mappings": "AAuDA,OAAS,SAAAA,EAAO,kBAAAC,EAAgB,cAAAC,EAAY,qBAAAC,MAAyB,aAGrE,OAAS,UAAAC,EAAQ,mBAAAC,EAAiB,eAAAC,EAAa,mBAAAC,EAAiB,sBAAAC,MAA0B,cAG1F,OAAS,QAAAC,EAAM,aAAAC,EAAW,mBAAAC,EAAiB,kBAAAC,EAAg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"badgeClass", "badgeVariantClass", "Button", "buttonBaseClass", "buttonClass", "buttonSizeClass", "buttonVariantClass", "Card", "cardClass", "cardHeaderClass", "cardTitleClass", "CardHeader", "CardTitle", "FocusInput", "Input", "Label", "Select", "Textarea", "fieldClass", "LoadingButton", "ModalShell", "ConfirmDeleteModal", "EmptyState", "LoadingSpinner", "AppPage", "PageHeaderCard", "ContextBar", "Unauthorized", "NoticeBar", "LanguageSelector", "RefreshButton", "ReadOnlyField", "TypeToConfirmModal", "useCopyToClipboard", "Pagination", "clampPage", "pageCountFor", "pageWindow", "Spinner", "btnBase", "btnBlueStyle", "btnGreenStyle", "btnSmallStyle", "buttonColors", "cardStyle", "inputStyle", "paginationBtnStyle", "tableCardStyle", "tdStyle", "theme", "thStyle", "cn", "configureClassMerge", "COPY_FEEDBACK_TIMEOUT_MS", "NOTICE_TIMEOUT_MS", "ZERO_TRUST_AUTHENTICATION_PATH", "useNotice", "canonicalizeLanguageTag", "DEFAULT_FALLBACK_LANGUAGE", "DEFAULT_LANGUAGE_STORAGE_KEY", "DEFAULT_SUPPORTED_LANGUAGES", "resolveLanguageTag", "useSpaLanguage", "useMutation", "useResource", "CURRENT_USER_PATH", "useCurrentUser", "buildQuery", "createApiClient", "HttpStatusError", "MAX_ERROR_MESSAGE_LENGTH", "createBookmarkStore", "D1_BOOKMARK_HEADER", "createContractClient"]
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/web` — the SPA layer of the kit.\n *\n * React primitives, the hooks every app's shell needs, and the one API client.\n * Every export is the converged form of a framework that lived as copies inside\n * the nine consumer repos; see the `## Provenance` block at the top of each\n * module for what it replaced and which copy won.\n *\n * ```ts\n * import { AppPage, Button, Card, createApiClient, useCurrentUser, useNotice, useSpaLanguage } from '@rexezuge/web';\n * ```\n *\n * ## What a consumer must provide\n *\n * - **The CSS variables the class-based components read.** Import\n * `@rexezuge/web/styles.css` for defaults (and the source scan), or define\n * them yourself:\n * `--color-accent`, `--color-accent-dim`, `--color-border`,\n * `--color-surface-base`, `--color-surface-1..4`,\n * `--color-text-primary`, `--color-text-secondary`, `--color-text-muted`, and\n * `--color-{success,error,warning,info,neutral}-{bg,text}`.\n * - **`animate-spin`**, for `Spinner` (and therefore `Button`'s busy state).\n * Tailwind ships it; a non-Tailwind app defines the keyframes once.\n * - **A dependency on `@rexezuge/errors`**, which `api.ts` imports for\n * `ServiceError` and the status classes.\n *\n * ## Glyphs in, strings out\n *\n * Three components (`RefreshButton`, `ReadOnlyField`, `TypeToConfirmModal`) take\n * their icon from `lucide-react`, which is why it is a peer rather than a\n * dependency. Everything *sayable* is a prop: no component here calls\n * `useTranslation`, because the app rendering a dialog knows what it says and a\n * kit that hard-codes English for it has taken over the app's string catalogue.\n *\n * The dividing line is deliberate. `Button` keeps using this package's own\n * `Spinner` rather than lucide's `Loader2` — chrome is cheap to draw, iconography\n * is not, and vendoring a glyph's path data freezes it at whatever version was\n * current when it was copied.\n *\n * ## Migrating the copies\n *\n * `codemods/` rewrites the family's `../components/…` imports onto this package\n * for every component converged here, and names the ones it has not. Those\n * imports are **relative**, so this is a separate transform from the\n * `@scope/pkg` one — see `codemods/src/web-components.ts`.\n *\n * ## What is deliberately not here\n *\n * Domain badges (`ConnectionBadge`, `TaskRunStatusBadge`, …), the OAuth\n * `?oauth2=` notice seeding, WebDAV `207` handling, the authed-first public\n * fallback, and every app's `SUPPORTED_LANGUAGES`. Each had\n * exactly one consumer, so each stays with it — see `constants.ts` and the\n * per-module provenance notes for the list.\n */\n\nexport { Badge, badgeBaseClass, badgeClass, badgeVariantClass } from './Badge.tsx';\nexport type { BadgeProps, BadgeVariant } from './Badge.tsx';\n\nexport { Button, buttonBaseClass, buttonClass, buttonSizeClass, buttonVariantClass } from './Button.tsx';\nexport type { ButtonProps, ButtonSize, ButtonVariant } from './Button.tsx';\n\nexport { Card, cardClass, cardHeaderClass, cardTitleClass, CardHeader, CardTitle } from './Card.tsx';\nexport type { CardHeaderProps, CardProps, CardTitleProps } from './Card.tsx';\n\nexport { FocusInput } from './FocusInput.tsx';\nexport type { FocusInputProps } from './FocusInput.tsx';\n\nexport { Input, Label, Select, Textarea, fieldClass } from './Input.tsx';\nexport type { InputProps, LabelProps, SelectProps, TextareaProps } from './Input.tsx';\n\nexport { LoadingButton } from './LoadingButton.tsx';\nexport type { LoadingButtonProps } from './LoadingButton.tsx';\n\n// Converged from the `ModalShell` / `ConfirmDeleteModal` / `PageState` copies\n// that Durable-DAV, Durable-DAV-Router, Mail-Otter and Edge-Git each shipped.\n// Deliberately dependency-free — labels are props, not `useTranslation` — so\n// adopting these does not require a translation library or an icon set.\nexport { ModalShell } from './ModalShell.tsx';\nexport type { ModalShellProps } from './ModalShell.tsx';\nexport { ConfirmDeleteModal, EmptyState, LoadingSpinner } from './PageState.tsx';\n\n// The second convergence round: page layout, the notice banner, the access\n// page, the language picker, and the two clipboard-bearing controls. Same rule\n// on labels — the app owns its string catalogue. Three of these need\n// `lucide-react`, which is why it is a peer and not a dependency.\nexport { AppPage } from './AppPage.tsx';\nexport type { AppPageProps, AppPageVariant } from './AppPage.tsx';\nexport { PageHeaderCard } from './PageHeaderCard.tsx';\nexport type { PageHeaderCardProps } from './PageHeaderCard.tsx';\nexport { ContextBar } from './ContextBar.tsx';\nexport type { ContextBarProps } from './ContextBar.tsx';\nexport { Unauthorized } from './Unauthorized.tsx';\nexport type { UnauthorizedProps } from './Unauthorized.tsx';\nexport { NoticeBar } from './NoticeBar.tsx';\nexport type { NoticeBarProps, NoticeStatusLabels } from './NoticeBar.tsx';\nexport { LanguageSelector } from './LanguageSelector.tsx';\nexport type { LanguageSelectorProps } from './LanguageSelector.tsx';\nexport { RefreshButton } from './RefreshButton.tsx';\nexport type { RefreshButtonProps } from './RefreshButton.tsx';\nexport { ReadOnlyField } from './ReadOnlyField.tsx';\nexport type { ReadOnlyFieldProps } from './ReadOnlyField.tsx';\nexport { TypeToConfirmModal } from './TypeToConfirmModal.tsx';\nexport type { TypeToConfirmModalProps } from './TypeToConfirmModal.tsx';\nexport { useCopyToClipboard } from './useCopyToClipboard.ts';\nexport type { UseCopyToClipboardResult } from './useCopyToClipboard.ts';\n\nexport { Pagination, clampPage, pageCountFor, pageWindow } from './Pagination.tsx';\nexport type { PaginationLabels, PaginationProps } from './Pagination.tsx';\n\nexport { Spinner } from './Spinner.tsx';\nexport type { SpinnerProps } from './Spinner.tsx';\n\nexport {\n btnBase,\n btnBlueStyle,\n btnGreenStyle,\n btnSmallStyle,\n buttonColors,\n cardStyle,\n inputStyle,\n paginationBtnStyle,\n tableCardStyle,\n tdStyle,\n theme,\n thStyle,\n} from './theme.ts';\n\nexport { cn, configureClassMerge } from './utils.ts';\nexport type { ClassDictionary, ClassValue } from './utils.ts';\n\nexport { COPY_FEEDBACK_TIMEOUT_MS, NOTICE_TIMEOUT_MS, ZERO_TRUST_AUTHENTICATION_PATH } from './constants.ts';\n\nexport { useNotice } from './useNotice.ts';\nexport type { Notice, NoticeKind, ShowNotice, UseNoticeOptions, UseNoticeResult } from './useNotice.ts';\n\nexport {\n canonicalizeLanguageTag,\n DEFAULT_FALLBACK_LANGUAGE,\n DEFAULT_LANGUAGE_STORAGE_KEY,\n DEFAULT_SUPPORTED_LANGUAGES,\n resolveLanguageTag,\n useSpaLanguage,\n} from './useSpaLanguage.ts';\nexport type { LanguageRuntime, LanguageStatus, LanguageTag, UseSpaLanguageOptions, UseSpaLanguageResult } from './useSpaLanguage.ts';\n\nexport { useMutation, useResource } from './useResource.ts';\nexport type { MutationState, MutationStatus, ResourceState, ResourceStatus, UseResourceOptions } from './useResource.ts';\n\nexport { CURRENT_USER_PATH, useCurrentUser } from './useCurrentUser.ts';\nexport type { CurrentUser, UseCurrentUserOptions, UseCurrentUserResult } from './useCurrentUser.ts';\n\nexport { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH, serviceErrorFromResponse } from './api.ts';\nexport type {\n ApiClient,\n ApiRequestInit,\n CreateApiClientOptions,\n ServiceErrorFromResponseOptions,\n FetchFn,\n QueryParams,\n QueryValue,\n} from './api.ts';\n\nexport { createBookmarkStore, D1_BOOKMARK_HEADER } from './bookmarks.ts';\nexport type { BookmarkStore } from './bookmarks.ts';\n\nexport { createContractClient } from './contractClient.ts';\nexport type { ContractCall, ContractCallOptions, ContractClient, CreateContractClientOptions } from './contractClient.ts';\n\n// `createSpaI18n` is deliberately NOT here: it imports the optional i18next\n// peers, so it lives at `@rexezuge/web/i18n` and the root stays i18n-free.\n"],
|
|
5
|
+
"mappings": "AAuDA,OAAS,SAAAA,EAAO,kBAAAC,EAAgB,cAAAC,EAAY,qBAAAC,MAAyB,aAGrE,OAAS,UAAAC,EAAQ,mBAAAC,EAAiB,eAAAC,EAAa,mBAAAC,EAAiB,sBAAAC,MAA0B,cAG1F,OAAS,QAAAC,EAAM,aAAAC,EAAW,mBAAAC,EAAiB,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,MAAiB,YAGxF,OAAS,cAAAC,MAAkB,kBAG3B,OAAS,SAAAC,EAAO,SAAAC,EAAO,UAAAC,EAAQ,YAAAC,EAAU,cAAAC,MAAkB,aAG3D,OAAS,iBAAAC,MAAqB,qBAO9B,OAAS,cAAAC,MAAkB,kBAE3B,OAAS,sBAAAC,EAAoB,cAAAC,EAAY,kBAAAC,MAAsB,iBAM/D,OAAS,WAAAC,MAAe,eAExB,OAAS,kBAAAC,MAAsB,sBAE/B,OAAS,cAAAC,MAAkB,kBAE3B,OAAS,gBAAAC,MAAoB,oBAE7B,OAAS,aAAAC,MAAiB,iBAE1B,OAAS,oBAAAC,MAAwB,wBAEjC,OAAS,iBAAAC,MAAqB,qBAE9B,OAAS,iBAAAC,MAAqB,qBAE9B,OAAS,sBAAAC,MAA0B,0BAEnC,OAAS,sBAAAC,OAA0B,0BAGnC,OAAS,cAAAC,GAAY,aAAAC,GAAW,gBAAAC,GAAc,cAAAC,OAAkB,kBAGhE,OAAS,WAAAC,OAAe,eAGxB,OACE,WAAAC,GACA,gBAAAC,GACA,iBAAAC,GACA,iBAAAC,GACA,gBAAAC,GACA,aAAAC,GACA,cAAAC,GACA,sBAAAC,GACA,kBAAAC,GACA,WAAAC,GACA,SAAAC,GACA,WAAAC,OACK,aAEP,OAAS,MAAAC,GAAI,uBAAAC,OAA2B,aAGxC,OAAS,4BAAAC,GAA0B,qBAAAC,GAAmB,kCAAAC,OAAsC,iBAE5F,OAAS,aAAAC,OAAiB,iBAG1B,OACE,2BAAAC,GACA,6BAAAC,GACA,gCAAAC,GACA,+BAAAC,GACA,sBAAAC,GACA,kBAAAC,OACK,sBAGP,OAAS,eAAAC,GAAa,eAAAC,OAAmB,mBAGzC,OAAS,qBAAAC,GAAmB,kBAAAC,OAAsB,sBAGlD,OAAS,cAAAC,GAAY,mBAAAC,GAAiB,mBAAAC,GAAiB,4BAAAC,GAA0B,4BAAAC,OAAgC,WAWjH,OAAS,uBAAAC,GAAqB,sBAAAC,OAA0B,iBAGxD,OAAS,wBAAAC,OAA4B",
|
|
6
|
+
"names": ["Badge", "badgeBaseClass", "badgeClass", "badgeVariantClass", "Button", "buttonBaseClass", "buttonClass", "buttonSizeClass", "buttonVariantClass", "Card", "cardClass", "cardHeaderClass", "cardTitleClass", "CardHeader", "CardTitle", "FocusInput", "Input", "Label", "Select", "Textarea", "fieldClass", "LoadingButton", "ModalShell", "ConfirmDeleteModal", "EmptyState", "LoadingSpinner", "AppPage", "PageHeaderCard", "ContextBar", "Unauthorized", "NoticeBar", "LanguageSelector", "RefreshButton", "ReadOnlyField", "TypeToConfirmModal", "useCopyToClipboard", "Pagination", "clampPage", "pageCountFor", "pageWindow", "Spinner", "btnBase", "btnBlueStyle", "btnGreenStyle", "btnSmallStyle", "buttonColors", "cardStyle", "inputStyle", "paginationBtnStyle", "tableCardStyle", "tdStyle", "theme", "thStyle", "cn", "configureClassMerge", "COPY_FEEDBACK_TIMEOUT_MS", "NOTICE_TIMEOUT_MS", "ZERO_TRUST_AUTHENTICATION_PATH", "useNotice", "canonicalizeLanguageTag", "DEFAULT_FALLBACK_LANGUAGE", "DEFAULT_LANGUAGE_STORAGE_KEY", "DEFAULT_SUPPORTED_LANGUAGES", "resolveLanguageTag", "useSpaLanguage", "useMutation", "useResource", "CURRENT_USER_PATH", "useCurrentUser", "buildQuery", "createApiClient", "HttpStatusError", "MAX_ERROR_MESSAGE_LENGTH", "serviceErrorFromResponse", "createBookmarkStore", "D1_BOOKMARK_HEADER", "createContractClient"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/web",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
"dist"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@rexezuge/contracts": "1.
|
|
34
|
-
"@rexezuge/errors": "1.
|
|
35
|
-
"@rexezuge/shared": "1.
|
|
33
|
+
"@rexezuge/contracts": "1.16.0",
|
|
34
|
+
"@rexezuge/errors": "1.16.0",
|
|
35
|
+
"@rexezuge/shared": "1.16.0"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
38
|
"i18next": "^26.0.0 || ^27.0.0",
|