@format.dev/client 0.2.0 → 0.3.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/index.cjs CHANGED
@@ -4,7 +4,7 @@ let form_data_encoder = require("form-data-encoder");
4
4
  let stream = require("stream");
5
5
 
6
6
  //#region package.json
7
- var version = "0.2.0";
7
+ var version = "0.3.0";
8
8
 
9
9
  //#endregion
10
10
  //#region src/constants.ts
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { FormDataEncoder } from "form-data-encoder";
4
4
  import { Readable as Readable$1 } from "stream";
5
5
 
6
6
  //#region package.json
7
- var version = "0.2.0";
7
+ var version = "0.3.0";
8
8
 
9
9
  //#endregion
10
10
  //#region src/constants.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["REGION_MAP: Record<FormatRegion, string>","FormDataFile","Readable","status: number","detail: unknown","chunks: Uint8Array[]","res: Response","options"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/node-assets.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.2.0\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","// Asset normalisation for the Node build only. It imports Node's stream module\n// and formdata-node, which the web build must never bundle.\nimport { Readable } from 'stream'\nimport { File as FormDataFile } from 'formdata-node'\nimport { isBlobLike, isWebReadable } from './helpers'\nimport type { AssetLike } from './node-types'\n\ntype FileLike = {\n\tname: string\n\ttype: string\n\treadonly [Symbol.toStringTag]: 'File'\n\tstream(): ReadableStream<Uint8Array>\n}\n\ntype FileLikeForFormData = FormDataFile | FileLike\n\nfunction toFileLike(webStream: ReadableStream<Uint8Array>, name: string, type: string): FileLike {\n\treturn {\n\t\tname,\n\t\ttype,\n\t\t[Symbol.toStringTag]: 'File' as const,\n\t\tstream() {\n\t\t\treturn webStream\n\t\t}\n\t}\n}\n\nfunction isNodeReadable(x: any): x is Readable {\n\treturn x != null && typeof (x as any).pipe === 'function' && typeof (x as any).read === 'function'\n}\n\n/**\n * Normalize assets into something FormData#set accepts (File or File-like)\n * whilst retaining multipart streaming where possible\n */\nexport function assetsToFormDataValue(\n\tinput: AssetLike,\n\tfilename = 'assets.zip',\n\tmime = 'application/zip'\n): FileLikeForFormData {\n\t// blob - wrap as File to ensure a filename\n\tif (isBlobLike(input)) {\n\t\treturn new FormDataFile([input as any], filename, { type: mime })\n\t}\n\n\t// bytes\n\tif (input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer?.isBuffer?.(input)) {\n\t\treturn new FormDataFile([input], filename, { type: mime })\n\t}\n\n\t// web ReadableStream\n\tif (isWebReadable(input)) {\n\t\treturn toFileLike(input, filename, mime)\n\t}\n\n\t// node Readable\n\tif (isNodeReadable(input)) {\n\t\tconst webStream = Readable.toWeb(input) as unknown as ReadableStream<Uint8Array>\n\t\treturn toFileLike(webStream, filename, mime)\n\t}\n\n\tthrow new TypeError('Unsupported assets type')\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import { Readable } from 'node:stream'\nimport { FormData } from 'formdata-node'\nimport { FormDataEncoder } from 'form-data-encoder'\nimport {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\trenderUrl,\n\tresolveBaseUrl,\n\ttimeoutSignal,\n\tresolveApiKey,\n\tserializeTags\n} from './helpers'\nimport { assetsToFormDataValue } from './node-assets'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse, WriteStreamOptions } from './node-types'\n\nconst USER_AGENT = `${CLIENT_IDENTIFIER} (${process.platform}) node ${process.version}`\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions = {}) {\n\t\tthis.apiKey = resolveApiKey(\n\t\t\topts.apiKey,\n\t\t\tprocess.env.FORMAT_API_KEY,\n\t\t\t'Pass `apiKey` explicitly or set `FORMAT_API_KEY` in your environment.'\n\t\t)\n\t\tthis.baseUrl = resolveBaseUrl(opts, process.env.FORMAT_BASE_URL)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\t// `doc` is either raw document model HTML (hand-authored / non-studio flows) or a\n\t\t// FormatDocument from studio's compile output\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\t// `getAssetsWebStream()` is the single source of truth: a stream means\n\t\t// attach it, `undefined` means this render has no assets, and a throw\n\t\t// (e.g. the rendered HTML references assets the bundle can't supply)\n\t\t// propagates to the caller with full context.\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', assetsToFormDataValue(assets))\n\t\t}\n\n\t\tconst encoder = new FormDataEncoder(form)\n\t\tconst headers = {\n\t\t\t...encoder.headers,\n\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t'User-Agent': USER_AGENT,\n\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t}\n\n\t\tlet res: Response\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\ttry {\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: Readable.toWeb(Readable.from(encoder)) as any,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tduplex: 'half' as any,\n\t\t\t\t// Node 24 otherwise reports a streamed upload's 401 as \"fetch failed\".\n\t\t\t\t// This leaves the explicit Authorization header intact.\n\t\t\t\tcredentials: 'omit'\n\t\t\t} as any)\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow await formatErrorFrom(res)\n\t\t}\n\n\t\tconst toFile = async (filePath: string, options?: WriteStreamOptions) => {\n\t\t\tif (res.bodyUsed) {\n\t\t\t\tthrow new Error('Response body already consumed')\n\t\t\t}\n\n\t\t\tif (!res.body) {\n\t\t\t\tthrow new Error('Response body is empty')\n\t\t\t}\n\n\t\t\tconst [{ pipeline }, { createWriteStream }, fs, path] = await Promise.all([\n\t\t\t\timport('node:stream/promises'),\n\t\t\t\timport('node:fs'),\n\t\t\t\timport('node:fs/promises'),\n\t\t\t\timport('node:path')\n\t\t\t])\n\n\t\t\tawait fs.mkdir(path.dirname(filePath), { recursive: true })\n\t\t\tconst nodeReadable = Readable.fromWeb(res.body as any)\n\t\t\tconst outStream = createWriteStream(filePath, { mode: options?.mode })\n\t\t\tawait pipeline(nodeReadable, outStream)\n\t\t\tconst stats = await fs.stat(filePath)\n\t\t\treturn { path: filePath, bytes: stats.size }\n\t\t}\n\n\t\treturn Object.assign(augmentResponse(res), { toFile })\n\t}\n}\n"],"mappings":";;;;;;cAEY;;;;ACCZ,MAAaA,aAA2C,EACvD,QAAQ,0BAGR;AAGD,MAAa,aAAa;AAE1B,MAAa,oBAAoB,sBAAsB;AAIvD,MAAa,WAAW,EACvB,SAAS,WAAW,QACpB;;;;ACdD,SAAgB,cAAc,GAAyC;AACtE,QAAO,OAAO,WAAW,mBAAmB,eAAe,KAAK,QAAQ,OAAQ,EAAU,cAAc;;AAGzG,SAAgB,WAAW,GAAmB;AAC7C,QACC,KAAK,QACL,OAAO,MAAM,YACb,OAAQ,EAAU,gBAAgB,cAClC,OAAQ,EAAU,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,OAAI,IAAI,SACP,OAAM,IAAI,MAAM,iCAAiC;AAGlD,OAAI,CAAC,IAAI,KACR,OAAM,IAAI,MAAM,yBAAyB;GAG1C,MAAM,CAAC,EAAE,YAAY,EAAE,qBAAqB,IAAI,QAAQ,MAAM,QAAQ,IAAI;IACzE,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,CAAC;AAEF,SAAM,GAAG,MAAM,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;AAG3D,SAAM,SAFe,SAAS,QAAQ,IAAI,KAAY,EACpC,kBAAkB,UAAU,EAAE,MAAMC,WAAS,MAAM,CAAC,CAC/B;AAEvC,UAAO;IAAE,MAAM;IAAU,QADX,MAAM,GAAG,KAAK,SAAS,EACC;IAAM;;AAG7C,SAAO,OAAO,OAAO,gBAAgB,IAAI,EAAE,EAAE,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["REGION_MAP: Record<FormatRegion, string>","FormDataFile","Readable","status: number","detail: unknown","chunks: Uint8Array[]","res: Response","options"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/node-assets.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.3.0\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","// Asset normalisation for the Node build only. It imports Node's stream module\n// and formdata-node, which the web build must never bundle.\nimport { Readable } from 'stream'\nimport { File as FormDataFile } from 'formdata-node'\nimport { isBlobLike, isWebReadable } from './helpers'\nimport type { AssetLike } from './node-types'\n\ntype FileLike = {\n\tname: string\n\ttype: string\n\treadonly [Symbol.toStringTag]: 'File'\n\tstream(): ReadableStream<Uint8Array>\n}\n\ntype FileLikeForFormData = FormDataFile | FileLike\n\nfunction toFileLike(webStream: ReadableStream<Uint8Array>, name: string, type: string): FileLike {\n\treturn {\n\t\tname,\n\t\ttype,\n\t\t[Symbol.toStringTag]: 'File' as const,\n\t\tstream() {\n\t\t\treturn webStream\n\t\t}\n\t}\n}\n\nfunction isNodeReadable(x: any): x is Readable {\n\treturn x != null && typeof (x as any).pipe === 'function' && typeof (x as any).read === 'function'\n}\n\n/**\n * Normalize assets into something FormData#set accepts (File or File-like)\n * whilst retaining multipart streaming where possible\n */\nexport function assetsToFormDataValue(\n\tinput: AssetLike,\n\tfilename = 'assets.zip',\n\tmime = 'application/zip'\n): FileLikeForFormData {\n\t// blob - wrap as File to ensure a filename\n\tif (isBlobLike(input)) {\n\t\treturn new FormDataFile([input as any], filename, { type: mime })\n\t}\n\n\t// bytes\n\tif (input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer?.isBuffer?.(input)) {\n\t\treturn new FormDataFile([input], filename, { type: mime })\n\t}\n\n\t// web ReadableStream\n\tif (isWebReadable(input)) {\n\t\treturn toFileLike(input, filename, mime)\n\t}\n\n\t// node Readable\n\tif (isNodeReadable(input)) {\n\t\tconst webStream = Readable.toWeb(input) as unknown as ReadableStream<Uint8Array>\n\t\treturn toFileLike(webStream, filename, mime)\n\t}\n\n\tthrow new TypeError('Unsupported assets type')\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import { Readable } from 'node:stream'\nimport { FormData } from 'formdata-node'\nimport { FormDataEncoder } from 'form-data-encoder'\nimport {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\trenderUrl,\n\tresolveBaseUrl,\n\ttimeoutSignal,\n\tresolveApiKey,\n\tserializeTags\n} from './helpers'\nimport { assetsToFormDataValue } from './node-assets'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse, WriteStreamOptions } from './node-types'\n\nconst USER_AGENT = `${CLIENT_IDENTIFIER} (${process.platform}) node ${process.version}`\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions = {}) {\n\t\tthis.apiKey = resolveApiKey(\n\t\t\topts.apiKey,\n\t\t\tprocess.env.FORMAT_API_KEY,\n\t\t\t'Pass `apiKey` explicitly or set `FORMAT_API_KEY` in your environment.'\n\t\t)\n\t\tthis.baseUrl = resolveBaseUrl(opts, process.env.FORMAT_BASE_URL)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\t// `doc` is either raw document model HTML (hand-authored / non-studio flows) or a\n\t\t// FormatDocument from studio's compile output\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\t// `getAssetsWebStream()` is the single source of truth: a stream means\n\t\t// attach it, `undefined` means this render has no assets, and a throw\n\t\t// (e.g. the rendered HTML references assets the bundle can't supply)\n\t\t// propagates to the caller with full context.\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', assetsToFormDataValue(assets))\n\t\t}\n\n\t\tconst encoder = new FormDataEncoder(form)\n\t\tconst headers = {\n\t\t\t...encoder.headers,\n\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t'User-Agent': USER_AGENT,\n\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t}\n\n\t\tlet res: Response\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\ttry {\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: Readable.toWeb(Readable.from(encoder)) as any,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tduplex: 'half' as any,\n\t\t\t\t// Node 24 otherwise reports a streamed upload's 401 as \"fetch failed\".\n\t\t\t\t// This leaves the explicit Authorization header intact.\n\t\t\t\tcredentials: 'omit'\n\t\t\t} as any)\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow await formatErrorFrom(res)\n\t\t}\n\n\t\tconst toFile = async (filePath: string, options?: WriteStreamOptions) => {\n\t\t\tif (res.bodyUsed) {\n\t\t\t\tthrow new Error('Response body already consumed')\n\t\t\t}\n\n\t\t\tif (!res.body) {\n\t\t\t\tthrow new Error('Response body is empty')\n\t\t\t}\n\n\t\t\tconst [{ pipeline }, { createWriteStream }, fs, path] = await Promise.all([\n\t\t\t\timport('node:stream/promises'),\n\t\t\t\timport('node:fs'),\n\t\t\t\timport('node:fs/promises'),\n\t\t\t\timport('node:path')\n\t\t\t])\n\n\t\t\tawait fs.mkdir(path.dirname(filePath), { recursive: true })\n\t\t\tconst nodeReadable = Readable.fromWeb(res.body as any)\n\t\t\tconst outStream = createWriteStream(filePath, { mode: options?.mode })\n\t\t\tawait pipeline(nodeReadable, outStream)\n\t\t\tconst stats = await fs.stat(filePath)\n\t\t\treturn { path: filePath, bytes: stats.size }\n\t\t}\n\n\t\treturn Object.assign(augmentResponse(res), { toFile })\n\t}\n}\n"],"mappings":";;;;;;cAEY;;;;ACCZ,MAAaA,aAA2C,EACvD,QAAQ,0BAGR;AAGD,MAAa,aAAa;AAE1B,MAAa,oBAAoB,sBAAsB;AAIvD,MAAa,WAAW,EACvB,SAAS,WAAW,QACpB;;;;ACdD,SAAgB,cAAc,GAAyC;AACtE,QAAO,OAAO,WAAW,mBAAmB,eAAe,KAAK,QAAQ,OAAQ,EAAU,cAAc;;AAGzG,SAAgB,WAAW,GAAmB;AAC7C,QACC,KAAK,Q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M,gBAAgB,IAAI;EAGjC,MAAM,SAAS,OAAO,UAAkB,cAAiC;AACxE,OAAI,IAAI,SACP,OAAM,IAAI,MAAM,iCAAiC;AAGlD,OAAI,CAAC,IAAI,KACR,OAAM,IAAI,MAAM,yBAAyB;GAG1C,MAAM,CAAC,EAAE,YAAY,EAAE,qBAAqB,IAAI,QAAQ,MAAM,QAAQ,IAAI;IACzE,OAAO;IACP,OAAO;IACP,OAAO;IACP,OAAO;IACP,CAAC;AAEF,SAAM,GAAG,MAAM,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;AAG3D,SAAM,SAFe,SAAS,QAAQ,IAAI,KAAY,EACpC,kBAAkB,UAAU,EAAE,MAAMC,WAAS,MAAM,CAAC,CAC/B;AAEvC,UAAO;IAAE,MAAM;IAAU,QADX,MAAM,GAAG,KAAK,SAAS,EACC;IAAM;;AAG7C,SAAO,OAAO,OAAO,gBAAgB,IAAI,EAAE,EAAE,QAAQ,CAAC"}
