@rexezuge/web 1.10.0 → 1.12.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.
Files changed (64) hide show
  1. package/README.md +81 -6
  2. package/dist/Button.d.ts +18 -2
  3. package/dist/Button.d.ts.map +1 -1
  4. package/dist/Button.js +1 -1
  5. package/dist/Button.js.map +3 -3
  6. package/dist/FocusInput.js +1 -1
  7. package/dist/FocusInput.js.map +3 -3
  8. package/dist/LanguageSelector.d.ts +22 -1
  9. package/dist/LanguageSelector.d.ts.map +1 -1
  10. package/dist/LanguageSelector.js +1 -1
  11. package/dist/LanguageSelector.js.map +3 -3
  12. package/dist/Spinner.d.ts +1 -1
  13. package/dist/Spinner.d.ts.map +1 -1
  14. package/dist/Spinner.js +1 -1
  15. package/dist/Spinner.js.map +3 -3
  16. package/dist/api.d.ts +8 -4
  17. package/dist/api.d.ts.map +1 -1
  18. package/dist/api.js +1 -1
  19. package/dist/api.js.map +3 -3
  20. package/dist/bookmarks.d.ts +50 -0
  21. package/dist/bookmarks.d.ts.map +1 -0
  22. package/dist/bookmarks.js +1 -0
  23. package/dist/bookmarks.js.map +7 -0
  24. package/dist/contractClient.d.ts +55 -0
  25. package/dist/contractClient.d.ts.map +1 -0
  26. package/dist/contractClient.js +1 -0
  27. package/dist/contractClient.js.map +7 -0
  28. package/dist/i18n.d.ts +110 -0
  29. package/dist/i18n.d.ts.map +1 -0
  30. package/dist/i18n.js +1 -0
  31. package/dist/i18n.js.map +7 -0
  32. package/dist/index.d.ts +13 -6
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +1 -1
  35. package/dist/index.js.map +3 -3
  36. package/dist/language.d.ts +30 -0
  37. package/dist/language.d.ts.map +1 -0
  38. package/dist/language.js +1 -0
  39. package/dist/language.js.map +7 -0
  40. package/dist/legacyPalette.d.ts +24 -0
  41. package/dist/legacyPalette.d.ts.map +1 -0
  42. package/dist/legacyPalette.js +1 -0
  43. package/dist/legacyPalette.js.map +7 -0
  44. package/dist/styles.css +99 -0
  45. package/dist/theme.d.ts +38 -7
  46. package/dist/theme.d.ts.map +1 -1
  47. package/dist/theme.js +1 -1
  48. package/dist/theme.js.map +3 -3
  49. package/dist/useNotice.d.ts +6 -3
  50. package/dist/useNotice.d.ts.map +1 -1
  51. package/dist/useNotice.js.map +2 -2
  52. package/dist/useResource.d.ts +107 -0
  53. package/dist/useResource.d.ts.map +1 -0
  54. package/dist/useResource.js +1 -0
  55. package/dist/useResource.js.map +7 -0
  56. package/dist/useSpaLanguage.d.ts +71 -39
  57. package/dist/useSpaLanguage.d.ts.map +1 -1
  58. package/dist/useSpaLanguage.js +1 -1
  59. package/dist/useSpaLanguage.js.map +3 -3
  60. package/dist/utils.d.ts +15 -6
  61. package/dist/utils.d.ts.map +1 -1
  62. package/dist/utils.js +1 -1
  63. package/dist/utils.js.map +3 -3
  64. package/package.json +21 -6
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';\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 * ## What is deliberately not here\n *\n * - **The D1 session bookmark** (`x-d1-bookmark`, CalDAV-Bridge and\n * Mail-Otter). It is module state threading a D1 replica pin through every\n * `/user/*` request; the kit has no D1 client, so the header policy stays\n * with the repos that own the binding.\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\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\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 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 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,mBAgIP,MAAMC,EAA2B,IAU3BC,EAAuF,CAC3F,IAAKf,EACL,IAAKY,EACL,IAAKV,EACL,IAAKG,EACL,IAAKD,EACL,IAAKH,EACL,IAAKO,EACL,IAAKD,EACL,IAAKM,EACL,IAAKJ,EACL,IAAKN,EACL,IAAKG,EACL,IAAKP,EACL,IAAKY,GAWP,MAAMK,UAAwBN,CAAY,CAnL1C,MAmL0C,CAAAO,EAAA,wBACxC,YAAYC,EAAgBC,EAAiBC,EAAmB,CAC9D,MAAMF,EAAQE,GAAQ,aAAaF,CAAM,GAAIC,CAAO,CACtD,EAcF,SAASE,EAAWC,EAAc,CAChC,OAAO,OAAOA,GAAU,UAAYA,EAAM,KAAI,IAAO,GAAKA,EAAQ,IACpE,CAFSL,EAAAI,EAAA,cAIT,SAASE,EAASD,EAAeE,EAAiB,CAChD,OAAOF,EAAM,OAASE,EAAY,GAAGF,EAAM,MAAM,EAAGE,CAAS,CAAC,SAAMF,CACtE,CAFSL,EAAAM,EAAA,YAQT,MAAME,EAAoB,wBAQ1B,SAASC,EAAgBC,EAAaH,EAAiB,CACrD,OAAIG,EAAI,SAAW,GAAKA,EAAI,OAASH,GAAaG,EAAI,SAAS,GAAG,EACzD,GAEF,CAACF,EAAkB,KAAKE,CAAG,CACpC,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AASC,EAAO,CACd,MAAMlD,EAAa,KAAKkD,CAAK,CAC/B,CACA,GAAI3B,EAAK,KAAI,IAAO,GAGpB,GAAI,CACF,OAAO,KAAK,MAAMA,CAAI,CACxB,MAAQ,CAIN,MAAM,IAAIjB,EAAgB2C,EAAS,OAAQ,4BAA4BD,CAAO,GAAI,IAAI,CACxF,CACF,CArBe,OAAAzC,EAAA6C,EAAA,YAuBR,CACL,QAAAX,EACA,IAAKlC,EAAA,MAAUmC,EAAcV,IAC3BS,EAAW,GAAGC,CAAI,GAAGV,IAAW,OAAY,GAAKD,EAAWC,CAAM,CAAC,EAAE,EADlE,OAEL,KAAMzB,EAAA,MAAUmC,EAAca,IAA+Bd,EAAWC,EAAM,CAAE,OAAQ,OAAQ,KAAAa,CAAI,CAAE,EAAhG,QACN,IAAKhD,EAAA,MAAUmC,EAAca,IAA+Bd,EAAWC,EAAM,CAAE,OAAQ,MAAO,KAAAa,CAAI,CAAE,EAA/F,OACL,MAAOhD,EAAA,MAAUmC,EAAca,IAA+Bd,EAAWC,EAAM,CAAE,OAAQ,QAAS,KAAAa,CAAI,CAAE,EAAjG,SACP,OAAQhD,EAAA,MAAUmC,EAAca,IAA+Bd,EAAWC,EAAM,CAAE,OAAQ,SAAU,KAAAa,CAAI,CAAE,EAAlG,UAEZ,CAvGShD,EAAA6B,EAAA",
6
- "names": ["BadGatewayError", "BadRequestError", "ConflictError", "ForbiddenError", "InternalServerError", "MethodNotAllowedError", "NotFoundError", "NotImplementedError", "PayloadTooLargeError", "PreconditionFailedError", "RateLimitedError", "ServiceError", "ServiceUnavailableError", "UnauthorizedError", "UnsupportedMediaTypeError", "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", "options", "baseUrl", "maxErrorMessageLength", "request", "path", "init", "method", "url", "hasBody", "requestInit", "context", "response", "cause", "toServiceError", "readJson", "decoded", "ErrorClass", "body"]
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,IAU3BC,EAAuF,CAC3F,IAAKjB,EACL,IAAKY,EACL,IAAKV,EACL,IAAKG,EACL,IAAKD,EACL,IAAKH,EACL,IAAKO,EACL,IAAKD,EACL,IAAKM,EACL,IAAKJ,EACL,IAAKN,EACL,IAAKG,EACL,IAAKP,EACL,IAAKY,GAWP,MAAMO,UAAwBR,CAAY,CAxL1C,MAwL0C,CAAAS,EAAA,wBACxC,YAAYC,EAAgBC,EAAiBC,EAAmB,CAC9D,MAAMF,EAAQE,GAAQ,aAAaF,CAAM,GAAIC,CAAO,CACtD,EAcF,SAASE,EAAWC,EAAc,CAChC,OAAO,OAAOA,GAAU,UAAYA,EAAM,KAAI,IAAO,GAAKA,EAAQ,IACpE,CAFSL,EAAAI,EAAA,cAIT,SAASE,EAASD,EAAeE,EAAiB,CAChD,OAAOF,EAAM,OAASE,EAAY,GAAGF,EAAM,MAAM,EAAGE,CAAS,CAAC,SAAMF,CACtE,CAFSL,EAAAM,EAAA,YAQT,MAAME,EAAoB,wBAQ1B,SAASC,EAAgBC,EAAaH,EAAiB,CACrD,OAAIG,EAAI,SAAW,GAAKA,EAAI,OAASH,GAAaG,EAAI,SAAS,GAAG,EACzD,GAEF,CAACF,EAAkB,KAAKE,CAAG,CACpC,CALSV,EAAAS,EAAA,mBAOT,SAASE,EAAgBC,EAAkBX,EAAgBM,EAAiB,CAC1E,GAAI,OAAOK,G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IAAKK,EAAQ,IAAI,CAC/H,CAjBejD,EAAA+C,EAAA,kBAmBf,eAAeC,EAAYJ,EAAoBD,EAAe,CAC5D,GAAIC,EAAS,SAAW,IACtB,OAEF,IAAI5B,EACJ,GAAI,CACFA,EAAO,MAAM4B,EAAS,KAAI,CAC5B,OAASC,EAAO,CACd,MAAMtD,EAAa,KAAKsD,CAAK,CAC/B,CACA,GAAI7B,EAAK,KAAI,IAAO,GAGpB,GAAI,CACF,OAAO,KAAK,MAAMA,CAAI,CACxB,MAAQ,CAIN,MAAM,IAAIjB,EAAgB6C,EAAS,OAAQ,4BAA4BD,CAAO,GAAI,IAAI,CACxF,CACF,CArBe,OAAA3C,EAAAgD,EAAA,YAuBR,CACL,QAAAb,EACA,IAAKnC,EAAA,MAAUoC,EAAcX,IAC3BU,EAAW,GAAGC,CAAI,GAAGX,IAAW,OAAY,GAAKD,EAAWC,CAAM,CAAC,EAAE,EADlE,OAEL,KAAMzB,EAAA,MAAUoC,EAAce,IAA+BhB,EAAWC,EAAM,CAAE,OAAQ,OAAQ,KAAAe,CAAI,CAAE,EAAhG,QACN,IAAKnD,EAAA,MAAUoC,EAAce,IAA+BhB,EAAWC,EAAM,CAAE,OAAQ,MAAO,KAAAe,CAAI,CAAE,EAA/F,OACL,MAAOnD,EAAA,MAAUoC,EAAce,IAA+BhB,EAAWC,EAAM,CAAE,OAAQ,QAAS,KAAAe,CAAI,CAAE,EAAjG,SACP,OAAQnD,EAAA,MAAUoC,EAAce,IAA+BhB,EAAWC,EAAM,CAAE,OAAQ,SAAU,KAAAe,CAAI,CAAE,EAAlG,UAEZ,CAjHSnD,EAAA6B,EAAA",
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", "options", "baseUrl", "maxErrorMessageLength", "bookmarks", "request", "path", "init", "method", "url", "hasBody", "bookmark", "requestInit", "context", "response", "cause", "nextBookmark", "toServiceError", "readJson", "decoded", "ErrorClass", "body"]
7
7
  }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * D1 session bookmarks for `createApiClient`.
