@rexezuge/web 1.16.0 → 1.17.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/dist/api.d.ts +6 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +1 -1
- package/dist/api.js.map +3 -3
- package/dist/contractClient.d.ts.map +1 -1
- package/dist/contractClient.js +1 -1
- package/dist/contractClient.js.map +3 -3
- package/package.json +4 -4
package/dist/api.d.ts
CHANGED
|
@@ -84,6 +84,12 @@ interface ApiRequestInit {
|
|
|
84
84
|
to reach around the client to set it.
|
|
85
85
|
*/
|
|
86
86
|
cache?: RequestCache;
|
|
87
|
+
/**
|
|
88
|
+
* How a 2xx body is read. `'json'` (the default) parses it; `'text'` returns it as a string, unparsed (a `204` or
|
|
89
|
+
* an empty body is `''`), and sends `Accept: text/*` unless the caller set one. Failures are still decoded as the
|
|
90
|
+
* `{Exception}` envelope.
|
|
91
|
+
*/
|
|
92
|
+
responseType?: 'json' | 'text';
|
|
87
93
|
}
|
|
88
94
|
interface CreateApiClientOptions {
|
|
89
95
|
/**
|
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,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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,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,CAuG1F;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 z=Object.defineProperty;var a=(e,r)=>z(e,"name",{value:r,configurable:!0});import{BadGatewayError as x,BadRequestError as P,ConflictError as C,DatabaseError as N,ForbiddenError as $,InternalServerError as g,MethodNotAllowedError as M,NotFoundError as _,NotImplementedError as k,PayloadTooLargeError as H,PreconditionFailedError as L,RateLimitedError as U,INTERNAL_ERROR_TYPE as K,ServiceError as h,ServiceUnavailableError as B,UnauthorizedError as F,UnsupportedMediaTypeError as j}from"@rexezuge/errors";import{D1_BOOKMARK_HEADER as T,resolveBookmarkStore as Q}from"./bookmarks.js";const b=500,v={400:P,401:F,403:$,404:_,405:M,409:C,412:L,413:H,415:j,429:U,500:g,501:k,502:x,503:B},q={BadRequest:P,Unauthorized:F,Forbidden:$,NotFound:_,MethodNotAllowed:M,Conflict:C,PreconditionFailed:L,PayloadTooLarge:H,UnsupportedMediaType:j,RateLimited:U,InternalServerError:g,[K]:g,NotImplemented:k,BadGateway:x,ServiceUnavailable:B,DatabaseError:N};class R extends h{static{a(this,"HttpStatusError")}constructor(r,s,t){super(r,t??`HttpStatus${r}`,s)}}function i(e){return typeof e=="string"&&e.trim()!==""?e:null}a(i,"readString");function S(e,r){return e.length>r?`${e.slice(0,r)}\u2026`:e}a(S,"truncate");const Y=/[\u0000-\u001F\u007F]/;function X(e,r){return e.length===0||e.length>r||e.includes("<")?!1:!Y.test(e)}a(X,"isProbablyProse");function V(e,r,s){if(typeof e=="string"){const l=e.trim();return{message:l===""?null:S(l,s),type:null}}if(typeof e!="object"||e===null)return{message:null,type:null};const t=e,o=typeof t.error=="object"&&t.error!==null?t.error:null,u=i(t.Exception?.Type)??(typeof t.error=="string"?i(t.error):null)??i(o?.code)??i(t.code)??null,d=i(t.Exception?.Message)??i(t.message)??(typeof t.error=="string"?i(t.error):null)??i(o?.message)??null;return d!==null?{message:S(d,s),type:u}:u!==null?{message:`${u} (HTTP ${r})`,type:u}:{message:null,type:null}}a(V,"decodeJsonError");function W(e,r,s){const t=e.trim();if(t==="")return{message:null,type:null};try{return V(JSON.parse(t),r,s)}catch{return{message:X(t,s)?S(t,s):null,type:null}}}a(W,"decodeErrorBody");async function G(e,r={}){let s="";try{s=await e.text()}catch{}const t=W(s,e.status,r.maxErrorMessageLength??b),{status:o}=e,d=(t.type!==null&&Object.hasOwn(q,t.type)?q[t.type]:void 0)??(Object.hasOwn(v,o)?v[o]:void 0);if(d===void 0)return new R(o,t.message??`Request failed with status ${o}.`,t.type);const l=new d(t.message??void 0);return l.status=o,t.type!==null&&(l.type=t.type),l instanceof N&&o===503&&(l.retryable=!0),l}a(G,"serviceErrorFromResponse");function Z(e,r){const s=new Headers(e);if(r===void 0)return s;for(const[t,o]of new Headers(r))s.set(t,o);return s}a(Z,"mergeHeaders");function ee(e){return Array.isArray(e)}a(ee,"isQueryList");function I(e){const r=new URLSearchParams;for(const[t,o]of Object.entries(e))if(!(o==null||o==="")){if(ee(o)){for(const u of o)u!=null&&u!==""&&r.append(t,String(u));continue}r.set(t,String(o))}const s=r.toString();return s===""?"":`?${s}`}a(I,"buildQuery");function te(e,r={}){const s=r.baseUrl??"",t=r.maxErrorMessageLength??b,o=Q(r.bookmarks);async function u(c,n={}){const y=(n.method??"GET").toUpperCase(),E=`${s}${c}`,w=n.body!==void 0,f=Z(r.headers,n.headers);f.has("Accept")||f.set("Accept",n.responseType==="text"?"text/*":"application/json"),w&&!f.has("Content-Type")&&f.set("Content-Type","application/json");const A=o?.get()??null;A!==null&&!f.has(T)&&f.set(T,A);const m={method:y,headers:f};r.credentials!==void 0&&(m.credentials=r.credentials),w&&(m.body=JSON.stringify(n.body)),n.signal!==void 0&&n.signal!==null&&(m.signal=n.signal),n.cache!==void 0&&(m.cache=n.cache);const J=`${y} ${E}`;let p;try{p=await e(E,m)}catch(D){throw h.from(D)}const O=p.headers.get(T);if(o!==null&&O!==null&&o.set(O),!p.ok)throw await G(p,{maxErrorMessageLength:t});return n.responseType==="text"?d(p):l(p,J)}a(u,"request");async function d(c){if(c.status===204)return"";try{return await c.text()}catch(n){throw h.from(n)}}a(d,"readText");async function l(c,n){if(c.status===204)return;let y;try{y=await c.text()}catch(E){throw h.from(E)}if(y.trim()!=="")try{return JSON.parse(y)}catch{throw new R(c.status,`Malformed response body: ${n}`,null)}}return a(l,"readJson"),{request:u,get:a(async(c,n)=>u(`${c}${n===void 0?"":I(n)}`),"get"),post:a(async(c,n)=>u(c,{method:"POST",body:n}),"post"),put:a(async(c,n)=>u(c,{method:"PUT",body:n}),"put"),patch:a(async(c,n)=>u(c,{method:"PATCH",body:n}),"patch"),delete:a(async(c,n)=>u(c,{method:"DELETE",body:n}),"delete")}}a(te,"createApiClient");export{R as HttpStatusError,b as MAX_ERROR_MESSAGE_LENGTH,I as buildQuery,te as createApiClient,G 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 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,
|
|
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"]
|
|
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 * How a 2xx body is read. `'json'` (the default) parses it; `'text'` returns it as a string, unparsed (a `204` or\n * an empty body is `''`), and sends `Accept: text/*` unless the caller set one. Failures are still decoded as the\n * `{Exception}` envelope.\n */\n responseType?: 'json' | 'text';\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', init.responseType === 'text' ? 'text/*' : '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 (init.responseType === 'text' ? readText(response) : readJson<T>(response, context)) as Promise<T>;\n }\n\n async function readText(response: Response): Promise<string> {\n if (response.status === 204) return '';\n try {\n return await response.text();\n } catch (cause) {\n throw ServiceError.from(cause);\n }\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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,EAAcY,IAA+Bb,EAAWC,EAAM,CAAE,OAAQ,OAAQ,KAAAY,CAAI,CAAE,EAAhG,QACN,IAAKrD,EAAA,MAAUyC,EAAcY,IAA+Bb,EAAWC,EAAM,CAAE,OAAQ,MAAO,KAAAY,CAAI,CAAE,EAA/F,OACL,MAAOrD,EAAA,MAAUyC,EAAcY,IAA+Bb,EAAWC,EAAM,CAAE,OAAQ,QAAS,KAAAY,CAAI,CAAE,EAAjG,SACP,OAAQrD,EAAA,MAAUyC,EAAcY,IAA+Bb,EAAWC,EAAM,CAAE,OAAQ,SAAU,KAAAY,CAAI,CAAE,EAAlG,UAEZ,CAvGSrD,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", "readText", "readJson", "body"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contractClient.d.ts","sourceRoot":"","sources":["../src/contractClient.ts"],"names":[],"mappings":"AA4BA,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G,gBAAgB,GAAG;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC,GAC1F,CAAC,gBAAgB,GAAG;IAAE,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC;AAsBlD;;;;;;;;GAQG;AACH,iBAAS,oBAAoB,CAAC,CAAC,SAAS,iBAAiB,EACvD,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAAC,CAAC,CAAC,CA8BnB;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAChC,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,2BAA2B,EAAE,CAAC"}
|
package/dist/contractClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var o=(t,r)=>b(t,"name",{value:r,configurable:!0});import{buildPath as y,isTextResponse as u}from"@rexezuge/contracts";import{BadGatewayError as C}from"@rexezuge/errors";import{buildQuery as g,createApiClient as w}from"./api.js";const R=["baseUrl","headers","credentials","maxErrorMessageLength","bookmarks","fetchFn"];function T(t){if(t.apiClient!==void 0){const e=R.filter(s=>t[s]!==void 0);if(e.length>0)throw new TypeError(`createContractClient: ${e.join(", ")} cannot be combined with apiClient; configure that client instead`);return t.apiClient}const{fetchFn:r,...c}=t,d=Object.fromEntries(Object.entries(c).filter(([e])=>e!=="validateResponses"&&e!=="apiClient"));return w(r??((e,s)=>fetch(e,s)),d)}o(T,"clientFor");function j(t,r={}){const c=T(r),d=r.validateResponses===!0,e={};for(const[s,n]of Object.entries(t)){const h=o(async(p={},a={})=>{const i=p,m=`${y(n.path,i.params)}${i.query===void 0?"":g(i.query)}`,f=await c.request(m,{method:n.method,...u(n.response)&&{responseType:"text"},...i.body!==void 0&&{body:i.body},...a.signal!==void 0&&{signal:a.signal},...a.headers!==void 0&&{headers:a.headers}});if(n.response===null)return null;if(u(n.response)||!d)return f;const l=n.response.safeParse(f);if(!l.success)throw new C(`Response did not match the contract: ${n.method} ${n.path}`);return l.data},"call");e[s]=h}return Object.freeze(e)}o(j,"createContractClient");export{j as createContractClient};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/contractClient.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `createContractClient`: the SPA half of `@rexezuge/contracts`.\n *\n * `client.getItem({ params: { id } })` is typed from the endpoint the backend\n * registered, so the hand-copied `apps/web/src/types.ts` (twelve repos) and its\n * hand-built URL strings go away together.\n *\n * ## Why in `web`, on `createApiClient`\n *\n * A contract call is an API call. It has to fail the way every other call fails\n * (a `ServiceError` decoded from the `{Exception}` envelope, `HttpStatusError`\n * for an uncatalogued status), send the same credentials, and carry the same D1\n * session bookmark. So it is a thin typed layer over `createApiClient`, and lives\n * beside it. `web` depends on `contracts` (framework-free), never the reverse.\n *\n * ## Closed / open\n *\n * Closed: the URL is built from the endpoint (`buildPath`, every segment\n * encoded), the method is the endpoint's, a `204` endpoint resolves `null`, and\n * a failure is always a `ServiceError`. Response validation, when on, fails as\n * `BadGatewayError` (the server answered something the contract does not allow)\n * and never quotes the body.\n *\n * Open: the transport (`fetchFn`, or a whole `apiClient` shared with\n * non-contract calls), every `createApiClient` option, per-call `signal` and\n * `headers`, and `validateResponses`.\n */\nimport { buildPath } from '@rexezuge/contracts';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointInput, EndpointOutput } from '@rexezuge/contracts';\nimport { BadGatewayError } from '@rexezuge/errors';\nimport { buildQuery, createApiClient } from './api.ts';\nimport type { ApiClient, CreateApiClientOptions, FetchFn, QueryParams } from './api.ts';\n\ninterface ContractCallOptions {\n /**\n Cancels the request: `useResource` passes its own.\n */\n signal?: AbortSignal;\n /**\n Extra headers for this call only.\n */\n headers?: HeadersInit;\n}\n\n/**\nOne endpoint as a function. `input` may be omitted when nothing in it is required.\n*/\ntype ContractCall<E extends Endpoint> =\n Record<never, never> extends EndpointInput<E>\n ? (input?: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>>\n : (input: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>>;\n\n/**\nThe client: one call per contract endpoint, by name.\n*/\ntype ContractClient<C extends ContractEndpoints> = { readonly [K in keyof C]: ContractCall<C[K]> };\n\ninterface ValidationOption {\n /**\n * Parse every response through the endpoint's schema. Off by default: the\n * server already serializes what its schema allows, and a parse per call costs\n * a production bundle for no new fact. Turn it on in development and tests\n * (`validateResponses: import.meta.env.DEV`), where it catches a backend that\n * drifted from the contract.\n */\n validateResponses?: boolean;\n}\n\n/**\n * Either the `createApiClient` options (and the `fetch` to use, the global one\n * by default), or an existing `apiClient`, whose transport options then apply.\n */\ntype CreateContractClientOptions =\n | (CreateApiClientOptions & ValidationOption & { fetchFn?: FetchFn; apiClient?: undefined })\n | (ValidationOption & { apiClient: ApiClient });\n\nconst TRANSPORT_OPTIONS = ['baseUrl', 'headers', 'credentials', 'maxErrorMessageLength', 'bookmarks', 'fetchFn'] as const;\n\nfunction clientFor(options: CreateContractClientOptions): ApiClient {\n if (options.apiClient !== undefined) {\n const conflicting = TRANSPORT_OPTIONS.filter((key) => (options as unknown as Record<string, unknown>)[key] !== undefined);\n if (conflicting.length > 0) {\n throw new TypeError(\n `createContractClient: ${conflicting.join(', ')} cannot be combined with apiClient; configure that client instead`,\n );\n }\n return options.apiClient;\n }\n const { fetchFn, ...rest } = options;\n // Only the transport options reach createApiClient; `validateResponses` is ours.\n const apiOptions = Object.fromEntries(\n Object.entries(rest).filter(([key]) => key !== 'validateResponses' && key !== 'apiClient'),\n ) as CreateApiClientOptions;\n return createApiClient(fetchFn ?? ((input, init) => fetch(input, init)), apiOptions);\n}\n\n/**\n * Build a typed client for a contract. Memoize it (a module constant): it holds\n * the D1 bookmark store.\n *\n * ```ts\n * export const api = createContractClient(itemsContract, { validateResponses: import.meta.env.DEV });\n * const item = await api.getItem({ params: { id } });\n * ```\n */\nfunction createContractClient<C extends ContractEndpoints>(\n contract: Contract<C>,\n options: CreateContractClientOptions = {},\n): ContractClient<C> {\n const api = clientFor(options);\n const validate = options.validateResponses === true;\n const client: Record<string, ContractCall<Endpoint>> = {};\n\n for (const [name, endpoint] of Object.entries(contract) as [string, Endpoint][]) {\n const call = async (input: unknown = {}, callOptions: ContractCallOptions = {}): Promise<unknown> => {\n const slots = input as { params?: Record<string, string | number>; query?: QueryParams; body?: unknown };\n const path = `${buildPath(endpoint.path, slots.params)}${slots.query === undefined ? '' : buildQuery(slots.query)}`;\n const result = await api.request<unknown>(path, {\n method: endpoint.method,\n ...(slots.body !== undefined && { body: slots.body }),\n ...(callOptions.signal !== undefined && { signal: callOptions.signal }),\n ...(callOptions.headers !== undefined && { headers: callOptions.headers }),\n });\n if (endpoint.response === null) return null;\n if (!validate) return result;\n const parsed = endpoint.response.safeParse(result);\n if (!parsed.success) {\n // The method and path only: a body that broke the contract may carry\n // anything, and an error message is not the place to quote it.\n throw new BadGatewayError(`Response did not match the contract: ${endpoint.method} ${endpoint.path}`);\n }\n return parsed.data;\n };\n client[name] = call as ContractCall<Endpoint>;\n }\n return Object.freeze(client) as unknown as ContractClient<C>;\n}\n\nexport { createContractClient };\nexport type { ContractCall, ContractCallOptions, ContractClient, CreateContractClientOptions };\n"],
|
|
5
|
-
"mappings": "+EA2BA,OAAS,aAAAA,
|
|
6
|
-
"names": ["buildPath", "BadGatewayError", "buildQuery", "createApiClient", "TRANSPORT_OPTIONS", "clientFor", "options", "conflicting", "key", "fetchFn", "rest", "apiOptions", "input", "init", "__name", "createContractClient", "contract", "api", "validate", "client", "name", "endpoint", "call", "callOptions", "slots", "path", "result", "parsed"]
|
|
4
|
+
"sourcesContent": ["/**\n * `createContractClient`: the SPA half of `@rexezuge/contracts`.\n *\n * `client.getItem({ params: { id } })` is typed from the endpoint the backend\n * registered, so the hand-copied `apps/web/src/types.ts` (twelve repos) and its\n * hand-built URL strings go away together.\n *\n * ## Why in `web`, on `createApiClient`\n *\n * A contract call is an API call. It has to fail the way every other call fails\n * (a `ServiceError` decoded from the `{Exception}` envelope, `HttpStatusError`\n * for an uncatalogued status), send the same credentials, and carry the same D1\n * session bookmark. So it is a thin typed layer over `createApiClient`, and lives\n * beside it. `web` depends on `contracts` (framework-free), never the reverse.\n *\n * ## Closed / open\n *\n * Closed: the URL is built from the endpoint (`buildPath`, every segment\n * encoded), the method is the endpoint's, a `204` endpoint resolves `null`, a `{ kind: 'text' }` endpoint resolves the body string, and\n * a failure is always a `ServiceError`. Response validation, when on, fails as\n * `BadGatewayError` (the server answered something the contract does not allow)\n * and never quotes the body.\n *\n * Open: the transport (`fetchFn`, or a whole `apiClient` shared with\n * non-contract calls), every `createApiClient` option, per-call `signal` and\n * `headers`, and `validateResponses`.\n */\nimport { buildPath, isTextResponse } from '@rexezuge/contracts';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointInput, EndpointOutput } from '@rexezuge/contracts';\nimport { BadGatewayError } from '@rexezuge/errors';\nimport { buildQuery, createApiClient } from './api.ts';\nimport type { ApiClient, CreateApiClientOptions, FetchFn, QueryParams } from './api.ts';\n\ninterface ContractCallOptions {\n /**\n Cancels the request: `useResource` passes its own.\n */\n signal?: AbortSignal;\n /**\n Extra headers for this call only.\n */\n headers?: HeadersInit;\n}\n\n/**\nOne endpoint as a function. `input` may be omitted when nothing in it is required.\n*/\ntype ContractCall<E extends Endpoint> =\n Record<never, never> extends EndpointInput<E>\n ? (input?: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>>\n : (input: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>>;\n\n/**\nThe client: one call per contract endpoint, by name.\n*/\ntype ContractClient<C extends ContractEndpoints> = { readonly [K in keyof C]: ContractCall<C[K]> };\n\ninterface ValidationOption {\n /**\n * Parse every response through the endpoint's schema. Off by default: the\n * server already serializes what its schema allows, and a parse per call costs\n * a production bundle for no new fact. Turn it on in development and tests\n * (`validateResponses: import.meta.env.DEV`), where it catches a backend that\n * drifted from the contract.\n */\n validateResponses?: boolean;\n}\n\n/**\n * Either the `createApiClient` options (and the `fetch` to use, the global one\n * by default), or an existing `apiClient`, whose transport options then apply.\n */\ntype CreateContractClientOptions =\n | (CreateApiClientOptions & ValidationOption & { fetchFn?: FetchFn; apiClient?: undefined })\n | (ValidationOption & { apiClient: ApiClient });\n\nconst TRANSPORT_OPTIONS = ['baseUrl', 'headers', 'credentials', 'maxErrorMessageLength', 'bookmarks', 'fetchFn'] as const;\n\nfunction clientFor(options: CreateContractClientOptions): ApiClient {\n if (options.apiClient !== undefined) {\n const conflicting = TRANSPORT_OPTIONS.filter((key) => (options as unknown as Record<string, unknown>)[key] !== undefined);\n if (conflicting.length > 0) {\n throw new TypeError(\n `createContractClient: ${conflicting.join(', ')} cannot be combined with apiClient; configure that client instead`,\n );\n }\n return options.apiClient;\n }\n const { fetchFn, ...rest } = options;\n // Only the transport options reach createApiClient; `validateResponses` is ours.\n const apiOptions = Object.fromEntries(\n Object.entries(rest).filter(([key]) => key !== 'validateResponses' && key !== 'apiClient'),\n ) as CreateApiClientOptions;\n return createApiClient(fetchFn ?? ((input, init) => fetch(input, init)), apiOptions);\n}\n\n/**\n * Build a typed client for a contract. Memoize it (a module constant): it holds\n * the D1 bookmark store.\n *\n * ```ts\n * export const api = createContractClient(itemsContract, { validateResponses: import.meta.env.DEV });\n * const item = await api.getItem({ params: { id } });\n * ```\n */\nfunction createContractClient<C extends ContractEndpoints>(\n contract: Contract<C>,\n options: CreateContractClientOptions = {},\n): ContractClient<C> {\n const api = clientFor(options);\n const validate = options.validateResponses === true;\n const client: Record<string, ContractCall<Endpoint>> = {};\n\n for (const [name, endpoint] of Object.entries(contract) as [string, Endpoint][]) {\n const call = async (input: unknown = {}, callOptions: ContractCallOptions = {}): Promise<unknown> => {\n const slots = input as { params?: Record<string, string | number>; query?: QueryParams; body?: unknown };\n const path = `${buildPath(endpoint.path, slots.params)}${slots.query === undefined ? '' : buildQuery(slots.query)}`;\n const result = await api.request<unknown>(path, {\n method: endpoint.method,\n ...(isTextResponse(endpoint.response) && { responseType: 'text' as const }),\n ...(slots.body !== undefined && { body: slots.body }),\n ...(callOptions.signal !== undefined && { signal: callOptions.signal }),\n ...(callOptions.headers !== undefined && { headers: callOptions.headers }),\n });\n if (endpoint.response === null) return null;\n // A text response is a string as sent: there is no schema to parse it with.\n if (isTextResponse(endpoint.response) || !validate) return result;\n const parsed = endpoint.response.safeParse(result);\n if (!parsed.success) {\n // The method and path only: a body that broke the contract may carry\n // anything, and an error message is not the place to quote it.\n throw new BadGatewayError(`Response did not match the contract: ${endpoint.method} ${endpoint.path}`);\n }\n return parsed.data;\n };\n client[name] = call as ContractCall<Endpoint>;\n }\n return Object.freeze(client) as unknown as ContractClient<C>;\n}\n\nexport { createContractClient };\nexport type { ContractCall, ContractCallOptions, ContractClient, CreateContractClientOptions };\n"],
|
|
5
|
+
"mappings": "+EA2BA,OAAS,aAAAA,EAAW,kBAAAC,MAAsB,sBAE1C,OAAS,mBAAAC,MAAuB,mBAChC,OAAS,cAAAC,EAAY,mBAAAC,MAAuB,WA8C5C,MAAMC,EAAoB,CAAC,UAAW,UAAW,cAAe,wBAAyB,YAAa,SAAS,EAE/G,SAASC,EAAUC,EAAoC,CACrD,GAAIA,EAAQ,YAAc,OAAW,CACnC,MAAMC,EAAcH,EAAkB,OAAQI,GAASF,EAA+CE,CAAG,IAAM,MAAS,EACxH,GAAID,EAAY,OAAS,EACvB,MAAM,IAAI,UACR,yBAAyBA,EAAY,KAAK,IAAI,CAAC,mEAAmE,EAGtH,OAAOD,EAAQ,SACjB,CACA,KAAM,CAAE,QAAAG,EAAS,GAAGC,CAAI,EAAKJ,EAEvBK,EAAa,OAAO,YACxB,OAAO,QAAQD,CAAI,EAAE,OAAO,CAAC,CAACF,CAAG,IAAMA,IAAQ,qBAAuBA,IAAQ,WAAW,CAAC,EAE5F,OAAOL,EAAgBM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ApiClient", "TRANSPORT_OPTIONS", "clientFor", "options", "conflicting", "key", "fetchFn", "rest", "apiOptions", "input", "init", "__name", "createContractClient", "contract", "api", "validate", "client", "name", "endpoint", "call", "callOptions", "slots", "path", "result", "parsed"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/web",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.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.17.0",
|
|
34
|
+
"@rexezuge/errors": "1.17.0",
|
|
35
|
+
"@rexezuge/shared": "1.17.0"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
38
|
"i18next": "^26.0.0 || ^27.0.0",
|