diff --git a/application/app/startupBundle.architecture.test.ts b/application/app/startupBundle.architecture.test.ts index d95939fbc..1f1c6d98f 100644 --- a/application/app/startupBundle.architecture.test.ts +++ b/application/app/startupBundle.architecture.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; import test from 'node:test'; import { fileURLToPath } from 'node:url'; @@ -11,6 +11,83 @@ const read = (path: string) => readFileSync(join(root, path), 'utf8'); const staticImports = (source: string) => [...source.matchAll(/^\s*import\s+(?!type\b)[^;]*?from\s+['"]([^'"]+)['"]/gm)].map((match) => match[1]); +const STATIC_SPECIFIER_RE = + /(?:^|\n)\s*(?:import\s+(?!type\b)(?:[^;'"]*?\s+from\s+)?|export\s+(?!type\b)[^;'"]*?\s+from\s+)['"]([^'"]+)['"]/g; +const CJS_REQUIRE_RE = /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g; + +function extractStaticModuleSpecifiers(filePath: string, source: string): string[] { + const specs: string[] = []; + for (const match of source.matchAll(STATIC_SPECIFIER_RE)) { + specs.push(match[1]); + } + if (filePath.endsWith('.cjs')) { + for (const match of source.matchAll(CJS_REQUIRE_RE)) { + specs.push(match[1]); + } + } + return specs; +} + +function resolveLocalModule(fromFile: string, specifier: string): string | null { + let base: string | null = null; + if (specifier.startsWith('@/')) { + base = join(root, specifier.slice(2)); + } else if (specifier.startsWith('.')) { + base = resolve(dirname(fromFile), specifier); + } + if (!base) return null; + + const candidates = [ + base, + `${base}.ts`, + `${base}.tsx`, + `${base}.js`, + `${base}.jsx`, + `${base}.mjs`, + `${base}.cjs`, + join(base, 'index.ts'), + join(base, 'index.tsx'), + join(base, 'index.js'), + join(base, 'index.jsx'), + ]; + for (const candidate of candidates) { + if (existsSync(candidate) && statSync(candidate).isFile()) { + return candidate; + } + } + return null; +} + +function collectStartupExternalDependencies(entryRelativePath: string): Map { + const entryAbs = join(root, entryRelativePath); + const visited = new Set([entryAbs]); + const parentChain = new Map([[entryAbs, [entryRelativePath]]]); + const externalPaths = new Map(); + const queue: string[] = [entryAbs]; + + while (queue.length > 0) { + const current = queue.shift()!; + const source = readFileSync(current, 'utf8'); + const chain = parentChain.get(current)!; + + for (const specifier of extractStaticModuleSpecifiers(current, source)) { + if (specifier.startsWith('.') || specifier.startsWith('@/')) { + const resolved = resolveLocalModule(current, specifier); + if (resolved && !visited.has(resolved)) { + visited.add(resolved); + parentChain.set(resolved, [...chain, relative(root, resolved)]); + queue.push(resolved); + } + continue; + } + if (!externalPaths.has(specifier)) { + externalPaths.set(specifier, [...chain, specifier]); + } + } + } + return externalPaths; +} + test('only the English dictionary is bundled with the startup entry', () => { const imports = staticImports(read('application/i18n/messages.ts')); assert.deepEqual(imports.filter((path) => path.startsWith('./locales/')), ['./locales/en']); @@ -34,6 +111,27 @@ test("Vite's preload helper stays out of the vendor-ai chunk", () => { assert.match(read('vite.config.ts'), /vite\/preload-helper'\)\) return 'preload-helper'/); }); -test('the QR decoder is loaded on demand', () => { - assert.ok(!staticImports(read('components/HostTotpFields.tsx')).includes('jsqr')); +test('the QR decoder and RE2JS regex validator are loaded on demand', () => { + const imports = staticImports(read('components/HostTotpFields.tsx')); + assert.ok(!imports.includes('jsqr')); + assert.ok(!imports.includes('re2js')); +}); + +test('startup entry does not statically reach re2js, css-tree, @remote-dom/core, or @monaco-editor/react', () => { + const externals = collectStartupExternalDependencies('index.tsx'); + const forbidden = [ + { label: 're2js', match: (spec: string) => spec === 're2js' || spec.startsWith('re2js/') }, + { label: 'css-tree', match: (spec: string) => spec === 'css-tree' || spec.startsWith('css-tree/') }, + { label: '@remote-dom/core', match: (spec: string) => spec === '@remote-dom/core' || spec.startsWith('@remote-dom/core/') }, + { label: '@monaco-editor/react', match: (spec: string) => spec === '@monaco-editor/react' || spec.startsWith('@monaco-editor/react/') }, + ]; + + for (const rule of forbidden) { + const matchEntry = [...externals.entries()].find(([spec]) => rule.match(spec)); + assert.equal( + matchEntry, + undefined, + `${rule.label} must not be statically reachable from index.tsx (found via ${matchEntry?.[1].join(' -> ')})`, + ); + } }); diff --git a/application/state/pluginViewSession.ts b/application/state/pluginViewSession.ts index f42db0a4d..991c74cd1 100644 --- a/application/state/pluginViewSession.ts +++ b/application/state/pluginViewSession.ts @@ -1,4 +1,5 @@ import { createPluginRemoteTree } from './pluginRemoteTree'; +import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry'; import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs'; import type { HostDrawnViewEvent } from '@netcatty/plugin-contract'; @@ -76,3 +77,4 @@ export class PluginViewSessions { dispose() { for (const session of [...this.sessions.values()]) session.dispose(); } } export const pluginViewSessions = new PluginViewSessions(); +registerLoadedPluginViewSessions(pluginViewSessions); diff --git a/application/state/pluginViewSessionRegistry.ts b/application/state/pluginViewSessionRegistry.ts new file mode 100644 index 000000000..0825a2b40 --- /dev/null +++ b/application/state/pluginViewSessionRegistry.ts @@ -0,0 +1,18 @@ +type CloseablePluginViewSessions = { + closeView(viewId: string): void; +}; + +let loadedSessions: CloseablePluginViewSessions | null = null; + +/** + * Registers the live PluginViewSessions singleton once the lazy host-drawn + * plugin view bundle loads, so startup lifecycle hooks can close views without + * statically importing css-tree / @remote-dom/core. + */ +export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSessions): void { + loadedSessions = sessions; +} + +export function closePluginViewSessionIfLoaded(viewId: string): void { + loadedSessions?.closeView(viewId); +} diff --git a/application/state/usePluginViewLifecycle.ts b/application/state/usePluginViewLifecycle.ts index 668f9bcac..96438fa7f 100644 --- a/application/state/usePluginViewLifecycle.ts +++ b/application/state/usePluginViewLifecycle.ts @@ -18,7 +18,7 @@ import { resolvePluginViewSnapshotSelection, type PluginViewSnapshotSelection, } from './pluginViewLifecycle'; -import { pluginViewSessions } from './pluginViewSession'; +import { closePluginViewSessionIfLoaded } from './pluginViewSessionRegistry'; import { usePluginContributions } from './usePluginContributions'; export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view'; @@ -161,13 +161,13 @@ export function usePluginViewLifecycle({ }, [activeView, requested]); useEffect(() => { - const stop = pluginViewTabStore.onDidClose(({ tab }) => pluginViewSessions.closeView(tab.viewId)); + const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId)); return () => { stop(); }; }, []); const close = useCallback(async () => { setRequested(null); - if (activeView) pluginViewSessions.closeView(activeView.view.id); + if (activeView) closePluginViewSessionIfLoaded(activeView.view.id); // An overlay can be requested while a different plugin tab stays active. // Dismissing that overlay must not close the tab underneath it. if (activeView?.view.location === 'tab' && activePluginTab?.viewId === activeView.view.id) { diff --git a/components/HostTotpFields.test.tsx b/components/HostTotpFields.test.tsx index fcdafe015..42e0c330d 100644 --- a/components/HostTotpFields.test.tsx +++ b/components/HostTotpFields.test.tsx @@ -93,6 +93,24 @@ test("host totp setup stays on the shared setting row and opens a dialog", async const passwordAt = sections.indexOf("hostDetails.password.placeholder"); const totpAt = sections.indexOf(" 0 && totpAt > passwordAt); + + // Custom prompt pattern validation loads re2js on demand and rejects invalid patterns. + const patternInput = dom.window.document.getElementById("host-totp-pattern") as HTMLInputElement | null; + assert.ok(patternInput); + const valueSetter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, "value")?.set; + assert.ok(valueSetter); + await act(async () => { + valueSetter.call(patternInput, "[unclosed"); + patternInput.dispatchEvent(new dom.window.Event("input", { bubbles: true })); + }); + const saveButton = [...dom.window.document.querySelectorAll("button")] + .find((node) => node.textContent?.includes("common.save")); + assert.ok(saveButton); + await act(async () => { + saveButton.click(); + await new Promise((resolve) => setTimeout(resolve, 30)); + }); + assert.ok(dom.window.document.body.textContent?.includes("hostDetails.totp.error.pattern")); } finally { await act(async () => { root.unmount(); }); await new Promise((resolve) => setTimeout(resolve, 50)); diff --git a/components/HostTotpFields.tsx b/components/HostTotpFields.tsx index e8ba6fb27..c647ca916 100644 --- a/components/HostTotpFields.tsx +++ b/components/HostTotpFields.tsx @@ -1,5 +1,4 @@ import React, { useEffect, useRef, useState } from "react"; -import { RE2JS } from "re2js"; import type { Host, HostTotpConfig } from "../domain/models"; import { netcattyBridge } from "@/infrastructure/services/netcattyBridge.ts"; import { Button } from "./ui/button"; @@ -77,11 +76,14 @@ async function decodeQrFile(file: File): Promise { } } -function validPattern(value: string): string | null { +async function validPattern(value: string): Promise { const trimmed = value.trim(); if (!trimmed) return ""; if (trimmed.length > 200) return null; try { + // Loaded on demand: RE2JS is only needed when validating a custom TOTP prompt + // regex, while the host editor is part of the startup bundle. + const { RE2JS } = await import("re2js"); RE2JS.compile(trimmed); return trimmed; } catch { @@ -259,7 +261,8 @@ export const HostTotpFields: React.FC = ({ const commitSetup = async (options?: { requireSecret?: boolean }): Promise => { const expectedHostId = hostIdRef.current; - const patternValue = validPattern(patternRef.current); + const patternValue = await validPattern(patternRef.current); + if (hostIdRef.current !== expectedHostId) return { ok: false }; if (patternValue == null) { setError("pattern"); return { ok: false }; diff --git a/components/PluginTerminalSidebar.test.tsx b/components/PluginTerminalSidebar.test.tsx index 45b946718..e7997814e 100644 --- a/components/PluginTerminalSidebar.test.tsx +++ b/components/PluginTerminalSidebar.test.tsx @@ -82,7 +82,11 @@ test('terminal extension pages use actual split panes, focus and session ownersh assert.equal(document.querySelector('button[aria-label="Extension pages"]'), null, 'pages do not require opening a grouped menu'); assert.ok(document.querySelector('button[aria-label="Second page — Synthetic plugin"]'), 'each contributed page has a direct toolbar button'); const firstButton = document.querySelector('button[aria-label="First page — Synthetic plugin"]')!; - await act(async () => { firstButton.click(); await settle(); }); + await act(async () => { + firstButton.click(); + await import('./plugins/PluginHostDrawnPage'); + await settle(); + }); assert.equal(document.querySelectorAll('[data-section="terminal-side-panel-pane"]').length, 1); assert.ok(document.querySelector('[data-pane-tool] [data-plugin-view-slot="terminal-sidebar"]')); assert.equal(document.querySelectorAll('[data-plugin-terminal-sidebar] header').length, 1); diff --git a/components/PluginVaultPages.test.tsx b/components/PluginVaultPages.test.tsx index c23951477..06ada0718 100644 --- a/components/PluginVaultPages.test.tsx +++ b/components/PluginVaultPages.test.tsx @@ -44,7 +44,13 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w } const root = createRoot(document.getElementById('root')!); const settle = () => new Promise((resolve) => setTimeout(resolve, 35)); - const clickPage = async () => { await act(async () => { document.querySelector('button[aria-label="Synthetic page — Synthetic plugin"]')!.click(); await settle(); }); }; + const clickPage = async () => { + await act(async () => { + document.querySelector('button[aria-label="Synthetic page — Synthetic plugin"]')!.click(); + await import('./plugins/PluginHostDrawnPage'); + await settle(); + }); + }; try { activeTabStore.setActiveTabId('vault'); await act(async () => { root.render(); await settle(); }); diff --git a/components/plugins/LazyPluginHostDrawnPage.tsx b/components/plugins/LazyPluginHostDrawnPage.tsx new file mode 100644 index 000000000..d9dbf8c7e --- /dev/null +++ b/components/plugins/LazyPluginHostDrawnPage.tsx @@ -0,0 +1,28 @@ +import React, { Suspense } from 'react'; +import type { PluginHostDrawnPageProps } from './PluginHostDrawnPage'; + +const PluginHostDrawnPageImpl = React.lazy(() => + import('./PluginHostDrawnPage').then((module) => ({ default: module.PluginHostDrawnPage })), +); + +/** + * Lazy boundary for host-drawn plugin views so css-tree, mdn-data, and + * @remote-dom/core stay out of the startup entry bundle until a plugin view + * actually opens. + */ +export function LazyPluginHostDrawnPage(props: PluginHostDrawnPageProps) { + const slot = props.slot.split(':')[0]; + return ( + + {props.loadingLabel} +

+ ) : null + } + > + +
+ ); +} diff --git a/components/plugins/PluginContributionHost.tsx b/components/plugins/PluginContributionHost.tsx index 16d7d5df5..131921b71 100644 --- a/components/plugins/PluginContributionHost.tsx +++ b/components/plugins/PluginContributionHost.tsx @@ -7,7 +7,7 @@ import { } from '../../application/state/usePluginViewLifecycle'; import { Button } from '../ui/button'; import { PluginContributionIcon } from './PluginContributionIcon'; -import { PluginHostDrawnPage } from './PluginHostDrawnPage'; +import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage'; export { requestOpenPluginView }; @@ -41,7 +41,7 @@ export function PluginContributionHost({ if (!effectiveRequested || !activeView) return null; const location = activeView.view.location; - const content = void close()} loadingLabel={t('plugins.vault.loading')} />; const containerClass = location === 'aside' ? 'absolute inset-y-0 right-0 z-40 w-[420px] border-l border-border bg-background shadow-2xl' diff --git a/components/plugins/PluginHostDrawnPage.tsx b/components/plugins/PluginHostDrawnPage.tsx index f11d053da..0871b670e 100644 --- a/components/plugins/PluginHostDrawnPage.tsx +++ b/components/plugins/PluginHostDrawnPage.tsx @@ -2,7 +2,12 @@ import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPlug import { PluginSettingsEntry } from './PluginSettingsEntry'; import { PluginRemoteSurface } from './PluginRemoteSurface'; -export function PluginHostDrawnPage(props: Parameters[0] & { loadingLabel: string; pluginId: string }) { +export type PluginHostDrawnPageProps = Parameters[0] & { + loadingLabel: string; + pluginId: string; +}; + +export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) { const view = useHostDrawnPluginView(props); if (!view.visible) return null; if (view.loading) return