3
+ *
4
+ * ## The D1 session bookmark
5
+ *
6
+ * Converged from `lib/api.ts` in **CalDAV-Bridge**, **Mail-Meow** and
7
+ * **Mail-Otter**, the three `apiFetch` copies that pinned a browser session to
8
+ * one D1 replica. Each stored `x-d1-bookmark` from a response and sent it on the
9
+ * next request, so a read after a write never lands on a replica that has not
10
+ * seen the write yet. The kit's version:
11
+ *
12
+ * - **On by default, and safe that way.** The client only ever echoes a value
13
+ * the server sent. Against a Worker that does not use D1 sessions no header
14
+ * arrives, so none is ever sent. A cross-origin API must expose the header
15
+ * through CORS before the client can even read it, which is itself an opt-in.
16
+ * `bookmarks: false` turns it off.
17
+ * - **Per client, not module state.** Mail-Otter needed a `resetD1Bookmark()`
18
+ * test seam because its bookmark leaked between tests. A store belongs to the
19
+ * client that made it. Pass one `createBookmarkStore()` to several clients to
20
+ * share a session.
21
+ * - **The newest wins** (Mail-Otter's rule). A slow response carrying an older
22
+ * bookmark must not move the session backwards. Mail-Meow kept the last one it
23
+ * saw, which is exactly that bug. D1 bookmarks order lexically.
24
+ * - An explicit per-request `x-d1-bookmark` header is left alone.
25
+ * - The copies scoped it to `/user/*`. Here the scope is the client (its
26
+ * `baseUrl`). A client for a surface that must not carry it passes
27
+ * `bookmarks: false`.
28
+ *
29
+ */
30
+ /**
31
+ * Where a client keeps its D1 session bookmark. `null` when it has none yet.
32
+ * `set` is offered every bookmark a response carries and decides what to keep.
33
+ */
34
+ interface BookmarkStore {
35
+ get(): string | null;
36
+ set(bookmark: string): void;
37
+ }
38
+ /**
39
+ The header a D1-session Worker reads and writes (`@rexezuge/d1`'s session helpers).
40
+ */
41
+ declare const D1_BOOKMARK_HEADER = "x-d1-bookmark";
42
+ /**
43
+ * A bookmark store that keeps the **newest** bookmark it is offered, so a slow
44
+ * response with an older one cannot move the session backwards.
45
+ */
46
+ declare function createBookmarkStore(initial?: string | null): BookmarkStore;
47
+ declare function resolveBookmarkStore(option: boolean | BookmarkStore | undefined): BookmarkStore | null;
48
+ export { createBookmarkStore, D1_BOOKMARK_HEADER, resolveBookmarkStore };
49
+ export type { BookmarkStore };
50
+ //# sourceMappingURL=bookmarks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bookmarks.d.ts","sourceRoot":"","sources":["../src/bookmarks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH;;;GAGG;AACH,UAAU,aAAa;IACrB,GAAG,IAAI,MAAM,GAAG,IAAI,CAAC;IACrB,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;EAEE;AACF,QAAA,MAAM,kBAAkB,kBAAkB,CAAC;AAE3C;;;GAGG;AACH,iBAAS,mBAAmB,CAAC,OAAO,GAAE,MAAM,GAAG,IAAW,GAAG,aAAa,CASzE;AAED,iBAAS,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,aAAa,GAAG,SAAS,GAAG,aAAa,GAAG,IAAI,CAI/F;AAED,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,CAAC;AACzE,YAAY,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var t=(e,r)=>o(e,"name",{value:r,configurable:!0});const f="x-d1-bookmark";function u(e=null){let r=e;return{get:t(()=>r,"get"),set(l){const n=l.trim();n!==""&&(r===null||r<n)&&(r=n)}}}t(u,"createBookmarkStore");function a(e){return e===!1?null:e===void 0||e===!0?u():e}t(a,"resolveBookmarkStore");export{f as D1_BOOKMARK_HEADER,u as createBookmarkStore,a as resolveBookmarkStore};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/bookmarks.ts"],
4
+ "sourcesContent": ["/**\n * D1 session bookmarks for `createApiClient`.\n *\n * ## The D1 session bookmark\n *\n * Converged from `lib/api.ts` in **CalDAV-Bridge**, **Mail-Meow** and\n * **Mail-Otter**, the three `apiFetch` copies that pinned a browser session to\n * one D1 replica. Each stored `x-d1-bookmark` from a response and sent it on the\n * next request, so a read after a write never lands on a replica that has not\n * seen the write yet. The kit's version:\n *\n * - **On by default, and safe that way.** The client only ever echoes a value\n * the server sent. Against a Worker that does not use D1 sessions no header\n * arrives, so none is ever sent. A cross-origin API must expose the header\n * through CORS before the client can even read it, which is itself an opt-in.\n * `bookmarks: false` turns it off.\n * - **Per client, not module state.** Mail-Otter needed a `resetD1Bookmark()`\n * test seam because its bookmark leaked between tests. A store belongs to the\n * client that made it. Pass one `createBookmarkStore()` to several clients to\n * share a session.\n * - **The newest wins** (Mail-Otter's rule). A slow response carrying an older\n * bookmark must not move the session backwards. Mail-Meow kept the last one it\n * saw, which is exactly that bug. D1 bookmarks order lexically.\n * - An explicit per-request `x-d1-bookmark` header is left alone.\n * - The copies scoped it to `/user/*`. Here the scope is the client (its\n * `baseUrl`). A client for a surface that must not carry it passes\n * `bookmarks: false`.\n *\n */\n\n/**\n * Where a client keeps its D1 session bookmark. `null` when it has none yet.\n * `set` is offered every bookmark a response carries and decides what to keep.\n */\ninterface BookmarkStore {\n get(): string | null;\n set(bookmark: string): void;\n}\n\n/**\nThe header a D1-session Worker reads and writes (`@rexezuge/d1`'s session helpers).\n*/\nconst D1_BOOKMARK_HEADER = 'x-d1-bookmark';\n\n/**\n * A bookmark store that keeps the **newest** bookmark it is offered, so a slow\n * response with an older one cannot move the session backwards.\n */\nfunction createBookmarkStore(initial: string | null = null): BookmarkStore {\n let latest: string | null = initial;\n return {\n get: () => latest,\n set(bookmark) {\n const next = bookmark.trim();\n if (next !== '' && (latest === null || latest < next)) latest = next;\n },\n };\n}\n\nfunction resolveBookmarkStore(option: boolean | BookmarkStore | undefined): BookmarkStore | null {\n if (option === false) return null;\n if (option === undefined || option === true) return createBookmarkStore();\n return option;\n}\n\nexport { createBookmarkStore, D1_BOOKMARK_HEADER, resolveBookmarkStore };\nexport type { BookmarkStore };\n"],
5
+ "mappings": "+EA0CA,MAAMA,EAAqB,gBAM3B,SAASC,EAAoBC,EAAyB,KAAI,CACxD,IAAIC,EAAwBD,EAC5B,MAAO,CACL,IAAKE,EAAA,IAAMD,EAAN,OACL,IAAIE,EAAQ,CACV,MAAMC,EAAOD,EAAS,KAAI,EACtBC,IAAS,KAAOH,IAAW,MAAQA,EAASG,KAAOH,EAASG,EAClE,EAEJ,CATSF,EAAAH,EAAA,uBAWT,SAASM,EAAqBC,EAA2C,CACvE,OAAIA,IAAW,GAAc,KACzBA,IAAW,QAAaA,IAAW,GAAaP,EAAmB,EAChEO,CACT,CAJSJ,EAAAG,EAAA",
6
+ "names": ["D1_BOOKMARK_HEADER", "createBookmarkStore", "initial", "latest", "__name", "bookmark", "next", "resolveBookmarkStore", "option"]
7
+ }
@@ -0,0 +1,55 @@
1
+ import type { Contract, ContractEndpoints, Endpoint, EndpointInput, EndpointOutput } from '@rexezuge/contracts';
2
+ import type { ApiClient, CreateApiClientOptions, FetchFn } from './api.ts';
3
+ interface ContractCallOptions {
4
+ /**
5
+ Cancels the request: `useResource` passes its own.
6
+ */
7
+ signal?: AbortSignal;
8
+ /**
9
+ Extra headers for this call only.
10
+ */
11
+ headers?: HeadersInit;
12
+ }
13
+ /**
14
+ One endpoint as a function. `input` may be omitted when nothing in it is required.
15
+ */
16
+ type ContractCall<E extends Endpoint> = Record<never, never> extends EndpointInput<E> ? (input?: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>> : (input: EndpointInput<E>, options?: ContractCallOptions) => Promise<EndpointOutput<E>>;
17
+ /**
18
+ The client: one call per contract endpoint, by name.
19
+ */
20
+ type ContractClient<C extends ContractEndpoints> = {
21
+ readonly [K in keyof C]: ContractCall<C[K]>;
22
+ };
23
+ interface ValidationOption {
24
+ /**
25
+ * Parse every response through the endpoint's schema. Off by default: the
26
+ * server already serializes what its schema allows, and a parse per call costs
27
+ * a production bundle for no new fact. Turn it on in development and tests
28
+ * (`validateResponses: import.meta.env.DEV`), where it catches a backend that
29
+ * drifted from the contract.
30
+ */
31
+ validateResponses?: boolean;
32
+ }
33
+ /**
34
+ * Either the `createApiClient` options (and the `fetch` to use, the global one
35
+ * by default), or an existing `apiClient`, whose transport options then apply.
36
+ */
37
+ type CreateContractClientOptions = (CreateApiClientOptions & ValidationOption & {
38
+ fetchFn?: FetchFn;
39
+ apiClient?: undefined;
40
+ }) | (ValidationOption & {
41
+ apiClient: ApiClient;
42
+ });
43
+ /**
44
+ * Build a typed client for a contract. Memoize it (a module constant): it holds
45
+ * the D1 bookmark store.
46
+ *
47
+ * ```ts
48
+ * export const api = createContractClient(itemsContract, { validateResponses: import.meta.env.DEV });
49
+ * const item = await api.getItem({ params: { id } });
50
+ * ```
51
+ */
52
+ declare function createContractClient<C extends ContractEndpoints>(contract: Contract<C>, options?: CreateContractClientOptions): ContractClient<C>;
53
+ export { createContractClient };
54
+ export type { ContractCall, ContractCallOptions, ContractClient, CreateContractClientOptions };
55
+ //# sourceMappingURL=contractClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contractClient.d.ts","sourceRoot":"","sources":["../src/contractClient.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,aAAa,EAAE,cAAc,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B,OAAO,GAAE,2BAAgC,GACxC,cAAc,CAAC,CAAC,CAAC,CA4BnB;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAChC,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,2BAA2B,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var o=(t,n)=>m(t,"name",{value:n,configurable:!0});import{buildPath as b}from"@rexezuge/contracts";import{BadGatewayError as C}from"@rexezuge/errors";import{buildQuery as g,createApiClient as y}from"./api.js";const w=["baseUrl","headers","credentials","maxErrorMessageLength","bookmarks","fetchFn"];function j(t){if(t.apiClient!==void 0){const e=w.filter(i=>t[i]!==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:n,...c}=t,d=Object.fromEntries(Object.entries(c).filter(([e])=>e!=="validateResponses"&&e!=="apiClient"));return y(n??((e,i)=>fetch(e,i)),d)}o(j,"clientFor");function O(t,n={}){const c=j(n),d=n.validateResponses===!0,e={};for(const[i,r]of Object.entries(t)){const u=o(async(h={},s={})=>{const a=h,p=`${b(r.path,a.params)}${a.query===void 0?"":g(a.query)}`,f=await c.request(p,{method:r.method,...a.body!==void 0&&{body:a.body},...s.signal!==void 0&&{signal:s.signal},...s.headers!==void 0&&{headers:s.headers}});if(r.response===null)return null;if(!d)return f;const l=r.response.safeParse(f);if(!l.success)throw new C(`Response did not match the contract: ${r.method} ${r.path}`);return l.data},"call");e[i]=u}return Object.freeze(e)}o(O,"createContractClient");export{O as createContractClient};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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,MAAiB,sBAE1B,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,IAAY,CAACG,EAAOC,IAAS,MAAMD,EAAOC,CAAI,GAAIF,CAAU,CACrF,CAhBSG,EAAAT,EAAA,aA2BT,SAASU,EACPC,EACAV,EAAuC,CAAA,EAAE,CAEzC,MAAMW,EAAMZ,EAAUC,CAAO,EACvBY,EAAWZ,EAAQ,oBAAsB,GACzCa,EAAiD,CAAA,EAEvD,SAAW,CAACC,EAAMC,CAAQ,IAAK,OAAO,QAAQL,CAAQ,EAA2B,CAC/E,MAAMM,EAAOR,EAAA,MAAOF,EAAiB,CAAA,EAAIW,EAAmC,CAAA,IAAwB,CAClG,MAAMC,EAAQZ,EACRa,EAAO,GAAGzB,EAAUqB,EAAS,KAAMG,EAAM,MAAM,CAAC,GAAGA,EAAM,QAAU,OAAY,GAAKtB,EAAWsB,EAAM,KAAK,CAAC,GAC3GE,EAAS,MAAMT,EAAI,QAAiBQ,EAAM,CAC9C,OAAQJ,EAAS,OACjB,GAAIG,EAAM,OAAS,QAAa,CAAE,KAAMA,EAAM,IAAI,EAClD,GAAID,EAAY,SAAW,QAAa,CAAE,OAAQA,EAAY,MAAM,EACpE,GAAIA,EAAY,UAAY,QAAa,CAAE,QAASA,EAAY,OAAO,EACxE,EACD,GAAIF,EAAS,WAAa,KAAM,OAAO,KACvC,GAAI,CAACH,EAAU,OAAOQ,EACtB,MAAMC,EAASN,EAAS,SAAS,UAAUK,CAAM,EACjD,GAAI,CAACC,EAAO,QAGV,MAAM,IAAI1B,EAAgB,wCAAwCoB,EAAS,MAAM,IAAIA,EAAS,IAAI,EAAE,EAEtG,OAAOM,EAAO,IAChB,EAlBa,QAmBbR,EAAOC,CAAI,EAAIE,CACjB,CACA,OAAO,OAAO,OAAOH,CAAM,CAC7B,CA/BSL,EAAAC,EAAA",
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"]
7
+ }
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,110 @@
1
+ import type { i18n as I18nInstance, InitOptions, TFunction } from 'i18next';
2
+ import type { LanguageTag } from '@rexezuge/shared';
3
+ /**
4
+ One language's strings, as the JSON catalogue file holds them.
5
+ */
6
+ type TranslationBundle = Record<string, unknown>;
7
+ /**
8
+ A lazy bundle: what `import.meta.glob` hands back (a module) or a plain bundle.
9
+ */
10
+ type BundleLoader = () => Promise<TranslationBundle | {
11
+ default: TranslationBundle;
12
+ }>;
13
+ interface CreateSpaI18nOptions<T extends LanguageTag> {
14
+ /**
15
+ The tags the app offers, in selector order.
16
+ */
17
+ supported: readonly T[];
18
+ /**
19
+ The language of last resort. Must be supported and present in `resources`.
20
+ */
21
+ fallback: T;
22
+ /**
23
+ Bundles available at startup, by tag (a bundle, or an eager glob module). Must include `fallback`.
24
+ */
25
+ resources: Partial<Record<T, TranslationBundle | {
26
+ default: TranslationBundle;
27
+ }>>;
28
+ /**
29
+ Bundles fetched on first use, by tag. A tag in both uses the eager bundle.
30
+ */
31
+ loaders?: Partial<Record<T, BundleLoader>>;
32
+ /**
33
+ The `localStorage` key the choice is read from. Use the same key in `useSpaLanguage`.
34
+ */
35
+ storageKey?: string;
36
+ /**
37
+ The i18next namespace. Defaults to `translation`.
38
+ */
39
+ namespace?: string;
40
+ /**
41
+ Your own i18next instance. Defaults to a fresh `i18next.createInstance()`.
42
+ */
43
+ instance?: I18nInstance;
44
+ /**
45
+ Any other i18next option. The language, fallback, supported list and resources are the kit's.
46
+ */
47
+ initOptions?: Omit<InitOptions, 'resources' | 'lng' | 'fallbackLng' | 'supportedLngs'>;
48
+ }
49
+ interface SpaI18n<T extends LanguageTag> {
50
+ /**
51
+ The initialized instance, also registered with react-i18next for `useTranslation`.
52
+ */
53
+ i18n: I18nInstance;
54
+ /**
55
+ `t` bound to the instance, for modules that translate outside React.
56
+ */
57
+ t: TFunction;
58
+ supported: readonly T[];
59
+ fallback: T;
60
+ storageKey: string;
61
+ /**
62
+ Resolves once init is done and the initial language's bundle is in (or failed).
63
+ */
64
+ ready: Promise<void>;
65
+ /**
66
+ A tag resolved onto a supported language (`zh-Hant-TW` → `zh-TW`, `ja` → fallback).
67
+ */
68
+ normalize(tag: string | null | undefined): T;
69
+ /**
70
+ The language to start in: `preferred`, then stored, then the browser's, then the fallback.
71
+ */
72
+ detect(preferred?: string | null): T;
73
+ /**
74
+ Load `tag`'s bundle if needed and switch to it. Rejects if the loader fails.
75
+ */
76
+ load(tag: LanguageTag): Promise<void>;
77
+ /**
78
+ Calls `listener` on every language change. Returns the unsubscribe.
79
+ */
80
+ subscribe(listener: (tag: string) => void): () => void;
81
+ }
82
+ /**
83
+ * Re-keys an `import.meta.glob` result by tag. A file named `fileName`
84
+ * (`translation.json`) takes its directory's name (`./locales/de/translation.json`
85
+ * becomes `de`). Any other `.json` file takes its own stem (`./locales/de.json`
86
+ * becomes `de`). Works for both an eager glob (modules) and a lazy one (loaders).
87
+ */
88
+ declare function bundlesByTag<V>(modules: Readonly<Record<string, V>>, fileName?: string): Record<string, V>;
89
+ /**
90
+ * Create and initialize the SPA's i18n instance. Call it once, at module level:
91
+ *
92
+ * ```ts
93
+ * // apps/web/src/i18n.ts
94
+ * import { createSpaI18n } from '@rexezuge/web/i18n';
95
+ * import en from './locales/en/translation.json';
96
+ *
97
+ * export const spaI18n = createSpaI18n({
98
+ * supported: ['en', 'de', 'zh-CN', 'zh-TW'],
99
+ * fallback: 'en',
100
+ * resources: { en },
101
+ * loaders: bundlesByTag(import.meta.glob<{ default: Record<string, unknown> }>('./locales/*\/translation.json')),
102
+ * storageKey: 'my-app-lng',
103
+ * });
104
+ * export const { t } = spaI18n;
105
+ * ```
106
+ */
107
+ declare function createSpaI18n<const T extends LanguageTag>(options: CreateSpaI18nOptions<T>): SpaI18n<T>;
108
+ export { bundlesByTag, createSpaI18n };
109
+ export type { BundleLoader, CreateSpaI18nOptions, SpaI18n, TranslationBundle };
110
+ //# sourceMappingURL=i18n.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AA8CA,OAAO,KAAK,EAAE,IAAI,IAAI,YAAY,EAAE,WA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ACrB;;MAEE;IACF,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,CAAC,CAAC;IAC7C;;MAEE;IACF,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,CAAC,CAAC;IACrC;;MAEE;IACF,IAAI,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC;;MAEE;IACF,SAAS,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxD;AAUD;;;;;GAKG;AACH,iBAAS,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,SAAqB,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAS/G;AAeD;;;;;;;;;;;;;;;;;GAiBG;AACH,iBAAS,aAAa,CAAC,KAAK,CAAC,CAAC,SAAS,WAAW,EAAE,OAAO,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA4EhG;AAED,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AACvC,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
package/dist/i18n.js ADDED
@@ -0,0 +1 @@
1
+ var k=Object.defineProperty;var r=(e,t)=>k(e,"name",{value:t,configurable:!0});import T from"i18next";import{initReactI18next as S}from"react-i18next";import{detectLanguage as L,resolveLanguageTag as j}from"./language.js";const I="translation",A="language";function y(e){const t=e;return typeof t.default=="object"&&t.default!==null?t.default:e}r(y,"unwrap");function v(e,t="translation.json"){const c={};for(const[l,u]of Object.entries(e)){const a=l.split("/"),o=a.at(-1)??"",f=o===t?a.at(-2)??"":o.replace(/\.json$/,"");f!==""&&f!=="."&&(c[f]=u)}return c}r(v,"bundlesByTag");function x(e){if(!e.supported.includes(e.fallback))throw new TypeError(`createSpaI18n: fallback "${e.fallback}" is not in supported`);if(e.resources[e.fallback]===void 0)throw new TypeError(`createSpaI18n: the fallback "${e.fallback}" bundle must be in resources`);const t=e.supported.filter(c=>e.resources[c]===void 0&&e.loaders?.[c]===void 0);if(t.length>0)throw new TypeError(`createSpaI18n: no catalogue (resource or loader) for ${t.join(", ")}`)}r(x,"validate");function B(e){x(e);const t=e.namespace??I,c=e.storageKey??A,l=Object.freeze([...e.supported]),u=e.fallback,a=e.instance??T.createInstance(),o=new Map,f=r(n=>j(n,l,u),"normalize"),i=r(n=>L({preferred:n,supported:l,fallback:u,storageKey:c}),"detect"),d={};for(const n of l){const s=e.resources[n];s!==void 0&&(d[n]={[t]:y(s)})}async function h(n){if(a.hasResourceBundle(n,t))return;const s=o.get(n);if(s!==void 0)return s;const w=e.loaders?.[n],p=w().then(E=>{a.addResourceBundle(n,t,y(E),!0,!0)});o.set(n,p);try{await p}finally{o.delete(n)}}r(h,"ensureBundle");async function g(n){const s=f(n);await h(s),await a.changeLanguage(s)}r(g,"load");const b=i();a.use(S);const m=a.init({defaultNS:t,ns:[t],interpolation:{escapeValue:!1},returnEmptyString:!1,...e.initOptions,resources:d,lng:b,fallbackLng:u,supportedLngs:[...l]}).then(()=>g(b)).catch(()=>{});return{i18n:a,t:a.t.bind(a),supported:l,fallback:u,storageKey:c,ready:m,normalize:f,detect:i,load:g,subscribe(n){return a.on("languageChanged",n),()=>{a.off("languageChanged",n)}}}}r(B,"createSpaI18n");export{v as bundlesByTag,B as createSpaI18n};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/i18n.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/web/i18n`: the SPA's i18next bootstrap.\n *\n * ## Provenance\n *\n * `apps/web/src/i18n.ts` in **Agent-Router**, **AWS-AccessBridge**,\n * **ChordDHT-Tracker**, **Durable-DAV**, **Durable-DAV-Router**, **Edge-Git**,\n * **Edge-Sonic**, **Mail-Meow**, **Mail-Otter** and **Pigeongram**. Ten copies of\n * the same 100 lines, each with its own tag canonicalizer. Three of them collapsed\n * a Traditional Chinese browser onto Simplified, and Mail-Meow alone had fixed it.\n * What they shared, and what is now one function:\n *\n * - `SUPPORTED_LANGUAGES` / `normalizeLanguage` / `detectInitialLanguage`. These\n * are the kit's `resolveLanguageTag` over `@rexezuge/shared`'s\n * `canonicalizeLanguageTag`, with the same precedence as `useSpaLanguage`\n * (stored > browser > fallback). The canonicalizer is not re-implemented here.\n * - The bundle strategies. Pigeongram loads all bundles **eagerly**\n * (`import.meta.glob(..., { eager: true })`) and Mail-Meow loads them **lazily**\n * (`import.meta.glob(...)`). The first goes in `resources`, the second in\n * `loaders`, and both can be mixed.\n * - `loadLanguage`, as `load(tag)`: fetch the bundle once (concurrent calls share\n * one request), add it, switch.\n * - The init options every copy used: `fallbackLng`, `supportedLngs`,\n * `defaultNS: 'translation'`, `escapeValue: false` (React escapes) and\n * `returnEmptyString: false`.\n *\n * ## Why a subpath\n *\n * `i18next` and `react-i18next` are **optional peers**, imported by this module\n * and nowhere else in the package, and the root barrel does not re-export it.\n * Components still take every label as a prop (glyph in, string out). This is the\n * app's catalogue bootstrap, not a component dependency.\n *\n * ## Closed / open\n *\n * Closed: a supported language without a catalogue (no resource, no loader), or a\n * fallback that is not supported or not eager, throws at creation. Pigeongram's\n * `validate:locales` enforced this at CI time, so a language can never be offered\n * empty. Tag resolution is the kit's. A loader failure rejects `load` and is never\n * logged here.\n *\n * Open: `resources`/`loaders`, `storageKey`, `namespace`, your own `instance`,\n * and `initOptions` for any other i18next option. The returned object satisfies\n * `useSpaLanguage`'s `LanguageRuntime` port: pass it as `runtime`.\n */\nimport i18next from 'i18next';\nimport type { i18n as I18nInstance, InitOptions, TFunction } from 'i18next';\nimport { initReactI18next } from 'react-i18next';\nimport type { LanguageTag } from '@rexezuge/shared';\nimport { detectLanguage, resolveLanguageTag } from './language.ts';\n\n/**\nOne language's strings, as the JSON catalogue file holds them.\n*/\ntype TranslationBundle = Record<string, unknown>;\n\n/**\nA lazy bundle: what `import.meta.glob` hands back (a module) or a plain bundle.\n*/\ntype BundleLoader = () => Promise<TranslationBundle | { default: TranslationBundle }>;\n\ninterface CreateSpaI18nOptions<T extends LanguageTag> {\n /**\n The tags the app offers, in selector order.\n */\n supported: readonly T[];\n /**\n The language of last resort. Must be supported and present in `resources`.\n */\n fallback: T;\n /**\n Bundles available at startup, by tag (a bundle, or an eager glob module). Must include `fallback`.\n */\n resources: Partial<Record<T, TranslationBundle | { default: TranslationBundle }>>;\n /**\n Bundles fetched on first use, by tag. A tag in both uses the eager bundle.\n */\n loaders?: Partial<Record<T, BundleLoader>>;\n /**\n The `localStorage` key the choice is read from. Use the same key in `useSpaLanguage`.\n */\n storageKey?: string;\n /**\n The i18next namespace. Defaults to `translation`.\n */\n namespace?: string;\n /**\n Your own i18next instance. Defaults to a fresh `i18next.createInstance()`.\n */\n instance?: I18nInstance;\n /**\n Any other i18next option. The language, fallback, supported list and resources are the kit's.\n */\n initOptions?: Omit<InitOptions, 'resources' | 'lng' | 'fallbackLng' | 'supportedLngs'>;\n}\n\ninterface SpaI18n<T extends LanguageTag> {\n /**\n The initialized instance, also registered with react-i18next for `useTranslation`.\n */\n i18n: I18nInstance;\n /**\n `t` bound to the instance, for modules that translate outside React.\n */\n t: TFunction;\n supported: readonly T[];\n fallback: T;\n storageKey: string;\n /**\n Resolves once init is done and the initial language's bundle is in (or failed).\n */\n ready: Promise<void>;\n /**\n A tag resolved onto a supported language (`zh-Hant-TW` → `zh-TW`, `ja` → fallback).\n */\n normalize(tag: string | null | undefined): T;\n /**\n The language to start in: `preferred`, then stored, then the browser's, then the fallback.\n */\n detect(preferred?: string | null): T;\n /**\n Load `tag`'s bundle if needed and switch to it. Rejects if the loader fails.\n */\n load(tag: LanguageTag): Promise<void>;\n /**\n Calls `listener` on every language change. Returns the unsubscribe.\n */\n subscribe(listener: (tag: string) => void): () => void;\n}\n\nconst DEFAULT_NAMESPACE = 'translation';\nconst DEFAULT_STORAGE_KEY = 'language';\n\nfunction unwrap(loaded: TranslationBundle | { default: TranslationBundle }): TranslationBundle {\n const module = loaded as { default?: unknown };\n return typeof module.default === 'object' && module.default !== null ? (module.default as TranslationBundle) : loaded;\n}\n\n/**\n * Re-keys an `import.meta.glob` result by tag. A file named `fileName`\n * (`translation.json`) takes its directory's name (`./locales/de/translation.json`\n * becomes `de`). Any other `.json` file takes its own stem (`./locales/de.json`\n * becomes `de`). Works for both an eager glob (modules) and a lazy one (loaders).\n */\nfunction bundlesByTag<V>(modules: Readonly<Record<string, V>>, fileName = 'translation.json'): Record<string, V> {\n const byTag: Record<string, V> = {};\n for (const [path, value] of Object.entries(modules)) {\n const segments = path.split('/');\n const file = segments.at(-1) ?? '';\n const tag = file === fileName ? (segments.at(-2) ?? '') : file.replace(/\\.json$/, '');\n if (tag !== '' && tag !== '.') byTag[tag] = value;\n }\n return byTag;\n}\n\nfunction validate<T extends LanguageTag>(options: CreateSpaI18nOptions<T>): void {\n if (!options.supported.includes(options.fallback)) {\n throw new TypeError(`createSpaI18n: fallback \"${options.fallback}\" is not in supported`);\n }\n if (options.resources[options.fallback] === undefined) {\n throw new TypeError(`createSpaI18n: the fallback \"${options.fallback}\" bundle must be in resources`);\n }\n const empty = options.supported.filter((tag) => options.resources[tag] === undefined && options.loaders?.[tag] === undefined);\n if (empty.length > 0) {\n throw new TypeError(`createSpaI18n: no catalogue (resource or loader) for ${empty.join(', ')}`);\n }\n}\n\n/**\n * Create and initialize the SPA's i18n instance. Call it once, at module level:\n *\n * ```ts\n * // apps/web/src/i18n.ts\n * import { createSpaI18n } from '@rexezuge/web/i18n';\n * import en from './locales/en/translation.json';\n *\n * export const spaI18n = createSpaI18n({\n * supported: ['en', 'de', 'zh-CN', 'zh-TW'],\n * fallback: 'en',\n * resources: { en },\n * loaders: bundlesByTag(import.meta.glob<{ default: Record<string, unknown> }>('./locales/*\\/translation.json')),\n * storageKey: 'my-app-lng',\n * });\n * export const { t } = spaI18n;\n * ```\n */\nfunction createSpaI18n<const T extends LanguageTag>(options: CreateSpaI18nOptions<T>): SpaI18n<T> {\n validate(options);\n const namespace = options.namespace ?? DEFAULT_NAMESPACE;\n const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;\n const supported = Object.freeze([...options.supported]);\n const fallback = options.fallback;\n const instance = options.instance ?? i18next.createInstance();\n const inFlight = new Map<string, Promise<void>>();\n\n const normalize = (tag: string | null | undefined): T => resolveLanguageTag(tag, supported, fallback) as T;\n const detect = (preferred?: string | null): T => detectLanguage({ preferred, supported, fallback, storageKey }) as T;\n\n const resources: Record<string, Record<string, TranslationBundle>> = {};\n for (const tag of supported) {\n const bundle = options.resources[tag];\n if (bundle !== undefined) resources[tag] = { [namespace]: unwrap(bundle) };\n }\n\n async function ensureBundle(tag: T): Promise<void> {\n if (instance.hasResourceBundle(tag, namespace)) return;\n const existing = inFlight.get(tag);\n if (existing !== undefined) return existing;\n const loader = options.loaders?.[tag] as BundleLoader;\n const loading = loader().then((loaded) => {\n instance.addResourceBundle(tag, namespace, unwrap(loaded), true, true);\n });\n inFlight.set(tag, loading);\n try {\n await loading;\n } finally {\n inFlight.delete(tag);\n }\n }\n\n async function load(tag: LanguageTag): Promise<void> {\n const resolved = normalize(tag);\n await ensureBundle(resolved);\n await instance.changeLanguage(resolved);\n }\n\n const initial = detect();\n instance.use(initReactI18next);\n const ready = instance\n .init({\n defaultNS: namespace,\n ns: [namespace],\n interpolation: { escapeValue: false },\n returnEmptyString: false,\n ...options.initOptions,\n resources,\n lng: initial,\n fallbackLng: fallback,\n supportedLngs: [...supported],\n })\n .then(() => load(initial))\n // A failed initial bundle leaves the fallback rendering; `useSpaLanguage`\n // retries it and reports `status: 'error'` if it fails again.\n .catch(() => {});\n\n return {\n i18n: instance,\n t: instance.t.bind(instance),\n supported,\n fallback,\n storageKey,\n ready,\n normalize,\n detect,\n load,\n subscribe(listener) {\n instance.on('languageChanged', listener);\n return () => {\n instance.off('languageChanged', listener);\n };\n },\n };\n}\n\nexport { bundlesByTag, createSpaI18n };\nexport type { BundleLoader, CreateSpaI18nOptions, SpaI18n, TranslationBundle };\n"],
5
+ "mappings": "+EA6CA,OAAOA,MAAa,UAEpB,OAAS,oBAAAC,MAAwB,gBAEjC,OAAS,kBAAAC,EAAgB,sBAAAC,MAA0B,gBAiFnD,MAAMC,EAAoB,cACpBC,EAAsB,WAE5B,SAASC,EAAOC,EAA0D,CACxE,MAAMC,EAASD,EACf,OAAO,OAAOC,EAAO,SAAY,UAAYA,EAAO,UAAY,KAAQA,EAAO,QAAgCD,CACjH,CAHSE,EAAAH,EAAA,UAWT,SAASI,EAAgBC,EAAsCC,EAAW,mBAAkB,CAC1F,MAAMC,EAA2B,CAAA,EACjC,SAAW,CAACC,EAAMC,CAAK,IAAK,OAAO,QAAQJ,CAAO,EAAG,CACnD,MAAMK,EAAWF,EAAK,MAAM,GAAG,EACzBG,EAAOD,EAAS,GAAG,EAAE,GAAK,GAC1BE,EAAMD,IAASL,EAAYI,EAAS,GAAG,EAAE,GAAK,GAAMC,EAAK,QAAQ,UAAW,EAAE,EAChFC,IAAQ,IAAMA,IAAQ,MAAKL,EAAMK,CAAG,EAAIH,EAC9C,CACA,OAAOF,CACT,CATSJ,EAAAC,EAAA,gBAWT,SAASS,EAAgCC,EAAgC,CACvE,GAAI,CAACA,EAAQ,UAAU,SAASA,EAAQ,QAAQ,EAC9C,MAAM,IAAI,UAAU,4BAA4BA,EAAQ,QAAQ,uBAAuB,EAEzF,GAAIA,EAAQ,UAAUA,EAAQ,QAAQ,IAAM,OAC1C,MAAM,IAAI,UAAU,gCAAgCA,EAAQ,QAAQ,+BAA+B,EAErG,MAAMC,EAAQD,EAAQ,UAAU,OAAQF,GAAQE,EAAQ,UAAUF,CAAG,IAAM,QAAaE,EAAQ,UAAUF,CAAG,IAAM,MAAS,EAC5H,GAAIG,EAAM,OAAS,EACjB,MAAM,IAAI,UAAU,wDAAwDA,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AeY,CAAQ,CACxC,CAJe9B,EAAA6B,EAAA,QAMf,MAAME,EAAUV,EAAM,EACtBH,EAAS,IAAI1B,CAAgB,EAC7B,MAAMwC,EAAQd,EACX,KAAK,CACJ,UAAWJ,EACX,GAAI,CAACA,CAAS,EACd,cAAe,CAAE,YAAa,EAAK,EACnC,kBAAmB,GACnB,GAAGH,EAAQ,YACX,UAAAY,EACA,IAAKQ,EACL,YAAad,EACb,cAAe,CAAC,GAAGD,CAAS,EAC7B,EACA,KAAK,IAAMa,EAAKE,CAAO,CAAC,EAGxB,MAAM,IAAK,CAAE,CAAC,EAEjB,MAAO,CACL,KAAMb,EACN,EAAGA,EAAS,EAAE,KAAKA,CAAQ,EAC3B,UAAAF,EACA,SAAAC,EACA,WAAAF,EACA,MAAAiB,EACA,UAAAZ,EACA,OAAAC,EACA,KAAAQ,EACA,UAAUI,EAAQ,CAChB,OAAAf,EAAS,GAAG,kBAAmBe,CAAQ,EAChC,IAAK,CACVf,EAAS,IAAI,kBAAmBe,CAAQ,CAC1C,CACF,EAEJ,CA5ESjC,EAAAa,EAAA",
6
+ "names": ["i18next", "initReactI18next", "detectLanguage", "resolveLanguageTag", "DEFAULT_NAMESPACE", "DEFAULT_STORAGE_KEY", "unwrap", "loaded", "module", "__name", "bundlesByTag", "modules", "fileName", "byTag", "path", "value", "segments", "file", "tag", "validate", "options", "empty", "createSpaI18n", "namespace", "storageKey", "supported", "fallback", "instance", "inFlight", "normalize", "detect", "preferred", "resources", "bundle", "ensureBundle", "existing", "loader", "loading", "load", "resolved", "initial", "ready", "listener"]
7
+ }
package/dist/index.d.ts CHANGED
@@ -12,8 +12,9 @@
12
12
  *
