@koinzhang/paseo-plugin-customize 0.1.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +58 -0
  4. package/client/category-visibility.test.ts +26 -0
  5. package/client/design-tokens.test.ts +39 -0
  6. package/client/design-tokens.ts +104 -0
  7. package/client/dropdown.tsx +139 -0
  8. package/client/entries.test.ts +50 -0
  9. package/client/entries.ts +47 -0
  10. package/client/entry-row.tsx +89 -0
  11. package/client/mechanism-card.tsx +75 -0
  12. package/client/preview-pane.tsx +101 -0
  13. package/client/provider-options.test.ts +31 -0
  14. package/client/provider-options.ts +37 -0
  15. package/client/query-policy.test.ts +57 -0
  16. package/client/query-policy.ts +20 -0
  17. package/client/route.ts +29 -0
  18. package/client/selection-settings.test.ts +16 -0
  19. package/client/slash-command.test.ts +94 -0
  20. package/client/slash-command.ts +36 -0
  21. package/client/surface.tsx +332 -0
  22. package/client/ui.tsx +265 -0
  23. package/client/use-app-language.ts +28 -0
  24. package/client/web.ts +111 -0
  25. package/index.client.tsx +57 -0
  26. package/index.server.ts +13 -0
  27. package/package.json +37 -0
  28. package/paseo-plugin.json +6 -0
  29. package/server/agent-plugins.ts +41 -0
  30. package/server/compatibility.test.ts +104 -0
  31. package/server/compatibility.ts +46 -0
  32. package/server/frontmatter.ts +49 -0
  33. package/server/glob.ts +46 -0
  34. package/server/handlers.ts +193 -0
  35. package/server/jsonc.ts +40 -0
  36. package/server/mcp.ts +87 -0
  37. package/server/parsers.test.ts +92 -0
  38. package/server/providers/acp.ts +186 -0
  39. package/server/providers/claude.ts +284 -0
  40. package/server/providers/codex.ts +219 -0
  41. package/server/providers/copilot.ts +116 -0
  42. package/server/providers/cursor.ts +194 -0
  43. package/server/providers/omp.ts +263 -0
  44. package/server/providers/opencode.ts +215 -0
  45. package/server/providers/pi.ts +102 -0
  46. package/server/providers.test.ts +306 -0
  47. package/server/scan-kit.ts +368 -0
  48. package/server/scan-snapshot.test.ts +56 -0
  49. package/server/scan-snapshot.ts +58 -0
  50. package/server/skill-aliases.ts +60 -0
  51. package/server/toml.ts +240 -0
  52. package/server/yaml-lite.ts +172 -0
  53. package/shared/acp-configs.ts +107 -0
  54. package/shared/category-visibility.ts +26 -0
  55. package/shared/compatibility.ts +6 -0
  56. package/shared/contracts.ts +116 -0
  57. package/shared/i18n.ts +293 -0
  58. package/shared/mechanisms.ts +380 -0
  59. package/shared/providers.ts +27 -0
  60. package/shared/selection-settings.ts +14 -0