{props.loadingLabel}

; diff --git a/components/plugins/PluginTerminalSidebar.tsx b/components/plugins/PluginTerminalSidebar.tsx index 6d2c3fdc4..bf3ba6a19 100644 --- a/components/plugins/PluginTerminalSidebar.tsx +++ b/components/plugins/PluginTerminalSidebar.tsx @@ -8,7 +8,7 @@ import { collectPluginTerminalSidebarPages, PLUGIN_TERMINAL_SIDEBAR_CONTEXT, req import { PluginContributionIcon } from './PluginContributionIcon'; import { Button } from '../ui/button'; import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; -import { PluginHostDrawnPage } from './PluginHostDrawnPage'; +import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage'; export function PluginTerminalSidebarLauncher({ sessionId, buttonClassName = 'h-6 w-6' }: { sessionId: string; buttonClassName?: string }) { const { locale } = useI18n(); @@ -44,6 +44,6 @@ export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSessi }, [getSession, sessionId, tabId]); return
{showHeader &&
{page.title}
} -
+
; } diff --git a/components/plugins/PluginVaultPages.tsx b/components/plugins/PluginVaultPages.tsx index ee00c769e..1b1061ba8 100644 --- a/components/plugins/PluginVaultPages.tsx +++ b/components/plugins/PluginVaultPages.tsx @@ -3,7 +3,7 @@ import { useI18n } from '../../application/i18n/I18nProvider'; import type { usePluginVaultPages } from '../../application/state/usePluginVaultPages'; import { PluginContributionIcon } from './PluginContributionIcon'; import { Button } from '../ui/button'; -import { PluginHostDrawnPage } from './PluginHostDrawnPage'; +import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage'; type VaultPages = ReturnType; const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); }); @@ -28,7 +28,7 @@ export function PluginVaultPage({ model }: { model: VaultPages }) { const { t } = useI18n(); const page = model.selected!; return
-
; } diff --git a/components/scripts/LazyScriptCodeEditor.tsx b/components/scripts/LazyScriptCodeEditor.tsx new file mode 100644 index 000000000..0165cc100 --- /dev/null +++ b/components/scripts/LazyScriptCodeEditor.tsx @@ -0,0 +1,31 @@ +import { Loader2 } from 'lucide-react'; +import React, { Suspense } from 'react'; +import type { ScriptCodeEditorHandle, ScriptCodeEditorProps } from './ScriptCodeEditor'; + +const ScriptCodeEditorImpl = React.lazy(() => + import('./ScriptCodeEditor').then((module) => ({ default: module.ScriptCodeEditor })), +); + +/** + * Lazy boundary for Monaco-backed ScriptCodeEditor so @monaco-editor/react + * stays out of the startup bundle while QuickAddSnippetDialog and + * QuickScriptEditorDialog remain mounted for global window events. + */ +export const LazyScriptCodeEditor = React.forwardRef( + (props, ref) => ( + + + + } + > + + + ), +); + +LazyScriptCodeEditor.displayName = 'LazyScriptCodeEditor'; diff --git a/components/scripts/ScriptEditorModal.tsx b/components/scripts/ScriptEditorModal.tsx index 2566ef2d0..a280773f4 100644 --- a/components/scripts/ScriptEditorModal.tsx +++ b/components/scripts/ScriptEditorModal.tsx @@ -6,7 +6,7 @@ import { DEFAULT_SCRIPT_TEMPLATE } from '@/domain/snippetScript.ts'; import { scheduleWindowInputFocus } from '@/application/state/windowInputFocus'; import { SelectHostDialog } from '@/components/SelectHostDialog'; import { SelectGroupDialog } from '@/components/SelectGroupDialog'; -import { ScriptCodeEditor } from './ScriptCodeEditor'; +import { LazyScriptCodeEditor } from './LazyScriptCodeEditor'; import { ScriptMetaFields } from './ScriptMetaFields'; import { SnippetTargetsSection } from '@/components/snippets/SnippetTargetsSection'; import { resolveSnippetTargetGroupsForSave } from '@/domain/snippetTargets.ts'; @@ -169,7 +169,7 @@ export const ScriptEditorModal: React.FC = ({
{open ? ( - onChange({ ...snippet, command })} language={language} diff --git a/components/scripts/ScriptEditorPanel.tsx b/components/scripts/ScriptEditorPanel.tsx index 25f757074..cb5d62ba8 100644 --- a/components/scripts/ScriptEditorPanel.tsx +++ b/components/scripts/ScriptEditorPanel.tsx @@ -5,7 +5,7 @@ import type { Snippet } from '@/domain/models'; import { DEFAULT_SCRIPT_TEMPLATE } from '@/domain/snippetScript.ts'; import { STORAGE_KEY_SCRIPT_EDITOR_HEIGHT } from '@/infrastructure/config/storageKeys.ts'; import { localStorageAdapter } from '@/infrastructure/persistence/localStorageAdapter.ts'; -import { ScriptCodeEditor } from './ScriptCodeEditor'; +import { LazyScriptCodeEditor } from './LazyScriptCodeEditor'; import { ScriptMetaFields } from './ScriptMetaFields'; import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; @@ -141,7 +141,7 @@ export const ScriptEditorPanel: React.FC = ({
- onChange({ ...snippet, command })} language={language} diff --git a/components/snippets/SnippetScriptEditor.tsx b/components/snippets/SnippetScriptEditor.tsx index 9a4d4cbf0..0557feb6f 100644 --- a/components/snippets/SnippetScriptEditor.tsx +++ b/components/snippets/SnippetScriptEditor.tsx @@ -4,10 +4,8 @@ import { useI18n } from '../../application/i18n/I18nProvider'; import { STORAGE_KEY_SNIPPET_SCRIPT_EDITOR_HEIGHT } from '@/infrastructure/config/storageKeys.ts'; import { localStorageAdapter } from '@/infrastructure/persistence/localStorageAdapter.ts'; import { Button } from '../ui/button'; -import { - ScriptCodeEditor, - type ScriptCodeEditorHandle, -} from '../scripts/ScriptCodeEditor'; +import { LazyScriptCodeEditor } from '../scripts/LazyScriptCodeEditor'; +import type { ScriptCodeEditorHandle } from '../scripts/ScriptCodeEditor'; import { Dialog, DialogContent, @@ -156,7 +154,7 @@ export const SnippetScriptEditor: React.FC = ({ className="relative overflow-hidden rounded-md border border-border/60 bg-background" style={{ height }} > - = ({ {t('snippets.scriptEditor.modalTitle')}
-