13
13
  * ## What a consumer must provide
14
14
  *
15
- * - **The CSS variables the class-based components read.** All six Tailwind
16
- * repos define the same set, so this is usually already present:
15
+ * - **The CSS variables the class-based components read.** Import
16
+ * `@rexezuge/web/styles.css` for defaults (and the source scan), or define
17
+ * them yourself:
17
18
  * `--color-accent`, `--color-accent-dim`, `--color-border`,
18
19
  * `--color-surface-base`, `--color-surface-1..4`,
19
20
  * `--color-text-primary`, `--color-text-secondary`, `--color-text-muted`, and
@@ -46,8 +47,8 @@
46
47
  * ## What is deliberately not here
47
48
  *
48
49
  * Domain badges (`ConnectionBadge`, `TaskRunStatusBadge`, …), the OAuth
49
- * `?oauth2=` notice seeding, the D1 bookmark header, WebDAV `207` handling, the
50
- * authed-first public fallback, and every app's `SUPPORTED_LANGUAGES`. Each had
50
+ * `?oauth2=` notice seeding, WebDAV `207` handling, the authed-first public
51
+ * fallback, and every app's `SUPPORTED_LANGUAGES`. Each had
51
52
  * exactly one consumer, so each stays with it — see `constants.ts` and the
52
53
  * per-module provenance notes for the list.
