AI-native design editor. Open-source Figma alternative.
refactor(core): centralize Base64 encoding
Danila Poyarkov141564071875
diff --git a/bun.lock b/bun.lockindex 6b86ca8ba..636b694ef 100644--- a/bun.lock+++ b/bun.lock@@ -156,6 +156,7 @@"fflate": "^0.8.2","fontoxpath": "^3.34.0","fzstd": "^0.1.1",+ "js-base64": "^3.9.2","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",@@ -2157,6 +2158,8 @@"jose": ["[email protected]", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],+ "js-base64": ["[email protected]", "", {}, "sha512-6zayE8QlUdiweYI6cETD/XBSqFcoCUlufn/29PJR99r82x1yDnIprRca0YvAYpAW+ez0GuQkVBC6xG5QkD7OjA=="],+"js-sdsl": ["[email protected]", "", {}, "sha512-mifzlm2+5nZ+lEcLJMoBK0/IH/bDg8XnJfd/Wq6IP+xoCjLZsTOnV2QpxlVbX9bMnkl5PdEjNtBJ9Cj1NjifhQ=="],"js-sha3": ["[email protected]", "", {}, "sha512-BcJPCQeLg6WjEx3FE591wVAevlli8lxsxm9/FzV4HXkV49TmBH38Yvrpce6fjbADGMKFrBMGTqrVz3qPIZ88Gg=="],diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex b0a134f3f..3c3ea91fd 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -3,6 +3,7 @@ import { basename, dirname, extname, join, resolve } from 'node:path'import { defineCommand } from 'citty'+import { decodeBase64 } from '@open-pencil/core/bytes'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import type { RasterExportFormat } from '@open-pencil/core/io'import {@@ -77,7 +78,7 @@ async function exportViaApp(format: string, args: ExportArgs) {printError('Nothing to export.')process.exit(1)}- const data = Uint8Array.from(atob(result.base64), (c) => c.charCodeAt(0))+ const data = decodeBase64(result.base64)await writeAndLog(resolve(args.output ?? 'export.pdf'), data)return}@@ -93,7 +94,7 @@ async function exportViaApp(format: string, args: ExportArgs) {scale: Number(args.scale),format: format.toLowerCase()})- const data = Uint8Array.from(atob(result.base64), (c) => c.charCodeAt(0))+ const data = decodeBase64(result.base64)const ext = format.toLowerCase() === 'jpg' ? 'jpg' : format.toLowerCase()await writeAndLog(resolve(args.output ?? `export.${ext}`), data)}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 8cb75d96f..1fc4c84cf 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -125,6 +125,11 @@"import": "./dist/clipboard.js","default": "./dist/clipboard.js"},+ "./bytes": {+ "types": "./dist/bytes/index.d.ts",+ "import": "./dist/bytes/index.js",+ "default": "./dist/bytes/index.js"+ },"./constants": {"types": "./dist/constants.d.ts","import": "./dist/constants.js",@@ -178,6 +183,7 @@"fflate": "^0.8.2","fontoxpath": "^3.34.0","fzstd": "^0.1.1",+ "js-base64": "^3.9.2","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",diff --git a/packages/core/src/bytes/base64.ts b/packages/core/src/bytes/base64.tsnew file mode 100644index 000000000..b69c02f1e--- /dev/null+++ b/packages/core/src/bytes/base64.ts@@ -0,0 +1,35 @@+import {+ decode as decodeText,+ encode as encodeText,+ fromUint8Array,+ isValid,+ toUint8Array+} from 'js-base64'++export type Base64Alphabet = 'base64' | 'base64url'++function assertValidBase64(value: string): void {+ if (!isValid(value)) throw new TypeError('Invalid Base64 string')+}++/** Encode binary data without converting it through a JavaScript string. */+export function encodeBase64(bytes: Uint8Array, alphabet: Base64Alphabet = 'base64'): string {+ return fromUint8Array(bytes, alphabet === 'base64url')+}++/** Decode standard or URL-safe Base64 into binary data. */+export function decodeBase64(value: string): Uint8Array {+ assertValidBase64(value)+ return toUint8Array(value)+}++/** Encode a Unicode string as UTF-8 Base64. */+export function encodeBase64Text(value: string, alphabet: Base64Alphabet = 'base64'): string {+ return encodeText(value, alphabet === 'base64url')+}++/** Decode standard or URL-safe UTF-8 Base64 into a Unicode string. */+export function decodeBase64Text(value: string): string {+ assertValidBase64(value)+ return decodeText(value)+}diff --git a/packages/core/src/bytes/index.ts b/packages/core/src/bytes/index.tsnew file mode 100644index 000000000..1506b5daf--- /dev/null+++ b/packages/core/src/bytes/index.ts@@ -0,0 +1,7 @@+export {+ decodeBase64,+ decodeBase64Text,+ encodeBase64,+ encodeBase64Text,+ type Base64Alphabet+} from './base64'diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 5106dad42..8b7b3947d 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -2,6 +2,7 @@ import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graimport type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { SnapGuide } from '@open-pencil/scene-graph/snap'+import { decodeBase64 } from '#core/bytes'import type { ResolvedRenderColor } from '#core/color/management'/* eslint-disable max-lines -- SkiaRenderer facade owns CanvasKit state and delegates domain drawing */import {@@ -683,10 +684,7 @@ export class SkiaRenderer {if (!dataUrl.startsWith(`data:${mime}`)) return nullconst base64 = dataUrl.split(',')[1]if (!base64) return null- const binary = atob(base64)- const bytes = new Uint8Array(binary.length)- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)- return bytes+ return decodeBase64(base64)} catch (err) {console.warn('Raster encode fallback failed:', err)return nulldiff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 695b58ff8..97c9f9e37 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -12,6 +12,7 @@ import type { NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { decodeBase64, decodeBase64Text, encodeBase64, encodeBase64Text } from './bytes'import { shapeTextForClipboard } from './canvas/text/clipboard'import {sceneNodeToKiwi,@@ -44,8 +45,8 @@ export async function parseFigmaClipboard(const bufMatch = html.match(/\(figma\)(.*?)\(\/figma\)/s)if (!metaMatch || !bufMatch) return null- const meta: FigmaClipboardMeta = JSON.parse(atob(metaMatch[1]))- const binary = Uint8Array.fromBase64(bufMatch[1])+ const meta: FigmaClipboardMeta = JSON.parse(decodeBase64Text(metaMatch[1]))+ const binary = decodeBase64(bufMatch[1])try {const chunks = parseFigKiwiChunks(binary)@@ -369,14 +370,14 @@ export async function buildFigmaClipboardHTML(const dataRaw = compiled.encodeMessage(msg)const figKiwiBinary = buildFigKiwi(schemaDeflated, dataRaw)- const bufferB64 = figKiwiBinary.toBase64()+ const bufferB64 = encodeBase64(figKiwiBinary)const meta: FigmaClipboardMeta = {fileKey: 'openpencil',pasteID: msg.pasteID as number,dataType: 'scene'}- const metaB64 = btoa(JSON.stringify(meta))+ const metaB64 = encodeBase64Text(JSON.stringify(meta))return (`<meta charset='utf-8'>` +diff --git a/packages/core/src/clipboard/openpencil.ts b/packages/core/src/clipboard/openpencil.tsindex bd42f5627..c3954a3e8 100644--- a/packages/core/src/clipboard/openpencil.ts+++ b/packages/core/src/clipboard/openpencil.ts@@ -3,6 +3,8 @@ import { deflateSync, inflateSync } from 'fflate'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { JsonObject } from '@open-pencil/scene-graph/primitives'+import { decodeBase64, encodeBase64 } from '#core/bytes'+// --- Internal copy/paste (OpenPencil ↔ OpenPencil) ---export interface OpenPencilClipboardData {@@ -15,7 +17,7 @@ export function parseOpenPencilClipboard(html: string): OpenPencilClipboardDataif (!match) return nulltry {- const raw = Uint8Array.fromBase64(match[1])+ const raw = decodeBase64(match[1])let bytes: Uint8Arraytry {bytes = inflateSync(raw)@@ -29,7 +31,7 @@ export function parseOpenPencilClipboard(html: string): OpenPencilClipboardDataif (decoded.images && typeof decoded.images === 'object') {for (const [hash, b64] of Object.entries(decoded.images)) {if (typeof b64 === 'string') {- images.set(hash, Uint8Array.fromBase64(b64))+ images.set(hash, decodeBase64(b64))}}}@@ -44,7 +46,7 @@ export function parseOpenPencilClipboard(html: string): OpenPencilClipboardDatafunction restoreTextPictures(nodes: JsonObject[]): void {for (const node of nodes) {if (typeof node.textPicture === 'string') {- node.textPicture = Uint8Array.fromBase64(node.textPicture)+ node.textPicture = decodeBase64(node.textPicture)}if (Array.isArray(node.children)) {restoreTextPictures(node.children)@@ -78,7 +80,7 @@ export function buildOpenPencilClipboardHTML(const images: Record<string, string> = {}for (const hash of hashes) {const bytes = graph.images.get(hash)- if (bytes) images[hash] = bytes.toBase64()+ if (bytes) images[hash] = encodeBase64(bytes)}const data = {format: 'openpencil/v1',@@ -86,7 +88,7 @@ export function buildOpenPencilClipboardHTML(images}const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))- return `<!--(openpencil)${compressed.toBase64()}(/openpencil)-->`+ return `<!--(openpencil)${encodeBase64(compressed)}(/openpencil)-->`}function collectNodeTree(@@ -100,7 +102,7 @@ function collectNodeTree(if (node.type === 'TEXT' && node.text && textPictureBuilder) {const pic = node.textPicture ?? textPictureBuilder(node)- if (pic) serialized.textPicture = pic.toBase64()+ if (pic) serialized.textPicture = encodeBase64(pic)} else {delete serialized.textPicture}diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 029e7c279..b170982ec 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -12,6 +12,7 @@ import { computeBounds } from '@open-pencil/scene-graph/geometry'import { computeImageHash } from '@open-pencil/scene-graph/images'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'+import { decodeBase64, encodeBase64 } from '#core/bytes'import type { SkiaRenderer } from '#core/canvas'import { canMakeBooleanSourceNode } from '#core/canvas/boolean'import { flattenNodesToVectorProps } from '#core/canvas/flatten'@@ -511,11 +512,11 @@ export class FigmaAPI implements NodeProxyHost {}base64Encode(data: Uint8Array): string {- return data.toBase64()+ return encodeBase64(data)}base64Decode(data: string): Uint8Array {- return Uint8Array.fromBase64(data)+ return decodeBase64(data)}notify(message: string): { cancel: () => void } {diff --git a/packages/core/src/global.d.ts b/packages/core/src/global.d.tsindex 7eda4fa08..023d46824 100644--- a/packages/core/src/global.d.ts+++ b/packages/core/src/global.d.ts@@ -10,14 +10,6 @@ interface Window {queryLocalFonts?(): Promise<FontData[]>}-interface Uint8ArrayConstructor {- fromBase64(base64: string, options?: { alphabet?: 'base64' | 'base64url' }): Uint8Array-}--interface Uint8Array {- toBase64(options?: { alphabet?: 'base64' | 'base64url' }): string-}-declare module '*.md' {const content: stringexport default contentdiff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex a05584990..a1f692cfd 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -10,6 +10,7 @@ import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwiimport type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'import type { GUID } from '@open-pencil/scene-graph/primitives'+import { decodeBase64 } from '#core/bytes'import type { SkiaRenderer } from '#core/canvas'import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'import { renderThumbnail } from '#core/io/formats/raster'@@ -23,11 +24,8 @@ import {makeCanvasNodeChange} from '#core/kiwi/fig/node-change/serialize'-const THUMBNAIL_1X1 = Uint8Array.from(- atob(- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='- ),- (c) => c.charCodeAt(0)+const THUMBNAIL_1X1 = decodeBase64(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==')type KiwiNodeChange = NodeChange & Record<string, unknown>diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex 139b2b4b9..7bd4e1e6f 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -1,6 +1,7 @@import type { Effect, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'+import { encodeBase64 } from '#core/bytes'import { colorToHex } from '#core/color'import { colorToDisplayCss, getDefaultRenderColorSpace } from '#core/color/management'import type { RenderColorSpace } from '#core/color/management'@@ -109,7 +110,7 @@ function createImagePattern(if (!data) return nullconst id = nextDefId(ctx, 'img')- const base64 = btoa(String.fromCharCode(...data))+ const base64 = encodeBase64(data)const mime = detectImageMime(data)return {diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.tsindex 4e6865a29..67be68e90 100644--- a/packages/core/src/tools/modify/paint.ts+++ b/packages/core/src/tools/modify/paint.ts@@ -1,5 +1,6 @@import type { Matrix } from '@open-pencil/scene-graph/primitives'+import { decodeBase64 } from '#core/bytes'import { parseColor } from '#core/color'import { BLACK } from '#core/constants'import { defineTool } from '#core/tools/schema'@@ -112,7 +113,7 @@ export const setImageFill = defineTool({execute: (figma, { id, image_data, scale_mode }) => {const node = figma.getNodeById(id)if (!node) return { error: `Node "${id}" not found` }- const bytes = Uint8Array.fromBase64(image_data)+ const bytes = decodeBase64(image_data)const image = figma.createImage(bytes)const mode = (scale_mode ?? 'FILL') as 'FILL' | 'FIT' | 'CROP' | 'TILE'node.fills = [diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.tsindex d496ca7ab..dc171ef3f 100644--- a/packages/core/src/tools/vector/export.ts+++ b/packages/core/src/tools/vector/export.ts@@ -1,20 +1,7 @@+import { encodeBase64 } from '#core/bytes'import type { RasterExportFormat } from '#core/io/formats/raster'import { defineTool } from '#core/tools/schema'-const CHUNK_SIZE = 0x8000--function uint8ArrayToBase64(bytes: Uint8Array): string {- if (typeof Buffer !== 'undefined') {- return Buffer.from(bytes).toString('base64')- }- let binary = ''- for (let index = 0; index < bytes.length; index += CHUNK_SIZE) {- const chunk = bytes.subarray(index, index + CHUNK_SIZE)- binary += String.fromCharCode(...chunk)- }- return btoa(binary)-}-export const exportSvg = defineTool({name: 'export_svg',description: 'Export nodes as SVG markup. Returns the SVG string.',@@ -61,7 +48,7 @@ export const exportPdf = defineTool({args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)const data = await renderNodesToPDF(figma.graph, pageId, ids)if (!data || data.length === 0) return { error: 'No visible nodes to export' }- const base64 = uint8ArrayToBase64(data)+ const base64 = encodeBase64(data)return { mimeType: 'application/pdf', base64, byteLength: data.length }}})@@ -106,7 +93,7 @@ export const exportImage = defineTool({format})if (!data || data.length === 0) return { error: 'No visible nodes to export' }- const base64 = uint8ArrayToBase64(data)+ const base64 = encodeBase64(data)const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as constreturn {mimeType: mimeMap[format],diff --git a/packages/dom-css/src/from-scene-graph.ts b/packages/dom-css/src/from-scene-graph.tsindex b85ea2f6f..098ab5afc 100644--- a/packages/dom-css/src/from-scene-graph.ts+++ b/packages/dom-css/src/from-scene-graph.ts@@ -1,3 +1,4 @@+import { encodeBase64 } from '@open-pencil/core/bytes'import { colorToCSS } from '@open-pencil/core/color'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { BLACK } from '@open-pencil/scene-graph/constants'@@ -209,12 +210,6 @@ function styleFromTextNode(node: SceneNode): DesignStyleDeclaration {return style}-function bytesToBase64(bytes: Uint8Array): string {- let binary = ''- for (const byte of bytes) binary += String.fromCharCode(byte)- return globalThis.btoa(binary)-}-function imageSourceURL(node: SceneNode): string | undefined {return node.pluginData.find((entry) => entry.pluginId === DOM_CSS_PLUGIN_ID && entry.key === IMAGE_SOURCE_URL_KEY@@ -235,7 +230,7 @@ function attrsForNode(if (fill?.type !== 'IMAGE' || !fill.imageHash) return attrsconst bytes = graph.images.get(fill.imageHash)if (!bytes) return attrs- return { ...attrs, src: `data:image/png;base64,${bytesToBase64(bytes)}` }+ return { ...attrs, src: `data:image/png;base64,${encodeBase64(bytes)}` }}function tagNameForNode(node: SceneNode): string {diff --git a/packages/dom-css/src/html-export.ts b/packages/dom-css/src/html-export.tsindex 5d8dbb899..f05fe7135 100644--- a/packages/dom-css/src/html-export.ts+++ b/packages/dom-css/src/html-export.ts@@ -1,6 +1,7 @@import { CSSFontFaceRule } from '@acemir/cssom'import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'+import { decodeBase64 } from '@open-pencil/core/bytes'import { normalizeFontFamily } from '@open-pencil/core/text'import {exportWebFontFaceAssets,@@ -256,10 +257,6 @@ function dataImageParts(value: string): { mime: string; base64: string } | undef}}-function bytesFromBase64(value: string): Uint8Array {- return Uint8Array.from(atob(value), (char) => char.charCodeAt(0))-}-function extensionForMime(mime: string): string {if (mime === 'image/jpeg') return 'jpg'if (mime === 'image/webp') return 'webp'@@ -287,7 +284,7 @@ function extractImageAssets(}const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`sources.set(src.value, path)- files.push({ path, content: bytesFromBase64(parts.base64) })+ files.push({ path, content: decodeBase64(parts.base64) })src.value = path})return { html: serialize(fragment), files }diff --git a/packages/dom-css/src/to-scene-graph.ts b/packages/dom-css/src/to-scene-graph.tsindex 07fa01405..54b62f770 100644--- a/packages/dom-css/src/to-scene-graph.ts+++ b/packages/dom-css/src/to-scene-graph.ts@@ -1,3 +1,4 @@+import { decodeBase64 } from '@open-pencil/core/bytes'import {SceneGraph,type Fill,@@ -239,8 +240,7 @@ function bytesFromDataURL(value: string | undefined): Uint8Array | null {const metadata = value.slice(0, commaIndex)const body = value.slice(commaIndex + 1)if (!metadata.endsWith(';base64')) return null- const binary = globalThis.atob(body)- return Uint8Array.from(binary, (char) => char.charCodeAt(0))+ return decodeBase64(body)}function applyImageFill(diff --git a/packages/mcp/src/tool/output.ts b/packages/mcp/src/tool/output.tsindex cbaf77fd1..7a52e660d 100644--- a/packages/mcp/src/tool/output.ts+++ b/packages/mcp/src/tool/output.ts@@ -1,6 +1,8 @@import { lstat, mkdir, readlink, realpath, writeFile } from 'node:fs/promises'import { dirname, basename, isAbsolute, join, parse, resolve, sep as osSep } from 'node:path'+import { decodeBase64 } from '@open-pencil/core/bytes'+import { ok } from '#mcp/result'import type { MCPResult } from '#mcp/result'@@ -237,10 +239,10 @@ export async function writeToolOutput(return ok({ written: resolved, byteLength: Buffer.byteLength(result.svg, 'utf8') })}if (toolName === 'export_image' && typeof result.base64 === 'string') {- const buffer = Buffer.from(result.base64, 'base64')- await writeFile(realPath, buffer)+ const bytes = decodeBase64(result.base64)+ await writeFile(realPath, bytes)await resolveSafePath(realPath, root)- return ok({ written: resolved, byteLength: buffer.length })+ return ok({ written: resolved, byteLength: bytes.length })}if (toolName === 'get_jsx' && typeof result.jsx === 'string') {await writeFile(realPath, result.jsx, 'utf8')diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.tsindex 39eb98f88..7c760423e 100644--- a/src/app/automation/bridge/export-handlers.ts+++ b/src/app/automation/bridge/export-handlers.ts@@ -1,3 +1,4 @@+import { encodeBase64 } from '@open-pencil/core/bytes'import { selectionToJSX, sceneNodeToJSX, type RasterExportFormat } from '@open-pencil/core/io'import type { AutomationTarget } from '@/app/automation/bridge/target'@@ -13,9 +14,7 @@ export async function handleExport(target: AutomationTarget, args: unknown): Pro(exportArgs?.format ?? 'PNG') as RasterExportFormat)if (!data) throw new Error('Export failed')- let binary = ''- for (const byte of data) binary += String.fromCharCode(byte)- const base64 = btoa(binary)+ const base64 = encodeBase64(data)return {ok: true,result: { base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }diff --git a/src/app/editor/vectorize/providers.ts b/src/app/editor/vectorize/providers.tsindex 5552e0788..8e3720301 100644--- a/src/app/editor/vectorize/providers.ts+++ b/src/app/editor/vectorize/providers.ts@@ -1,3 +1,4 @@+import { encodeBase64 } from '@open-pencil/core/bytes'import { IS_TAURI } from '@open-pencil/core/constants'import { tauriFetch } from '@/app/tauri/http'@@ -15,7 +16,6 @@ const NATIVE_TIMEOUT_GRACE_MS = 1000const MAX_SVG_BYTES = 20 * 1024 * 1024const MAX_API_RESPONSE_BYTES = 1024 * 1024const MAX_IMAGE_BYTES = 5 * 1024 * 1024-const BASE64_CHUNK_SIZE = 32_768const RECRAFT_DEFINITION = {id: 'recraft',@@ -61,14 +61,6 @@ async function vectorizeFetch(}}-function bytesToBase64(bytes: Uint8Array): string {- let binary = ''- for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {- binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE))- }- return btoa(binary)-}-type VectorizeResponseRecord = {image?: unknowndata?: unknown@@ -240,7 +232,7 @@ const fal: VectorizeProvider = {Authorization: `Key ${apiKey}`,'Content-Type': 'application/json'},- body: JSON.stringify({ image_url: `data:image/png;base64,${bytesToBase64(pngBytes)}` }),+ body: JSON.stringify({ image_url: `data:image/png;base64,${encodeBase64(pngBytes)}` }),credentials: 'omit',redirect: 'error'})diff --git a/src/global.d.ts b/src/global.d.tsindex 131983748..4e32d6be7 100644--- a/src/global.d.ts+++ b/src/global.d.ts@@ -1,14 +1,6 @@export {}declare global {- interface Uint8ArrayConstructor {- fromBase64(base64: string, options?: { alphabet?: 'base64' | 'base64url' }): Uint8Array- }-- interface Uint8Array {- toBase64(options?: { alphabet?: 'base64' | 'base64url' }): string- }-interface GestureEvent extends UIEvent {scale: numberrotation: numberdiff --git a/tests/engine/bytes/base64.test.ts b/tests/engine/bytes/base64.test.tsnew file mode 100644index 000000000..4f6b8965f--- /dev/null+++ b/tests/engine/bytes/base64.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'bun:test'++import {+ decodeBase64,+ decodeBase64Text,+ encodeBase64,+ encodeBase64Text+} from '@open-pencil/core/bytes'++describe('Base64 byte helpers', () => {+ test('encode and decode empty and binary data', () => {+ expect(encodeBase64(new Uint8Array())).toBe('')++ const bytes = new Uint8Array([0, 1, 127, 128, 254, 255])+ expect(decodeBase64(encodeBase64(bytes))).toEqual(bytes)+ })++ test('encode and decode Unicode text as UTF-8', () => {+ const text = 'OpenPencil — Привет 🎨'+ expect(decodeBase64Text(encodeBase64Text(text))).toBe(text)+ })++ test('support URL-safe Base64', () => {+ const bytes = new Uint8Array([251, 255, 254])+ expect(encodeBase64(bytes, 'base64url')).toBe('-__-')+ expect(decodeBase64('-__-')).toEqual(bytes)+ })++ test('handle data larger than browser argument limits', () => {+ const bytes = Uint8Array.from({ length: 256 * 1024 }, (_, index) => index % 251)+ expect(decodeBase64(encodeBase64(bytes))).toEqual(bytes)+ })++ test('reject malformed Base64', () => {+ expect(() => decodeBase64('not%base64')).toThrow('Invalid Base64 string')+ expect(() => decodeBase64Text('%%%')).toThrow('Invalid Base64 string')+ })+})