fix(plugins): stabilize plugin integration
This commit is contained in:
1 parent
b70d6da227
commit
3d1b84831f
76 files changed
+3846
-431
No files matched your search
+5
-2
@@ -33,9 +33,12 @@ describe("ConnectionDialog service deep-link hydration", () => {
|
||||
});
|
||||
|
||||
it("keeps failed one-time connections available for error inspection and retry", () => {
|
||||
const saveStart = source.indexOf("async function save(");
|
||||
// The save path delegates one-time connects to startSavedConnection,
|
||||
// which owns the connectFailed emission for failed retries.
|
||||
const start = source.indexOf("function startSavedConnection");
|
||||
const saveStart = source.indexOf("async function save(", start);
|
||||
const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
|
||||
const saveBody = source.slice(saveStart, saveEnd);
|
||||
const saveBody = source.slice(start, saveEnd);
|
||||
|
||||
expect(saveBody).not.toContain("store.removeConnection(config.id)");
|
||||
expect(saveBody).toContain('emit("connectFailed"');
|
||||
|
||||
+2
-1
@@ -60,7 +60,7 @@ function profileSwitchHarness(selectedProfile: string, editing = false) {
|
||||
const javascript = ts.transpileModule(functionSource("onDbTypeChange"), {
|
||||
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText;
|
||||
const selectProfile = new Function("editingId", "selectedType", "resetForm", "dbCategoryForOption", "selectedDbCategory", "customDriverName", "applyProfile", "resetTestState", "resetVisibleSchemasState", `${javascript}\nreturn onDbTypeChange;`)(
|
||||
const selectProfile = new Function("editingId", "selectedType", "resetForm", "dbCategoryForOption", "selectedDbCategory", "customDriverName", "applyProfile", "resetTestState", "resetVisibleSchemasState", "parsePluginConnectionProviderOptionValue", `${javascript}\nreturn onDbTypeChange;`)(
|
||||
editingId,
|
||||
selectedType,
|
||||
resetForm,
|
||||
@@ -70,6 +70,7 @@ function profileSwitchHarness(selectedProfile: string, editing = false) {
|
||||
applyProfile,
|
||||
() => events.push("reset-test"),
|
||||
() => events.push("reset-schemas"),
|
||||
() => null,
|
||||
) as (profile: string) => void;
|
||||
|
||||
return { customDriverName, events, form, selectProfile, selectedType };
|
||||
|
||||
@@ -16,7 +16,9 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
|
||||
const javascript = ts.transpileModule(declaration!.getText(), {
|
||||
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText;
|
||||
const selectedProfile = new Function("driverProfiles", "selectedType", "form", `${javascript}\nreturn selectedProfile;`)(
|
||||
// The merged dialog checks plugin providers before the profile table; the
|
||||
// plugin branch is stubbed out so this harness pins the GBase profile path.
|
||||
const selectedProfile = new Function("driverProfiles", "selectedType", "form", "parsePluginConnectionProviderOptionValue", "selectedPluginProvider", `${javascript}\nreturn selectedProfile;`)(
|
||||
{
|
||||
mysql: { label: "MySQL" },
|
||||
gbase: { label: "南大通用 GBase 8a" },
|
||||
@@ -25,6 +27,8 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
|
||||
},
|
||||
{ value: selectedTypeValue },
|
||||
{ value: { driver_profile: driverProfile } },
|
||||
() => null,
|
||||
{ value: null },
|
||||
) as () => { label: string };
|
||||
return selectedProfile();
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
|
||||
const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
|
||||
const editorGroupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
|
||||
const groupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
|
||||
const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
|
||||
const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
|
||||
const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
|
||||
@@ -15,7 +15,10 @@ describe("plugin center integration", () => {
|
||||
expect(toolbarSource).toContain("emit('open-plugin-center')");
|
||||
expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
|
||||
expect(appSource).toContain("<PluginCenterPage");
|
||||
expect(editorGroupTabBarSource).toContain("data-plugin-center-tab");
|
||||
// The plugin center pill lives in the focused group's tab strip, like the
|
||||
// settings and driver-store special pages.
|
||||
expect(groupTabBarSource).toContain("data-plugin-center-tab");
|
||||
expect(appSource).toContain(':plugin-center-open="pluginCenterTabOpen"');
|
||||
});
|
||||
|
||||
it("keeps plugin management out of Driver Manager", () => {
|
||||
|
||||
@@ -223,6 +223,8 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
|
||||
: {}),
|
||||
...(tab.mode === "query" && tab.activeResultRunId !== undefined ? { activeResultRunId: tab.activeResultRunId } : {}),
|
||||
...(tab.mode === "query" && typeof tab.resultAutoSave === "boolean" ? { resultAutoSave: tab.resultAutoSave } : {}),
|
||||
...(tab.pluginWorkbench ? { pluginWorkbench: tab.pluginWorkbench } : {}),
|
||||
...(tab.pluginFilesystem ? { pluginFilesystem: tab.pluginFilesystem } : {}),
|
||||
...(tab.uiState ? { uiState: sanitizeTabUiState(tab.uiState) } : {}),
|
||||
...(tab.mode === "query" && tab.resultAutoSave ? { resultAutoSave: true } : {}),
|
||||
}));
|
||||
|
||||
@@ -406,6 +406,7 @@ export const setAiGlobalCustomInstructions = forward("setAiGlobalCustomInstructi
|
||||
// System
|
||||
export const listSystemFonts = forward("listSystemFonts");
|
||||
export const listSshConfigHosts = forward("listSshConfigHosts");
|
||||
export const listLocalSshKeys = forward("listLocalSshKeys");
|
||||
|
||||
// SQL File Execution
|
||||
export const previewSqlFile = forward("previewSqlFile");
|
||||
|
||||
@@ -46,6 +46,7 @@ import type {
|
||||
SavedSqlFolder,
|
||||
SavedSqlLibrary,
|
||||
SshConfigHostEntry,
|
||||
LocalSshKey,
|
||||
TunnelProfile,
|
||||
} from "@/types/database";
|
||||
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
|
||||
@@ -531,6 +532,11 @@ export async function listSshConfigHosts(): Promise<SshConfigHostEntry[]> {
|
||||
return get("/api/ssh/config-hosts");
|
||||
}
|
||||
|
||||
export async function listLocalSshKeys(): Promise<LocalSshKey[]> {
|
||||
console.warn("listLocalSshKeys: local SSH key discovery is not available in the web backend");
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function listPlugins(): Promise<InstalledPlugin[]> {
|
||||
return get("/api/plugins");
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ import type {
|
||||
SavedSqlFolder,
|
||||
SavedSqlLibrary,
|
||||
SshConfigHostEntry,
|
||||
LocalSshKey,
|
||||
TunnelProfile,
|
||||
TransactionLog,
|
||||
ExternalSqlFileVersion,
|
||||
@@ -982,6 +983,10 @@ export async function listSshConfigHosts(): Promise<SshConfigHostEntry[]> {
|
||||
return invoke("list_ssh_config_hosts");
|
||||
}
|
||||
|
||||
export async function listLocalSshKeys(): Promise<LocalSshKey[]> {
|
||||
return invoke("list_local_ssh_keys");
|
||||
}
|
||||
|
||||
export async function pendingOpenSqlFiles(): Promise<string[]> {
|
||||
return invoke("pending_open_sql_files");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PluginFormField } from "@/types/database";
|
||||
import { connectionNeedsPasswordPrompt, pluginConnectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
|
||||
|
||||
/** Mirrors the io.dbx.ssh connection-provider password/authentication fields. */
|
||||
const sshAuthFields: PluginFormField[] = [
|
||||
{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] },
|
||||
{
|
||||
key: "password",
|
||||
label: "Password",
|
||||
type: "password",
|
||||
binding: "password",
|
||||
visible_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||
required_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||
},
|
||||
];
|
||||
|
||||
describe("connectionNeedsPasswordPrompt", () => {
|
||||
it("keeps requiring a prompt for password-carrying connections with saving disabled", () => {
|
||||
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: false, password: "" } as never)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps skipping the prompt when a password is stored or saving is allowed", () => {
|
||||
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: false, password: "pw" } as never)).toBe(false);
|
||||
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: true, password: "" } as never)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pluginConnectionNeedsPasswordPrompt", () => {
|
||||
it("does not prompt for SSH key auth even with save_password disabled", () => {
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "private-key" })).toBe(false);
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "agent" })).toBe(false);
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "none" })).toBe(false);
|
||||
});
|
||||
|
||||
it("prompts when the manifest marks the password field required for the auth mode", () => {
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "password" })).toBe(true);
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "private-key-password" })).toBe(true);
|
||||
});
|
||||
|
||||
it("falls back to the manifest field default when external_config omits the condition key", () => {
|
||||
// Default "password" → the form (and this check) sees password auth as active.
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, {})).toBe(true);
|
||||
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("never prompts when the manifest declares no password-bound field", () => {
|
||||
const keyPathOnly: PluginFormField[] = [{ key: "private_key_path", label: "Key", type: "text", binding: "config" }];
|
||||
expect(pluginConnectionNeedsPasswordPrompt(keyPathOnly, { authentication: "password" })).toBe(false);
|
||||
expect(pluginConnectionNeedsPasswordPrompt([], {})).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a condition key with no value and no manifest default as unmatched", () => {
|
||||
const noDefaultAuth: PluginFormField[] = [
|
||||
{ key: "authentication", label: "Authentication", type: "select", binding: "config", options: [] },
|
||||
{
|
||||
key: "password",
|
||||
label: "Password",
|
||||
type: "password",
|
||||
binding: "password",
|
||||
visible_when: { field: "authentication", one_of: ["password"] },
|
||||
required_when: { field: "authentication", one_of: ["password"] },
|
||||
},
|
||||
];
|
||||
expect(pluginConnectionNeedsPasswordPrompt(noDefaultAuth, {})).toBe(false);
|
||||
expect(pluginConnectionNeedsPasswordPrompt(noDefaultAuth, undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("prompts when the password field is statically required", () => {
|
||||
const staticallyRequired: PluginFormField[] = [{ key: "password", label: "Password", type: "password", binding: "password", required: true }];
|
||||
expect(pluginConnectionNeedsPasswordPrompt(staticallyRequired, {})).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
import type { ConnectionConfig, PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||
import { pluginFieldIsRequired } from "@/lib/plugins/pluginFieldConditions";
|
||||
|
||||
type PasswordAuthenticationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "url_params">;
|
||||
|
||||
@@ -30,3 +31,26 @@ export function connectionUsesPasswordlessAuthentication(config: PasswordAuthent
|
||||
export function connectionNeedsPasswordPrompt(config: ConnectionConfig): boolean {
|
||||
return config.save_password === false && !config.password && !connectionUsesPasswordlessAuthentication(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Manifest-driven re-check for plugin connections. The shared prompt can only
|
||||
* collect a field bound to `password`, so it applies only when the plugin's
|
||||
* manifest marks that field required for the connection's current
|
||||
* external_config. Auth modes that do not consume a login password (e.g. SSH
|
||||
* private key / agent) declare no matching `required_when` and must connect
|
||||
* without the prompt, even when save_password is disabled and no password is
|
||||
* stored.
|
||||
*/
|
||||
export function pluginConnectionNeedsPasswordPrompt(fields: readonly PluginFormField[], externalConfig: unknown): boolean {
|
||||
const passwordFields = fields.filter((field) => field.binding === "password");
|
||||
if (!passwordFields.length) return false;
|
||||
const readValue = (key: string): PluginFormFieldValue => {
|
||||
const stored = isRecord(externalConfig) ? (externalConfig[key] as PluginFormFieldValue) : undefined;
|
||||
return stored !== undefined ? stored : fields.find((candidate) => candidate.key === key)?.default;
|
||||
};
|
||||
return passwordFields.some((field) => pluginFieldIsRequired(field, readValue));
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -124,8 +124,7 @@ export function supportsClearableQuerySchema(dbType?: DatabaseType): boolean {
|
||||
* SQL editor against a broker (issue #8415).
|
||||
*/
|
||||
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
|
||||
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "mq" && dbType !== "mqtt";
|
||||
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase";
|
||||
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "plugin" && dbType !== "mq" && dbType !== "mqtt";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -31,6 +31,45 @@ function connectionProvider(overrides: Partial<PluginConnectionProviderContribut
|
||||
}
|
||||
|
||||
describe("FrontendPluginRegistry", () => {
|
||||
it("migrates a config-bound secret on edit, preserves multiline values and removes the plaintext copy", () => {
|
||||
const provider = connectionProvider({ fields: [{ key: "key", label: "Private key", type: "textarea", binding: "secret" }] });
|
||||
const pem = "-----BEGIN PRIVATE KEY-----\nexample\n-----END PRIVATE KEY-----\n";
|
||||
const existing = buildPluginConnectionConfig("example.plugin", connectionProvider({ fields: [] }), {});
|
||||
existing.external_config = { key: pem, root: "/files" };
|
||||
const values = pluginConnectionFormValues(provider, existing);
|
||||
expect(values.key).toBe(pem);
|
||||
|
||||
const saved = buildPluginConnectionConfig("example.plugin", provider, values, existing);
|
||||
expect(saved.connection_secrets?.key).toBe(pem);
|
||||
expect(saved.external_config).toEqual({ root: "/files" });
|
||||
expect(existing.external_config).toEqual({ key: pem, root: "/files" });
|
||||
expect(pluginConnectionFormValues(provider, saved).key).toBe(pem);
|
||||
|
||||
existing.connection_secrets = { key: "newer secret" };
|
||||
expect(pluginConnectionFormValues(provider, existing).key).toBe("newer secret");
|
||||
const cleared = buildPluginConnectionConfig("example.plugin", provider, { key: "" }, existing);
|
||||
expect(cleared.connection_secrets?.key).toBeUndefined();
|
||||
expect(cleared.external_config).toEqual({ root: "/files" });
|
||||
});
|
||||
|
||||
it("round-trips automatic ports as an empty input and preserves explicit custom ports", () => {
|
||||
const provider = connectionProvider({ fields: [{ key: "port", label: "Port", type: "number", binding: "port" }] });
|
||||
const automatic = buildPluginConnectionConfig("example.plugin", provider, {});
|
||||
expect(automatic.port).toBe(0);
|
||||
expect(pluginConnectionFormValues(provider, automatic).port).toBeUndefined();
|
||||
const explicit = buildPluginConnectionConfig("example.plugin", provider, { port: 1636 });
|
||||
expect(pluginConnectionFormValues(provider, explicit).port).toBe(1636);
|
||||
});
|
||||
|
||||
it("preserves the save-password preference for plugin connections", () => {
|
||||
const provider = connectionProvider({ fields: [] });
|
||||
const defaultConfig = buildPluginConnectionConfig("example.plugin", provider, {});
|
||||
expect(defaultConfig.save_password).toBe(true);
|
||||
|
||||
const transient = buildPluginConnectionConfig("example.plugin", provider, {}, { ...defaultConfig, save_password: false });
|
||||
expect(transient.save_password).toBe(false);
|
||||
});
|
||||
|
||||
it("round-trips plugin connection provider picker values", () => {
|
||||
const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
|
||||
expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
|
||||
@@ -327,4 +366,23 @@ describe("FrontendPluginRegistry", () => {
|
||||
keepalive: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("builds from a reactive (non-structured-cloneable) existing config", () => {
|
||||
// Connection configs reach the builder through props as Vue reactive
|
||||
// proxies; structuredClone refuses them ("The object can not be cloned.").
|
||||
const provider = connectionProvider({
|
||||
id: "example.ssh",
|
||||
database_type: "ssh",
|
||||
fields: [{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] }],
|
||||
});
|
||||
const existing = {
|
||||
id: "ssh-1",
|
||||
external_config: new Proxy({ authentication: "private-key" }, {}),
|
||||
} as unknown as Parameters<typeof buildPluginConnectionConfig>[3];
|
||||
|
||||
const config = buildPluginConnectionConfig("example.plugin", provider, { authentication: "private-key" }, existing);
|
||||
|
||||
expect(config.external_config).toEqual({ authentication: "private-key" });
|
||||
expect(config.id).toBe("ssh-1");
|
||||
});
|
||||
});
|
||||
@@ -139,9 +139,12 @@ export function pluginConnectionFormValues(contribution: PluginConnectionProvide
|
||||
: binding === "database"
|
||||
? config.database
|
||||
: binding === "secret"
|
||||
? secrets[field.key]
|
||||
? (secrets[field.key] ?? externalConfig[field.key])
|
||||
: externalConfig[field.key];
|
||||
if (isPluginFormFieldValue(value)) values[field.key] = value;
|
||||
// Port 0 is the stored representation of an optional, automatic port.
|
||||
// Keep that input empty on reopen so its protocol-default hint remains visible.
|
||||
if (binding === "port" && value === 0 && field.default === undefined) delete values[field.key];
|
||||
else if (isPluginFormFieldValue(value)) values[field.key] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
@@ -172,6 +175,7 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
||||
idle_timeout_secs: existing?.idle_timeout_secs || 60,
|
||||
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
|
||||
read_only: existing?.read_only || false,
|
||||
save_password: existing?.save_password !== false,
|
||||
is_production: existing?.is_production || false,
|
||||
production_databases: existing?.production_databases || [],
|
||||
};
|
||||
@@ -182,6 +186,9 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
||||
if (value === undefined) delete externalConfig[field.key];
|
||||
else externalConfig[field.key] = value;
|
||||
} else if (binding === "secret") {
|
||||
// A plugin may migrate a formerly config-bound field to secret binding.
|
||||
// Load its legacy value above, then remove the plaintext copy on save.
|
||||
delete externalConfig[field.key];
|
||||
if (value === undefined || value === "") delete connectionSecrets[field.key];
|
||||
else connectionSecrets[field.key] = String(value);
|
||||
} else if (binding === "name") {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPluginAppearance, FALLBACK_APPEARANCE_COLORS, readAppearanceTokens } from "./pluginAppearance";
|
||||
|
||||
describe("buildPluginAppearance", () => {
|
||||
it("uses the pearl (white) fallback tokens for light and the .dark tokens for dark", () => {
|
||||
const light = buildPluginAppearance(false, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||
expect(light.colorScheme).toBe("light");
|
||||
expect(light.colors).toEqual(FALLBACK_APPEARANCE_COLORS.light);
|
||||
expect(FALLBACK_APPEARANCE_COLORS.light.background).toBe("rgb(255 255 255)");
|
||||
|
||||
const dark = buildPluginAppearance(true, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||
expect(dark.colorScheme).toBe("dark");
|
||||
expect(dark.colors).toEqual(FALLBACK_APPEARANCE_COLORS.dark);
|
||||
});
|
||||
|
||||
it("prefers live design tokens over the fallback palette", () => {
|
||||
const appearance = buildPluginAppearance(false, { background: "rgb(250 251 253)", foreground: "rgb(40 44 52)" }, { fontFamily: "Fira Code", fontSize: 14 }, "SF Pro");
|
||||
expect(appearance.colors.background).toBe("rgb(250 251 253)");
|
||||
expect(appearance.colors.foreground).toBe("rgb(40 44 52)");
|
||||
expect(appearance.colors.muted).toBe(FALLBACK_APPEARANCE_COLORS.light.muted);
|
||||
expect(appearance.terminal).toEqual({ fontFamily: "Fira Code", fontSize: 14 });
|
||||
expect(appearance.ui).toEqual({ fontFamily: "SF Pro" });
|
||||
});
|
||||
|
||||
it("omits the ui font when the host has none", () => {
|
||||
const appearance = buildPluginAppearance(true, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||
expect(appearance.ui).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns no tokens outside a browser context", () => {
|
||||
// jsdom 环境下 getComputedStyle 存在,但令牌读取不应抛错。
|
||||
expect(() => readAppearanceTokens()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// 插件沙箱外观快照:读取 DBX 根节点的设计令牌(随 .dark / 调色板类
|
||||
// 实时变化)加编辑器字体设置,组装成插件契约里的 appearance 对象,
|
||||
// 供 PluginHostBridge 在 init 下发、主题变化时实时推送。
|
||||
|
||||
export interface PluginAppearanceColors {
|
||||
background: string;
|
||||
foreground: string;
|
||||
muted: string;
|
||||
mutedForeground: string;
|
||||
accent: string;
|
||||
accentForeground: string;
|
||||
border: string;
|
||||
destructive: string;
|
||||
}
|
||||
|
||||
export interface PluginAppearance {
|
||||
colorScheme: "light" | "dark";
|
||||
colors: PluginAppearanceColors;
|
||||
terminal: { fontFamily: string; fontSize: number };
|
||||
ui?: { fontFamily: string };
|
||||
}
|
||||
|
||||
// camelCase 字段 → DBX globals.css 的 CSS 令牌名。
|
||||
const APPEARANCE_TOKENS = [
|
||||
["background", "--background"],
|
||||
["foreground", "--foreground"],
|
||||
["muted", "--muted"],
|
||||
["mutedForeground", "--muted-foreground"],
|
||||
["accent", "--accent"],
|
||||
["accentForeground", "--accent-foreground"],
|
||||
["border", "--border"],
|
||||
["destructive", "--destructive"],
|
||||
] as const;
|
||||
|
||||
// 读取失败时的兜底:与 DBX globals.css 的 :root(pearl)/.dark 规范块一致。
|
||||
export const FALLBACK_APPEARANCE_COLORS: Record<"light" | "dark", PluginAppearanceColors> = {
|
||||
light: {
|
||||
background: "rgb(255 255 255)",
|
||||
foreground: "rgb(10 10 10)",
|
||||
muted: "rgb(245 245 245)",
|
||||
mutedForeground: "rgb(115 115 115)",
|
||||
accent: "rgb(245 245 245)",
|
||||
accentForeground: "rgb(23 23 23)",
|
||||
border: "rgb(229 229 229)",
|
||||
destructive: "rgb(231 0 11)",
|
||||
},
|
||||
dark: {
|
||||
background: "rgb(19 20 22)",
|
||||
foreground: "rgb(215 215 219)",
|
||||
muted: "rgb(42 42 45)",
|
||||
mutedForeground: "rgb(151 152 157)",
|
||||
accent: "rgb(46 47 51)",
|
||||
accentForeground: "rgb(221 221 226)",
|
||||
border: "rgb(110 110 114 / 0.28)",
|
||||
destructive: "rgb(243 98 95)",
|
||||
},
|
||||
};
|
||||
|
||||
export function readAppearanceTokens(): Partial<Record<(typeof APPEARANCE_TOKENS)[number][0], string>> {
|
||||
const tokens: Record<string, string> = {};
|
||||
if (typeof window === "undefined" || typeof getComputedStyle !== "function") return tokens;
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
for (const [key, cssName] of APPEARANCE_TOKENS) {
|
||||
const value = style.getPropertyValue(cssName).trim();
|
||||
if (value) tokens[key] = value;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function buildPluginAppearance(isDark: boolean, tokens: ReturnType<typeof readAppearanceTokens>, terminal: { fontFamily: string; fontSize: number }, uiFontFamily?: string): PluginAppearance {
|
||||
const fallback = FALLBACK_APPEARANCE_COLORS[isDark ? "dark" : "light"];
|
||||
const colors = { ...fallback };
|
||||
for (const [key] of APPEARANCE_TOKENS) {
|
||||
const value = tokens[key];
|
||||
if (value) colors[key] = value;
|
||||
}
|
||||
const appearance: PluginAppearance = {
|
||||
colorScheme: isDark ? "dark" : "light",
|
||||
colors,
|
||||
terminal,
|
||||
};
|
||||
if (uiFontFamily) appearance.ui = { fontFamily: uiFontFamily };
|
||||
return appearance;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pluginFieldConditionMatches, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions";
|
||||
import type { PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||
|
||||
function field(overrides: Partial<PluginFormField>): PluginFormField {
|
||||
return { key: "demo", label: "Demo", type: "text", ...overrides } as PluginFormField;
|
||||
}
|
||||
|
||||
const readValue = (key: string) => (key === "mode" ? "custom" : undefined);
|
||||
|
||||
describe("pluginFieldConditionMatches", () => {
|
||||
it("matches a missing condition and a listed value", () => {
|
||||
expect(pluginFieldConditionMatches(undefined, undefined)).toBe(true);
|
||||
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "custom")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an unlisted or empty value", () => {
|
||||
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "direct")).toBe(false);
|
||||
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pluginFieldIsRequired", () => {
|
||||
it("honors static required", () => {
|
||||
expect(pluginFieldIsRequired(field({ required: true }), readValue)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a field without required_when as optional", () => {
|
||||
expect(pluginFieldIsRequired(field({}), readValue)).toBe(false);
|
||||
});
|
||||
|
||||
it("requires a field only while its required_when matches", () => {
|
||||
const conditional = field({ required_when: { field: "mode", one_of: ["custom"] } });
|
||||
expect(pluginFieldIsRequired(conditional, readValue)).toBe(true);
|
||||
expect(pluginFieldIsRequired(conditional, () => "direct")).toBe(false);
|
||||
expect(pluginFieldIsRequired(conditional, () => undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pluginFieldIsVisible", () => {
|
||||
it("renders fields without visible_when and gates conditional ones", () => {
|
||||
expect(pluginFieldIsVisible(field({}), readValue)).toBe(true);
|
||||
const conditional = field({ visible_when: { field: "mode", one_of: ["custom"] } });
|
||||
expect(pluginFieldIsVisible(conditional, readValue)).toBe(true);
|
||||
expect(pluginFieldIsVisible(conditional, () => "direct")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a condition dormant while its referenced sibling is hidden, even when the sibling default would match", () => {
|
||||
// kafka-shaped chain: sasl_mechanism (default PLAIN, hidden) →
|
||||
// oauth_token_source (visible only for OAUTHBEARER, defaults msk_iam) →
|
||||
// msk_region. The msk_iam default must not surface msk_region while SASL
|
||||
// is off, otherwise the dialog footer dead-locks on an unfillable field.
|
||||
const fields: Record<string, PluginFormField> = {
|
||||
security_protocol: field({ key: "security_protocol", default: "PLAINTEXT" }),
|
||||
sasl_mechanism: field({ key: "sasl_mechanism", default: "PLAIN", visible_when: { field: "security_protocol", one_of: ["SASL_PLAINTEXT", "SASL_SSL"] } }),
|
||||
oauth_token_source: field({ key: "oauth_token_source", default: "msk_iam", visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] } }),
|
||||
msk_region: field({ key: "msk_region", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] } }),
|
||||
};
|
||||
const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default;
|
||||
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
|
||||
|
||||
expect(pluginFieldIsVisible(fields.msk_region, read, resolve)).toBe(false);
|
||||
// Turning OAUTHBEARER on makes the whole chain visible again.
|
||||
const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : fields[key]?.default);
|
||||
expect(pluginFieldIsVisible(fields.oauth_token_source, readOauth, resolve)).toBe(true);
|
||||
expect(pluginFieldIsVisible(fields.msk_region, readOauth, resolve)).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores unknown condition fields and survives self-referencing cycles", () => {
|
||||
const unknown = field({ visible_when: { field: "missing", one_of: ["x"] } });
|
||||
expect(
|
||||
pluginFieldIsVisible(
|
||||
unknown,
|
||||
() => "x",
|
||||
() => undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
const selfRef = field({ key: "loop", visible_when: { field: "loop", one_of: ["x"] } });
|
||||
expect(
|
||||
pluginFieldIsVisible(
|
||||
selfRef,
|
||||
() => "x",
|
||||
(key) => (key === "loop" ? selfRef : undefined),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||
|
||||
/**
|
||||
* Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
|
||||
* Host API 1.1). A condition matches when the current value of the referenced
|
||||
* sibling field is listed in `one_of`. Missing conditions always match.
|
||||
*/
|
||||
export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, value: PluginFormFieldValue): boolean {
|
||||
if (!condition) return true;
|
||||
if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false;
|
||||
return condition.one_of.includes(String(value));
|
||||
}
|
||||
|
||||
/** Looks a sibling field up by key; returns undefined when the key is unknown. */
|
||||
export type PluginFieldResolver = (key: string) => PluginFormField | undefined;
|
||||
|
||||
/**
|
||||
* A field is rendered when its `visible_when` (if any) matches current values.
|
||||
* Conditions cascade: when the referenced sibling is itself hidden, its stored
|
||||
* or default value must not light the condition up — otherwise a nested
|
||||
* default (e.g. `oauth_token_source: "msk_iam"` while SASL is off) marks
|
||||
* grandchild fields visible and required and dead-locks the dialog footer.
|
||||
*/
|
||||
export function pluginFieldIsVisible(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField?: PluginFieldResolver): boolean {
|
||||
return pluginFieldIsVisibleCached(field, readValue, resolveField, new Set([field.key]));
|
||||
}
|
||||
|
||||
function pluginFieldIsVisibleCached(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
|
||||
const condition = field.visible_when;
|
||||
if (!condition) return true;
|
||||
if (!pluginFieldConditionMatches(condition, readValue(condition.field))) return false;
|
||||
const target = resolveField?.(condition.field);
|
||||
if (!target || seen.has(target.key)) return true;
|
||||
seen.add(target.key);
|
||||
return pluginFieldIsVisibleCached(target, readValue, resolveField, seen);
|
||||
}
|
||||
|
||||
/** Effective required = static `required` OR a matching `required_when`. */
|
||||
export function pluginFieldIsRequired(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue): boolean {
|
||||
if (field.required) return true;
|
||||
// No `required_when` means the field is simply optional: the shared
|
||||
// condition helper treats a missing condition as "always matches" (correct
|
||||
// for visibility), so it must not be consulted here — that used to mark
|
||||
// every plugin field required and dead-locked the connection footer.
|
||||
if (!field.required_when) return false;
|
||||
return pluginFieldConditionMatches(field.required_when, readValue(field.required_when.field));
|
||||
}
|
||||
+83
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { reactive, readonly } from "vue";
|
||||
import { PluginHostBridge, pluginSandboxDocument } from "./pluginHostBridge";
|
||||
import { PluginHostBridge, pluginSandboxDocument, pluginSdkSource } from "./pluginHostBridge";
|
||||
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
|
||||
|
||||
function plugin(permissions: string[] = []): InstalledPlugin {
|
||||
@@ -291,6 +291,7 @@ describe("PluginHostBridge", () => {
|
||||
expect(document).toContain("window.dbxPlugin");
|
||||
expect(document).toContain("get locale() { return locale; }");
|
||||
expect(document).toContain("openFilesystem");
|
||||
expect(document).toContain("document.dispatchEvent(new CustomEvent('dbx-plugin-env'");
|
||||
expect(document).toContain("shortcut: 'closeTab'");
|
||||
expect(document).toContain("connect-src 'none'");
|
||||
expect(document).toContain(".dbx-btn");
|
||||
@@ -340,6 +341,30 @@ describe("PluginHostBridge", () => {
|
||||
expect(closed).toContain("host.stream.chunk");
|
||||
});
|
||||
|
||||
it("pre-seeds the current theme as the sandbox first paint", () => {
|
||||
const themed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events"], { appearance: "dark", tokens: { "--color-background": "#131416", "--color-foreground": "rgb(215 215 219)" } });
|
||||
expect(themed).toContain("color-scheme: dark");
|
||||
expect(themed).toContain("--color-background: #131416");
|
||||
expect(themed).toContain("--color-foreground: rgb(215 215 219)");
|
||||
expect(themed.indexOf("<style>:root{")).toBeGreaterThan(themed.indexOf(".dbx-btn"));
|
||||
|
||||
const unthemed = pluginSandboxDocument("<html><head></head><body></body></html>");
|
||||
expect(unthemed).not.toContain("color-scheme: dark");
|
||||
expect(unthemed).not.toContain("--color-background: #131416");
|
||||
});
|
||||
|
||||
it("drops boot theme declarations that could break out of the style element", () => {
|
||||
const hostile = pluginSandboxDocument("<html><head></head><body></body></html>", [], {
|
||||
appearance: "dark",
|
||||
tokens: { "--color-background": "#131416", color: "red", "--evil": "red}</style><script>alert(1)</script>", "--empty": " " },
|
||||
});
|
||||
expect(hostile).toContain("--color-background: #131416");
|
||||
expect(hostile).not.toContain("--bad-name");
|
||||
expect(hostile).not.toContain("--evil");
|
||||
expect(hostile).not.toContain("--empty");
|
||||
expect((hostile.match(/<script\b/gi) ?? []).length).toBe(1);
|
||||
});
|
||||
|
||||
it("sends the theme in init and pushes theme updates through env messages", () => {
|
||||
const messages: unknown[] = [];
|
||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||
@@ -353,3 +378,60 @@ describe("PluginHostBridge", () => {
|
||||
expect(messages[1]).toMatchObject({ type: "env", locale: "en", theme: { appearance: "light" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin SDK source", () => {
|
||||
interface SdkWindow {
|
||||
dbxPlugin?: { invoke: (method: string, params?: unknown, options?: { timeoutMs?: number }) => Promise<unknown> };
|
||||
}
|
||||
|
||||
function loadSdk(posted: unknown[]): SdkWindow {
|
||||
const sandbox = {} as SdkWindow;
|
||||
// The SDK IIFE only touches window and the bare-global addEventListener at
|
||||
// boot; parent.postMessage is captured for later request() calls, so a
|
||||
// stub window/parent is enough here.
|
||||
new Function("window", "parent", "addEventListener", pluginSdkSource())(sandbox, { postMessage: (message: unknown) => posted.push(message) }, () => {});
|
||||
return sandbox;
|
||||
}
|
||||
|
||||
/** The SDK posts a `ready` message at boot; the first request follows it. */
|
||||
function firstRequest(posted: unknown[]): { type: string; method: string; params: { method: string; params: Record<string, unknown> } } {
|
||||
const request = posted.find((message) => (message as { type: string }).type === "request");
|
||||
if (!request) throw new Error("SDK posted no request message");
|
||||
return request as { type: string; method: string; params: { method: string; params: Record<string, unknown> } };
|
||||
}
|
||||
|
||||
it("plainifies reactive (Proxy) params before postMessage", () => {
|
||||
const posted: unknown[] = [];
|
||||
const { dbxPlugin } = loadSdk(posted);
|
||||
expect(dbxPlugin).toBeDefined();
|
||||
|
||||
// Vue reactive arrays/objects are Proxies; structured clone rejects them
|
||||
// with "The object can not be cloned." (WebKit wording) — the SDK must
|
||||
// recover the plain data before crossing the postMessage boundary.
|
||||
const reactive: string[] = ["session-a", "session-b"];
|
||||
const proxy = new Proxy(reactive, {});
|
||||
|
||||
void dbxPlugin!.invoke("ssh/terminal/batchInput", { sessionIds: proxy, command: "ls -la" });
|
||||
|
||||
const message = firstRequest(posted);
|
||||
expect(message.method).toBe("backend.invoke");
|
||||
expect(message.params.params).toEqual({ sessionIds: ["session-a", "session-b"], command: "ls -la" });
|
||||
// The posted sessionIds must not be the incoming Proxy itself.
|
||||
expect(message.params.params.sessionIds).not.toBe(proxy);
|
||||
expect(JSON.stringify(message.params.params.sessionIds)).toBe(JSON.stringify(["session-a", "session-b"]));
|
||||
});
|
||||
|
||||
it("keeps cloneable values intact and plain scalars by reference", () => {
|
||||
const posted: unknown[] = [];
|
||||
const { dbxPlugin } = loadSdk(posted);
|
||||
|
||||
const stamp = new Date("2026-09-06T00:00:00Z");
|
||||
void dbxPlugin!.invoke("sample/hello", { count: 3, stamp, nested: new Map([["k", "v"]]) });
|
||||
|
||||
const params = firstRequest(posted).params.params as { count: number; stamp: Date; nested: Map<string, string> };
|
||||
// structuredClone path: cloneable types keep their identity class.
|
||||
expect(params.count).toBe(3);
|
||||
expect(params.stamp).toBeInstanceOf(Date);
|
||||
expect(params.nested).toBeInstanceOf(Map);
|
||||
});
|
||||
});
|
||||
@@ -221,18 +221,36 @@ export function pluginSandboxDocument(html: string, permissions?: readonly strin
|
||||
const networkOrigins = pluginNetworkOrigins(permissions);
|
||||
const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
|
||||
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; ${connectSrc} media-src data: blob:;">`;
|
||||
const sdk = `<script>${pluginSdkSource()}</script>`;
|
||||
const sdk = `<script>${pluginSdkSource(theme)}</script>`;
|
||||
const uiKit = `<style>${pluginUiKitCss()}</style>`;
|
||||
const themeBootstrap = pluginThemeBootstrap(theme);
|
||||
const injection = `${csp}${uiKit}${themeBootstrap}${sdk}`;
|
||||
// Placed after the uiKit so the boot `color-scheme` wins the cascade: the
|
||||
// bridge init message (and the SDK's applyTheme) only runs once the iframe
|
||||
// has loaded, and the uiKit's token fallbacks would otherwise paint the
|
||||
// first frame white on dark hosts.
|
||||
const bootTheme = pluginBootThemeCss(theme);
|
||||
const injection = `${csp}${uiKit}${bootTheme ? `<style>${bootTheme}</style>` : ""}${sdk}`;
|
||||
if (/<head(?:\s[^>]*)?>/i.test(html)) return html.replace(/<head(?:\s[^>]*)?>/i, (head) => `${head}${injection}`);
|
||||
return `<!doctype html><html><head>${injection}</head><body>${html}</body></html>`;
|
||||
}
|
||||
|
||||
function pluginThemeBootstrap(theme?: PluginBridgeTheme): string {
|
||||
if (!theme) return "";
|
||||
const serializedTheme = JSON.stringify(theme).replace(/</g, "\\u003c");
|
||||
return `<script>(() => { const theme = ${serializedTheme}; const root = document.documentElement; root.dataset.dbxTheme = theme.appearance === "dark" ? "dark" : "light"; root.style.colorScheme = theme.appearance === "dark" ? "dark" : "light"; for (const [name, value] of Object.entries(theme.tokens || {})) { if (/^--[a-z0-9-]+$/i.test(name) && typeof value === "string") root.style.setProperty(name, value); } })();</script>`;
|
||||
/**
|
||||
* Pre-paint theme seed for the sandbox document. The bridge init message only
|
||||
* arrives after the iframe load event, so without this style the first frame
|
||||
* renders with the uiKit fallbacks (white background) before the real tokens
|
||||
* land — the white flash when opening a plugin workbench on a dark host.
|
||||
*/
|
||||
export function pluginBootThemeCss(theme?: PluginBridgeTheme): string {
|
||||
if (!theme || (theme.appearance !== "dark" && theme.appearance !== "light")) return "";
|
||||
const declarations: string[] = [`color-scheme: ${theme.appearance}`];
|
||||
const tokens = theme.tokens && typeof theme.tokens === "object" ? theme.tokens : {};
|
||||
for (const [name, value] of Object.entries(tokens)) {
|
||||
// Same name validation as the SDK's applyTheme; values must stay inside a
|
||||
// single CSS declaration so they cannot break out of the style element.
|
||||
if (!/^--[a-z0-9-]+$/i.test(name) || typeof value !== "string" || !value.trim()) continue;
|
||||
if (!/^[^"{}<>;]*$/.test(value)) continue;
|
||||
declarations.push(`${name}: ${value}`);
|
||||
}
|
||||
return `:root{${declarations.join(";")}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,7 +329,14 @@ body {
|
||||
`.trim();
|
||||
}
|
||||
|
||||
function pluginSdkSource(): string {
|
||||
export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
|
||||
const safeTokens = Object.fromEntries(Object.entries(initialTheme?.tokens || {}).filter(([name, value]) => /^--[a-z0-9-]+$/i.test(name) && typeof value === "string" && !!value.trim() && /^[^"{}<>;]*$/.test(value)));
|
||||
const safeInitialTheme = initialTheme && (initialTheme.appearance === "dark" || initialTheme.appearance === "light") ? { appearance: initialTheme.appearance, tokens: safeTokens } : null;
|
||||
const serializedInitialTheme = JSON.stringify(safeInitialTheme)
|
||||
.replace(/</g, "\\u003c")
|
||||
.replace(/>/g, "\\u003e")
|
||||
.replace(/\u2028/g, "\\u2028")
|
||||
.replace(/\u2029/g, "\\u2029");
|
||||
return `(() => {
|
||||
const pending = new Map();
|
||||
const listeners = { event: new Set(), binary: new Set(), init: new Set(), context: new Set() };
|
||||
@@ -320,21 +345,37 @@ function pluginSdkSource(): string {
|
||||
let locale = 'en';
|
||||
let theme;
|
||||
let resolveReady;
|
||||
const initialTheme = ${serializedInitialTheme};
|
||||
const applyTheme = (value) => {
|
||||
if (!value || typeof value !== 'object') return;
|
||||
theme = value;
|
||||
const theme = value;
|
||||
const root = document.documentElement;
|
||||
root.dataset.dbxTheme = value.appearance === 'dark' ? 'dark' : 'light';
|
||||
root.dataset.dbxTheme = theme.appearance === "dark" ? "dark" : "light";
|
||||
root.style.colorScheme = theme.appearance === "dark" ? "dark" : "light";
|
||||
const tokens = value.tokens && typeof value.tokens === 'object' ? value.tokens : {};
|
||||
for (const [name, tokenValue] of Object.entries(tokens)) {
|
||||
if (/^--[a-z0-9-]+$/i.test(name) && typeof tokenValue === 'string') root.style.setProperty(name, tokenValue);
|
||||
}
|
||||
};
|
||||
const ready = new Promise((resolve) => { resolveReady = resolve; });
|
||||
if (initialTheme) applyTheme(initialTheme);
|
||||
// Plugin UIs routinely hand reactive state (Vue Proxy arrays/objects)
|
||||
// straight to invoke(); postMessage cannot structured-clone a Proxy and
|
||||
// WebKit rejects with "The object can not be cloned.". Mirror the host's
|
||||
// structuredCloneSafe: clone when possible, otherwise recover the plain
|
||||
// data with a JSON round-trip (the sidecar transport is JSON anyway).
|
||||
const toPlain = (value) => {
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if (typeof structuredClone === 'function') {
|
||||
try { return structuredClone(value); } catch {}
|
||||
}
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
};
|
||||
const request = (method, params, options = {}) => new Promise((resolve, reject) => {
|
||||
const id = String(++sequence);
|
||||
pending.set(id, { resolve, reject });
|
||||
const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params };
|
||||
const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params: toPlain(params) };
|
||||
if (options.transfer) {
|
||||
message.data = options.transfer;
|
||||
parent.postMessage(message, '*', [options.transfer]);
|
||||
@@ -369,14 +410,14 @@ function pluginSdkSource(): string {
|
||||
return;
|
||||
}
|
||||
removeListener?.();
|
||||
removeListener = undefined;
|
||||
if (message.method === 'host.stream.error') {
|
||||
removeListener = undefined;
|
||||
if (message.method === 'host.stream.error') {
|
||||
const error = new Error(event.message || 'Plugin stream failed');
|
||||
rejectOpen(error);
|
||||
controller.error(error);
|
||||
} else {
|
||||
Object.assign(metadata, event);
|
||||
controller.close();
|
||||
} else {
|
||||
Object.assign(metadata, event);
|
||||
controller.close();
|
||||
}
|
||||
};
|
||||
removeListener = () => listeners.event.delete(onEvent);
|
||||
@@ -441,23 +482,26 @@ function pluginSdkSource(): string {
|
||||
applyTheme(message.theme);
|
||||
resolveReady(context);
|
||||
listeners.init.forEach((listener) => listener(context));
|
||||
dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
|
||||
// Plugin listeners register on the document (onHostThemeChange);
|
||||
// bare dispatchEvent targets window, which document listeners never
|
||||
// receive — env theme pushes were silently lost.
|
||||
document.dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
|
||||
} else if (message.type === 'context') {
|
||||
context = message.context;
|
||||
listeners.context.forEach((listener) => listener(context));
|
||||
dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
|
||||
document.dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
|
||||
} else if (message.type === 'env') {
|
||||
if (typeof message.locale === 'string') locale = message.locale;
|
||||
if (message.theme) applyTheme(message.theme);
|
||||
listeners.event.forEach((listener) => listener(message));
|
||||
dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
|
||||
document.dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
|
||||
} else if (message.type === 'event') {
|
||||
listeners.event.forEach((listener) => listener(message));
|
||||
dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
|
||||
document.dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
|
||||
} else if (message.type === 'binary') {
|
||||
const payload = { channel: message.channel, data: message.data ? new Uint8Array(message.data) : new Uint8Array(0) };
|
||||
listeners.binary.forEach((listener) => listener(payload));
|
||||
dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
|
||||
document.dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
|
||||
}
|
||||
});
|
||||
addEventListener('keydown', (event) => {
|
||||
|
||||
Reference in new issue
Block a user