53
54
  */
@@ -91,15 +92,21 @@ export type { PaginationLabels, PaginationProps } from './Pagination.tsx';
91
92
  export { Spinner } from './Spinner.tsx';
92
93
  export type { SpinnerProps } from './Spinner.tsx';
93
94
  export { btnBase, btnBlueStyle, btnGreenStyle, btnSmallStyle, buttonColors, cardStyle, inputStyle, paginationBtnStyle, tableCardStyle, tdStyle, theme, thStyle, } from './theme.ts';
94
- export { cn } from './utils.ts';
95
+ export { cn, configureClassMerge } from './utils.ts';
95
96
  export type { ClassDictionary, ClassValue } from './utils.ts';
96
97
  export { COPY_FEEDBACK_TIMEOUT_MS, NOTICE_TIMEOUT_MS, ZERO_TRUST_AUTHENTICATION_PATH } from './constants.ts';
97
98
  export { useNotice } from './useNotice.ts';
98
99
  export type { Notice, NoticeKind, ShowNotice, UseNoticeOptions, UseNoticeResult } from './useNotice.ts';
99
100
  export { canonicalizeLanguageTag, DEFAULT_FALLBACK_LANGUAGE, DEFAULT_LANGUAGE_STORAGE_KEY, DEFAULT_SUPPORTED_LANGUAGES, resolveLanguageTag, useSpaLanguage, } from './useSpaLanguage.ts';
