diff --git a/AGENTS.md b/AGENTS.md index 423b21b5b..71a2fb574 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -164,6 +164,8 @@ August 2026; recover it from git history if useful, but do not trust it.) `vite.config.ts` outputs a CommonJS bundle as `main.js` for Obsidian. Externals: `obsidian`, `electron`, all `@codemirror/*` and `@lezer/*` (provided by host), `@sap-ai-sdk/langchain` (optional dep), and Node builtins. Dev mode emits to `build/smart-second-brain/` with sourcemaps; production wipes and emits minified to `build/prod`. +`main.js` must stay small: Obsidian Sync Standard refuses files over 5 MB and the plugin review warns past it. Large text the plugin carries but rarely reads whole ships deflated and is inflated on first use (`src/bundling/compressedAssets.ts` at build time, `lib/compressedAsset.ts` at runtime): the widget Plotly build (`?deflate` import) and every non-English locale (`virtual:s2b-locale-packs`). Put any new large embedded text on the same path rather than inlining it raw. + Tests mock `obsidian`, `electron`, and `@sap-ai-sdk/langchain` via `test/__mocks__/` aliases in `vitest.config.ts`. The unit suite uses `jsdom`, runs `pool: forks` with `fileParallelism: false` and `mockReset: true` to prevent leakage. Coverage scope is `src/providers/**` only. ## Code conventions diff --git a/bun.lock b/bun.lock index 543f6fd94..0084daf96 100644 --- a/bun.lock +++ b/bun.lock @@ -25,6 +25,7 @@ "langsmith": "^0.12.0", "leiden-ts": "^0.1.0", "minisearch": "^7.2.0", + "pako": "^1.0.11", "pdf-lib": "^1.17.1", "pixi-viewport": "^6.0.3", "pixi.js": "^8.20.1", @@ -41,6 +42,7 @@ "@tsconfig/svelte": "^5.0.8", "@types/d3-force": "^3.0.10", "@types/node": "^22", + "@types/pako": "^1.0.7", "@types/stopword": "^2.0.3", "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.5.5", @@ -340,6 +342,8 @@ "@types/node": ["@types/node@22.20.1", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="], + "@types/pako": ["@types/pako@1.0.7", "", {}, "sha512-YBtzT2ztNF6R/9+UXj2wTGFnC9NklAnASt3sC0h2m1bbH7G6FyBIkt4AN8ThZpNfxUo1b2iMVO0UawiJymEt8A=="], + "@types/stopword": ["@types/stopword@2.0.3", "", {}, "sha512-hioMj0lOvISM+EDevf7ijG8EMbU+J3pj4SstCyfQC1t39uPYpAe7beSfBdU6c1d9jeECTQQtR3UJWtVoUO8Weg=="], "@types/tern": ["@types/tern@0.23.9", "", { "dependencies": { "@types/estree": "*" } }, "sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw=="], diff --git a/package.json b/package.json index 68fe59927..94083ef7c 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "@tsconfig/svelte": "^5.0.8", "@types/d3-force": "^3.0.10", "@types/node": "^22", + "@types/pako": "^1.0.7", "@types/stopword": "^2.0.3", "@vitest/coverage-v8": "^4.1.11", "autoprefixer": "^10.5.5", @@ -70,6 +71,7 @@ "langsmith": "^0.12.0", "leiden-ts": "^0.1.0", "minisearch": "^7.2.0", + "pako": "^1.0.11", "pdf-lib": "^1.17.1", "pixi-viewport": "^6.0.3", "pixi.js": "^8.20.1", diff --git a/src/bundling/compressedAssetImports.d.ts b/src/bundling/compressedAssetImports.d.ts new file mode 100644 index 000000000..6d86680c5 --- /dev/null +++ b/src/bundling/compressedAssetImports.d.ts @@ -0,0 +1,14 @@ +/** + * Imports served by the build plugin in `bundling/compressedAssets.ts`. Both resolve to base64 + * raw-deflate text; decode with `inflateAsset` from `lib/compressedAsset.ts`. + */ +declare module "*?deflate" { + const deflated: string; + export default deflated; +} + +declare module "virtual:s2b-locale-packs" { + /** Every non-English locale: `{ : deflated JSON of { : catalog } }`. */ + const packs: Record; + export default packs; +} diff --git a/src/bundling/compressedAssets.ts b/src/bundling/compressedAssets.ts new file mode 100644 index 000000000..d017cad6a --- /dev/null +++ b/src/bundling/compressedAssets.ts @@ -0,0 +1,93 @@ +/** + * Build-time half of the compressed-asset scheme (runtime half: `lib/compressedAsset.ts`). + * + * Obsidian Sync's Standard plan refuses files over 5 MB, and the plugin-review scan warns + * when `main.js` crosses that. The two largest things in the bundle are text the plugin + * carries but rarely reads in full: the Plotly build widgets may inline, and ten non-English + * UI locales of which a user needs at most one. Both ship raw-deflated and base64-encoded, + * and are inflated on first use. Base64 rather than raw bytes because the minifier escapes + * every non-ASCII character in a string literal (`\uXXXX`, six bytes), which is also why the + * Cyrillic and CJK catalogs cost far more as JSON than their UTF-8 size suggests. + * + * Two entry points, both registered in `vite.config.ts` and `vitest.config.ts` so tests + * exercise the same decode path as the plugin: + * - `import x from "?deflate"`: one file as a deflated string. A vendored widget + * library gets its build-time patches (`widget/vendoredLibPatches.ts`) first. + * - `import packs from "virtual:s2b-locale-packs"`: every non-English locale's catalogs, + * one deflated JSON object `{ : catalog }` per locale. English stays a plain + * import: it is the fallback for every locale and the source of the key types. + * + * Build-time only (Node APIs): never import this from plugin code. + */ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { deflateRawSync } from "node:zlib"; +import type { Plugin } from "vite"; +import { patchVendoredLib, vendoredLibPatchesFor } from "../widget/vendoredLibPatches"; + +const DEFLATE_QUERY = "deflate"; +const LOCALE_PACKS_ID = "virtual:s2b-locale-packs"; +const RESOLVED_LOCALE_PACKS_ID = `\0${LOCALE_PACKS_ID}`; + +/** Deflate UTF-8 text and encode it as base64, the form `inflateAsset` reads. */ +export function deflateToBase64(text: string): string { + return deflateRawSync(Buffer.from(text, "utf8"), { level: 9 }).toString("base64"); +} + +/** Locale directory names (dotfiles and stray files such as `.DS_Store` skipped), sorted. */ +function localeDirs(localesDir: string): string[] { + return readdirSync(localesDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")) + .map((entry) => entry.name) + .sort(); +} + +/** A locale's catalog files (`.json`), sorted. */ +function catalogFiles(localeDir: string): string[] { + return readdirSync(localeDir) + .filter((file) => file.endsWith(".json")) + .sort(); +} + +/** Every locale except English, as `{ : { : catalog } }`. */ +export function readLocalePacks(localesDir: string): Record> { + const packs: Record> = {}; + for (const locale of localeDirs(localesDir)) { + if (locale === "en") continue; + const pack: Record = {}; + for (const file of catalogFiles(join(localesDir, locale))) { + pack[file.slice(0, -".json".length)] = JSON.parse(readFileSync(join(localesDir, locale, file), "utf8")); + } + packs[locale] = pack; + } + return packs; +} + +export function compressedAssets(options: { localesDir: string }): Plugin { + return { + name: "s2b-compressed-assets", + enforce: "pre", + resolveId(id) { + return id === LOCALE_PACKS_ID ? RESOLVED_LOCALE_PACKS_ID : null; + }, + load(id) { + if (id === RESOLVED_LOCALE_PACKS_ID) { + const encoded: Record = {}; + for (const [locale, pack] of Object.entries(readLocalePacks(options.localesDir))) { + encoded[locale] = deflateToBase64(JSON.stringify(pack)); + } + for (const locale of localeDirs(options.localesDir)) { + const dir = join(options.localesDir, locale); + for (const file of catalogFiles(dir)) this.addWatchFile(join(dir, file)); + } + return { code: `export default ${JSON.stringify(encoded)};`, map: null }; + } + const [path, query] = id.split("?"); + if (query !== DEFLATE_QUERY) return null; + this.addWatchFile(path); + let text = readFileSync(path, "utf8"); + if (vendoredLibPatchesFor(path)) text = patchVendoredLib(path, text); + return { code: `export default ${JSON.stringify(deflateToBase64(text))};`, map: null }; + }, + }; +} diff --git a/src/i18n/index.ts b/src/i18n/index.ts index bf05affc4..69d63d0f5 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -6,7 +6,9 @@ * and the model answers in the user's language on its own (see the `# Formatting` rule in * `agent/prompts.ts`). * - * Catalogs live in `locales//.json`. A key is `.`, e.g. + * Catalogs live in `locales//.json`. English is bundled as plain JSON; every + * other locale ships compressed (`virtual:s2b-locale-packs`, see `bundling/compressedAssets.ts`) + * and only the one in use is inflated. A key is `.`, e.g. * `t("chat.input.placeholder")`. English is the source of truth and the type of every key is * derived from it, so a typo or a key missing from `en` fails `bun run check`. Other locales may * lag behind: a key missing there falls back to English at runtime, and @@ -24,6 +26,8 @@ * language needs (Russian `one`/`few`/`many`/`other`; Japanese, Chinese and Korean only `other`). */ import { getLanguage } from "obsidian"; +import localePacks from "virtual:s2b-locale-packs"; +import { inflateAsset } from "../lib/compressedAsset"; import agents from "./locales/en/agents.json"; import common from "./locales/en/common.json"; @@ -60,22 +64,16 @@ type LeafPaths = { /** Every translatable key, derived from the English catalogs. */ export type MessageKey = LeafPaths; -const localeModules = import.meta.glob("./locales/*/*.json", { eager: true, import: "default" }); +const catalogs: Partial> = { en }; -function buildCatalogs(): Record { - const catalogs: Record = {}; - for (const [path, catalog] of Object.entries(localeModules)) { - const match = /\.\/locales\/([^/]+)\/([^/]+)\.json$/.exec(path); - if (!match) continue; - const [, locale, namespace] = match; - catalogs[locale] ??= {}; - catalogs[locale][namespace] = catalog; - } - return catalogs; +/** The catalog for `locale`, inflating its compressed pack on first use. */ +function catalogFor(locale: Locale): Catalog | undefined { + if (locale in catalogs) return catalogs[locale]; + const pack = localePacks[locale]; + catalogs[locale] = pack === undefined ? undefined : (JSON.parse(inflateAsset(pack)) as Catalog); + return catalogs[locale]; } -const catalogs = buildCatalogs(); - /** * Map an Obsidian language code onto a shipped locale: exact match, then the base language * (`pt` → `pt-BR`, `de-AT` → `de`), else English. Traditional Chinese (`zh-TW`, `zh-HK`) falls @@ -144,7 +142,7 @@ const englishRules = new Intl.PluralRules("en"); * already have rejected). */ export function t(key: MessageKey, vars?: Vars): string { - const localized = lookup(catalogs[currentLocale], key); + const localized = lookup(catalogFor(currentLocale), key); if (localized !== undefined) return interpolate(select(localized, vars, pluralRules), vars); const fallback = lookup(catalogs.en, key); if (fallback !== undefined) return interpolate(select(fallback, vars, englishRules), vars); diff --git a/src/lib/compressedAsset.ts b/src/lib/compressedAsset.ts new file mode 100644 index 000000000..508f52dfe --- /dev/null +++ b/src/lib/compressedAsset.ts @@ -0,0 +1,27 @@ +/** + * Runtime half of the compressed-asset scheme: see `bundling/compressedAssets.ts` for what is + * compressed and why. + * + * Synchronous on purpose. `t()` must answer during module evaluation and first render, long + * before anything could await a `DecompressionStream`, so this uses pako, which pdf-lib + * already brings into the bundle (the direct dependency pins the same major so it stays one + * copy). + */ +import { inflateRaw } from "pako"; + +/** Inflate a base64 raw-deflate string produced at build time back into its text. */ +export function inflateAsset(base64: string): string { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return inflateRaw(bytes, { to: "string" }); +} + +/** A value decoded from a compressed asset on first read and kept from then on. */ +export function lazyAsset(decode: () => T): () => T { + let value: { v: T } | undefined; + return () => { + value ??= { v: decode() }; + return value.v; + }; +} diff --git a/src/widget/rawJs.d.ts b/src/widget/rawJs.d.ts deleted file mode 100644 index bfee4485c..000000000 --- a/src/widget/rawJs.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Vendored browser bundles inlined into widget frames (see `widgetLibs.ts`). Imported as raw - * text and injected as an inline `