Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
14 changes: 14 additions & 0 deletions src/bundling/compressedAssetImports.d.ts
Original file line number Diff line number Diff line change
@@ -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: `{ <locale>: deflated JSON of { <namespace>: catalog } }`. */
const packs: Record<string, string>;
export default packs;
}
93 changes: 93 additions & 0 deletions src/bundling/compressedAssets.ts
Original file line number Diff line number Diff line change
@@ -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 "<file>?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 `{ <namespace>: 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 (`<namespace>.json`), sorted. */
function catalogFiles(localeDir: string): string[] {
return readdirSync(localeDir)
.filter((file) => file.endsWith(".json"))
.sort();
}

/** Every locale except English, as `{ <locale>: { <namespace>: catalog } }`. */
export function readLocalePacks(localesDir: string): Record<string, Record<string, unknown>> {
const packs: Record<string, Record<string, unknown>> = {};
for (const locale of localeDirs(localesDir)) {
if (locale === "en") continue;
const pack: Record<string, unknown> = {};
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<string, string> = {};
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 };
},
};
}
28 changes: 13 additions & 15 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/<locale>/<namespace>.json`. A key is `<namespace>.<path>`, e.g.
* Catalogs live in `locales/<locale>/<namespace>.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 `<namespace>.<path>`, 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
Expand All @@ -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";
Expand Down Expand Up @@ -60,22 +64,16 @@ type LeafPaths<T, Prefix extends string = ""> = {
/** Every translatable key, derived from the English catalogs. */
export type MessageKey = LeafPaths<typeof en>;

const localeModules = import.meta.glob<Catalog>("./locales/*/*.json", { eager: true, import: "default" });
const catalogs: Partial<Record<Locale, Catalog>> = { en };

function buildCatalogs(): Record<string, Catalog> {
const catalogs: Record<string, Catalog> = {};
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
Expand Down Expand Up @@ -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);
Expand Down
27 changes: 27 additions & 0 deletions src/lib/compressedAsset.ts
Original file line number Diff line number Diff line change
@@ -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<T>(decode: () => T): () => T {
let value: { v: T } | undefined;
return () => {
value ??= { v: decode() };
return value.v;
};
}
9 changes: 0 additions & 9 deletions src/widget/rawJs.d.ts

This file was deleted.

30 changes: 19 additions & 11 deletions src/widget/widgetLibs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
* bundle cost (the source ships inside main.js as a string), which is why the set is
* small, opt-in, and each entry is a single self-contained UMD/IIFE build.
*
* Adding one: vendor a browser build that defines a global, import it `?raw`, add an
* entry, and document the global and its scope in the `widgets` skill.
* Adding one: vendor a browser build that defines a global, import it `?deflate` (shipped
* compressed, inflated on first use: see `bundling/compressedAssets.ts`), add an entry, and
* document the global and its scope in the `widgets` skill.
*/

import plotlySource from "plotly.js-gl3d-dist-min/plotly-gl3d.min.js?raw";
import plotlyDeflated from "plotly.js-gl3d-dist-min/plotly-gl3d.min.js?deflate";
import { inflateAsset, lazyAsset } from "../lib/compressedAsset";

export interface WidgetLib {
/** The id a widget writes under `libs:`. */
Expand All @@ -20,8 +22,19 @@ export interface WidgetLib {
displayName: string;
/** The global the inlined build defines, for the skill's documentation. */
global: string;
/** The build's source text, injected verbatim (after inline-script escaping). */
source: string;
/** The build's source text, injected verbatim (after inline-script escaping). Inflated on first read. */
readonly source: string;
}

/** A widget library whose source is inflated from its compressed form the first time it is read. */
function compressedLib(meta: Omit<WidgetLib, "source">, deflated: string): WidgetLib {
const source = lazyAsset(() => inflateAsset(deflated));
return {
...meta,
get source() {
return source();
},
};
}

/**
Expand All @@ -30,12 +43,7 @@ export interface WidgetLib {
* full bundle because it is less than half its size and covers both study plots and 3D.
*/
export const WIDGET_LIBS: Readonly<Record<string, WidgetLib>> = {
plotly: {
id: "plotly",
displayName: "Plotly",
global: "Plotly",
source: plotlySource,
},
plotly: compressedLib({ id: "plotly", displayName: "Plotly", global: "Plotly" }, plotlyDeflated),
};

/** Resolve requested ids (deduplicated, in order) to sources; unknown ids are reported, not dropped silently. */
Expand Down
50 changes: 50 additions & 0 deletions test/bundling/compressedAssets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import localePacks from "virtual:s2b-locale-packs";
import { deflateToBase64, readLocalePacks } from "../../src/bundling/compressedAssets";
import { getLocale, SUPPORTED_LOCALES, setLocale, t } from "../../src/i18n";
import { inflateAsset, lazyAsset } from "../../src/lib/compressedAsset";

const LOCALES_DIR = resolve("src/i18n/locales");

describe("compressed assets", () => {
it("round-trips text, including non-ASCII, through build-time deflate and runtime inflate", () => {
const text = "plain ascii · Кириллица · 日本語 · 한국어 · emoji 🧠\n".repeat(50);
const encoded = deflateToBase64(text);
expect(encoded).toMatch(/^[A-Za-z0-9+/]+=*$/);
expect(encoded.length).toBeLessThan(text.length);
expect(inflateAsset(encoded)).toBe(text);
expect(inflateAsset(deflateToBase64(""))).toBe("");
});

it("decodes a lazy asset once", () => {
let calls = 0;
const get = lazyAsset(() => ++calls);
expect(get()).toBe(1);
expect(get()).toBe(1);
expect(calls).toBe(1);
});

it("packs every non-English locale, and each pack inflates to that locale's catalogs", () => {
const expected = readLocalePacks(LOCALES_DIR);
const shipped = SUPPORTED_LOCALES.filter((l) => l !== "en");
expect(Object.keys(localePacks).sort()).toEqual([...shipped].sort());
expect(Object.keys(expected).sort()).toEqual([...shipped].sort());
for (const locale of shipped) expect(JSON.parse(inflateAsset(localePacks[locale]))).toEqual(expected[locale]);
});

it("translates from a compressed locale", () => {
const before = getLocale();
try {
setLocale("de");
const german = t("chat.input.placeholder");
setLocale("en");
expect(german).not.toBe(t("chat.input.placeholder"));
expect(german).toBe(
(readLocalePacks(LOCALES_DIR).de.chat as { input: { placeholder: string } }).input.placeholder,
);
} finally {
setLocale(before);
}
});
});
12 changes: 7 additions & 5 deletions test/widget/widgetLibs.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { patchVendoredLib, VENDORED_LIB_FORBIDDEN } from "../../src/widget/vendoredLibPatches";
import { resolveWidgetLibs, WIDGET_LIBS } from "../../src/widget/widgetLibs";
Expand All @@ -12,13 +13,14 @@ describe("widget libraries", () => {
expect(plotly.source).toContain("Plotly");
});

it("patches the Plotly build so no dynamic-code construct ships in main.js", () => {
// The unit-test import is the unpatched file (vitest does not run vite.config's
// plugins); the build applies exactly this function before inlining it.
const patched = patchVendoredLib(PLOTLY_PATH, WIDGET_LIBS.plotly.source);
it("patches the Plotly build so no dynamic-code construct reaches a widget frame", () => {
const original = readFileSync(PLOTLY_PATH, "utf8");
const patched = patchVendoredLib(PLOTLY_PATH, original);
for (const [, pattern] of VENDORED_LIB_FORBIDDEN) expect(patched).not.toMatch(pattern);
expect(patched).toContain("globalThis");
expect(patched.length).toBeLessThan(WIDGET_LIBS.plotly.source.length);
expect(patched.length).toBeLessThan(original.length);
// The shipped source is the compressed copy, inflated: exactly the patched text.
expect(WIDGET_LIBS.plotly.source).toBe(patched);
});

it("fails loudly when a library changes under a patch", () => {
Expand Down
Loading
Loading