100
- export type { LanguageTag, UseSpaLanguageOptions, UseSpaLanguageResult } from './useSpaLanguage.ts';
101
+ export type { LanguageRuntime, LanguageStatus, LanguageTag, UseSpaLanguageOptions, UseSpaLanguageResult } from './useSpaLanguage.ts';
102
+ export { useMutation, useResource } from './useResource.ts';
103
+ export type { MutationState, MutationStatus, ResourceState, ResourceStatus, UseResourceOptions } from './useResource.ts';
101
104
  export { CURRENT_USER_PATH, useCurrentUser } from './useCurrentUser.ts';
102
105
  export type { CurrentUser, UseCurrentUserOptions, UseCurrentUserResult } from './useCurrentUser.ts';
103
106
  export { buildQuery, createApiClient, HttpStatusError, MAX_ERROR_MESSAGE_LENGTH } from './api.ts';
104
107
  export type { ApiClient, ApiRequestInit, CreateApiClientOptions, FetchFn, QueryParams, QueryValue } from './api.ts';
108
+ export { createBookmarkStore, D1_BOOKMARK_HEADER } from './bookmarks.ts';
109
+ export type { BookmarkStore } from './bookmarks.ts';
110
+ export { createContractClient } from './contractClient.ts';
111
+ export type { ContractCall, ContractCallOptions, ContractClient, CreateContractClientOptions } from './contractClient.ts';
105
112
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAEH,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACnF,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE5D,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACzG,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE3E,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,eAAe,EAAE,cAAc,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACrG,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;A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e,EAAE,cAAc,EAAE,WAAW,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAErI,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC5D,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEzH,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACxE,YAAY,EAAE,WAAW,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAEpG,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAClG,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,sBAAsB,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEpH,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 t,badgeBaseClass as o,badgeClass as a,badgeVariantClass as l}from"./Badge.js";import{Button as p,buttonBaseClass as s,buttonClass as m,buttonSizeClass as f,buttonVariantClass as C}from"./Button.js";import{Card as x,cardClass as i,cardHeaderClass as S,cardTitleClass as u,CardHeader as T,CardTitle as E}from"./Card.js";import{FocusInput as A}from"./FocusInput.js";import{Input as b,Label as L,Select as U,Textarea as c,fieldClass as y}from"./Input.js";import{LoadingButton as R}from"./LoadingButton.js";import{ModalShell as N}from"./ModalShell.js";import{ConfirmDeleteModal as M,EmptyState as P,LoadingSpinner as F}from"./PageState.js";import{AppPage as I}from"./AppPage.js";import{PageHeaderCard as h}from"./PageHeaderCard.js";import{ContextBar as K}from"./ContextBar.js";import{Unauthorized as Y}from"./Unauthorized.js";import{NoticeBar as w}from"./NoticeBar.js";import{LanguageSelector as W}from"./LanguageSelector.js";import{RefreshButton as Z}from"./RefreshButton.js";import{ReadOnlyField as k}from"./ReadOnlyField.js";import{TypeToConfirmModal as J}from"./TypeToConfirmModal.js";import{useCopyToClipboard as ee}from"./useCopyToClipboard.js";import{Pagination as te,clampPage as oe,pageCountFor as ae,pageWindow as le}from"./Pagination.js";import{Spinner as pe}from"./Spinner.js";import{btnBase as me,btnBlueStyle as fe,btnGreenStyle as Ce,btnSmallStyle as de,buttonColors as xe,cardStyle as ie,inputStyle as Se,paginationBtnStyle as ue,tableCardStyle as Te,tdStyle as Ee,theme as ge,thStyle as Ae}from"./theme.js";import{cn as be}from"./utils.js";import{COPY_FEEDBACK_TIMEOUT_MS as Ue,NOTICE_TIMEOUT_MS as ce,ZERO_TRUST_AUTHENTICATION_PATH as ye}from"./constants.js";import{useNotice as Re}from"./useNotice.js";import{canonicalizeLanguageTag as Ne,DEFAULT_FALLBACK_LANGUAGE as Oe,DEFAULT_LANGUAGE_STORAGE_KEY as Me,DEFAULT_SUPPORTED_LANGUAGES as Pe,resolveLanguageTag as Fe,useSpaLanguage as He}from"./useSpaLanguage.js";import{CURRENT_USER_PATH as De,useCurrentUser as he}from"./useCurrentUser.js";import{buildQuery as Ke,createApiClient as Ve,HttpStatusError as Ye,MAX_ERROR_MESSAGE_LENGTH as ve}from"./api.js";export{I as AppPage,t as Badge,p as Button,Ue as COPY_FEEDBACK_TIMEOUT_MS,De as CURRENT_USER_PATH,x as Card,T as CardHeader,E as CardTitle,M as ConfirmDeleteModal,K as ContextBar,Oe as DEFAULT_FALLBACK_LANGUAGE,Me as DEFAULT_LANGUAGE_STORAGE_KEY,Pe as DEFAULT_SUPPORTED_LANGUAGES,P as EmptyState,A as FocusInput,Ye as HttpStatusError,b as Input,L as Label,W as LanguageSelector,R as LoadingButton,F as LoadingSpinner,ve as MAX_ERROR_MESSAGE_LENGTH,N as ModalShell,ce as NOTICE_TIMEOUT_MS,w as NoticeBar,h as PageHeaderCard,te as Pagination,k as ReadOnlyField,Z as RefreshButton,U as Select,pe as Spinner,c as Textarea,J as TypeToConfirmModal,Y as Unauthorized,ye as ZERO_TRUST_AUTHENTICATION_PATH,o as badgeBaseClass,a as badgeClass,l as badgeVariantClass,me as btnBase,fe as btnBlueStyle,Ce as btnGreenStyle,de as btnSmallStyle,Ke as buildQuery,s as buttonBaseClass,m as buttonClass,xe as buttonColors,f as buttonSizeClass,C as buttonVariantClass,Ne as canonicalizeLanguageTag,i as cardClass,S as cardHeaderClass,ie as cardStyle,u as cardTitleClass,oe as clampPage,be as cn,Ve as createApiClient,y as fieldClass,Se as inputStyle,ae as pageCountFor,le as pageWindow,ue as paginationBtnStyle,Fe as resolveLanguageTag,Te as tableCardStyle,Ee as tdStyle,Ae as thStyle,ge as theme,ee as useCopyToClipboard,he as useCurrentUser,Re as useNotice,He as useSpaLanguage};
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 x,cardClass as i,cardHeaderClass as d,cardTitleClass as S,CardHeader as T,CardTitle as E}from"./Card.js";import{FocusInput as A}from"./FocusInput.js";import{Input as c,Label as b,Select as L,Textarea as B,fieldClass as R}from"./Input.js";import{LoadingButton as y}from"./LoadingButton.js";import{ModalShell as O}from"./ModalShell.js";import{ConfirmDeleteModal as N,EmptyState as H,LoadingSpinner as P}from"./PageState.js";import{AppPage as F}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 v}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 ue,buttonColors as xe,cardStyle as ie,inputStyle as de,paginationBtnStyle as Se,tableCardStyle as Te,tdStyle as Ee,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 Be,NOTICE_TIMEOUT_MS as Re,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 He,DEFAULT_SUPPORTED_LANGUAGES as Pe,resolveLanguageTag as De,useSpaLanguage as Fe}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 ve,createApiClient as we,HttpStatusError as Qe,MAX_ERROR_MESSAGE_LENGTH as We}from"./api.js";import{createBookmarkStore as Ze,D1_BOOKMARK_HEADER as je}from"./bookmarks.js";import{createContractClient as Je}from"./contractClient.js";export{F as AppPage,o as Badge,l as Button,Be as COPY_FEEDBACK_TIMEOUT_MS,ke as CURRENT_USER_PATH,x as Card,T as CardHeader,E as CardTitle,N as ConfirmDeleteModal,z as ContextBar,je as D1_BOOKMARK_HEADER,Ne as DEFAULT_FALLBACK_LANGUAGE,He as DEFAULT_LANGUAGE_STORAGE_KEY,Pe as DEFAULT_SUPPORTED_LANGUAGES,H as EmptyState,A as FocusInput,Qe as HttpStatusError,c as Input,b as Label,Q as LanguageSelector,y as LoadingButton,P as LoadingSpinner,We as MAX_ERROR_MESSAGE_LENGTH,O as ModalShell,Re as NOTICE_TIMEOUT_MS,v as NoticeBar,h as PageHeaderCard,oe as Pagination,j as ReadOnlyField,X as RefreshButton,L as Select,le as Spinner,B 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,ue as btnSmallStyle,ve as buildQuery,s as buttonBaseClass,m as buttonClass,xe as buttonColors,f as buttonSizeClass,C as buttonVariantClass,Ge as canonicalizeLanguageTag,i as cardClass,d as cardHeaderClass,ie as cardStyle,S as cardTitleClass,te as clampPage,ce as cn,be as configureClassMerge,we as createApiClient,Ze as createBookmarkStore,Je as createContractClient,R as fieldClass,de as inputStyle,ae as pageCountFor,ne as pageWindow,Se as paginationBtnStyle,De as resolveLanguageTag,Te as tableCardStyle,Ee as tdStyle,Ae as thStyle,ge as theme,ee as useCopyToClipboard,Ve as useCurrentUser,he as useMutation,Me as useNotice,Ke as useResource,Fe as useSpaLanguage};