tempest-react-sdk 0.49.0 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/audio/sfx-pool.cjs +1 -1
- package/dist/audio/sfx-pool.cjs.map +1 -1
- package/dist/audio/sfx-pool.js +36 -36
- package/dist/audio/sfx-pool.js.map +1 -1
- package/dist/components/BarList/BarList.cjs +1 -1
- package/dist/components/BarList/BarList.cjs.map +1 -1
- package/dist/components/BarList/BarList.js +6 -1
- package/dist/components/BarList/BarList.js.map +1 -1
- package/dist/components/BarList/bar-list-model.cjs +1 -1
- package/dist/components/BarList/bar-list-model.cjs.map +1 -1
- package/dist/components/BarList/bar-list-model.js +8 -8
- package/dist/components/BarList/bar-list-model.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +112 -110
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.js +5 -3
- package/dist/components/DataTable/use-dev-warnings.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +5 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +66 -63
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.cjs +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js +25 -45
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.js.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs +2 -0
- package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -0
- package/dist/components/Sidebar/SidebarEntry.js +40 -0
- package/dist/components/Sidebar/SidebarEntry.js.map +1 -0
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +84 -71
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +112 -104
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/timeout.cjs +2 -0
- package/dist/http/timeout.cjs.map +1 -0
- package/dist/http/timeout.js +22 -0
- package/dist/http/timeout.js.map +1 -0
- package/dist/icons/material-symbols.cjs.map +1 -1
- package/dist/icons/material-symbols.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.d.ts +104 -18
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +49 -41
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { buildApiError, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n withCredentials = false,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n function baseHeaders(): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) result.Authorization = `Bearer ${token}`;\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n resync.needed = true;\n return retryOptions?.shouldRetry?.(error, attempt) ?? true;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;;AAaA,IAAa,IAAc,SAGd,IAAqB;AA+IlC,SAAS,EAAW,GAAuB;CACvC,OAAO,EAAc,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACxD;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OA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,GACb,MACD,KACA,MAAM,EAAY;IACd,QAAQ;IACR;IACA,SAAS,EAAY;IACrB;IACA,gBAAgB,KAAA;GACpB,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS,GAExB,KAAS,MAAM,EAAQ,OAAO,CAAG;EACzC;EACA,IAAI,QAAQ;GACR,OAAO;EACX;EACA,IAAI,SAAS;GACT,OAAO;EACX;EACA,IAAI,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { buildApiError, isApiError, isRetriableStatus, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\n/**\n * The two statuses a chunk retry fixes that the shared policy cannot know about.\n *\n * `409` and `412` are the offset-divergence answers, and they are the entire\n * reason `resync` exists: the next attempt re-reads the server's offset with\n * `HEAD` and writes from there. They are 4xx refusals a replay genuinely fixes,\n * which is the one thing {@link isRetriableStatus} has no way to tell — from\n * outside this protocol they look like any other deliberate rejection.\n */\nconst RESYNCABLE_STATUSES: ReadonlySet<number> = new Set([409, 412]);\n\n/**\n * Whether a chunk failure is worth another attempt.\n *\n * The default used to be `true` for everything, which cost five round trips\n * before surfacing an answer the first one already gave. Two groups matter here\n * and both are specific to the resume protocol:\n *\n * - **`409`/`412` retry**, even though the shared policy rejects 4xx: they mean\n * \"your offset is wrong\", and `resync` is how the next attempt fixes it.\n * - **`404`/`410` do not**, even though a lost resource can look transient.\n * `probe()` turns them into \"O upload expirou no servidor. Comece de novo.\" and\n * recreating the upload only happens in `ensureUpload`, at attach time — never\n * inside the chunk loop. So a retry here re-runs `HEAD` against a resource that\n * is gone, five times, and then reports the same thing with the backoff added\n * on top.\n *\n * Anything with no API shape still retries: a transport failure has no status to\n * judge, and losing a large upload to one dropped connection is the outcome this\n * whole module exists to avoid.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the chunk loop should try again.\n */\nfunction isRetriableChunkFailure(error: unknown): boolean {\n if (!isApiError(error)) return true;\n if (RESYNCABLE_STATUSES.has(error.status)) return true;\n return isRetriableStatus(error.status);\n}\n\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n withCredentials = false,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n function baseHeaders(): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) result.Authorization = `Bearer ${token}`;\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * `resync` is armed only when the attempt is actually going to happen. A\n * caller's own `shouldRetry` still wins the decision, and still arms the\n * resync when it says yes — the flag describes what the *next* attempt must\n * do, so setting it for an attempt that never comes describes nothing.\n * {@link isRetriableChunkFailure} is the default, and it is where `409`/`412`\n * earn a retry the shared policy would refuse and `404`/`410` lose one it\n * would have granted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n const again =\n retryOptions?.shouldRetry?.(error, attempt) ??\n isRetriableChunkFailure(error);\n if (again) resync.needed = true;\n return again;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;;AAaA,IAAa,IAAc,SAGd,IAAqB;AA+IlC,SAAS,EAAW,GAAuB;CACvC,OAAO,EAAc,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACxD;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OAAO,QAAQ,CAAQ,CAAC,CAAC,KAAK,CAAC,GAAM,OAAW,GAAG,EAAK,GAAG,EAAW,CAAK,GAAG;CAC5F,OAAO,EAAM,SAAS,IAAI,EAAM,KAAK,GAAG,IAAI;AAChD;AAcA,SAAgB,EAAkB,GAAkB,GAA2B;CAC3E,IAAM,IAAQ,GACR,IAAO,OAAO,EAAM,QAAS,WAAW,EAAM,OAAO,QACrD,IAAW,OAAO,EAAM,gBAAiB,WAAW,EAAM,eAAe;CAC/E,OAAO,GAAG,EAAS,GAAG,EAAK,GAAG,EAAK,KAAK,GAAG,EAAK,KAAK,GAAG;AAC5D;AAcA,SAAgB,EAAyB,IAAS,mBAA2C;CACzF,SAAS,IAA0B;EAC/B,IAAI;GACA,OAAO,OAAO,eAAiB,MAAc,OAAO;EACxD,QAAQ;GAC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GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t){if(t===null)return{signal:e??void 0,timedOut:()=>!1,dispose:()=>{}};let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t),a=()=>n.abort();return e&&(e.aborted?n.abort():e.addEventListener(`abort`,a,{once:!0})),{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener(`abort`,a)}}}exports.withTimeout=e;
|
|
2
|
+
//# sourceMappingURL=timeout.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout.cjs","names":[],"sources":["../../src/http/timeout.ts"],"sourcesContent":["/**\n * The timeout half of `createApiClient`'s request plumbing.\n *\n * It lives beside the client rather than inside it because it is the one piece\n * with no knowledge of the SDK: given a caller's signal and a deadline it hands\n * back a signal to pass `fetch`, a way to tell whose abort fired, and the\n * cleanup. That makes it testable on its own and keeps the client file about\n * requests.\n */\n\n/** A signal to hand `fetch`, plus how to read the outcome and clean up. */\nexport interface TimedSignal {\n /** Pass this to `fetch`. */\n signal: AbortSignal | undefined;\n /** Whether the abort came from the timeout rather than the caller. */\n timedOut: () => boolean;\n /** Clear the timer and drop the listener. Always call it. */\n dispose: () => void;\n}\n\n/**\n * Compose the caller's signal with a timeout, tracking which one fires.\n *\n * Written with an explicit flag rather than `AbortSignal.timeout()`, whose\n * `TimeoutError` reason would tell the two apart for free. Two reasons: this\n * needs no `AbortSignal.any`, which is Baseline 2024 and would raise the\n * package's support floor for one line of convenience, and the flag is read\n * directly instead of through a reason string that a polyfill could reshape.\n *\n * A caller signal that is already aborted aborts immediately, so a request never\n * goes out for a query react-query has already cancelled.\n *\n * @param signal - The caller's signal, if any.\n * @param ms - Timeout in milliseconds, or `null` to only forward the signal.\n * @returns The composed signal, the outcome reader, and the cleanup.\n */\nexport function withTimeout(\n signal: AbortSignal | null | undefined,\n ms: number | null,\n): TimedSignal {\n if (ms === null) {\n return { signal: signal ?? undefined, timedOut: () => false, dispose: () => {} };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, ms);\n const onAbort = (): void => controller.abort();\n\n if (signal) {\n if (signal.aborted) controller.abort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n dispose: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n },\n };\n}\n"],"mappings":"AAoCA,SAAgB,EACZ,EACA,EACW,CACX,GAAI,IAAO,KACP,MAAO,CAAE,OAAQ,GAAU,IAAA,GAAW,aAAgB,GAAO,YAAe,CAAC,CAAE,EAGnF,IAAM,EAAa,IAAI,gBACnB,EAAW,GACT,EAAQ,eAAiB,CAC3B,EAAW,GACX,EAAW,MAAM,CACrB,EAAG,CAAE,EACC,MAAsB,EAAW,MAAM,EAO7C,OALI,IACI,EAAO,QAAS,EAAW,MAAM,EAChC,EAAO,iBAAiB,QAAS,EAAS,CAAE,KAAM,EAAK,CAAC,GAG1D,CACH,OAAQ,EAAW,OACnB,aAAgB,EAChB,YAAe,CACX,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,CAAO,CAChD,CACJ,CACJ"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/http/timeout.ts
|
|
2
|
+
function e(e, t) {
|
|
3
|
+
if (t === null) return {
|
|
4
|
+
signal: e ?? void 0,
|
|
5
|
+
timedOut: () => !1,
|
|
6
|
+
dispose: () => {}
|
|
7
|
+
};
|
|
8
|
+
let n = new AbortController(), r = !1, i = setTimeout(() => {
|
|
9
|
+
r = !0, n.abort();
|
|
10
|
+
}, t), a = () => n.abort();
|
|
11
|
+
return e && (e.aborted ? n.abort() : e.addEventListener("abort", a, { once: !0 })), {
|
|
12
|
+
signal: n.signal,
|
|
13
|
+
timedOut: () => r,
|
|
14
|
+
dispose: () => {
|
|
15
|
+
clearTimeout(i), e?.removeEventListener("abort", a);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { e as withTimeout };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=timeout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timeout.js","names":[],"sources":["../../src/http/timeout.ts"],"sourcesContent":["/**\n * The timeout half of `createApiClient`'s request plumbing.\n *\n * It lives beside the client rather than inside it because it is the one piece\n * with no knowledge of the SDK: given a caller's signal and a deadline it hands\n * back a signal to pass `fetch`, a way to tell whose abort fired, and the\n * cleanup. That makes it testable on its own and keeps the client file about\n * requests.\n */\n\n/** A signal to hand `fetch`, plus how to read the outcome and clean up. */\nexport interface TimedSignal {\n /** Pass this to `fetch`. */\n signal: AbortSignal | undefined;\n /** Whether the abort came from the timeout rather than the caller. */\n timedOut: () => boolean;\n /** Clear the timer and drop the listener. Always call it. */\n dispose: () => void;\n}\n\n/**\n * Compose the caller's signal with a timeout, tracking which one fires.\n *\n * Written with an explicit flag rather than `AbortSignal.timeout()`, whose\n * `TimeoutError` reason would tell the two apart for free. Two reasons: this\n * needs no `AbortSignal.any`, which is Baseline 2024 and would raise the\n * package's support floor for one line of convenience, and the flag is read\n * directly instead of through a reason string that a polyfill could reshape.\n *\n * A caller signal that is already aborted aborts immediately, so a request never\n * goes out for a query react-query has already cancelled.\n *\n * @param signal - The caller's signal, if any.\n * @param ms - Timeout in milliseconds, or `null` to only forward the signal.\n * @returns The composed signal, the outcome reader, and the cleanup.\n */\nexport function withTimeout(\n signal: AbortSignal | null | undefined,\n ms: number | null,\n): TimedSignal {\n if (ms === null) {\n return { signal: signal ?? undefined, timedOut: () => false, dispose: () => {} };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, ms);\n const onAbort = (): void => controller.abort();\n\n if (signal) {\n if (signal.aborted) controller.abort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n dispose: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n },\n };\n}\n"],"mappings":";AAoCA,SAAgB,EACZ,GACA,GACW;CACX,IAAI,MAAO,MACP,OAAO;EAAE,QAAQ,KAAU,KAAA;EAAW,gBAAgB;EAAO,eAAe,CAAC;CAAE;CAGnF,IAAM,IAAa,IAAI,gBAAgB,GACnC,IAAW,IACT,IAAQ,iBAAiB;EAE3B,AADA,IAAW,IACX,EAAW,MAAM;CACrB,GAAG,CAAE,GACC,UAAsB,EAAW,MAAM;CAO7C,OALI,MACI,EAAO,UAAS,EAAW,MAAM,IAChC,EAAO,iBAAiB,SAAS,GAAS,EAAE,MAAM,GAAK,CAAC,IAG1D;EACH,QAAQ,EAAW;EACnB,gBAAgB;EAChB,eAAe;GAEX,AADA,aAAa,CAAK,GAClB,GAAQ,oBAAoB,SAAS,CAAO;EAChD;CACJ;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"material-symbols.cjs","names":[],"sources":["../../src/icons/material-symbols.ts"],"sourcesContent":["import type { IconName } from \"./generated/icon-name\";\n\n/**\n * The slug `fromMaterialSymbol` falls back to when a code is unknown.\n *\n * A neutral glyph rather than nothing: a category created in an admin with a\n * code this table has not learned yet still has to draw something, or it opens a\n * hole in the grid and the bug reads as a layout problem instead of a missing\n * mapping.\n *\n * Lucide's `circle-help` is a deprecated alias of this slug. `<Icon>` resolves\n * aliases, so both render — but the bridge emits the canonical name, since a\n * value that gets persisted should not be one lucide has already renamed.\n */\nexport const MATERIAL_SYMBOL_FALLBACK: IconName = \"circle-question-mark\";\n\n/**\n * Material Symbols code → lucide slug, for backends that store `icon_code`.\n *\n * Every Python backend we write stores a category icon as a Material Symbol\n * (`build`, `format_paint`, `electrical_services`) — the vocabulary Flutter,\n * Android and the administrative seeds already speak. The SDK speaks lucide in\n * kebab-case. The two lists do not meet, and the failure is nastier than an\n * empty screen: a handful of codes collide by accident, so roughly one row in\n * ten draws the right icon and the bug reads as \"some icons went missing\".\n *\n * **Still not the full vocabulary.** Material Symbols publishes ~6100 names and\n * almost none of them will ever appear in an `icon_code` of ours, so this grows\n * on demand, one hand-written pair at a time — a map generated by name\n * heuristics gets it badly wrong, starting with `build`, which is a wrench in\n * Material Symbols and nothing to do with construction.\n *\n * **How the codes were chosen.** Two lots, merged. The first was the trades seed\n * the bridge started as. The second is the head of Material Symbols' own\n * published popularity ranking (`fonts.google.com/metadata/icons`), which is\n * measured usage rather than a guess at which names a seed will contain — every\n * key was checked to exist in that vocabulary before landing.\n *\n * **Where the two lots disagreed**, six keys, the tie went to whichever mapping\n * keeps two distinct Material Symbols names distinct in lucide: `error` →\n * `circle-alert` because `cancel` already owns `circle-x`; `payments` →\n * `banknote` because `account_balance_wallet` already owns `wallet`;\n * `receipt_long` → `receipt-text` because `receipt` already owns `receipt`;\n * `construction` → itself because `engineering` already owns `hard-hat`; and\n * `today` → `calendar` with `event` → `calendar-days`, splitting the generic\n * calendar names from the dated one.\n *\n * Every target is checked mechanically against the slug list by\n * `material-symbols.test.ts`, so a pair pointing at a name lucide does not ship\n * — or at one it has since deprecated — fails the suite instead of reaching a\n * grid. What no test can check is whether the *chosen* icon is the right\n * metaphor, which is why pairs go in by hand.\n *\n * **Approximations, deliberate and not one-to-one** (the full list lives in\n * `docs/icons.md`):\n *\n * - `plumbing` → `shower-head`, because lucide has no pipe.\n * - `build`, `handyman` and `hardware` all land on `wrench` — Material Symbols\n * distinguishes the tools, lucide does not.\n * - `pedal_bike`, `two_wheeler` and `delivery_dining` all land on `bike`.\n * - `dentistry` → `face-slightly-smiling`, since lucide ships no tooth.\n * - `iron` → `shirt` and `cleaning_services` → `spray-can`: the activity, not\n * the implement.\n * - `roofing` → `house`, the same glyph as `home`, because lucide has no roof.\n *\n * The identity pairs are here on purpose. Their names happen to match in both\n * vocabularies, so they already render today — leaving them out would send them\n * to {@link MATERIAL_SYMBOL_FALLBACK} and make this bridge a regression for\n * exactly the codes that used to work.\n *\n * @see fromMaterialSymbol — the lookup you normally call.\n */\nexport const materialToLucide: Readonly<Record<string, IconName>> = {\n ac_unit: \"snowflake\",\n account_balance: \"landmark\",\n account_balance_wallet: \"wallet\",\n account_box: \"square-user\",\n account_circle: \"circle-user\",\n add: \"plus\",\n add_circle: \"circle-plus\",\n add_circle_outline: \"circle-plus\",\n add_shopping_cart: \"shopping-cart\",\n admin_panel_settings: \"shield-user\",\n analytics: \"chart-column\",\n apps: \"layout-grid\",\n arrow_back: \"arrow-left\",\n arrow_back_ios: \"chevron-left\",\n arrow_back_ios_new: \"chevron-left\",\n arrow_downward: \"arrow-down\",\n arrow_drop_down: \"chevron-down\",\n arrow_forward: \"arrow-right\",\n arrow_forward_ios: \"chevron-right\",\n arrow_right: \"chevron-right\",\n arrow_right_alt: \"arrow-right\",\n arrow_upward: \"arrow-up\",\n article: \"newspaper\",\n assignment: \"clipboard-list\",\n attach_file: \"paperclip\",\n attach_money: \"dollar-sign\",\n autorenew: \"refresh-cw\",\n badge: \"id-card\",\n balance: \"scale\",\n bar_chart: \"chart-column\",\n battery_full: \"battery-full\",\n bluetooth: \"bluetooth\",\n bolt: \"zap\",\n bookmark: \"bookmark\",\n brush: \"brush\",\n build: \"wrench\",\n business: \"building-2\",\n cake: \"cake\",\n calculate: \"calculator\",\n calendar_month: \"calendar\",\n calendar_today: \"calendar\",\n call: \"phone\",\n campaign: \"megaphone\",\n cancel: \"circle-x\",\n car_repair: \"car\",\n carpenter: \"hammer\",\n category: \"shapes\",\n chair: \"armchair\",\n chat: \"message-circle\",\n check: \"check\",\n check_box: \"square-check\",\n check_box_outline_blank: \"square\",\n check_circle: \"circle-check\",\n check_circle_outline: \"circle-check\",\n chevron_left: \"chevron-left\",\n chevron_right: \"chevron-right\",\n child_care: \"baby\",\n circle: \"circle\",\n cleaning_services: \"spray-can\",\n clear: \"x\",\n close: \"x\",\n cloud: \"cloud\",\n code: \"code\",\n computer: \"monitor\",\n construction: \"construction\",\n content_copy: \"copy\",\n content_cut: \"scissors\",\n credit_card: \"credit-card\",\n dark_mode: \"moon\",\n dashboard: \"layout-dashboard\",\n date_range: \"calendar-range\",\n delete: \"trash-2\",\n delete_forever: \"trash-2\",\n delete_outline: \"trash-2\",\n delivery_dining: \"bike\",\n dentistry: \"face-slightly-smiling\",\n description: \"file-text\",\n directions_car: \"car\",\n done: \"check\",\n done_all: \"check-check\",\n door_front: \"door-open\",\n download: \"download\",\n east: \"arrow-right\",\n edit: \"pencil\",\n edit_note: \"pencil-line\",\n electrical_services: \"plug-zap\",\n email: \"mail\",\n emoji_events: \"trophy\",\n engineering: \"hard-hat\",\n error: \"circle-alert\",\n error_outline: \"circle-alert\",\n event: \"calendar-days\",\n expand_less: \"chevron-up\",\n expand_more: \"chevron-down\",\n explore: \"compass\",\n face: \"face-slightly-smiling\",\n fact_check: \"clipboard-check\",\n favorite: \"heart\",\n favorite_border: \"heart\",\n file_download: \"download\",\n file_upload: \"upload\",\n filter_alt: \"funnel\",\n filter_list: \"funnel\",\n fingerprint: \"fingerprint-pattern\",\n fitness_center: \"dumbbell\",\n flight: \"plane\",\n folder: \"folder\",\n format_list_bulleted: \"list\",\n format_paint: \"paint-roller\",\n forum: \"messages-square\",\n gavel: \"gavel\",\n grade: \"star\",\n grass: \"sprout\",\n grid_view: \"layout-grid\",\n group: \"users\",\n groups: \"users\",\n handyman: \"wrench\",\n hardware: \"wrench\",\n help: \"circle-question-mark\",\n help_outline: \"circle-question-mark\",\n highlight_off: \"circle-x\",\n history: \"rotate-ccw-clock\",\n home: \"house\",\n hotel: \"bed-double\",\n image: \"image\",\n info: \"info\",\n insights: \"chart-line\",\n inventory: \"package\",\n inventory_2: \"package\",\n iron: \"shirt\",\n key: \"key\",\n kitchen: \"refrigerator\",\n language: \"globe\",\n laptop: \"laptop\",\n light_mode: \"sun\",\n lightbulb: \"lightbulb\",\n link: \"link\",\n list: \"list\",\n list_alt: \"list\",\n local_bar: \"wine\",\n local_cafe: \"coffee\",\n local_florist: \"flower\",\n local_gas_station: \"fuel\",\n local_laundry_service: \"washing-machine\",\n local_offer: \"tag\",\n local_shipping: \"truck\",\n local_taxi: \"car-taxi-front\",\n location_on: \"map-pin\",\n lock: \"lock\",\n lock_open: \"lock-open\",\n login: \"log-in\",\n logout: \"log-out\",\n mail: \"mail\",\n mail_outline: \"mail\",\n manage_accounts: \"user-cog\",\n map: \"map\",\n medical_services: \"stethoscope\",\n menu: \"menu\",\n menu_book: \"book-open\",\n mic: \"mic\",\n mode_edit: \"pencil\",\n monetization_on: \"circle-dollar-sign\",\n more_horiz: \"ellipsis\",\n more_vert: \"ellipsis-vertical\",\n music_note: \"music\",\n navigate_next: \"chevron-right\",\n note_add: \"file-plus\",\n notifications: \"bell\",\n notifications_active: \"bell-ring\",\n open_in_new: \"external-link\",\n paid: \"circle-dollar-sign\",\n palette: \"palette\",\n pause: \"pause\",\n payments: \"banknote\",\n pedal_bike: \"bike\",\n people: \"users\",\n perm_identity: \"user\",\n person: \"user\",\n person_add: \"user-plus\",\n person_outline: \"user\",\n pest_control: \"bug\",\n pets: \"paw-print\",\n phone: \"phone\",\n phone_iphone: \"smartphone\",\n photo_camera: \"camera\",\n picture_as_pdf: \"file-text\",\n pie_chart: \"chart-pie\",\n place: \"map-pin\",\n play_arrow: \"play\",\n play_circle: \"circle-play\",\n play_circle_filled: \"circle-play\",\n plumbing: \"shower-head\",\n power_settings_new: \"power\",\n print: \"printer\",\n public: \"globe\",\n qr_code_scanner: \"scan-line\",\n question_answer: \"messages-square\",\n radio_button_checked: \"circle-dot\",\n radio_button_unchecked: \"circle\",\n receipt: \"receipt\",\n receipt_long: \"receipt-text\",\n refresh: \"refresh-cw\",\n remove: \"minus\",\n remove_circle_outline: \"circle-minus\",\n reorder: \"list\",\n report_problem: \"triangle-alert\",\n restart_alt: \"rotate-ccw\",\n restaurant: \"utensils\",\n roofing: \"house\",\n room: \"map-pin\",\n router: \"router\",\n save: \"save\",\n savings: \"piggy-bank\",\n schedule: \"clock\",\n school: \"graduation-cap\",\n search: \"search\",\n security: \"shield-check\",\n send: \"send\",\n settings: \"settings\",\n share: \"share-2\",\n shield: \"shield\",\n shopping_bag: \"shopping-bag\",\n shopping_cart: \"shopping-cart\",\n smartphone: \"smartphone\",\n soap: \"soap-dispenser-droplet\",\n sort: \"arrow-down-up\",\n spa: \"flower-2\",\n star: \"star\",\n star_border: \"star\",\n star_rate: \"star\",\n store: \"store\",\n storefront: \"store\",\n support_agent: \"headset\",\n sync: \"refresh-cw\",\n task_alt: \"circle-check\",\n timer: \"timer\",\n today: \"calendar\",\n toggle_on: \"toggle-right\",\n translate: \"languages\",\n trending_up: \"trending-up\",\n tune: \"sliders-horizontal\",\n tv: \"tv\",\n two_wheeler: \"bike\",\n upload: \"upload\",\n upload_file: \"upload\",\n vaccines: \"syringe\",\n verified: \"badge-check\",\n verified_user: \"shield-check\",\n videocam: \"video\",\n view_list: \"list\",\n visibility: \"eye\",\n visibility_off: \"eye-off\",\n vpn_key: \"key-round\",\n warehouse: \"warehouse\",\n warning: \"triangle-alert\",\n warning_amber: \"triangle-alert\",\n watch_later: \"clock\",\n water_drop: \"droplet\",\n wifi: \"wifi\",\n work: \"briefcase\",\n yard: \"trees\",\n};\n\n/**\n * Translate a Material Symbols code into a lucide slug, always returning one.\n *\n * Never returns `undefined`: an unknown code resolves to `fallback`, so a row\n * whose `icon_code` this table has not learned yet still renders. The input is\n * trimmed and lower-cased before lookup, because a seed written by hand is the\n * kind of source that carries stray whitespace and the odd capital.\n *\n * Nothing else in `/icons` imports this module, so an app that does not store\n * Material Symbols never pays for the table.\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code)} size={20} />\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code, \"folder\")} size={20} />\n *\n * @param code - A Material Symbols name, or `null`/`undefined` for a row that has none.\n * @param fallback - Slug to use when `code` is empty or unknown. Defaults to {@link MATERIAL_SYMBOL_FALLBACK}.\n * @returns A lucide slug `<Icon>` can render.\n */\nexport function fromMaterialSymbol(\n code: string | null | undefined,\n fallback: IconName = MATERIAL_SYMBOL_FALLBACK,\n): IconName {\n if (!code) return fallback;\n return materialToLucide[code.trim().toLowerCase()] ?? fallback;\n}\n"],"mappings":"AAcA,IAAa,EAAqC,uBA0DrC,EAAuD,CAChE,QAAS,YACT,gBAAiB,WACjB,uBAAwB,SACxB,YAAa,cACb,eAAgB,cAChB,IAAK,OACL,WAAY,cACZ,mBAAoB,cACpB,kBAAmB,gBACnB,qBAAsB,cACtB,UAAW,eACX,KAAM,cACN,WAAY,aACZ,eAAgB,eAChB,mBAAoB,eACpB,eAAgB,aAChB,gBAAiB,eACjB,cAAe,cACf,kBAAmB,gBACnB,YAAa,gBACb,gBAAiB,cACjB,aAAc,WACd,QAAS,YACT,WAAY,iBACZ,YAAa,YACb,aAAc,cACd,UAAW,aACX,MAAO,UACP,QAAS,QACT,UAAW,eACX,aAAc,eACd,UAAW,YACX,KAAM,MACN,SAAU,WACV,MAAO,QACP,MAAO,SACP,SAAU,aACV,KAAM,OACN,UAAW,aACX,eAAgB,WAChB,eAAgB,WAChB,KAAM,QACN,SAAU,YACV,OAAQ,WACR,WAAY,MACZ,UAAW,SACX,SAAU,SACV,MAAO,WACP,KAAM,iBACN,MAAO,QACP,UAAW,eACX,wBAAyB,SACzB,aAAc,eACd,qBAAsB,eACtB,aAAc,eACd,cAAe,gBACf,WAAY,OACZ,OAAQ,SACR,kBAAmB,YACnB,MAAO,IACP,MAAO,IACP,MAAO,QACP,KAAM,OACN,SAAU,UACV,aAAc,eACd,aAAc,OACd,YAAa,WACb,YAAa,cACb,UAAW,OACX,UAAW,mBACX,WAAY,iBACZ,OAAQ,UACR,eAAgB,UAChB,eAAgB,UAChB,gBAAiB,OACjB,UAAW,wBACX,YAAa,YACb,eAAgB,MAChB,KAAM,QACN,SAAU,cACV,WAAY,YACZ,SAAU,WACV,KAAM,cACN,KAAM,SAC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BAAoB,cACpB,SAAU,cACV,mBAAoB,QACpB,MAAO,UACP,OAAQ,QACR,gBAAiB,YACjB,gBAAiB,kBACjB,qBAAsB,aACtB,uBAAwB,SACxB,QAAS,UACT,aAAc,eACd,QAAS,aACT,OAAQ,QACR,sBAAuB,eACvB,QAAS,OACT,eAAgB,iBAChB,YAAa,aACb,WAAY,WACZ,QAAS,QACT,KAAM,UACN,OAAQ,SACR,KAAM,OACN,QAAS,aACT,SAAU,QACV,OAAQ,iBACR,OAAQ,SACR,SAAU,eACV,KAAM,OACN,SAAU,WACV,MAAO,UACP,OAAQ,SACR,aAAc,eACd,cAAe,gBACf,WAAY,aACZ,KAAM,yBACN,KAAM,gBACN,IAAK,WACL,KAAM,OACN,YAAa,OACb,UAAW,OACX,MAAO,QACP,WAAY,QACZ,cAAe,UACf,KAAM,aACN,SAAU,eACV,MAAO,QACP,MAAO,WACP,UAAW,eACX,UAAW,YACX,YAAa,cACb,KAAM,qBACN,GAAI,KACJ,YAAa,OACb,OAAQ,SACR,YAAa,SACb,SAAU,UACV,SAAU,cACV,cAAe,eACf,SAAU,QACV,UAAW,OACX,WAAY,MACZ,eAAgB,UAChB,QAAS,YACT,UAAW,YACX,QAAS,iBACT,cAAe,iBACf,YAAa,QACb,WAAY,UACZ,KAAM,OACN,KAAM,YACN,KAAM,OACV,EAuBA,SAAgB,EACZ,EACA,EAAqB,EACb,CAER,OADK,EACE,EAAiB,EAAK,KAAK,CAAC,CAAC,YAAY,IAAM,EADpC,CAEtB"}
|
|
1
|
+
{"version":3,"file":"material-symbols.cjs","names":[],"sources":["../../src/icons/material-symbols.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — the file is one hand-written lookup table plus the\n * two functions that read it. Splitting a table by row count would put pairs that\n * belong together (`format_*`, `electrical_*`) in different files and make the\n * next hand-written pair a question of which file it lands in; the length is the\n * vocabulary's, not the code's.\n */\nimport type { IconName } from \"./generated/icon-name\";\n\n/**\n * The slug `fromMaterialSymbol` falls back to when a code is unknown.\n *\n * A neutral glyph rather than nothing: a category created in an admin with a\n * code this table has not learned yet still has to draw something, or it opens a\n * hole in the grid and the bug reads as a layout problem instead of a missing\n * mapping.\n *\n * Lucide's `circle-help` is a deprecated alias of this slug. `<Icon>` resolves\n * aliases, so both render — but the bridge emits the canonical name, since a\n * value that gets persisted should not be one lucide has already renamed.\n */\nexport const MATERIAL_SYMBOL_FALLBACK: IconName = \"circle-question-mark\";\n\n/**\n * Material Symbols code → lucide slug, for backends that store `icon_code`.\n *\n * Every Python backend we write stores a category icon as a Material Symbol\n * (`build`, `format_paint`, `electrical_services`) — the vocabulary Flutter,\n * Android and the administrative seeds already speak. The SDK speaks lucide in\n * kebab-case. The two lists do not meet, and the failure is nastier than an\n * empty screen: a handful of codes collide by accident, so roughly one row in\n * ten draws the right icon and the bug reads as \"some icons went missing\".\n *\n * **Still not the full vocabulary.** Material Symbols publishes ~6100 names and\n * almost none of them will ever appear in an `icon_code` of ours, so this grows\n * on demand, one hand-written pair at a time — a map generated by name\n * heuristics gets it badly wrong, starting with `build`, which is a wrench in\n * Material Symbols and nothing to do with construction.\n *\n * **How the codes were chosen.** Two lots, merged. The first was the trades seed\n * the bridge started as. The second is the head of Material Symbols' own\n * published popularity ranking (`fonts.google.com/metadata/icons`), which is\n * measured usage rather than a guess at which names a seed will contain — every\n * key was checked to exist in that vocabulary before landing.\n *\n * **Where the two lots disagreed**, six keys, the tie went to whichever mapping\n * keeps two distinct Material Symbols names distinct in lucide: `error` →\n * `circle-alert` because `cancel` already owns `circle-x`; `payments` →\n * `banknote` because `account_balance_wallet` already owns `wallet`;\n * `receipt_long` → `receipt-text` because `receipt` already owns `receipt`;\n * `construction` → itself because `engineering` already owns `hard-hat`; and\n * `today` → `calendar` with `event` → `calendar-days`, splitting the generic\n * calendar names from the dated one.\n *\n * Every target is checked mechanically against the slug list by\n * `material-symbols.test.ts`, so a pair pointing at a name lucide does not ship\n * — or at one it has since deprecated — fails the suite instead of reaching a\n * grid. What no test can check is whether the *chosen* icon is the right\n * metaphor, which is why pairs go in by hand.\n *\n * **Approximations, deliberate and not one-to-one** (the full list lives in\n * `docs/icons.md`):\n *\n * - `plumbing` → `shower-head`, because lucide has no pipe.\n * - `build`, `handyman` and `hardware` all land on `wrench` — Material Symbols\n * distinguishes the tools, lucide does not.\n * - `pedal_bike`, `two_wheeler` and `delivery_dining` all land on `bike`.\n * - `dentistry` → `face-slightly-smiling`, since lucide ships no tooth.\n * - `iron` → `shirt` and `cleaning_services` → `spray-can`: the activity, not\n * the implement.\n * - `roofing` → `house`, the same glyph as `home`, because lucide has no roof.\n *\n * The identity pairs are here on purpose. Their names happen to match in both\n * vocabularies, so they already render today — leaving them out would send them\n * to {@link MATERIAL_SYMBOL_FALLBACK} and make this bridge a regression for\n * exactly the codes that used to work.\n *\n * @see fromMaterialSymbol — the lookup you normally call.\n */\nexport const materialToLucide: Readonly<Record<string, IconName>> = {\n ac_unit: \"snowflake\",\n account_balance: \"landmark\",\n account_balance_wallet: \"wallet\",\n account_box: \"square-user\",\n account_circle: \"circle-user\",\n add: \"plus\",\n add_circle: \"circle-plus\",\n add_circle_outline: \"circle-plus\",\n add_shopping_cart: \"shopping-cart\",\n admin_panel_settings: \"shield-user\",\n analytics: \"chart-column\",\n apps: \"layout-grid\",\n arrow_back: \"arrow-left\",\n arrow_back_ios: \"chevron-left\",\n arrow_back_ios_new: \"chevron-left\",\n arrow_downward: \"arrow-down\",\n arrow_drop_down: \"chevron-down\",\n arrow_forward: \"arrow-right\",\n arrow_forward_ios: \"chevron-right\",\n arrow_right: \"chevron-right\",\n arrow_right_alt: \"arrow-right\",\n arrow_upward: \"arrow-up\",\n article: \"newspaper\",\n assignment: \"clipboard-list\",\n attach_file: \"paperclip\",\n attach_money: \"dollar-sign\",\n autorenew: \"refresh-cw\",\n badge: \"id-card\",\n balance: \"scale\",\n bar_chart: \"chart-column\",\n battery_full: \"battery-full\",\n bluetooth: \"bluetooth\",\n bolt: \"zap\",\n bookmark: \"bookmark\",\n brush: \"brush\",\n build: \"wrench\",\n business: \"building-2\",\n cake: \"cake\",\n calculate: \"calculator\",\n calendar_month: \"calendar\",\n calendar_today: \"calendar\",\n call: \"phone\",\n campaign: \"megaphone\",\n cancel: \"circle-x\",\n car_repair: \"car\",\n carpenter: \"hammer\",\n category: \"shapes\",\n chair: \"armchair\",\n chat: \"message-circle\",\n check: \"check\",\n check_box: \"square-check\",\n check_box_outline_blank: \"square\",\n check_circle: \"circle-check\",\n check_circle_outline: \"circle-check\",\n chevron_left: \"chevron-left\",\n chevron_right: \"chevron-right\",\n child_care: \"baby\",\n circle: \"circle\",\n cleaning_services: \"spray-can\",\n clear: \"x\",\n close: \"x\",\n cloud: \"cloud\",\n code: \"code\",\n computer: \"monitor\",\n construction: \"construction\",\n content_copy: \"copy\",\n content_cut: \"scissors\",\n credit_card: \"credit-card\",\n dark_mode: \"moon\",\n dashboard: \"layout-dashboard\",\n date_range: \"calendar-range\",\n delete: \"trash-2\",\n delete_forever: \"trash-2\",\n delete_outline: \"trash-2\",\n delivery_dining: \"bike\",\n dentistry: \"face-slightly-smiling\",\n description: \"file-text\",\n directions_car: \"car\",\n done: \"check\",\n done_all: \"check-check\",\n door_front: \"door-open\",\n download: \"download\",\n east: \"arrow-right\",\n edit: \"pencil\",\n edit_note: \"pencil-line\",\n electrical_services: \"plug-zap\",\n email: \"mail\",\n emoji_events: \"trophy\",\n engineering: \"hard-hat\",\n error: \"circle-alert\",\n error_outline: \"circle-alert\",\n event: \"calendar-days\",\n expand_less: \"chevron-up\",\n expand_more: \"chevron-down\",\n explore: \"compass\",\n face: \"face-slightly-smiling\",\n fact_check: \"clipboard-check\",\n favorite: \"heart\",\n favorite_border: \"heart\",\n file_download: \"download\",\n file_upload: \"upload\",\n filter_alt: \"funnel\",\n filter_list: \"funnel\",\n fingerprint: \"fingerprint-pattern\",\n fitness_center: \"dumbbell\",\n flight: \"plane\",\n folder: \"folder\",\n format_list_bulleted: \"list\",\n format_paint: \"paint-roller\",\n forum: \"messages-square\",\n gavel: \"gavel\",\n grade: \"star\",\n grass: \"sprout\",\n grid_view: \"layout-grid\",\n group: \"users\",\n groups: \"users\",\n handyman: \"wrench\",\n hardware: \"wrench\",\n help: \"circle-question-mark\",\n help_outline: \"circle-question-mark\",\n highlight_off: \"circle-x\",\n history: \"rotate-ccw-clock\",\n home: \"house\",\n hotel: \"bed-double\",\n image: \"image\",\n info: \"info\",\n insights: \"chart-line\",\n inventory: \"package\",\n inventory_2: \"package\",\n iron: \"shirt\",\n key: \"key\",\n kitchen: \"refrigerator\",\n language: \"globe\",\n laptop: \"laptop\",\n light_mode: \"sun\",\n lightbulb: \"lightbulb\",\n link: \"link\",\n list: \"list\",\n list_alt: \"list\",\n local_bar: \"wine\",\n local_cafe: \"coffee\",\n local_florist: \"flower\",\n local_gas_station: \"fuel\",\n local_laundry_service: \"washing-machine\",\n local_offer: \"tag\",\n local_shipping: \"truck\",\n local_taxi: \"car-taxi-front\",\n location_on: \"map-pin\",\n lock: \"lock\",\n lock_open: \"lock-open\",\n login: \"log-in\",\n logout: \"log-out\",\n mail: \"mail\",\n mail_outline: \"mail\",\n manage_accounts: \"user-cog\",\n map: \"map\",\n medical_services: \"stethoscope\",\n menu: \"menu\",\n menu_book: \"book-open\",\n mic: \"mic\",\n mode_edit: \"pencil\",\n monetization_on: \"circle-dollar-sign\",\n more_horiz: \"ellipsis\",\n more_vert: \"ellipsis-vertical\",\n music_note: \"music\",\n navigate_next: \"chevron-right\",\n note_add: \"file-plus\",\n notifications: \"bell\",\n notifications_active: \"bell-ring\",\n open_in_new: \"external-link\",\n paid: \"circle-dollar-sign\",\n palette: \"palette\",\n pause: \"pause\",\n payments: \"banknote\",\n pedal_bike: \"bike\",\n people: \"users\",\n perm_identity: \"user\",\n person: \"user\",\n person_add: \"user-plus\",\n person_outline: \"user\",\n pest_control: \"bug\",\n pets: \"paw-print\",\n phone: \"phone\",\n phone_iphone: \"smartphone\",\n photo_camera: \"camera\",\n picture_as_pdf: \"file-text\",\n pie_chart: \"chart-pie\",\n place: \"map-pin\",\n play_arrow: \"play\",\n play_circle: \"circle-play\",\n play_circle_filled: \"circle-play\",\n plumbing: \"shower-head\",\n power_settings_new: \"power\",\n print: \"printer\",\n public: \"globe\",\n qr_code_scanner: \"scan-line\",\n question_answer: \"messages-square\",\n radio_button_checked: \"circle-dot\",\n radio_button_unchecked: \"circle\",\n receipt: \"receipt\",\n receipt_long: \"receipt-text\",\n refresh: \"refresh-cw\",\n remove: \"minus\",\n remove_circle_outline: \"circle-minus\",\n reorder: \"list\",\n report_problem: \"triangle-alert\",\n restart_alt: \"rotate-ccw\",\n restaurant: \"utensils\",\n roofing: \"house\",\n room: \"map-pin\",\n router: \"router\",\n save: \"save\",\n savings: \"piggy-bank\",\n schedule: \"clock\",\n school: \"graduation-cap\",\n search: \"search\",\n security: \"shield-check\",\n send: \"send\",\n settings: \"settings\",\n share: \"share-2\",\n shield: \"shield\",\n shopping_bag: \"shopping-bag\",\n shopping_cart: \"shopping-cart\",\n smartphone: \"smartphone\",\n soap: \"soap-dispenser-droplet\",\n sort: \"arrow-down-up\",\n spa: \"flower-2\",\n star: \"star\",\n star_border: \"star\",\n star_rate: \"star\",\n store: \"store\",\n storefront: \"store\",\n support_agent: \"headset\",\n sync: \"refresh-cw\",\n task_alt: \"circle-check\",\n timer: \"timer\",\n today: \"calendar\",\n toggle_on: \"toggle-right\",\n translate: \"languages\",\n trending_up: \"trending-up\",\n tune: \"sliders-horizontal\",\n tv: \"tv\",\n two_wheeler: \"bike\",\n upload: \"upload\",\n upload_file: \"upload\",\n vaccines: \"syringe\",\n verified: \"badge-check\",\n verified_user: \"shield-check\",\n videocam: \"video\",\n view_list: \"list\",\n visibility: \"eye\",\n visibility_off: \"eye-off\",\n vpn_key: \"key-round\",\n warehouse: \"warehouse\",\n warning: \"triangle-alert\",\n warning_amber: \"triangle-alert\",\n watch_later: \"clock\",\n water_drop: \"droplet\",\n wifi: \"wifi\",\n work: \"briefcase\",\n yard: \"trees\",\n};\n\n/**\n * Translate a Material Symbols code into a lucide slug, always returning one.\n *\n * Never returns `undefined`: an unknown code resolves to `fallback`, so a row\n * whose `icon_code` this table has not learned yet still renders. The input is\n * trimmed and lower-cased before lookup, because a seed written by hand is the\n * kind of source that carries stray whitespace and the odd capital.\n *\n * Nothing else in `/icons` imports this module, so an app that does not store\n * Material Symbols never pays for the table.\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code)} size={20} />\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code, \"folder\")} size={20} />\n *\n * @param code - A Material Symbols name, or `null`/`undefined` for a row that has none.\n * @param fallback - Slug to use when `code` is empty or unknown. Defaults to {@link MATERIAL_SYMBOL_FALLBACK}.\n * @returns A lucide slug `<Icon>` can render.\n */\nexport function fromMaterialSymbol(\n code: string | null | undefined,\n fallback: IconName = MATERIAL_SYMBOL_FALLBACK,\n): IconName {\n if (!code) return fallback;\n return materialToLucide[code.trim().toLowerCase()] ?? fallback;\n}\n"],"mappings":"AAqBA,IAAa,EAAqC,uBA0DrC,EAAuD,CAChE,QAAS,YACT,gBAAiB,WACjB,uBAAwB,SACxB,YAAa,cACb,eAAgB,cAChB,IAAK,OACL,WAAY,cACZ,mBAAoB,cACpB,kBAAmB,gBACnB,qBAAsB,cACtB,UAAW,eACX,KAAM,cACN,WAAY,aACZ,eAAgB,eAChB,mBAAoB,eACpB,eAAgB,aAChB,gBAAiB,eACjB,cAAe,cACf,kBAAmB,gBACnB,YAAa,gBACb,gBAAiB,cACjB,aAAc,WACd,QAAS,YACT,WAAY,iBACZ,YAAa,YACb,aAAc,cACd,UAAW,aACX,MAAO,UACP,QAAS,QACT,UAAW,eACX,aAAc,eACd,UAAW,YACX,KAAM,MACN,SAAU,WACV,MAAO,QACP,MAAO,SACP,SAAU,aACV,KAAM,OACN,UAAW,aACX,eAAgB,WAChB,eAAgB,WAChB,KAAM,QACN,SAAU,YACV,OAAQ,WACR,WAAY,MACZ,UAAW,SACX,SAAU,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M,OACN,KAAM,YACN,KAAM,OACV,EAuBA,SAAgB,EACZ,EACA,EAAqB,EACb,CAER,OADK,EACE,EAAiB,EAAK,KAAK,CAAC,CAAC,YAAY,IAAM,EADpC,CAEtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"material-symbols.js","names":[],"sources":["../../src/icons/material-symbols.ts"],"sourcesContent":["import type { IconName } from \"./generated/icon-name\";\n\n/**\n * The slug `fromMaterialSymbol` falls back to when a code is unknown.\n *\n * A neutral glyph rather than nothing: a category created in an admin with a\n * code this table has not learned yet still has to draw something, or it opens a\n * hole in the grid and the bug reads as a layout problem instead of a missing\n * mapping.\n *\n * Lucide's `circle-help` is a deprecated alias of this slug. `<Icon>` resolves\n * aliases, so both render — but the bridge emits the canonical name, since a\n * value that gets persisted should not be one lucide has already renamed.\n */\nexport const MATERIAL_SYMBOL_FALLBACK: IconName = \"circle-question-mark\";\n\n/**\n * Material Symbols code → lucide slug, for backends that store `icon_code`.\n *\n * Every Python backend we write stores a category icon as a Material Symbol\n * (`build`, `format_paint`, `electrical_services`) — the vocabulary Flutter,\n * Android and the administrative seeds already speak. The SDK speaks lucide in\n * kebab-case. The two lists do not meet, and the failure is nastier than an\n * empty screen: a handful of codes collide by accident, so roughly one row in\n * ten draws the right icon and the bug reads as \"some icons went missing\".\n *\n * **Still not the full vocabulary.** Material Symbols publishes ~6100 names and\n * almost none of them will ever appear in an `icon_code` of ours, so this grows\n * on demand, one hand-written pair at a time — a map generated by name\n * heuristics gets it badly wrong, starting with `build`, which is a wrench in\n * Material Symbols and nothing to do with construction.\n *\n * **How the codes were chosen.** Two lots, merged. The first was the trades seed\n * the bridge started as. The second is the head of Material Symbols' own\n * published popularity ranking (`fonts.google.com/metadata/icons`), which is\n * measured usage rather than a guess at which names a seed will contain — every\n * key was checked to exist in that vocabulary before landing.\n *\n * **Where the two lots disagreed**, six keys, the tie went to whichever mapping\n * keeps two distinct Material Symbols names distinct in lucide: `error` →\n * `circle-alert` because `cancel` already owns `circle-x`; `payments` →\n * `banknote` because `account_balance_wallet` already owns `wallet`;\n * `receipt_long` → `receipt-text` because `receipt` already owns `receipt`;\n * `construction` → itself because `engineering` already owns `hard-hat`; and\n * `today` → `calendar` with `event` → `calendar-days`, splitting the generic\n * calendar names from the dated one.\n *\n * Every target is checked mechanically against the slug list by\n * `material-symbols.test.ts`, so a pair pointing at a name lucide does not ship\n * — or at one it has since deprecated — fails the suite instead of reaching a\n * grid. What no test can check is whether the *chosen* icon is the right\n * metaphor, which is why pairs go in by hand.\n *\n * **Approximations, deliberate and not one-to-one** (the full list lives in\n * `docs/icons.md`):\n *\n * - `plumbing` → `shower-head`, because lucide has no pipe.\n * - `build`, `handyman` and `hardware` all land on `wrench` — Material Symbols\n * distinguishes the tools, lucide does not.\n * - `pedal_bike`, `two_wheeler` and `delivery_dining` all land on `bike`.\n * - `dentistry` → `face-slightly-smiling`, since lucide ships no tooth.\n * - `iron` → `shirt` and `cleaning_services` → `spray-can`: the activity, not\n * the implement.\n * - `roofing` → `house`, the same glyph as `home`, because lucide has no roof.\n *\n * The identity pairs are here on purpose. Their names happen to match in both\n * vocabularies, so they already render today — leaving them out would send them\n * to {@link MATERIAL_SYMBOL_FALLBACK} and make this bridge a regression for\n * exactly the codes that used to work.\n *\n * @see fromMaterialSymbol — the lookup you normally call.\n */\nexport const materialToLucide: Readonly<Record<string, IconName>> = {\n ac_unit: \"snowflake\",\n account_balance: \"landmark\",\n account_balance_wallet: \"wallet\",\n account_box: \"square-user\",\n account_circle: \"circle-user\",\n add: \"plus\",\n add_circle: \"circle-plus\",\n add_circle_outline: \"circle-plus\",\n add_shopping_cart: \"shopping-cart\",\n admin_panel_settings: \"shield-user\",\n analytics: \"chart-column\",\n apps: \"layout-grid\",\n arrow_back: \"arrow-left\",\n arrow_back_ios: \"chevron-left\",\n arrow_back_ios_new: \"chevron-left\",\n arrow_downward: \"arrow-down\",\n arrow_drop_down: \"chevron-down\",\n arrow_forward: \"arrow-right\",\n arrow_forward_ios: \"chevron-right\",\n arrow_right: \"chevron-right\",\n arrow_right_alt: \"arrow-right\",\n arrow_upward: \"arrow-up\",\n article: \"newspaper\",\n assignment: \"clipboard-list\",\n attach_file: \"paperclip\",\n attach_money: \"dollar-sign\",\n autorenew: \"refresh-cw\",\n badge: \"id-card\",\n balance: \"scale\",\n bar_chart: \"chart-column\",\n battery_full: \"battery-full\",\n bluetooth: \"bluetooth\",\n bolt: \"zap\",\n bookmark: \"bookmark\",\n brush: \"brush\",\n build: \"wrench\",\n business: \"building-2\",\n cake: \"cake\",\n calculate: \"calculator\",\n calendar_month: \"calendar\",\n calendar_today: \"calendar\",\n call: \"phone\",\n campaign: \"megaphone\",\n cancel: \"circle-x\",\n car_repair: \"car\",\n carpenter: \"hammer\",\n category: \"shapes\",\n chair: \"armchair\",\n chat: \"message-circle\",\n check: \"check\",\n check_box: \"square-check\",\n check_box_outline_blank: \"square\",\n check_circle: \"circle-check\",\n check_circle_outline: \"circle-check\",\n chevron_left: \"chevron-left\",\n chevron_right: \"chevron-right\",\n child_care: \"baby\",\n circle: \"circle\",\n cleaning_services: \"spray-can\",\n clear: \"x\",\n close: \"x\",\n cloud: \"cloud\",\n code: \"code\",\n computer: \"monitor\",\n construction: \"construction\",\n content_copy: \"copy\",\n content_cut: \"scissors\",\n credit_card: \"credit-card\",\n dark_mode: \"moon\",\n dashboard: \"layout-dashboard\",\n date_range: \"calendar-range\",\n delete: \"trash-2\",\n delete_forever: \"trash-2\",\n delete_outline: \"trash-2\",\n delivery_dining: \"bike\",\n dentistry: \"face-slightly-smiling\",\n description: \"file-text\",\n directions_car: \"car\",\n done: \"check\",\n done_all: \"check-check\",\n door_front: \"door-open\",\n download: \"download\",\n east: \"arrow-right\",\n edit: \"pencil\",\n edit_note: \"pencil-line\",\n electrical_services: \"plug-zap\",\n email: \"mail\",\n emoji_events: \"trophy\",\n engineering: \"hard-hat\",\n error: \"circle-alert\",\n error_outline: \"circle-alert\",\n event: \"calendar-days\",\n expand_less: \"chevron-up\",\n expand_more: \"chevron-down\",\n explore: \"compass\",\n face: \"face-slightly-smiling\",\n fact_check: \"clipboard-check\",\n favorite: \"heart\",\n favorite_border: \"heart\",\n file_download: \"download\",\n file_upload: \"upload\",\n filter_alt: \"funnel\",\n filter_list: \"funnel\",\n fingerprint: \"fingerprint-pattern\",\n fitness_center: \"dumbbell\",\n flight: \"plane\",\n folder: \"folder\",\n format_list_bulleted: \"list\",\n format_paint: \"paint-roller\",\n forum: \"messages-square\",\n gavel: \"gavel\",\n grade: \"star\",\n grass: \"sprout\",\n grid_view: \"layout-grid\",\n group: \"users\",\n groups: \"users\",\n handyman: \"wrench\",\n hardware: \"wrench\",\n help: \"circle-question-mark\",\n help_outline: \"circle-question-mark\",\n highlight_off: \"circle-x\",\n history: \"rotate-ccw-clock\",\n home: \"house\",\n hotel: \"bed-double\",\n image: \"image\",\n info: \"info\",\n insights: \"chart-line\",\n inventory: \"package\",\n inventory_2: \"package\",\n iron: \"shirt\",\n key: \"key\",\n kitchen: \"refrigerator\",\n language: \"globe\",\n laptop: \"laptop\",\n light_mode: \"sun\",\n lightbulb: \"lightbulb\",\n link: \"link\",\n list: \"list\",\n list_alt: \"list\",\n local_bar: \"wine\",\n local_cafe: \"coffee\",\n local_florist: \"flower\",\n local_gas_station: \"fuel\",\n local_laundry_service: \"washing-machine\",\n local_offer: \"tag\",\n local_shipping: \"truck\",\n local_taxi: \"car-taxi-front\",\n location_on: \"map-pin\",\n lock: \"lock\",\n lock_open: \"lock-open\",\n login: \"log-in\",\n logout: \"log-out\",\n mail: \"mail\",\n mail_outline: \"mail\",\n manage_accounts: \"user-cog\",\n map: \"map\",\n medical_services: \"stethoscope\",\n menu: \"menu\",\n menu_book: \"book-open\",\n mic: \"mic\",\n mode_edit: \"pencil\",\n monetization_on: \"circle-dollar-sign\",\n more_horiz: \"ellipsis\",\n more_vert: \"ellipsis-vertical\",\n music_note: \"music\",\n navigate_next: \"chevron-right\",\n note_add: \"file-plus\",\n notifications: \"bell\",\n notifications_active: \"bell-ring\",\n open_in_new: \"external-link\",\n paid: \"circle-dollar-sign\",\n palette: \"palette\",\n pause: \"pause\",\n payments: \"banknote\",\n pedal_bike: \"bike\",\n people: \"users\",\n perm_identity: \"user\",\n person: \"user\",\n person_add: \"user-plus\",\n person_outline: \"user\",\n pest_control: \"bug\",\n pets: \"paw-print\",\n phone: \"phone\",\n phone_iphone: \"smartphone\",\n photo_camera: \"camera\",\n picture_as_pdf: \"file-text\",\n pie_chart: \"chart-pie\",\n place: \"map-pin\",\n play_arrow: \"play\",\n play_circle: \"circle-play\",\n play_circle_filled: \"circle-play\",\n plumbing: \"shower-head\",\n power_settings_new: \"power\",\n print: \"printer\",\n public: \"globe\",\n qr_code_scanner: \"scan-line\",\n question_answer: \"messages-square\",\n radio_button_checked: \"circle-dot\",\n radio_button_unchecked: \"circle\",\n receipt: \"receipt\",\n receipt_long: \"receipt-text\",\n refresh: \"refresh-cw\",\n remove: \"minus\",\n remove_circle_outline: \"circle-minus\",\n reorder: \"list\",\n report_problem: \"triangle-alert\",\n restart_alt: \"rotate-ccw\",\n restaurant: \"utensils\",\n roofing: \"house\",\n room: \"map-pin\",\n router: \"router\",\n save: \"save\",\n savings: \"piggy-bank\",\n schedule: \"clock\",\n school: \"graduation-cap\",\n search: \"search\",\n security: \"shield-check\",\n send: \"send\",\n settings: \"settings\",\n share: \"share-2\",\n shield: \"shield\",\n shopping_bag: \"shopping-bag\",\n shopping_cart: \"shopping-cart\",\n smartphone: \"smartphone\",\n soap: \"soap-dispenser-droplet\",\n sort: \"arrow-down-up\",\n spa: \"flower-2\",\n star: \"star\",\n star_border: \"star\",\n star_rate: \"star\",\n store: \"store\",\n storefront: \"store\",\n support_agent: \"headset\",\n sync: \"refresh-cw\",\n task_alt: \"circle-check\",\n timer: \"timer\",\n today: \"calendar\",\n toggle_on: \"toggle-right\",\n translate: \"languages\",\n trending_up: \"trending-up\",\n tune: \"sliders-horizontal\",\n tv: \"tv\",\n two_wheeler: \"bike\",\n upload: \"upload\",\n upload_file: \"upload\",\n vaccines: \"syringe\",\n verified: \"badge-check\",\n verified_user: \"shield-check\",\n videocam: \"video\",\n view_list: \"list\",\n visibility: \"eye\",\n visibility_off: \"eye-off\",\n vpn_key: \"key-round\",\n warehouse: \"warehouse\",\n warning: \"triangle-alert\",\n warning_amber: \"triangle-alert\",\n watch_later: \"clock\",\n water_drop: \"droplet\",\n wifi: \"wifi\",\n work: \"briefcase\",\n yard: \"trees\",\n};\n\n/**\n * Translate a Material Symbols code into a lucide slug, always returning one.\n *\n * Never returns `undefined`: an unknown code resolves to `fallback`, so a row\n * whose `icon_code` this table has not learned yet still renders. The input is\n * trimmed and lower-cased before lookup, because a seed written by hand is the\n * kind of source that carries stray whitespace and the odd capital.\n *\n * Nothing else in `/icons` imports this module, so an app that does not store\n * Material Symbols never pays for the table.\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code)} size={20} />\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code, \"folder\")} size={20} />\n *\n * @param code - A Material Symbols name, or `null`/`undefined` for a row that has none.\n * @param fallback - Slug to use when `code` is empty or unknown. Defaults to {@link MATERIAL_SYMBOL_FALLBACK}.\n * @returns A lucide slug `<Icon>` can render.\n */\nexport function fromMaterialSymbol(\n code: string | null | undefined,\n fallback: IconName = MATERIAL_SYMBOL_FALLBACK,\n): IconName {\n if (!code) return fallback;\n return materialToLucide[code.trim().toLowerCase()] ?? fallback;\n}\n"],"mappings":";AAcA,IAAa,IAAqC,wBA0DrC,IAAuD;CAChE,SAAS;CACT,iBAAiB;CACjB,wBAAwB;CACxB,aAAa;CACb,gBAAgB;CAChB,KAAK;CACL,YAAY;CACZ,oBAAoB;CACpB,mBAAmB;CACnB,sBAAsB;CACtB,WAAW;CACX,MAAM;CACN,YAAY;CACZ,gBAAgB;CAChB,oBAAoB;CACpB,gBAAgB;CAChB,iBAAiB;CACjB,eAAe;CACf,mBAAmB;CACnB,aAAa;CACb,i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CACN,UAAU;CACV,OAAO;CACP,OAAO;CACP,WAAW;CACX,WAAW;CACX,aAAa;CACb,MAAM;CACN,IAAI;CACJ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,UAAU;CACV,UAAU;CACV,eAAe;CACf,UAAU;CACV,WAAW;CACX,YAAY;CACZ,gBAAgB;CAChB,SAAS;CACT,WAAW;CACX,SAAS;CACT,eAAe;CACf,aAAa;CACb,YAAY;CACZ,MAAM;CACN,MAAM;CACN,MAAM;AACV;AAuBA,SAAgB,EACZ,GACA,IAAqB,GACb;CAER,OADK,IACE,EAAiB,EAAK,KAAK,CAAC,CAAC,YAAY,MAAM,IADpC;AAEtB"}
|
|
1
|
+
{"version":3,"file":"material-symbols.js","names":[],"sources":["../../src/icons/material-symbols.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — the file is one hand-written lookup table plus the\n * two functions that read it. Splitting a table by row count would put pairs that\n * belong together (`format_*`, `electrical_*`) in different files and make the\n * next hand-written pair a question of which file it lands in; the length is the\n * vocabulary's, not the code's.\n */\nimport type { IconName } from \"./generated/icon-name\";\n\n/**\n * The slug `fromMaterialSymbol` falls back to when a code is unknown.\n *\n * A neutral glyph rather than nothing: a category created in an admin with a\n * code this table has not learned yet still has to draw something, or it opens a\n * hole in the grid and the bug reads as a layout problem instead of a missing\n * mapping.\n *\n * Lucide's `circle-help` is a deprecated alias of this slug. `<Icon>` resolves\n * aliases, so both render — but the bridge emits the canonical name, since a\n * value that gets persisted should not be one lucide has already renamed.\n */\nexport const MATERIAL_SYMBOL_FALLBACK: IconName = \"circle-question-mark\";\n\n/**\n * Material Symbols code → lucide slug, for backends that store `icon_code`.\n *\n * Every Python backend we write stores a category icon as a Material Symbol\n * (`build`, `format_paint`, `electrical_services`) — the vocabulary Flutter,\n * Android and the administrative seeds already speak. The SDK speaks lucide in\n * kebab-case. The two lists do not meet, and the failure is nastier than an\n * empty screen: a handful of codes collide by accident, so roughly one row in\n * ten draws the right icon and the bug reads as \"some icons went missing\".\n *\n * **Still not the full vocabulary.** Material Symbols publishes ~6100 names and\n * almost none of them will ever appear in an `icon_code` of ours, so this grows\n * on demand, one hand-written pair at a time — a map generated by name\n * heuristics gets it badly wrong, starting with `build`, which is a wrench in\n * Material Symbols and nothing to do with construction.\n *\n * **How the codes were chosen.** Two lots, merged. The first was the trades seed\n * the bridge started as. The second is the head of Material Symbols' own\n * published popularity ranking (`fonts.google.com/metadata/icons`), which is\n * measured usage rather than a guess at which names a seed will contain — every\n * key was checked to exist in that vocabulary before landing.\n *\n * **Where the two lots disagreed**, six keys, the tie went to whichever mapping\n * keeps two distinct Material Symbols names distinct in lucide: `error` →\n * `circle-alert` because `cancel` already owns `circle-x`; `payments` →\n * `banknote` because `account_balance_wallet` already owns `wallet`;\n * `receipt_long` → `receipt-text` because `receipt` already owns `receipt`;\n * `construction` → itself because `engineering` already owns `hard-hat`; and\n * `today` → `calendar` with `event` → `calendar-days`, splitting the generic\n * calendar names from the dated one.\n *\n * Every target is checked mechanically against the slug list by\n * `material-symbols.test.ts`, so a pair pointing at a name lucide does not ship\n * — or at one it has since deprecated — fails the suite instead of reaching a\n * grid. What no test can check is whether the *chosen* icon is the right\n * metaphor, which is why pairs go in by hand.\n *\n * **Approximations, deliberate and not one-to-one** (the full list lives in\n * `docs/icons.md`):\n *\n * - `plumbing` → `shower-head`, because lucide has no pipe.\n * - `build`, `handyman` and `hardware` all land on `wrench` — Material Symbols\n * distinguishes the tools, lucide does not.\n * - `pedal_bike`, `two_wheeler` and `delivery_dining` all land on `bike`.\n * - `dentistry` → `face-slightly-smiling`, since lucide ships no tooth.\n * - `iron` → `shirt` and `cleaning_services` → `spray-can`: the activity, not\n * the implement.\n * - `roofing` → `house`, the same glyph as `home`, because lucide has no roof.\n *\n * The identity pairs are here on purpose. Their names happen to match in both\n * vocabularies, so they already render today — leaving them out would send them\n * to {@link MATERIAL_SYMBOL_FALLBACK} and make this bridge a regression for\n * exactly the codes that used to work.\n *\n * @see fromMaterialSymbol — the lookup you normally call.\n */\nexport const materialToLucide: Readonly<Record<string, IconName>> = {\n ac_unit: \"snowflake\",\n account_balance: \"landmark\",\n account_balance_wallet: \"wallet\",\n account_box: \"square-user\",\n account_circle: \"circle-user\",\n add: \"plus\",\n add_circle: \"circle-plus\",\n add_circle_outline: \"circle-plus\",\n add_shopping_cart: \"shopping-cart\",\n admin_panel_settings: \"shield-user\",\n analytics: \"chart-column\",\n apps: \"layout-grid\",\n arrow_back: \"arrow-left\",\n arrow_back_ios: \"chevron-left\",\n arrow_back_ios_new: \"chevron-left\",\n arrow_downward: \"arrow-down\",\n arrow_drop_down: \"chevron-down\",\n arrow_forward: \"arrow-right\",\n arrow_forward_ios: \"chevron-right\",\n arrow_right: \"chevron-right\",\n arrow_right_alt: \"arrow-right\",\n arrow_upward: \"arrow-up\",\n article: \"newspaper\",\n assignment: \"clipboard-list\",\n attach_file: \"paperclip\",\n attach_money: \"dollar-sign\",\n autorenew: \"refresh-cw\",\n badge: \"id-card\",\n balance: \"scale\",\n bar_chart: \"chart-column\",\n battery_full: \"battery-full\",\n bluetooth: \"bluetooth\",\n bolt: \"zap\",\n bookmark: \"bookmark\",\n brush: \"brush\",\n build: \"wrench\",\n business: \"building-2\",\n cake: \"cake\",\n calculate: \"calculator\",\n calendar_month: \"calendar\",\n calendar_today: \"calendar\",\n call: \"phone\",\n campaign: \"megaphone\",\n cancel: \"circle-x\",\n car_repair: \"car\",\n carpenter: \"hammer\",\n category: \"shapes\",\n chair: \"armchair\",\n chat: \"message-circle\",\n check: \"check\",\n check_box: \"square-check\",\n check_box_outline_blank: \"square\",\n check_circle: \"circle-check\",\n check_circle_outline: \"circle-check\",\n chevron_left: \"chevron-left\",\n chevron_right: \"chevron-right\",\n child_care: \"baby\",\n circle: \"circle\",\n cleaning_services: \"spray-can\",\n clear: \"x\",\n close: \"x\",\n cloud: \"cloud\",\n code: \"code\",\n computer: \"monitor\",\n construction: \"construction\",\n content_copy: \"copy\",\n content_cut: \"scissors\",\n credit_card: \"credit-card\",\n dark_mode: \"moon\",\n dashboard: \"layout-dashboard\",\n date_range: \"calendar-range\",\n delete: \"trash-2\",\n delete_forever: \"trash-2\",\n delete_outline: \"trash-2\",\n delivery_dining: \"bike\",\n dentistry: \"face-slightly-smiling\",\n description: \"file-text\",\n directions_car: \"car\",\n done: \"check\",\n done_all: \"check-check\",\n door_front: \"door-open\",\n download: \"download\",\n east: \"arrow-right\",\n edit: \"pencil\",\n edit_note: \"pencil-line\",\n electrical_services: \"plug-zap\",\n email: \"mail\",\n emoji_events: \"trophy\",\n engineering: \"hard-hat\",\n error: \"circle-alert\",\n error_outline: \"circle-alert\",\n event: \"calendar-days\",\n expand_less: \"chevron-up\",\n expand_more: \"chevron-down\",\n explore: \"compass\",\n face: \"face-slightly-smiling\",\n fact_check: \"clipboard-check\",\n favorite: \"heart\",\n favorite_border: \"heart\",\n file_download: \"download\",\n file_upload: \"upload\",\n filter_alt: \"funnel\",\n filter_list: \"funnel\",\n fingerprint: \"fingerprint-pattern\",\n fitness_center: \"dumbbell\",\n flight: \"plane\",\n folder: \"folder\",\n format_list_bulleted: \"list\",\n format_paint: \"paint-roller\",\n forum: \"messages-square\",\n gavel: \"gavel\",\n grade: \"star\",\n grass: \"sprout\",\n grid_view: \"layout-grid\",\n group: \"users\",\n groups: \"users\",\n handyman: \"wrench\",\n hardware: \"wrench\",\n help: \"circle-question-mark\",\n help_outline: \"circle-question-mark\",\n highlight_off: \"circle-x\",\n history: \"rotate-ccw-clock\",\n home: \"house\",\n hotel: \"bed-double\",\n image: \"image\",\n info: \"info\",\n insights: \"chart-line\",\n inventory: \"package\",\n inventory_2: \"package\",\n iron: \"shirt\",\n key: \"key\",\n kitchen: \"refrigerator\",\n language: \"globe\",\n laptop: \"laptop\",\n light_mode: \"sun\",\n lightbulb: \"lightbulb\",\n link: \"link\",\n list: \"list\",\n list_alt: \"list\",\n local_bar: \"wine\",\n local_cafe: \"coffee\",\n local_florist: \"flower\",\n local_gas_station: \"fuel\",\n local_laundry_service: \"washing-machine\",\n local_offer: \"tag\",\n local_shipping: \"truck\",\n local_taxi: \"car-taxi-front\",\n location_on: \"map-pin\",\n lock: \"lock\",\n lock_open: \"lock-open\",\n login: \"log-in\",\n logout: \"log-out\",\n mail: \"mail\",\n mail_outline: \"mail\",\n manage_accounts: \"user-cog\",\n map: \"map\",\n medical_services: \"stethoscope\",\n menu: \"menu\",\n menu_book: \"book-open\",\n mic: \"mic\",\n mode_edit: \"pencil\",\n monetization_on: \"circle-dollar-sign\",\n more_horiz: \"ellipsis\",\n more_vert: \"ellipsis-vertical\",\n music_note: \"music\",\n navigate_next: \"chevron-right\",\n note_add: \"file-plus\",\n notifications: \"bell\",\n notifications_active: \"bell-ring\",\n open_in_new: \"external-link\",\n paid: \"circle-dollar-sign\",\n palette: \"palette\",\n pause: \"pause\",\n payments: \"banknote\",\n pedal_bike: \"bike\",\n people: \"users\",\n perm_identity: \"user\",\n person: \"user\",\n person_add: \"user-plus\",\n person_outline: \"user\",\n pest_control: \"bug\",\n pets: \"paw-print\",\n phone: \"phone\",\n phone_iphone: \"smartphone\",\n photo_camera: \"camera\",\n picture_as_pdf: \"file-text\",\n pie_chart: \"chart-pie\",\n place: \"map-pin\",\n play_arrow: \"play\",\n play_circle: \"circle-play\",\n play_circle_filled: \"circle-play\",\n plumbing: \"shower-head\",\n power_settings_new: \"power\",\n print: \"printer\",\n public: \"globe\",\n qr_code_scanner: \"scan-line\",\n question_answer: \"messages-square\",\n radio_button_checked: \"circle-dot\",\n radio_button_unchecked: \"circle\",\n receipt: \"receipt\",\n receipt_long: \"receipt-text\",\n refresh: \"refresh-cw\",\n remove: \"minus\",\n remove_circle_outline: \"circle-minus\",\n reorder: \"list\",\n report_problem: \"triangle-alert\",\n restart_alt: \"rotate-ccw\",\n restaurant: \"utensils\",\n roofing: \"house\",\n room: \"map-pin\",\n router: \"router\",\n save: \"save\",\n savings: \"piggy-bank\",\n schedule: \"clock\",\n school: \"graduation-cap\",\n search: \"search\",\n security: \"shield-check\",\n send: \"send\",\n settings: \"settings\",\n share: \"share-2\",\n shield: \"shield\",\n shopping_bag: \"shopping-bag\",\n shopping_cart: \"shopping-cart\",\n smartphone: \"smartphone\",\n soap: \"soap-dispenser-droplet\",\n sort: \"arrow-down-up\",\n spa: \"flower-2\",\n star: \"star\",\n star_border: \"star\",\n star_rate: \"star\",\n store: \"store\",\n storefront: \"store\",\n support_agent: \"headset\",\n sync: \"refresh-cw\",\n task_alt: \"circle-check\",\n timer: \"timer\",\n today: \"calendar\",\n toggle_on: \"toggle-right\",\n translate: \"languages\",\n trending_up: \"trending-up\",\n tune: \"sliders-horizontal\",\n tv: \"tv\",\n two_wheeler: \"bike\",\n upload: \"upload\",\n upload_file: \"upload\",\n vaccines: \"syringe\",\n verified: \"badge-check\",\n verified_user: \"shield-check\",\n videocam: \"video\",\n view_list: \"list\",\n visibility: \"eye\",\n visibility_off: \"eye-off\",\n vpn_key: \"key-round\",\n warehouse: \"warehouse\",\n warning: \"triangle-alert\",\n warning_amber: \"triangle-alert\",\n watch_later: \"clock\",\n water_drop: \"droplet\",\n wifi: \"wifi\",\n work: \"briefcase\",\n yard: \"trees\",\n};\n\n/**\n * Translate a Material Symbols code into a lucide slug, always returning one.\n *\n * Never returns `undefined`: an unknown code resolves to `fallback`, so a row\n * whose `icon_code` this table has not learned yet still renders. The input is\n * trimmed and lower-cased before lookup, because a seed written by hand is the\n * kind of source that carries stray whitespace and the odd capital.\n *\n * Nothing else in `/icons` imports this module, so an app that does not store\n * Material Symbols never pays for the table.\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code)} size={20} />\n *\n * @example\n * <Icon name={fromMaterialSymbol(category.icon_code, \"folder\")} size={20} />\n *\n * @param code - A Material Symbols name, or `null`/`undefined` for a row that has none.\n * @param fallback - Slug to use when `code` is empty or unknown. Defaults to {@link MATERIAL_SYMBOL_FALLBACK}.\n * @returns A lucide slug `<Icon>` can render.\n */\nexport function fromMaterialSymbol(\n code: string | null | undefined,\n fallback: IconName = MATERIAL_SYMBOL_FALLBACK,\n): IconName {\n if (!code) return fallback;\n return materialToLucide[code.trim().toLowerCase()] ?? fallback;\n}\n"],"mappings":";AAqBA,IAAa,IAAqC,wBA0DrC,IAAuD;CAChE,SAAS;CACT,iBAAiB;CACjB,wBAAwB;CACxB,aAAa;CACb,gBAAgB;CAChB,KAAK;CACL,YAAY;CACZ,oBAAoB;CACpB,mBAAmB;CACnB,sBAAsB;CACtB,WAAW;CACX,MAAM;CACN,YAAY;CACZ,gBAAgB;CAChB,oBAAoB;CACpB,gBAAgB;CAChB,iBAAiB;CACjB,eAAe;CACf,mBAAmB;CACnB,aAAa;CACb,iBAAiB;CACjB,cAAc;CACd,SAAS;CACT,YAAY;CACZ,aAAa;CACb,cAAc;CACd,WAAW;CACX,OAAO;CACP,SAAS;CACT,WAAW;CACX,cAAc;CACd,WAAW;CACX,MAAM;CACN,UAAU;CACV,OAAO;CACP,OAAO;CACP,UAAU;CACV,MAAM;CACN,WAAW;CACX,gBAAgB;CAChB,gBAAgB;CAChB,MAAM;CACN,UAAU;CACV,QAAQ;CACR,YAAY;CACZ,WAAW;CACX,UAAU;CACV,OAAO;CACP,MAAM;CACN,OAAO;CACP,WAAW;CACX,yBAAyB;CACzB,cAAc;CACd,sBAAsB;CACtB,cAAc;CACd,eAAe;CACf,YAAY;CACZ,QAAQ;CACR,mBAAmB;CACnB,OAAO;CACP,OAAO;CACP,OAAO;CACP,MAAM;CACN,UAAU;CACV,cAAc;CACd,cAAc;CACd,aAAa;CACb,aAAa;CACb,WAAW;CACX,WAAW;CACX,YAAY;CACZ,QAAQ;CACR,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,WAAW;CACX,aAAa;CACb,gBAAgB;CAChB,MAAM;CACN,UAAU;CACV,YAAY;CACZ,UAAU;CACV,MAAM;CACN,MAAM;CACN,WAAW;CACX,qBAAqB;CACrB,OAAO;CACP,cAAc;CACd,aAAa;CACb,OAAO;CACP,eAAe;CACf,OAA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