package/client/web.ts ADDED
@@ -0,0 +1,111 @@
1
+ // Browser-only bridge: the SDK does not expose the app language, and the host
2
+ // leaves `<html lang="en">` static. The Paseo `language` setting lives in the
3
+ // app settings blob in localStorage; keep DOM / storage access here and call it
4
+ // only on the web platform.
5
+ import { resolveAppLanguage, type AppLanguage } from "../shared/i18n.ts";
6
+ import { workspaceIdFromPath } from "./route.ts";
7
+
8
+ const APP_SETTINGS_KEY = "@paseo:app-settings";
9
+ /** Same-window writes do not fire `storage`; poll the (small) settings string. */
10
+ const POLL_MS = 1_500;
11
+
12
+ type BrowserEventTarget = {
13
+ addEventListener(type: string, listener: () => void): void;
14
+ removeEventListener(type: string, listener: () => void): void;
15
+ };
16
+ const browser = globalThis as unknown as BrowserEventTarget & {
17
+ location?: { pathname: string };
18
+ localStorage?: { getItem(key: string): string | null };
19
+ navigator?: { languages?: readonly string[]; language?: string };
20
+ document?: BrowserEventTarget;
21
+ };
22
+
23
+ function readLanguageSetting(): string | null {
24
+ try {
25
+ const raw = browser.localStorage?.getItem(APP_SETTINGS_KEY);
26
+ if (!raw) return null;
27
+ const parsed = JSON.parse(raw) as { language?: unknown };
28
+ return typeof parsed.language === "string" ? parsed.language : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ function systemLanguages(): readonly string[] {
35
+ const nav = browser.navigator;
36
+ if (!nav) return [];
37
+ if (nav.languages && nav.languages.length > 0) return nav.languages;
38
+ return nav.language ? [nav.language] : [];
39
+ }
40
+
41
+ let current: AppLanguage = "en";
42
+ let initialized = false;
43
+ const listeners = new Set<() => void>();
44
+ let stopWatching: (() => void) | null = null;
45
+
46
+ function refresh(): void {
47
+ const next = resolveAppLanguage(readLanguageSetting(), systemLanguages());
48
+ if (next === current) return;
49
+ current = next;
50
+ for (const listener of [...listeners]) listener();
51
+ }
52
+
53
+ export function readAppLanguage(): AppLanguage {
54
+ if (!initialized) {
55
+ initialized = true;
56
+ current = resolveAppLanguage(readLanguageSetting(), systemLanguages());
57
+ }
58
+ return current;
59
+ }
60
+
61
+ export function subscribeAppLanguage(onChange: () => void): () => void {
62
+ listeners.add(onChange);
63
+ if (!stopWatching) {
64
+ readAppLanguage();
65
+ const timer = setInterval(refresh, POLL_MS);
66
+ browser.addEventListener?.("storage", refresh);
67
+ browser.addEventListener?.("focus", refresh);
68
+ browser.addEventListener?.("languagechange", refresh);
69
+ browser.document?.addEventListener?.("visibilitychange", refresh);
70
+ stopWatching = () => {
71
+ clearInterval(timer);
72
+ browser.removeEventListener?.("storage", refresh);
73
+ browser.removeEventListener?.("focus", refresh);
74
+ browser.removeEventListener?.("languagechange", refresh);
75
+ browser.document?.removeEventListener?.("visibilitychange", refresh);
76
+ };
77
+ }
78
+ return () => {
79
+ listeners.delete(onChange);
80
+ if (listeners.size === 0 && stopWatching) {
81
+ stopWatching();
82
+ stopWatching = null;
83
+ }
84
+ };
85
+ }
86
+
87
+ // The sidebar surface has no workspace context, and the SDK exposes no active
88
+ // workspace. Remember the last `/workspace/<id>` route the user was on so the
89
+ // board can default to that workspace's project.
90
+ const ROUTE_POLL_MS = 500;
91
+ let lastWorkspaceId: string | null = null;
92
+
93
+ function readRoute(): void {
94
+ const id = browser.location ? workspaceIdFromPath(browser.location.pathname) : null;
95
+ if (id) lastWorkspaceId = id;
96
+ }
97
+
98
+ export function readLastWorkspaceId(): string | null {
99
+ readRoute();
100
+ return lastWorkspaceId;
101
+ }
102
+
103
+ export function trackWorkspaceRoute(): () => void {
104
+ readRoute();
105
+ const timer = setInterval(readRoute, ROUTE_POLL_MS);
106
+ browser.addEventListener?.("popstate", readRoute);
107
+ return () => {
108
+ clearInterval(timer);
109
+ browser.removeEventListener?.("popstate", readRoute);
110
+ };
111
+ }
@@ -0,0 +1,57 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { Platform } from "react-native";
3
+ import { CustomizeSurface } from "./client/surface.tsx";
4
+ import { openCustomizeFromAgent } from "./client/slash-command.ts";
5
+ import { currentAppLanguage, watchAppLanguage } from "./client/use-app-language.ts";
6
+ import { trackWorkspaceRoute } from "./client/web.ts";
7
+ import { messagesFor } from "./shared/i18n.ts";
8
+
9
+ const SURFACE_ID = "customize";
10
+
11
+ /** Command titles follow the app language; the host has no update(), so re-register on change. */
12
+ function addCommands(client: PluginClientContext): () => void {
13
+ const description = messagesFor(currentAppLanguage()).openBoard;
14
+ const removeCommandCenterItem = client.addCommandCenterItem({
15
+ id: "open-customize",
16
+ title: description,
17
+ icon: "FolderCog",
18
+ keywords: ["customize", "agents.md", "claude.md", "rules", "skills", "mcp", "instructions", "provider"],
19
+ context: "global",
20
+ onSelect({ openSurface }) {
21
+ openSurface(SURFACE_ID);
22
+ },
23
+ });
24
+ const removeSlashCommand = client.addSlashCommand({
25
+ name: "customize",
26
+ description,
27
+ argumentHint: "",
28
+ context: "agent",
29
+ onSubmit: openCustomizeFromAgent,
30
+ });
31
+ return () => {
32
+ removeSlashCommand();
33
+ removeCommandCenterItem();
34
+ };
35
+ }
36
+
37
+ export default function contribute(client: PluginClientContext) {
38
+ const stopRouteTracking = Platform.OS === "web" ? trackWorkspaceRoute() : () => {};
39
+ client.addSurface(SURFACE_ID, CustomizeSurface);
40
+ client.addSidebarItem({
41
+ id: "customize",
42
+ title: "Customize",
43
+ icon: "FolderCog",
44
+ surface: SURFACE_ID,
45
+ });
46
+
47
+ let removeCommands = addCommands(client);
48
+ const stopLanguage = watchAppLanguage(() => {
49
+ removeCommands();
50
+ removeCommands = addCommands(client);
51
+ });
52
+ return () => {
53
+ stopRouteTracking();
54
+ stopLanguage();
55
+ removeCommands();
56
+ };
57
+ }
@@ -0,0 +1,13 @@
1
+ import type { PluginServerContext } from "@getpaseo/plugin/server";
2
+ import { handleCachedScan, handleOpen, handlePreview, handleScan } from "./server/handlers.ts";
3
+ import { cachedScanRpc, openRpc, previewRpc, scanRpc } from "./shared/contracts.ts";
4
+ import { selectionSettings } from "./shared/selection-settings.ts";
5
+
6
+ export default function contribute(server: PluginServerContext) {
7
+ server.registerSettings(selectionSettings);
8
+ server.handle(scanRpc, handleScan);
9
+ server.handle(cachedScanRpc, handleCachedScan);
10
+ server.handle(previewRpc, handlePreview);
11
+ server.handle(openRpc, handleOpen);
12
+ return () => {};
13
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@koinzhang/paseo-plugin-customize",
3
+ "version": "0.1.0",
4
+ "description": "Inspect local instructions, rules, skills, MCP servers, commands, subagents, and plugins for Paseo providers.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/koinzhang/paseo-plugins.git",
10
+ "directory": "customize"
11
+ },
12
+ "files": [
13
+ "paseo-plugin.json",
14
+ "CHANGELOG.md",
15
+ "index.client.tsx",
16
+ "index.server.ts",
17
+ "client/",
18
+ "server/",
19
+ "shared/",
20
+ "LICENSE",
21
+ "README.md"
22
+ ],
23
+ "scripts": {
24
+ "typecheck": "tsc --noEmit",
25
+ "test": "node --experimental-strip-types --test server/*.test.ts client/*.test.ts"
26
+ },
27
+ "devDependencies": {
28
+ "@getpaseo/plugin": "0.9.1",
29
+ "@tanstack/react-query": "^5.90.11",
30
+ "@types/node": "^24.13.5",
31
+ "@types/react": "~19.2.0",
32
+ "react": "19.1.0",
33
+ "react-native": "0.81.5",
34
+ "typescript": "^5.9.3",
35
+ "zod": "^4.6.5"
36
+ }
37
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "id": "customize",
3
+ "requirements": {
4
+ "paseo": ">=0.9.0"
5
+ }
6
+ }
@@ -0,0 +1,41 @@
1
+ import path from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { isFile, isRecord, readJson } from "./scan-kit.ts";
4
+
5
+ const SCHEMA = /^https:\/\/agent-plugins\.org\/schemas\/((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))\/plugin\.schema\.json$/;
6
+ const NAME = /^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/;
7
+ const METADATA = ["version", "description", "homepage", "repository", "license"] as const;
8
+
9
+ export interface AgentPluginManifest {
10
+ version: string;
11
+ validation: "valid" | "unsupported";
12
+ }
13
+
14
+ /** Reads the declared version; only locally supported versions are validated. */
15
+ export function agentPluginManifest(file: string): AgentPluginManifest | null {
16
+ if (path.basename(file) !== "plugin.json" || !isFile(file)) return null;
17
+ try {
18
+ const root = realpathSync(path.dirname(file));
19
+ const relative = path.relative(root, realpathSync(file));
20
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return null;
21
+ } catch {
22
+ return null;
23
+ }
24
+ const manifest = readJson(file);
25
+ if (!isRecord(manifest) || typeof manifest.$schema !== "string") return null;
26
+ const match = SCHEMA.exec(manifest.$schema);
27
+ if (!match) return null;
28
+ const version = match[1]!;
29
+ if (version !== "1.0.0") return { version, validation: "unsupported" };
30
+ if (typeof manifest.name !== "string" || manifest.name.length > 64 || !NAME.test(manifest.name)) return null;
31
+ for (const field of METADATA) {
32
+ if (manifest[field] !== undefined && typeof manifest[field] !== "string") return null;
33
+ }
34
+ if (manifest.author !== undefined) {
35
+ if (!isRecord(manifest.author)) return null;
36
+ if (Object.entries(manifest.author).some(([key, value]) => !["name", "email", "url"].includes(key) || typeof value !== "string")) return null;
37
+ }
38
+ if (manifest.keywords !== undefined && (!Array.isArray(manifest.keywords) || manifest.keywords.some((value) => typeof value !== "string"))) return null;
39
+ // Unknown top-level fields and a non-object extensions value are ignored by §5.2.
40
+ return { version, validation: "valid" };
41
+ }
@@ -0,0 +1,104 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { DatabaseSync } from "node:sqlite";
6
+ import { test } from "node:test";
7
+ import { mechanismFor } from "../shared/mechanisms.ts";
8
+ import { cursorThirdPartySwitch, opencodeExternalSkillSwitch } from "./compatibility.ts";
9
+ import { handleCachedScan, scanProvider } from "./handlers.ts";
10
+ import { writeSnapshot } from "./scan-snapshot.ts";
11
+
12
+ function skill(root: string, name: string): string {
13
+ const directory = path.join(root, name);
14
+ mkdirSync(directory, { recursive: true });
15
+ const file = path.join(directory, "SKILL.md");
16
+ writeFileSync(file, `---\nname: ${name}\ndescription: ${name} skill\n---\n`);
17
+ return file;
18
+ }
19
+
20
+ test("physical skill aliases use native, then .agents, while distinct same-name files remain", () => {
21
+ const home = mkdtempSync(path.join(tmpdir(), "customize-alias-"));
22
+ const project = path.join(home, "project");
23
+ try {
24
+ const agents = path.join(project, ".agents", "skills");
25
+ const native = path.join(project, ".cursor", "skills");
26
+ const claude = path.join(project, ".claude", "skills");
27
+ const entity = skill(agents, "shared");
28
+ mkdirSync(path.dirname(native), { recursive: true });
29
+ mkdirSync(path.dirname(claude), { recursive: true });
30
+ symlinkSync(agents, native);
31
+ symlinkSync(agents, claude);
32
+ const distinct = skill(path.join(home, ".agents", "skills"), "shared");
33
+ const scan = () => scanProvider("cursor", project, { home, env: {}, platform: "darwin" }).filter((entry) => entry.category === "skills");
34
+ assert.deepEqual(scan().map((entry) => entry.path).sort(), [path.join(native, "shared", "SKILL.md"), distinct].sort());
35
+ rmSync(native);
36
+ assert.deepEqual(scan().map((entry) => entry.path).sort(), [entity, distinct].sort());
37
+ } finally {
38
+ rmSync(home, { recursive: true, force: true });
39
+ }
40
+ });
41
+
42
+ test("Cursor's persisted third-party switch gates external skills and updates the explanation", () => {
43
+ const home = mkdtempSync(path.join(tmpdir(), "customize-cursor-switch-"));
44
+ const project = path.join(home, "project");
45
+ const dbFile = path.join(home, "Library/Application Support/Cursor/User/globalStorage/state.vscdb");
46
+ try {
47
+ skill(path.join(project, ".cursor", "skills"), "native");
48
+ skill(path.join(project, ".claude", "skills"), "external");
49
+ assert.deepEqual(cursorThirdPartySwitch({ home, platform: "darwin" }), { enabled: true, source: "default" });
50
+ mkdirSync(path.dirname(dbFile), { recursive: true });
51
+ const db = new DatabaseSync(dbFile);
52
+ db.exec("CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT)");
53
+ db.prepare("INSERT INTO ItemTable VALUES (?, ?)").run("cursor/thirdPartyExtensibilityEnabled", "false");
54
+ db.close();
55
+ const state = cursorThirdPartySwitch({ home, platform: "darwin" });
56
+ assert.deepEqual(state, { enabled: false, source: "cursorSettings" });
57
+ const entries = scanProvider("cursor", project, { home, env: {}, platform: "darwin" });
58
+ assert.equal(entries.find((entry) => entry.name === "native")?.status, "auto");
59
+ assert.equal(entries.find((entry) => entry.name === "external")?.status, "disabled");
60
+ const mechanism = mechanismFor("cursor", "skills", state);
61
+ assert.match(mechanism.notes[0]!.en, /off/);
62
+ assert.equal(mechanism.locations.some((location) => location.path.includes(".claude")), false);
63
+ } finally {
64
+ rmSync(home, { recursive: true, force: true });
65
+ }
66
+ });
67
+
68
+ test("OpenCode external skill discovery defaults on and can be disabled by environment", () => {
69
+ const home = mkdtempSync(path.join(tmpdir(), "customize-opencode-switch-"));
70
+ const project = path.join(home, "project");
71
+ try {
72
+ skill(path.join(project, ".opencode", "skills"), "native");
73
+ skill(path.join(project, ".agents", "skills"), "shared");
74
+ assert.deepEqual(opencodeExternalSkillSwitch({}), { enabled: true });
75
+ const env = { OPENCODE_DISABLE_EXTERNAL_SKILLS: "1" };
76
+ const entries = scanProvider("opencode", project, { home, env, platform: "linux" });
77
+ assert.equal(entries.find((entry) => entry.name === "native")?.status, "auto");
78
+ assert.equal(entries.find((entry) => entry.name === "shared")?.status, "disabled");
79
+ const mechanism = mechanismFor("opencode", "skills", { enabled: false, source: "OPENCODE_DISABLE_EXTERNAL_SKILLS" });
80
+ assert.equal(mechanism.locations.some((location) => location.path.includes(".agents")), false);
81
+ } finally {
82
+ rmSync(home, { recursive: true, force: true });
83
+ }
84
+ });
85
+
86
+ test("a changed compatibility switch makes an otherwise fresh snapshot stale", () => {
87
+ const paseoHome = mkdtempSync(path.join(tmpdir(), "customize-switch-cache-"));
88
+ const originalHome = process.env.PASEO_HOME;
89
+ const originalFlag = process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS;
90
+ try {
91
+ process.env.PASEO_HOME = paseoHome;
92
+ delete process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS;
93
+ writeSnapshot({ provider: "opencode", projectRoot: null, home: homedir(), entries: [], compatibility: { enabled: true, source: "default" }, scannedAt: new Date().toISOString() });
94
+ assert.equal(handleCachedScan({ provider: "opencode", projectRoot: null }).stale, false);
95
+ process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS = "1";
96
+ assert.equal(handleCachedScan({ provider: "opencode", projectRoot: null }).stale, true);
97
+ } finally {
98
+ if (originalHome === undefined) delete process.env.PASEO_HOME;
99
+ else process.env.PASEO_HOME = originalHome;
100
+ if (originalFlag === undefined) delete process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS;
101
+ else process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS = originalFlag;
102
+ rmSync(paseoHome, { recursive: true, force: true });
103
+ }
104
+ });
@@ -0,0 +1,46 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import type { Compatibility } from "../shared/contracts.ts";
5
+ import type { ProviderId } from "../shared/providers.ts";
6
+ import { COMPATIBLE_PROVIDERS } from "../shared/compatibility.ts";
7
+ import type { ScanContext } from "./scan-kit.ts";
8
+
9
+ const truthy = (value: string | undefined) => value != null && value !== "" && value !== "0" && value.toLowerCase() !== "false";
10
+
11
+ export function opencodeExternalSkillSwitch(env: ScanContext["env"]): { enabled: boolean; disabledBy?: string } {
12
+ for (const key of ["OPENCODE_DISABLE_EXTERNAL_SKILLS", "OPENCODE_DISABLE_CLAUDE_CODE", "OPENCODE_DISABLE_CLAUDE_CODE_SKILLS"] as const) {
13
+ if (truthy(env[key])) return { enabled: false, disabledBy: key };
14
+ }
15
+ return { enabled: true };
16
+ }
17
+
18
+ /** Cursor IDE preference; absence of the key means its documented default-on behavior. */
19
+ export function cursorThirdPartySwitch(ctx: Pick<ScanContext, "home" | "platform">): Compatibility {
20
+ if (ctx.platform !== "darwin") return { enabled: null, source: "unavailable" };
21
+ const file = path.join(ctx.home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb");
22
+ if (!existsSync(file)) return { enabled: true, source: "default" };
23
+ let db: DatabaseSync | undefined;
24
+ try {
25
+ db = new DatabaseSync(file, { readOnly: true });
26
+ const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursor/thirdPartyExtensibilityEnabled") as { value?: unknown } | undefined;
27
+ if (!row) return { enabled: true, source: "default" };
28
+ if (row.value === "true") return { enabled: true, source: "cursorSettings" };
29
+ if (row.value === "false") return { enabled: false, source: "cursorSettings" };
30
+ return { enabled: null, source: "unavailable" };
31
+ } catch {
32
+ return { enabled: null, source: "unavailable" };
33
+ } finally {
34
+ db?.close();
35
+ }
36
+ }
37
+
38
+ export function compatibilityFor(provider: ProviderId, ctx: ScanContext): Compatibility | null {
39
+ if (!COMPATIBLE_PROVIDERS.has(provider)) return null;
40
+ if (provider === "cursor") return cursorThirdPartySwitch(ctx);
41
+ if (provider === "opencode") {
42
+ const flag = opencodeExternalSkillSwitch(ctx.env);
43
+ return { enabled: flag.enabled, source: flag.disabledBy ?? "default" };
44
+ }
45
+ return { enabled: true, source: "builtIn" };
46
+ }
@@ -0,0 +1,49 @@
1
+ import { parseYaml } from "./yaml-lite.ts";
2
+
3
+ export type Frontmatter = Record<string, unknown>;
4
+
5
+ /** Leading `---` YAML block; `{}` when absent or malformed. */
6
+ export function parseFrontmatter(content: string): { data: Frontmatter; body: string } {
7
+ const text = content.replace(/^\uFEFF/, "");
8
+ const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
9
+ if (!match) return { data: {}, body: text };
10
+ try {
11
+ return { data: parseYaml(match[1]!), body: text.slice(match[0].length) };
12
+ } catch {
13
+ return { data: {}, body: text.slice(match[0].length) };
14
+ }
15
+ }
16
+
17
+ export function fmString(data: Frontmatter, key: string): string | undefined {
18
+ const value = data[key];
19
+ if (typeof value === "string") return value.trim() || undefined;
20
+ if (typeof value === "number") return String(value);
21
+ return undefined;
22
+ }
23
+
24
+ /** A string or list field (globs / paths / applyTo) as display text. */
25
+ export function fmList(data: Frontmatter, key: string): string | undefined {
26
+ const value = data[key];
27
+ if (Array.isArray(value)) {
28
+ const items = value.filter((item): item is string => typeof item === "string" && item.trim() !== "");
29
+ return items.length ? items.join(", ") : undefined;
30
+ }
31
+ return fmString(data, key);
32
+ }
33
+
34
+ export function fmBool(data: Frontmatter, key: string): boolean | undefined {
35
+ const value = data[key];
36
+ if (typeof value === "boolean") return value;
37
+ if (value === "true") return true;
38
+ if (value === "false") return false;
39
+ return undefined;
40
+ }
41
+
42
+ /** First heading or non-empty line, for entries without a description. */
43
+ export function firstLine(body: string): string | undefined {
44
+ for (const raw of body.split("\n")) {
45
+ const line = raw.replace(/^#+\s*/, "").trim();
46
+ if (line) return line.length > 160 ? `${line.slice(0, 157)}…` : line;
47
+ }
48
+ return undefined;
49
+ }
package/server/glob.ts ADDED
@@ -0,0 +1,46 @@
1
+ /** Glob → RegExp: `**`, `*`, `?`, `{a,b}`, and `[...]` classes. */
2
+ export function globToRegExp(glob: string): RegExp {
3
+ let out = "";
4
+ let braces = 0;
5
+ for (let i = 0; i < glob.length; i++) {
6
+ const ch = glob[i]!;
7
+ if (ch === "*") {
8
+ if (glob[i + 1] === "*") {
9
+ const slashAfter = glob[i + 2] === "/";
10
+ out += slashAfter ? "(?:.*/)?" : ".*";
11
+ i += slashAfter ? 2 : 1;
12
+ } else {
13
+ out += "[^/]*";
14
+ }
15
+ } else if (ch === "?") {
16
+ out += "[^/]";
17
+ } else if (ch === "{") {
18
+ braces++;
19
+ out += "(?:";
20
+ } else if (ch === "}" && braces > 0) {
21
+ braces--;
22
+ out += ")";
23
+ } else if (ch === "," && braces > 0) {
24
+ out += "|";
25
+ } else if (ch === "[") {
26
+ const end = glob.indexOf("]", i + 1);
27
+ if (end < 0) {
28
+ out += "\\[";
29
+ } else {
30
+ out += `[${glob.slice(i + 1, end).replace(/^!/, "^").replace(/\\/g, "\\\\")}]`;
31
+ i = end;
32
+ }
33
+ } else {
34
+ out += /[.+^$()|\\/]/.test(ch) ? `\\${ch}` : ch;
35
+ }
36
+ }
37
+ return new RegExp(`^${out}$`);
38
+ }
39
+
40
+ export function matchGlob(glob: string, value: string): boolean {
41
+ try {
42
+ return globToRegExp(glob).test(value);
43
+ } catch {
44
+ return false;
45
+ }
46
+ }