package/dist/web.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  //#region package.json
3
- var version = "0.2.0";
3
+ var version = "0.3.0";
4
4
 
5
5
  //#endregion
6
6
  //#region src/constants.ts
package/dist/web.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.2.0";
2
+ var version = "0.3.0";
3
3
 
4
4
  //#endregion
5
5
  //#region src/constants.ts
package/dist/web.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"web.mjs","names":["REGION_MAP: Record<FormatRegion, string>","status: number","detail: unknown","chunks: Uint8Array[]","chunks: Uint8Array<ArrayBuffer>[]","res: Response"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/web-client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.2.0\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\tisBlobLike,\n\tisWebReadable,\n\trenderUrl,\n\tresolveApiKey,\n\tresolveBaseUrl,\n\tserializeTags,\n\ttimeoutSignal\n} from './helpers'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { AssetLike, FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse } from './types'\n\nconst ASSETS_FILENAME = 'assets.zip'\nconst ASSETS_TYPE = 'application/zip'\n\n// Cancelling the reader releases a stalled read as well as its underlying source.\nasync function readStream(stream: ReadableStream<Uint8Array>, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>[]> {\n\tconst reader = stream.getReader()\n\tconst onAbort = () => void reader.cancel(signal.reason).catch(() => {})\n\tconst chunks: Uint8Array<ArrayBuffer>[] = []\n\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\n\ttry {\n\t\tif (signal.aborted) {\n\t\t\tonAbort()\n\t\t\tthrow getAbortErrorOrElse(signal)\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\t\t\tif (done) return chunks\n\t\t\tchunks.push(new Uint8Array(value))\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener('abort', onAbort)\n\t\treader.releaseLock()\n\t}\n}\n\n/** The assets archive as a Blob for native FormData. */\nasync function assetsToBlob(input: AssetLike, signal: AbortSignal): Promise<Blob> {\n\tif (isBlobLike(input)) {\n\t\treturn input.type === ASSETS_TYPE ? input : new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (input instanceof ArrayBuffer) {\n\t\treturn new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (ArrayBuffer.isView(input)) {\n\t\treturn new Blob([new Uint8Array(input)], {\n\t\t\ttype: ASSETS_TYPE\n\t\t})\n\t}\n\n\tif (isWebReadable(input)) {\n\t\treturn new Blob(await readStream(input, signal), { type: ASSETS_TYPE })\n\t}\n\n\tthrow new TypeError('Unsupported assets type. Pass a Blob, an ArrayBuffer, a Uint8Array or a ReadableStream.')\n}\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions) {\n\t\tthis.apiKey = resolveApiKey(opts?.apiKey)\n\t\tthis.baseUrl = resolveBaseUrl(opts)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\t// Include asset preparation in the timeout: native FormData needs the\n\t\t// complete Blob before the client can send the request.\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', await assetsToBlob(assets, combinedSignal), ASSETS_FILENAME)\n\t\t}\n\n\t\t// an abort that landed while the form was being built sends nothing\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\tlet res: Response\n\n\t\ttry {\n\t\t\t// Let the browser set the multipart boundary. The explicit bearer key\n\t\t\t// authenticates the request. Cookies would prevent wildcard CORS.\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t\t\t},\n\t\t\t\tbody: form,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t\tmode: 'cors'\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow await formatErrorFrom(res)\n\t\t}\n\n\t\treturn augmentResponse(res)\n\t}\n}\n"],"mappings":";cAEY;;;;ACCZ,MAAaA,aAA2C,EACvD,QAAQ,0BAGR;AAGD,MAAa,aAAa;AAE1B,MAAa,oBAAoB,sBAAsB;AAIvD,MAAa,WAAW,EACvB,SAAS,WAAW,QACpB;;;;ACdD,SAAgB,cAAc,GAAyC;AACtE,QAAO,OAAO,WAAW,mBAAmB,eAAe,KAAK,QAAQ,OAAQ,EAAU,cAAc;;AAGzG,SAAgB,WAAW,GAAmB;AAC7C,QACC,KAAK,QACL,OAAO,MAAM,YACb,OAAQ,EAAU,gBAAgB,cAClC,OAAQ,EAAU,WAAW,cAC7B,OAAQ,EAAU,SAAS,YAC3B,OAAQ,EAAU,SAAS;;;;;;;AAS7B,SAAgB,eAAe,MAAqB,oBAA6B;AAIhF,SAFC,KAAK,YAAY,KAAK,SAAS,WAAW,KAAK,UAAU,WAAc,sBAAsB,SAAS,SAExF,QAAQ,QAAQ,GAAG;;;AAInC,SAAgB,UAAU,SAAyB;AAClD,QAAO,GAAG,UAAU,WAAW;;;AAIhC,SAAgB,cAAc,MAAwB;AACrD,QAAO,KAAK,UAAU,MAAM,KAAK,IAAI,IAAI,KAAK,KAAI,MAAK,EAAE,MAAM,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC;;AAIpF,SAAgB,oCAAoC,QAA2C;AAC9F,KAAI,CAAC,OAAQ;CAGb,MAAM,OAAO,OAAO,MAAM,4BAA4B;AACtD,KAAI,MAAM;EACT,MAAM,IAAI,KAAK,GAAG,MAAM;EACxB,MAAM,IAAI,4BAA4B,KAAK,EAAE;AAC7C,MAAI,GAAG;GACN,MAAM,QAAQ,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E5F,MAAM,cAAc,OAAO,QAAQ;EACnC,MAAM,OAAO,cAAc,IAAI,OAAO;EAEtC,MAAM,OAAO,IAAI,UAAU;AAC3B,OAAK,IAAI,QAAQ,KAAK;AAEtB,MAAI,SAAS,KACZ,MAAK,IAAI,QAAQ,cAAc,QAAQ,KAAK,CAAC;EAG9C,IAAI,SAAS,SAAS;AACtB,MAAI,CAAC,UAAU,YACd,UAAS,MAAM,eAAe,KAAK,eAAe;AAGnD,MAAI,OACH,MAAK,IAAI,UAAU,MAAM,aAAa,QAAQ,eAAe,EAAE,gBAAgB;AAIhF,MAAI,eAAe,QAAS,OAAM,oBAAoB,eAAe;EAErE,IAAIC;AAEJ,MAAI;AAGH,SAAM,MAAM,MAAM,UAAU,KAAK,QAAQ,EAAE;IAC1C,QAAQ;IACR,SAAS;KACR,eAAe,UAAU,KAAK;KAC9B,mBAAmB;KACnB;IACD,MAAM;IACN,QAAQ;IACR,aAAa;IACb,MAAM;IACN,CAAC;WACM,KAAK;AACb,SAAM,oBAAoB,gBAAgB,IAAI;;AAG/C,MAAI,CAAC,IAAI,GACR,OAAM,MAAM,gBAAgB,IAAI;AAGjC,SAAO,gBAAgB,IAAI"}
1
+ {"version":3,"file":"web.mjs","names":["REGION_MAP: Record<FormatRegion, string>","status: number","detail: unknown","chunks: Uint8Array[]","chunks: Uint8Array<ArrayBuffer>[]","res: Response"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/web-client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.3.0\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\tisBlobLike,\n\tisWebReadable,\n\trenderUrl,\n\tresolveApiKey,\n\tresolveBaseUrl,\n\tserializeTags,\n\ttimeoutSignal\n} from './helpers'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { AssetLike, FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse } from './types'\n\nconst ASSETS_FILENAME = 'assets.zip'\nconst ASSETS_TYPE = 'application/zip'\n\n// Cancelling the reader releases a stalled read as well as its underlying source.\nasync function readStream(stream: ReadableStream<Uint8Array>, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>[]> {\n\tconst reader = stream.getReader()\n\tconst onAbort = () => void reader.cancel(signal.reason).catch(() => {})\n\tconst chunks: Uint8Array<ArrayBuffer>[] = []\n\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\n\ttry {\n\t\tif (signal.aborted) {\n\t\t\tonAbort()\n\t\t\tthrow getAbortErrorOrElse(signal)\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\t\t\tif (done) return chunks\n\t\t\tchunks.push(new Uint8Array(value))\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener('abort', onAbort)\n\t\treader.releaseLock()\n\t}\n}\n\n/** The assets archive as a Blob for native FormData. */\nasync function assetsToBlob(input: AssetLike, signal: AbortSignal): Promise<Blob> {\n\tif (isBlobLike(input)) {\n\t\treturn input.type === ASSETS_TYPE ? input : new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (input instanceof ArrayBuffer) {\n\t\treturn new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (ArrayBuffer.isView(input)) {\n\t\treturn new Blob([new Uint8Array(input)], {\n\t\t\ttype: ASSETS_TYPE\n\t\t})\n\t}\n\n\tif (isWebReadable(input)) {\n\t\treturn new Blob(await readStream(input, signal), { type: ASSETS_TYPE })\n\t}\n\n\tthrow new TypeError('Unsupported assets type. Pass a Blob, an ArrayBuffer, a Uint8Array or a ReadableStream.')\n}\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions) {\n\t\tthis.apiKey = resolveApiKey(opts?.apiKey)\n\t\tthis.baseUrl = resolveBaseUrl(opts)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\t// Include asset preparation in the timeout: native FormData needs the\n\t\t// complete Blob before the client can send the request.\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', await assetsToBlob(assets, combinedSignal), ASSETS_FILENAME)\n\t\t}\n\n\t\t// an abort that landed while the form was being built sends nothing\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\tlet res: Response\n\n\t\ttry {\n\t\t\t// Let the browser set the multipart boundary. The explicit bearer key\n\t\t\t// authenticates the request. Cookies would prevent wildcard CORS.\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t\t\t},\n\t\t\t\tbody: form,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t\tmode: 'cors'\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow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Q,cAAc,QAAQ,KAAK,CAAC;EAG9C,IAAI,SAAS,SAAS;AACtB,MAAI,CAAC,UAAU,YACd,UAAS,MAAM,eAAe,KAAK,eAAe;AAGnD,MAAI,OACH,MAAK,IAAI,UAAU,MAAM,aAAa,QAAQ,eAAe,EAAE,gBAAgB;AAIhF,MAAI,eAAe,QAAS,OAAM,oBAAoB,eAAe;EAErE,IAAIC;AAEJ,MAAI;AAGH,SAAM,MAAM,MAAM,UAAU,KAAK,QAAQ,EAAE;IAC1C,QAAQ;IACR,SAAS;KACR,eAAe,UAAU,KAAK;KAC9B,mBAAmB;KACnB;IACD,MAAM;IACN,QAAQ;IACR,aAAa;IACb,MAAM;IACN,CAAC;WACM,KAAK;AACb,SAAM,oBAAoB,gBAAgB,IAAI;;AAG/C,MAAI,CAAC,IAAI,GACR,OAAM,MAAM,gBAAgB,IAAI;AAGjC,SAAO,gBAAgB,IAAI"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@format.dev/client",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "description": "The JavaScript client for the Format API.",
6
6
  "author": "the format.dev developers",
@@ -54,7 +54,7 @@
54
54
  "form-data-encoder": "^4.1.0",
55
55
  "formdata-node": "^6.0.3",
56
56
  "is-stream": "^4.0.1",
57
- "@format.dev/types": "0.2.0"
57
+ "@format.dev/types": "0.3.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^24.2.1",