@_linked/cli 1.28.1 → 1.28.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.28.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#162](https://github.com/linked-fw/cli/pull/162) [`e965600`](https://github.com/linked-fw/cli/commit/e9656005679f137b023d811fc057409071109d27) Thanks [@flyon](https://github.com/flyon)! - `createViteConfig` now keeps compiled decorated classes named as written. Vite re-prints any published module that mentions `process.env` or `import.meta.env` (client build) or `process.env.NODE_ENV` (dev client) with esbuild, which renamed tsc's `let Foo = class Foo` to `class Foo2` — and an unnamed shape's IRI is its class name. A new `linked:pin-compiled-class-names` plugin pins each such class's name right after its declaration, before its decorators run.
8
+
9
+ - [#170](https://github.com/linked-fw/cli/pull/170) [`7a9e465`](https://github.com/linked-fw/cli/commit/7a9e465d498ff01247967d586b17e81c29536e08) Thanks [@flyon](https://github.com/flyon)! - `createViteConfig` now bundles `@_linked/server` in the dev SSR runner (`ssr.noExternal`), in workspace and standalone mode alike. `linked start` loads `LinkedServer` through `vite.ssrLoadModule`, so Vite already evaluated that entry and every file it reaches by relative import, while bare `@_linked/server/...` imports from the app and its storage config went to Node. The package was split across two loaders, and which one evaluated a given file depended on import order: in Create Now, `package.js` and `ontologies/lincd-server.js` evaluated once in each, and `shapes/filestores/LocalFileStore.js` too once the package's `backend` loaded. Vite is now the only loader for it. The new `SSR_ENTRY_PACKAGES` export names the packages this applies to.
10
+
3
11
  ## 1.28.1
4
12
 
5
13
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../../../src/commands/start.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAC,YAAY,EAAoB,aAAa,EAAC,MAAM,MAAM,CAAC;AAExE,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,EAAE,M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AAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,eAAO,MAAM,iBAAiB,UAA0D,CAAC;AAEzF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,UAA0C,CAAC;AAE3E;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAM3D;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,YAAY,EAAE,GAAG,GAAG,OAAO,CAExE;AAED;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,YAAY,CAAC,CA6BvB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,GAAG,EACjB,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,aAAa,GAAG,eAAe,CAAC,EAC1D,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,OAAO,GACf,IAAI,CA0CN;AAED,UAAU,gBAAgB;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAkExF;AAqFD,wBAAsB,aAAa,CAAC,IAAI,GAAE,YAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAqJ1E"}
@@ -367,6 +367,9 @@ export function startWithVite() {
367
367
  // created in one tree don't reach consumers in the other, causing
368
368
  // "Cannot destructure property 'isNativeApp' of useAppContext()" type
369
369
  // errors on every SSR render.
370
+ // Loading this entry through Vite is why `@_linked/server` is in
371
+ // `SSR_ENTRY_PACKAGES` (vite-config.ts): the package's bare imports must go
372
+ // through Vite as well, or some of its files evaluate once per loader.
370
373
  const ServerClass = (yield vite.ssrLoadModule('@_linked/server/shapes/LinkedServer')).LinkedServer;
371
374
  const server = new ServerClass(linkedConfig);
372
375
  // Surface stack traces from Vite ssrLoadModule failures cleanly.
@@ -1 +1 @@
1
- {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../src/commands/start.ts"],"names":[],"mappings":";;;;;;;;;AAAA,sCAAsC;AACtC,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,uEAAuE;AACvE,yDAAyD;AACzD,EAAE;AACF,+CAA+C;AAC/C,kFAAkF;AAClF,8CAA8C;AAC9C,uEAAuE;AACvE,yEAAyE;AACzE,uCAAuC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAC,KAAK,EAAC,MAAM,oBAAoB,CAAC;AACzC,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAC,sBAAsB,EAAE,sBAAsB,EAAC,MAAM,uBAAuB,CAAC;AAerF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,iBAAiB,CAAC,CAAC;AAEzF;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,CAAC;AAE3E;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAW;;IACjD,OAAO,CACL,MAAA,mBAAmB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CACzE,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,CAC9B,mCAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAC5C,CAAC;AACJ,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ACH,MAAO,MAAc,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;oBAC5C,CAAC;oBAAC,OAAO,GAAQ,EAAE,CAAC;wBAClB,OAAO,CAAC,IAAI,CACV,sBAAsB,GAAG,YAAY,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,mCAAI,GAAG,EAAE,CAC3D,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC,CAAA,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EAAE;YAC7C,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC;gBAAE,OAAO;YAC7C,MAAM,GAAG,GAAG,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;YACjE,IAAI,CAAC,GAAG;gBAAE,OAAO;YACjB,IAAI,OAAQ,MAAc,CAAC,cAAc,KAAK,UAAU;gBAAE,OAAO;YACjE,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACxB,YAAY,CAAC,WAAW,CAAC,CAAC;YAC1B,WAAW,GAAG,UAAU,CAAC,YAAY,EAAE,kBAAkB,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;QAEH,0BAA0B;QAC1B,MAAM,IAAI,GAAG,MAAA,MAAC,YAAY,CAAC,MAAc,CAAC,IAAI,mCAAI,IAAI,CAAC,IAAI,mCAAI,IAAI,CAAC;QACpE,gBAAgB,CAAC;YACf,GAAG,EAAE,oBAAoB,IAAI,GAAG;YAChC,SAAS,EAAE,cAAc;SAC1B,CAAC,CAAC;IACL,CAAC;CAAA","sourcesContent":["// `linked start --vite` orchestrator.\n//\n// Follows the existing startServer() flow from cli-methods.ts but injects\n// a Vite dev server in middleware mode + overrides loadAppComponent /\n// loadRoutes to use vite.ssrLoadModule. This means LinkedServer's existing\n// initialization works unchanged; we just route module loading through\n// Vite instead of loading modules through Node directly.\n//\n// What's different vs the plain startServer():\n// - LinkedServer renders through the Vite middleware when viteMiddleware is set\n// - Vite handles the client transform + HMR\n// - ssrLoadModule handles the server transform (decorators, jsx, ts)\n// - Server changes still need full process restart for now (server HMR\n// deferred to vite-node migration)\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport {spawn} from 'node:child_process';\nimport fsExtra from 'fs-extra';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from '../workspace-globs.js';\n\nimport type {InlineConfig, UserConfigExport, ViteDevServer} from 'vite';\n\nexport interface StartOptions {\n env?: string;\n port?: number;\n /**\n * Serve only the backend API (`/call/...`, `/api/...`, provider routes).\n * No `vite.config.*`, `src/App.tsx` or `src/routes.tsx` is needed, and page\n * requests get a 404 instead of server-side rendering.\n */\n apiOnly?: boolean;\n}\n\nexport const VITE_CONFIG_FILES = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n/**\n * Names for the app's linked config, in priority order. `lincd.config.js` is\n * the legacy name: apps predating the rename still ship it, and dropping it\n * would silently discard their whole `server` config (cachePaths, `apiOnly`, …).\n */\nexport const LINKED_CONFIG_FILES = ['linked.config.js', 'lincd.config.js'];\n\n/**\n * Absolute path to the app's linked config. Returns the first name that exists;\n * when none does, the current name — the caller still `existsSync`-guards the\n * import, so this is simply the \"no config here\" path, not a promise of a file.\n */\nexport function resolveLinkedConfigPath(cwd: string): string {\n return (\n LINKED_CONFIG_FILES.map((name) => path.join(cwd, name)).find((candidate) =>\n fsExtra.existsSync(candidate),\n ) ?? path.join(cwd, LINKED_CONFIG_FILES[0])\n );\n}\n\n/**\n * API-only mode is explicit: `linked start --api-only`, or `server.apiOnly: true`\n * in `linked.config.js`. It is never inferred from missing frontend files, so a\n * web app that lost its `vite.config.ts` still fails loudly instead of silently\n * serving no pages.\n */\nexport function isApiOnly(opts: StartOptions, linkedConfig: any): boolean {\n return opts.apiOnly === true || linkedConfig?.server?.apiOnly === true;\n}\n\n/**\n * The Vite dev-server config for `linked start`.\n *\n * With a `vite.config.*` in `cwd`, Vite loads it itself. Without one, API-only\n * mode uses `createViteConfig()`'s defaults inline — Vite is still needed on the\n * backend to transform TypeScript, decorators and extensionless imports of\n * source-only shape packages. Without one in page mode, it is an error.\n */\nexport async function resolveViteServerConfig(\n cwd: string,\n apiOnly: boolean,\n): Promise<InlineConfig> {\n const base: InlineConfig = {\n root: cwd,\n server: {middlewareMode: true},\n appType: 'custom',\n };\n if (VITE_CONFIG_FILES.some((c) => fsExtra.existsSync(path.join(cwd, c)))) {\n return base;\n }\n if (!apiOnly) {\n throw new Error(\n `[linked start] no vite.config.{ts,js,mjs} found in ${cwd}. Add one:\\n\\n import {createViteConfig} from '@_linked/cli/vite-config';\\n export default createViteConfig({port: 4040, cssMode: 'tailwind'});\\n\\nFor a backend without a web frontend, run \\`linked start --api-only\\` instead.\\n`,\n );\n }\n const {createViteConfig} = await import('../vite-config.js');\n const exported: UserConfigExport = createViteConfig();\n const defaults =\n typeof exported === 'function'\n ? await exported({command: 'serve', mode: 'development'})\n : await exported;\n return {\n ...defaults,\n ...base,\n configFile: false,\n server: {...defaults.server, ...base.server},\n // No browser client: skip the client dependency scan, whose entry\n // (`src/index.tsx`) does not exist in a backend.\n optimizeDeps: {...defaults.optimizeDeps, noDiscovery: true},\n };\n}\n\n/**\n * Inject Vite into LinkedServer's config:\n * - vite: handle for ssrLoadModule (used to load app's backend.ts via self-reference)\n * and, unless API-only (where `apiOnly` makes LinkedServer skip page rendering):\n * - viteMiddleware: mounted as the dev-server middleware\n * - loadAppComponent / loadRoutes: route through vite.ssrLoadModule for SSR transform\n * - viteSsrPreload: page modules to preload for SSR CSS collection\n */\nexport function configureLinkedServer(\n serverConfig: any,\n vite: Pick<ViteDevServer, 'middlewares' | 'ssrLoadModule'>,\n cwd: string,\n apiOnly: boolean,\n): void {\n serverConfig.vite = vite;\n if (apiOnly) {\n serverConfig.apiOnly = true;\n return;\n }\n serverConfig.viteMiddleware = vite.middlewares;\n serverConfig.loadAppComponent = async () => {\n const mod = await vite.ssrLoadModule('/src/App.tsx');\n return mod.default;\n };\n serverConfig.loadRoutes = async () => {\n return await vite.ssrLoadModule('/src/routes.tsx');\n };\n\n // Vite SSR CSS collection support:\n // List all `src/pages/*.{ts,tsx}` files so LinkedServer can ssrLoadModule\n // each into Vite's moduleGraph BEFORE the first render of a session.\n // React.lazy() doesn't auto-fire — without this, only App's eager\n // imports' CSS is collected; lazy pages' CSS arrives after hydration\n // causing an unstyled flash. After the first preload sweep, all\n // subsequent renders have full CSS available.\n serverConfig.viteSsrPreload = async () => {\n const pagesDir = path.join(cwd, 'src', 'pages');\n if (!fsExtra.existsSync(pagesDir)) return [];\n const files = fsExtra.readdirSync(pagesDir, {withFileTypes: true});\n const paths: string[] = [];\n for (const file of files) {\n // Test files live beside pages but call vi.mock() at module scope,\n // which throws outside Vitest — never load them into the SSR graph.\n // `.d.ts` files are types only: they have no runtime module to load.\n if (\n file.isFile() &&\n /\\.(tsx|ts)$/.test(file.name) &&\n !/\\.(test|spec)\\.(tsx|ts)$/.test(file.name) &&\n !file.name.endsWith('.d.ts')\n ) {\n paths.push(`/src/pages/${file.name}`);\n }\n }\n return paths;\n };\n}\n\ninterface WorkspacePackage {\n name: string;\n root: string;\n srcDir: string;\n}\n\n/**\n * Discover the packages whose sources `linked start` watches for HMR, from two\n * sources. No hand-maintained list anywhere.\n *\n * 1. The app's `package.json` `workspaces` field — adding a new linked package\n * = appearing in the right glob.\n * 2. The app's linked dependencies that are installed as SOURCE — the same rule\n * the Vite resolver table uses (`discoverLinkedSourceDependencies`), so the\n * two lists cannot disagree about what is source. This covers a LOCALIZED\n * checkout (`packages-local/<pkg>`), which is deliberately in no workspace\n * glob and reachable only through its `node_modules` symlink. Without it\n * `workspacePackageForPath` returns null for the checkout, so a saved backend\n * edit is reloaded by Vite and then never re-indexed: the registered provider\n * instance is never replaced.\n *\n * Returns each package's npm `name` (so we can call `onSourceChange(name)`), its\n * absolute root, and its `src/` directory for fast prefix matching. Dependency\n * roots are realpathed by the shared discovery, matching the ids Vite reports.\n */\nexport async function discoverWorkspacePackages(cwd: string): Promise<WorkspacePackage[]> {\n const pkgJsonPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgJsonPath))) return [];\n const pkgJson = await fsExtra.readJson(pkgJsonPath);\n const {patterns, negatedPatterns} = parseWorkspacePatterns(pkgJson.workspaces);\n const out: WorkspacePackage[] = [];\n\n // Include the root app itself so edits to <cwd>/src/* trigger HMR for\n // the app's own providers (e.g. CN's src/backend.ts which registers ~25\n // Express routes).\n if (pkgJson.name && (await fsExtra.pathExists(path.join(cwd, 'src')))) {\n out.push({name: pkgJson.name, root: cwd, srcDir: path.join(cwd, 'src')});\n }\n for (const glob of patterns) {\n // Positive patterns are expanded by directory listing rather than with a\n // full glob library, so only a trailing /* is honoured. Negated entries\n // (\"!packages/core\") are honoured in full — watching an excluded directory\n // would trigger HMR for a package the app does not actually resolve.\n const m = glob.match(/^(.+?)\\/\\*$/);\n const candidates: string[] = [];\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n const entries = await fs.readdir(parent, {withFileTypes: true});\n for (const dirent of entries) {\n if (dirent.isDirectory() || dirent.isSymbolicLink()) {\n candidates.push(path.join(parent, dirent.name));\n }\n }\n }\n } else {\n candidates.push(path.join(cwd, glob));\n }\n for (const root of candidates) {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) continue;\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) continue;\n try {\n const sub = await fsExtra.readJson(pkgPath);\n if (sub.name) {\n out.push({name: sub.name, root, srcDir: path.join(root, 'src')});\n }\n } catch {\n // ignore broken package.json\n }\n }\n }\n\n // Linked deps installed as source, realpathed — a localized checkout is here\n // and nowhere else. Imported lazily because vite-config pulls in Vite itself.\n const {discoverLinkedSourceDependencies} = await import('../vite-config.js');\n const names = new Set(out.map((p) => p.name));\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (names.has(entry.name)) continue;\n // Only working copies. Some PUBLISHED packages ship `src/` in their tarball,\n // so the resolver registers them (it serves that source) — but they stay\n // inside `node_modules`, which Vite's watcher ignores, so no change event\n // can ever match them. Listing them would inflate the count printed at boot\n // with packages nothing watches. A localized checkout, a workspace clone and\n // an `npm link` all realpath to a directory outside `node_modules`.\n if (isInsideNodeModules(entry.srcDir)) continue;\n names.add(entry.name);\n out.push({name: entry.name, root: path.dirname(entry.srcDir), srcDir: entry.srcDir});\n }\n return out;\n}\n\nfunction isInsideNodeModules(p: string): boolean {\n return p.split(path.sep).includes('node_modules');\n}\n\nfunction workspacePackageForPath(\n filepath: string,\n pkgs: WorkspacePackage[],\n): string | null {\n for (const p of pkgs) {\n if (filepath.startsWith(p.srcDir + path.sep) || filepath === p.srcDir) {\n return p.name;\n }\n }\n return null;\n}\n\nfunction openBrowser(url: string): void {\n const cmd =\n process.platform === 'darwin'\n ? 'open'\n : process.platform === 'win32'\n ? 'start'\n : 'xdg-open';\n spawn(cmd, [url], {detached: true, stdio: 'ignore'}).unref();\n}\n\nfunction installShortcuts(opts: {url: string; onRestart: () => void}): void {\n if (!process.stdin.isTTY) return;\n let buf = '';\n try {\n process.stdin.setRawMode(true);\n } catch {\n return;\n }\n process.stdin.resume();\n process.stdin.setEncoding('utf8');\n const cleanup = () => {\n try {\n process.stdin.setRawMode(false);\n } catch {}\n };\n process.on('exit', cleanup);\n process.stdin.on('data', (chunk: string) => {\n for (const ch of chunk) {\n // Ctrl-C → graceful exit, restore terminal first.\n if (ch === '\u0003') {\n cleanup();\n process.exit(0);\n }\n if (ch === '\\r' || ch === '\\n') {\n const cmd = buf.trim();\n buf = '';\n if (cmd === 'r') {\n console.log('[linked] restarting…');\n opts.onRestart();\n } else if (cmd === 'o') {\n console.log(`[linked] opening ${opts.url}`);\n openBrowser(opts.url);\n }\n } else {\n buf += ch;\n }\n }\n });\n console.log(\n `[linked] press r<enter> to restart · o<enter> to open ${opts.url}`,\n );\n}\n\nfunction restartProcess(): void {\n // nodemon-style respawn: launch a fresh process from the same argv,\n // then exit. The new process inherits stdio so the dev experience is\n // continuous.\n const [node, ...argv] = process.argv;\n const child = spawn(node, argv, {\n stdio: 'inherit',\n detached: true,\n env: process.env,\n });\n child.unref();\n process.exit(0);\n}\n\nexport async function startWithVite(opts: StartOptions = {}): Promise<void> {\n const cwd = process.cwd();\n\n // Load the app's own `.env` (Node 20.12+ `process.loadEnvFile`) if present — the\n // standard, dependency-free env source for a linked app. Node does NOT override\n // vars already set in the environment, so CN's injected per-(project,branch) vars\n // (PORT, FUSEKI_DATASET, CN_APP_ADMIN_SECRET, …) take precedence over the file.\n try {\n const envPath = path.join(cwd, '.env');\n if (\n (await fsExtra.pathExists(envPath)) &&\n typeof (process as {loadEnvFile?: (p: string) => void}).loadEnvFile === 'function'\n ) {\n (process as {loadEnvFile: (p: string) => void}).loadEnvFile(envPath);\n }\n } catch {\n // best-effort — a missing/invalid .env never blocks start\n }\n\n // `--env` still loads env-cmd (`.env-cmdrc.json`) for CN's own start:local flow.\n const {ensureEnvironmentLoaded} = await import('../lifecycle.js');\n await ensureEnvironmentLoaded();\n\n // Load user's linked.config.js (legacy hook). It still drives things\n // like server.cachePaths and the rest of LinkedServer's options.\n const linkedConfigPath = resolveLinkedConfigPath(cwd);\n let linkedConfig: any = {};\n if (fsExtra.existsSync(linkedConfigPath)) {\n linkedConfig = (await import(linkedConfigPath)).default ?? {};\n }\n linkedConfig.server = linkedConfig.server || {};\n const apiOnly = isApiOnly(opts, linkedConfig);\n\n const {createServer: createViteServer} = await import('vite');\n const vite = await createViteServer(await resolveViteServerConfig(cwd, apiOnly));\n configureLinkedServer(linkedConfig.server, vite, cwd, apiOnly);\n\n // Load the storage config through Vite SSR so it\n // configures the SAME LinkedStorage instance the rest of the SSR graph\n // (LinkedServer, CN providers) uses. Replaces the former Node-direct\n // `loadBackendStorageConfig()` (which resolved @_linked/core via the\n // `default`→lib condition, a SEPARATE instance). Safe now that core's lib\n // `initTree` is idempotent. `loadBackendStorageConfig` stays in\n // lifecycle.ts for the Node-only CLI commands (`script`/`call`) that have no\n // Vite server (contract C5).\n // The first two names are current; the rest are legacy filenames kept so\n // older apps that never renamed their storage config still start.\n for (const rel of [\n '/linked.backend.storage.ts',\n '/linked.backend.storage.js',\n '/backend-storage-config.ts',\n '/backend-storage-config.js',\n '/scripts/backend-storage-config.ts',\n '/scripts/backend-storage-config.js',\n '/scripts/storage-config.js',\n ]) {\n if (fsExtra.existsSync(path.join(cwd, rel.slice(1)))) {\n await vite.ssrLoadModule(rel);\n break;\n }\n }\n\n // Load LinkedServer through Vite SSR so it shares the SAME\n // module instances as everything else in the SSR call graph. Without\n // this, LinkedServer is loaded by Node (→ lib/esm) while CN's App.tsx +\n // its transitive imports are loaded by Vite (→ src/). React contexts\n // created in one tree don't reach consumers in the other, causing\n // \"Cannot destructure property 'isNativeApp' of useAppContext()\" type\n // errors on every SSR render.\n const ServerClass = (\n await vite.ssrLoadModule('@_linked/server/shapes/LinkedServer')\n ).LinkedServer;\n\n const server = new (ServerClass as any)(linkedConfig);\n\n // Surface stack traces from Vite ssrLoadModule failures cleanly.\n process.on('unhandledRejection', (err: any) => {\n if (err && err.stack) {\n try {\n vite.ssrFixStacktrace(err);\n } catch {\n // ignore\n }\n }\n console.error(err);\n });\n\n await server.start();\n\n // Watcher → onSourceChange wiring.\n //\n // Discover workspace packages once at boot. On each change, look up\n // which workspace package the file belongs to and call onSourceChange\n // with that package's npm name. LinkedServer disposes the old providers,\n // re-imports via vite.ssrLoadModule (transparent because Vite invalidated\n // the module already), and re-instantiates. No process restart.\n const workspacePackages = await discoverWorkspacePackages(cwd);\n if (workspacePackages.length > 0) {\n console.log(\n `[linked] watching ${workspacePackages.length} workspace packages for HMR`,\n );\n }\n // Reloads are DEBOUNCED and SERIALISED. `onSourceChange` disposes a\n // package's providers and re-registers their express routes, i.e. it mutates\n // the shared router stack. Firing it per file change (a multi-file save, a\n // format-on-save, a branch switch) ran overlapping dispose/re-register\n // cycles against that same stack with nothing ordering them. Collect the\n // affected packages over a short window, then run the cycles one at a time.\n const RELOAD_DEBOUNCE_MS = 150;\n const pendingReloads = new Set<string>();\n let reloadTimer: NodeJS.Timeout | undefined;\n // Tail of the reload chain — each flush appends, so cycles never interleave.\n let reloadChain: Promise<void> = Promise.resolve();\n\n const flushReloads = () => {\n const pkgs = [...pendingReloads];\n pendingReloads.clear();\n reloadChain = reloadChain.then(async () => {\n for (const pkg of pkgs) {\n try {\n await (server as any).onSourceChange(pkg);\n } catch (err: any) {\n console.warn(\n `[linked] reload of ${pkg} failed: ${err?.message ?? err}`,\n );\n }\n }\n });\n };\n\n vite.watcher.on('change', (filepath: string) => {\n if (!/\\.(tsx?|jsx?)$/.test(filepath)) return;\n const pkg = workspacePackageForPath(filepath, workspacePackages);\n if (!pkg) return;\n if (typeof (server as any).onSourceChange !== 'function') return;\n pendingReloads.add(pkg);\n clearTimeout(reloadTimer);\n reloadTimer = setTimeout(flushReloads, RELOAD_DEBOUNCE_MS);\n });\n\n // r/o keyboard shortcuts.\n const port = (linkedConfig.server as any).port ?? opts.port ?? 4040;\n installShortcuts({\n url: `http://localhost:${port}/`,\n onRestart: restartProcess,\n });\n}\n"]}
1
+ {"version":3,"file":"start.js","sourceRoot":"","sources":["../../../src/commands/start.ts"],"names":[],"mappings":";;;;;;;;;AAAA,sCAAsC;AACtC,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,uEAAuE;AACvE,yDAAyD;AACzD,EAAE;AACF,+CAA+C;AAC/C,kFAAkF;AAClF,8CAA8C;AAC9C,uEAAuE;AACvE,yEAAyE;AACzE,uCAAuC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAC,KAAK,EAAC,MAAM,oBAAoB,CAAC;AACzC,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,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AO;YACjB,IAAI,OAAQ,MAAc,CAAC,cAAc,KAAK,UAAU;gBAAE,OAAO;YACjE,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACxB,YAAY,CAAC,WAAW,CAAC,CAAC;YAC1B,WAAW,GAAG,UAAU,CAAC,YAAY,EAAE,kBAAkB,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;QAEH,0BAA0B;QAC1B,MAAM,IAAI,GAAG,MAAA,MAAC,YAAY,CAAC,MAAc,CAAC,IAAI,mCAAI,IAAI,CAAC,IAAI,mCAAI,IAAI,CAAC;QACpE,gBAAgB,CAAC;YACf,GAAG,EAAE,oBAAoB,IAAI,GAAG;YAChC,SAAS,EAAE,cAAc;SAC1B,CAAC,CAAC;IACL,CAAC;CAAA","sourcesContent":["// `linked start --vite` orchestrator.\n//\n// Follows the existing startServer() flow from cli-methods.ts but injects\n// a Vite dev server in middleware mode + overrides loadAppComponent /\n// loadRoutes to use vite.ssrLoadModule. This means LinkedServer's existing\n// initialization works unchanged; we just route module loading through\n// Vite instead of loading modules through Node directly.\n//\n// What's different vs the plain startServer():\n// - LinkedServer renders through the Vite middleware when viteMiddleware is set\n// - Vite handles the client transform + HMR\n// - ssrLoadModule handles the server transform (decorators, jsx, ts)\n// - Server changes still need full process restart for now (server HMR\n// deferred to vite-node migration)\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport {spawn} from 'node:child_process';\nimport fsExtra from 'fs-extra';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from '../workspace-globs.js';\n\nimport type {InlineConfig, UserConfigExport, ViteDevServer} from 'vite';\n\nexport interface StartOptions {\n env?: string;\n port?: number;\n /**\n * Serve only the backend API (`/call/...`, `/api/...`, provider routes).\n * No `vite.config.*`, `src/App.tsx` or `src/routes.tsx` is needed, and page\n * requests get a 404 instead of server-side rendering.\n */\n apiOnly?: boolean;\n}\n\nexport const VITE_CONFIG_FILES = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n/**\n * Names for the app's linked config, in priority order. `lincd.config.js` is\n * the legacy name: apps predating the rename still ship it, and dropping it\n * would silently discard their whole `server` config (cachePaths, `apiOnly`, …).\n */\nexport const LINKED_CONFIG_FILES = ['linked.config.js', 'lincd.config.js'];\n\n/**\n * Absolute path to the app's linked config. Returns the first name that exists;\n * when none does, the current name — the caller still `existsSync`-guards the\n * import, so this is simply the \"no config here\" path, not a promise of a file.\n */\nexport function resolveLinkedConfigPath(cwd: string): string {\n return (\n LINKED_CONFIG_FILES.map((name) => path.join(cwd, name)).find((candidate) =>\n fsExtra.existsSync(candidate),\n ) ?? path.join(cwd, LINKED_CONFIG_FILES[0])\n );\n}\n\n/**\n * API-only mode is explicit: `linked start --api-only`, or `server.apiOnly: true`\n * in `linked.config.js`. It is never inferred from missing frontend files, so a\n * web app that lost its `vite.config.ts` still fails loudly instead of silently\n * serving no pages.\n */\nexport function isApiOnly(opts: StartOptions, linkedConfig: any): boolean {\n return opts.apiOnly === true || linkedConfig?.server?.apiOnly === true;\n}\n\n/**\n * The Vite dev-server config for `linked start`.\n *\n * With a `vite.config.*` in `cwd`, Vite loads it itself. Without one, API-only\n * mode uses `createViteConfig()`'s defaults inline — Vite is still needed on the\n * backend to transform TypeScript, decorators and extensionless imports of\n * source-only shape packages. Without one in page mode, it is an error.\n */\nexport async function resolveViteServerConfig(\n cwd: string,\n apiOnly: boolean,\n): Promise<InlineConfig> {\n const base: InlineConfig = {\n root: cwd,\n server: {middlewareMode: true},\n appType: 'custom',\n };\n if (VITE_CONFIG_FILES.some((c) => fsExtra.existsSync(path.join(cwd, c)))) {\n return base;\n }\n if (!apiOnly) {\n throw new Error(\n `[linked start] no vite.config.{ts,js,mjs} found in ${cwd}. Add one:\\n\\n import {createViteConfig} from '@_linked/cli/vite-config';\\n export default createViteConfig({port: 4040, cssMode: 'tailwind'});\\n\\nFor a backend without a web frontend, run \\`linked start --api-only\\` instead.\\n`,\n );\n }\n const {createViteConfig} = await import('../vite-config.js');\n const exported: UserConfigExport = createViteConfig();\n const defaults =\n typeof exported === 'function'\n ? await exported({command: 'serve', mode: 'development'})\n : await exported;\n return {\n ...defaults,\n ...base,\n configFile: false,\n server: {...defaults.server, ...base.server},\n // No browser client: skip the client dependency scan, whose entry\n // (`src/index.tsx`) does not exist in a backend.\n optimizeDeps: {...defaults.optimizeDeps, noDiscovery: true},\n };\n}\n\n/**\n * Inject Vite into LinkedServer's config:\n * - vite: handle for ssrLoadModule (used to load app's backend.ts via self-reference)\n * and, unless API-only (where `apiOnly` makes LinkedServer skip page rendering):\n * - viteMiddleware: mounted as the dev-server middleware\n * - loadAppComponent / loadRoutes: route through vite.ssrLoadModule for SSR transform\n * - viteSsrPreload: page modules to preload for SSR CSS collection\n */\nexport function configureLinkedServer(\n serverConfig: any,\n vite: Pick<ViteDevServer, 'middlewares' | 'ssrLoadModule'>,\n cwd: string,\n apiOnly: boolean,\n): void {\n serverConfig.vite = vite;\n if (apiOnly) {\n serverConfig.apiOnly = true;\n return;\n }\n serverConfig.viteMiddleware = vite.middlewares;\n serverConfig.loadAppComponent = async () => {\n const mod = await vite.ssrLoadModule('/src/App.tsx');\n return mod.default;\n };\n serverConfig.loadRoutes = async () => {\n return await vite.ssrLoadModule('/src/routes.tsx');\n };\n\n // Vite SSR CSS collection support:\n // List all `src/pages/*.{ts,tsx}` files so LinkedServer can ssrLoadModule\n // each into Vite's moduleGraph BEFORE the first render of a session.\n // React.lazy() doesn't auto-fire — without this, only App's eager\n // imports' CSS is collected; lazy pages' CSS arrives after hydration\n // causing an unstyled flash. After the first preload sweep, all\n // subsequent renders have full CSS available.\n serverConfig.viteSsrPreload = async () => {\n const pagesDir = path.join(cwd, 'src', 'pages');\n if (!fsExtra.existsSync(pagesDir)) return [];\n const files = fsExtra.readdirSync(pagesDir, {withFileTypes: true});\n const paths: string[] = [];\n for (const file of files) {\n // Test files live beside pages but call vi.mock() at module scope,\n // which throws outside Vitest — never load them into the SSR graph.\n // `.d.ts` files are types only: they have no runtime module to load.\n if (\n file.isFile() &&\n /\\.(tsx|ts)$/.test(file.name) &&\n !/\\.(test|spec)\\.(tsx|ts)$/.test(file.name) &&\n !file.name.endsWith('.d.ts')\n ) {\n paths.push(`/src/pages/${file.name}`);\n }\n }\n return paths;\n };\n}\n\ninterface WorkspacePackage {\n name: string;\n root: string;\n srcDir: string;\n}\n\n/**\n * Discover the packages whose sources `linked start` watches for HMR, from two\n * sources. No hand-maintained list anywhere.\n *\n * 1. The app's `package.json` `workspaces` field — adding a new linked package\n * = appearing in the right glob.\n * 2. The app's linked dependencies that are installed as SOURCE — the same rule\n * the Vite resolver table uses (`discoverLinkedSourceDependencies`), so the\n * two lists cannot disagree about what is source. This covers a LOCALIZED\n * checkout (`packages-local/<pkg>`), which is deliberately in no workspace\n * glob and reachable only through its `node_modules` symlink. Without it\n * `workspacePackageForPath` returns null for the checkout, so a saved backend\n * edit is reloaded by Vite and then never re-indexed: the registered provider\n * instance is never replaced.\n *\n * Returns each package's npm `name` (so we can call `onSourceChange(name)`), its\n * absolute root, and its `src/` directory for fast prefix matching. Dependency\n * roots are realpathed by the shared discovery, matching the ids Vite reports.\n */\nexport async function discoverWorkspacePackages(cwd: string): Promise<WorkspacePackage[]> {\n const pkgJsonPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgJsonPath))) return [];\n const pkgJson = await fsExtra.readJson(pkgJsonPath);\n const {patterns, negatedPatterns} = parseWorkspacePatterns(pkgJson.workspaces);\n const out: WorkspacePackage[] = [];\n\n // Include the root app itself so edits to <cwd>/src/* trigger HMR for\n // the app's own providers (e.g. CN's src/backend.ts which registers ~25\n // Express routes).\n if (pkgJson.name && (await fsExtra.pathExists(path.join(cwd, 'src')))) {\n out.push({name: pkgJson.name, root: cwd, srcDir: path.join(cwd, 'src')});\n }\n for (const glob of patterns) {\n // Positive patterns are expanded by directory listing rather than with a\n // full glob library, so only a trailing /* is honoured. Negated entries\n // (\"!packages/core\") are honoured in full — watching an excluded directory\n // would trigger HMR for a package the app does not actually resolve.\n const m = glob.match(/^(.+?)\\/\\*$/);\n const candidates: string[] = [];\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n const entries = await fs.readdir(parent, {withFileTypes: true});\n for (const dirent of entries) {\n if (dirent.isDirectory() || dirent.isSymbolicLink()) {\n candidates.push(path.join(parent, dirent.name));\n }\n }\n }\n } else {\n candidates.push(path.join(cwd, glob));\n }\n for (const root of candidates) {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) continue;\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) continue;\n try {\n const sub = await fsExtra.readJson(pkgPath);\n if (sub.name) {\n out.push({name: sub.name, root, srcDir: path.join(root, 'src')});\n }\n } catch {\n // ignore broken package.json\n }\n }\n }\n\n // Linked deps installed as source, realpathed — a localized checkout is here\n // and nowhere else. Imported lazily because vite-config pulls in Vite itself.\n const {discoverLinkedSourceDependencies} = await import('../vite-config.js');\n const names = new Set(out.map((p) => p.name));\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (names.has(entry.name)) continue;\n // Only working copies. Some PUBLISHED packages ship `src/` in their tarball,\n // so the resolver registers them (it serves that source) — but they stay\n // inside `node_modules`, which Vite's watcher ignores, so no change event\n // can ever match them. Listing them would inflate the count printed at boot\n // with packages nothing watches. A localized checkout, a workspace clone and\n // an `npm link` all realpath to a directory outside `node_modules`.\n if (isInsideNodeModules(entry.srcDir)) continue;\n names.add(entry.name);\n out.push({name: entry.name, root: path.dirname(entry.srcDir), srcDir: entry.srcDir});\n }\n return out;\n}\n\nfunction isInsideNodeModules(p: string): boolean {\n return p.split(path.sep).includes('node_modules');\n}\n\nfunction workspacePackageForPath(\n filepath: string,\n pkgs: WorkspacePackage[],\n): string | null {\n for (const p of pkgs) {\n if (filepath.startsWith(p.srcDir + path.sep) || filepath === p.srcDir) {\n return p.name;\n }\n }\n return null;\n}\n\nfunction openBrowser(url: string): void {\n const cmd =\n process.platform === 'darwin'\n ? 'open'\n : process.platform === 'win32'\n ? 'start'\n : 'xdg-open';\n spawn(cmd, [url], {detached: true, stdio: 'ignore'}).unref();\n}\n\nfunction installShortcuts(opts: {url: string; onRestart: () => void}): void {\n if (!process.stdin.isTTY) return;\n let buf = '';\n try {\n process.stdin.setRawMode(true);\n } catch {\n return;\n }\n process.stdin.resume();\n process.stdin.setEncoding('utf8');\n const cleanup = () => {\n try {\n process.stdin.setRawMode(false);\n } catch {}\n };\n process.on('exit', cleanup);\n process.stdin.on('data', (chunk: string) => {\n for (const ch of chunk) {\n // Ctrl-C → graceful exit, restore terminal first.\n if (ch === '\u0003') {\n cleanup();\n process.exit(0);\n }\n if (ch === '\\r' || ch === '\\n') {\n const cmd = buf.trim();\n buf = '';\n if (cmd === 'r') {\n console.log('[linked] restarting…');\n opts.onRestart();\n } else if (cmd === 'o') {\n console.log(`[linked] opening ${opts.url}`);\n openBrowser(opts.url);\n }\n } else {\n buf += ch;\n }\n }\n });\n console.log(\n `[linked] press r<enter> to restart · o<enter> to open ${opts.url}`,\n );\n}\n\nfunction restartProcess(): void {\n // nodemon-style respawn: launch a fresh process from the same argv,\n // then exit. The new process inherits stdio so the dev experience is\n // continuous.\n const [node, ...argv] = process.argv;\n const child = spawn(node, argv, {\n stdio: 'inherit',\n detached: true,\n env: process.env,\n });\n child.unref();\n process.exit(0);\n}\n\nexport async function startWithVite(opts: StartOptions = {}): Promise<void> {\n const cwd = process.cwd();\n\n // Load the app's own `.env` (Node 20.12+ `process.loadEnvFile`) if present — the\n // standard, dependency-free env source for a linked app. Node does NOT override\n // vars already set in the environment, so CN's injected per-(project,branch) vars\n // (PORT, FUSEKI_DATASET, CN_APP_ADMIN_SECRET, …) take precedence over the file.\n try {\n const envPath = path.join(cwd, '.env');\n if (\n (await fsExtra.pathExists(envPath)) &&\n typeof (process as {loadEnvFile?: (p: string) => void}).loadEnvFile === 'function'\n ) {\n (process as {loadEnvFile: (p: string) => void}).loadEnvFile(envPath);\n }\n } catch {\n // best-effort — a missing/invalid .env never blocks start\n }\n\n // `--env` still loads env-cmd (`.env-cmdrc.json`) for CN's own start:local flow.\n const {ensureEnvironmentLoaded} = await import('../lifecycle.js');\n await ensureEnvironmentLoaded();\n\n // Load user's linked.config.js (legacy hook). It still drives things\n // like server.cachePaths and the rest of LinkedServer's options.\n const linkedConfigPath = resolveLinkedConfigPath(cwd);\n let linkedConfig: any = {};\n if (fsExtra.existsSync(linkedConfigPath)) {\n linkedConfig = (await import(linkedConfigPath)).default ?? {};\n }\n linkedConfig.server = linkedConfig.server || {};\n const apiOnly = isApiOnly(opts, linkedConfig);\n\n const {createServer: createViteServer} = await import('vite');\n const vite = await createViteServer(await resolveViteServerConfig(cwd, apiOnly));\n configureLinkedServer(linkedConfig.server, vite, cwd, apiOnly);\n\n // Load the storage config through Vite SSR so it\n // configures the SAME LinkedStorage instance the rest of the SSR graph\n // (LinkedServer, CN providers) uses. Replaces the former Node-direct\n // `loadBackendStorageConfig()` (which resolved @_linked/core via the\n // `default`→lib condition, a SEPARATE instance). Safe now that core's lib\n // `initTree` is idempotent. `loadBackendStorageConfig` stays in\n // lifecycle.ts for the Node-only CLI commands (`script`/`call`) that have no\n // Vite server (contract C5).\n // The first two names are current; the rest are legacy filenames kept so\n // older apps that never renamed their storage config still start.\n for (const rel of [\n '/linked.backend.storage.ts',\n '/linked.backend.storage.js',\n '/backend-storage-config.ts',\n '/backend-storage-config.js',\n '/scripts/backend-storage-config.ts',\n '/scripts/backend-storage-config.js',\n '/scripts/storage-config.js',\n ]) {\n if (fsExtra.existsSync(path.join(cwd, rel.slice(1)))) {\n await vite.ssrLoadModule(rel);\n break;\n }\n }\n\n // Load LinkedServer through Vite SSR so it shares the SAME\n // module instances as everything else in the SSR call graph. Without\n // this, LinkedServer is loaded by Node (→ lib/esm) while CN's App.tsx +\n // its transitive imports are loaded by Vite (→ src/). React contexts\n // created in one tree don't reach consumers in the other, causing\n // \"Cannot destructure property 'isNativeApp' of useAppContext()\" type\n // errors on every SSR render.\n // Loading this entry through Vite is why `@_linked/server` is in\n // `SSR_ENTRY_PACKAGES` (vite-config.ts): the package's bare imports must go\n // through Vite as well, or some of its files evaluate once per loader.\n const ServerClass = (\n await vite.ssrLoadModule('@_linked/server/shapes/LinkedServer')\n ).LinkedServer;\n\n const server = new (ServerClass as any)(linkedConfig);\n\n // Surface stack traces from Vite ssrLoadModule failures cleanly.\n process.on('unhandledRejection', (err: any) => {\n if (err && err.stack) {\n try {\n vite.ssrFixStacktrace(err);\n } catch {\n // ignore\n }\n }\n console.error(err);\n });\n\n await server.start();\n\n // Watcher → onSourceChange wiring.\n //\n // Discover workspace packages once at boot. On each change, look up\n // which workspace package the file belongs to and call onSourceChange\n // with that package's npm name. LinkedServer disposes the old providers,\n // re-imports via vite.ssrLoadModule (transparent because Vite invalidated\n // the module already), and re-instantiates. No process restart.\n const workspacePackages = await discoverWorkspacePackages(cwd);\n if (workspacePackages.length > 0) {\n console.log(\n `[linked] watching ${workspacePackages.length} workspace packages for HMR`,\n );\n }\n // Reloads are DEBOUNCED and SERIALISED. `onSourceChange` disposes a\n // package's providers and re-registers their express routes, i.e. it mutates\n // the shared router stack. Firing it per file change (a multi-file save, a\n // format-on-save, a branch switch) ran overlapping dispose/re-register\n // cycles against that same stack with nothing ordering them. Collect the\n // affected packages over a short window, then run the cycles one at a time.\n const RELOAD_DEBOUNCE_MS = 150;\n const pendingReloads = new Set<string>();\n let reloadTimer: NodeJS.Timeout | undefined;\n // Tail of the reload chain — each flush appends, so cycles never interleave.\n let reloadChain: Promise<void> = Promise.resolve();\n\n const flushReloads = () => {\n const pkgs = [...pendingReloads];\n pendingReloads.clear();\n reloadChain = reloadChain.then(async () => {\n for (const pkg of pkgs) {\n try {\n await (server as any).onSourceChange(pkg);\n } catch (err: any) {\n console.warn(\n `[linked] reload of ${pkg} failed: ${err?.message ?? err}`,\n );\n }\n }\n });\n };\n\n vite.watcher.on('change', (filepath: string) => {\n if (!/\\.(tsx?|jsx?)$/.test(filepath)) return;\n const pkg = workspacePackageForPath(filepath, workspacePackages);\n if (!pkg) return;\n if (typeof (server as any).onSourceChange !== 'function') return;\n pendingReloads.add(pkg);\n clearTimeout(reloadTimer);\n reloadTimer = setTimeout(flushReloads, RELOAD_DEBOUNCE_MS);\n });\n\n // r/o keyboard shortcuts.\n const port = (linkedConfig.server as any).port ?? opts.port ?? 4040;\n installShortcuts({\n url: `http://localhost:${port}/`,\n onRestart: restartProcess,\n });\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { Plugin } from 'vite';
2
+ /** An ESTree parser — the plugin context's `this.parse` (Rollup's parser). */
3
+ export type ParseAst = (code: string) => any;
4
+ /**
5
+ * Returns `code` with the runtime name of every top-level tsc-style decorated
6
+ * class expression pinned, or `null` when there is nothing to pin (or the
7
+ * module does not parse as JavaScript).
8
+ */
9
+ export declare function pinDecoratedClassNames(code: string, parse: ParseAst): string | null;
10
+ export declare function pinCompiledClassNames(): Plugin;
11
+ //# sourceMappingURL=pin-compiled-class-names.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pin-compiled-class-names.d.ts","sourceRoot":"","sources":["../../../src/plugins/pin-compiled-class-names.ts"],"names":[],"mappings":"AA+BA,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,MAAM,CAAC;AAEjC,8EAA8E;AAC9E,MAAM,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,CAAC;AAO7C;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,QAAQ,GACd,MAAM,GAAG,IAAI,CA+Bf;AAED,wBAAgB,qBAAqB,IAAI,MAAM,CAU9C"}
@@ -0,0 +1,59 @@
1
+ /** Cheap pre-filter: a self-named class expression bound to a variable. */
2
+ const SELF_NAMED_CLASS = /\b(?:let|var|const)\s+([\w$]+)\s*=\s*(?:[\w$]+\s*=\s*)*class\s+\1\b/;
3
+ const JS_ID = /\.[cm]?js$/;
4
+ /**
5
+ * Returns `code` with the runtime name of every top-level tsc-style decorated
6
+ * class expression pinned, or `null` when there is nothing to pin (or the
7
+ * module does not parse as JavaScript).
8
+ */
9
+ export function pinDecoratedClassNames(code, parse) {
10
+ var _a;
11
+ if (!code.includes('__decorate(') || !SELF_NAMED_CLASS.test(code))
12
+ return null;
13
+ let ast;
14
+ try {
15
+ ast = parse(code);
16
+ }
17
+ catch (_b) {
18
+ return null;
19
+ }
20
+ const pins = [];
21
+ for (let node of ast.body) {
22
+ if (node.type === 'ExportNamedDeclaration' && node.declaration)
23
+ node = node.declaration;
24
+ if (node.type !== 'VariableDeclaration')
25
+ continue;
26
+ for (const decl of node.declarations) {
27
+ if (decl.id.type !== 'Identifier')
28
+ continue;
29
+ // `let Foo = Foo_1 = class Foo` — tsc's form when the class refers to itself.
30
+ let init = decl.init;
31
+ while (init && init.type === 'AssignmentExpression')
32
+ init = init.right;
33
+ if ((init === null || init === void 0 ? void 0 : init.type) === 'ClassExpression' && ((_a = init.id) === null || _a === void 0 ? void 0 : _a.name) === decl.id.name) {
34
+ pins.push({ at: node.end, name: decl.id.name });
35
+ }
36
+ }
37
+ }
38
+ if (pins.length === 0)
39
+ return null;
40
+ let out = code;
41
+ for (const { at, name } of pins.reverse()) {
42
+ const pin = ` Object.defineProperty(${name}, "name", {value: ${JSON.stringify(name)}, configurable: true});`;
43
+ out = out.slice(0, at) + pin + out.slice(at);
44
+ }
45
+ return out;
46
+ }
47
+ export function pinCompiledClassNames() {
48
+ return {
49
+ name: 'linked:pin-compiled-class-names',
50
+ enforce: 'pre',
51
+ transform(code, id) {
52
+ if (!JS_ID.test(id.split('?', 1)[0]))
53
+ return null;
54
+ const pinned = pinDecoratedClassNames(code, (c) => this.parse(c));
55
+ return pinned === null ? null : { code: pinned, map: null };
56
+ },
57
+ };
58
+ }
59
+ //# sourceMappingURL=pin-compiled-class-names.js.map
@@ -0,0 +1 @@
1
+ {"version":3,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time name of tsc-compiled decorated classes stable through Vite.\n//\n// A shape's IRI is built from its class name when `@linkedShape` is given no\n// explicit `name`, so anything that renames a shape class changes the shape's\n// identity. For a decorated class tsc emits\n//\n// let Foo = class Foo { ... };\n// Foo = __decorate([linkedShape], Foo);\n//\n// and esbuild, whenever it re-prints such a module, renames the inner binding\n// to avoid the shadowing: `let Foo = class Foo2`. The class is then called\n// `Foo2` at runtime — before any decorator sees it — and registers under the\n// wrong IRI. Vite re-prints a module with esbuild, without `keepNames`, in its\n// `vite:define` pass (client build: any module mentioning `process.env`,\n// `import.meta.env`, `import.meta.hot` or an app `define` key) and in the dev\n// client whenever a module mentions `process.env.NODE_ENV`. Neither pass can be\n// given `keepNames`, and `esbuild.keepNames` in the Vite config does not reach\n// them: it only reaches the minifier, which then keeps the already-wrong name.\n//\n// TypeScript source is not affected — esbuild lowers its decorators to an\n// anonymous `let Foo = class {`, which takes its name from the binding. Only\n// published lib JavaScript carries the self-named class expression.\n//\n// So before any of that runs, this plugin pins each such class's name with a\n// string literal placed right after its declaration — before the property and\n// class decorators run — which no later renaming can touch:\n//\n// let Foo = class Foo { ... }; Object.defineProperty(Foo, \"name\", {value: \"Foo\", configurable: true});\n//\n// The insertion is on the declaration's own last line and moves no code, so\n// existing source maps stay valid (`map: null`).\nimport type {Plugin} from 'vite';\n\n/** An ESTree parser — the plugin context's `this.parse` (Rollup's parser). */\nexport type ParseAst = (code: string) => any;\n\n/** Cheap pre-filter: a self-named class expression bound to a variable. */\nconst SELF_NAMED_CLASS =\n /\\b(?:let|var|const)\\s+([\\w$]+)\\s*=\\s*(?:[\\w$]+\\s*=\\s*)*class\\s+\\1\\b/;\nconst JS_ID = /\\.[cm]?js$/;\n\n/**\n * Returns `code` with the runtime name of every top-level tsc-style decorated\n * class expression pinned, or `null` when there is nothing to pin (or the\n * module does not parse as JavaScript).\n */\nexport function pinDecoratedClassNames(\n code: string,\n parse: ParseAst,\n): string | null {\n if (!code.includes('__decorate(') || !SELF_NAMED_CLASS.test(code))\n return null;\n let ast: any;\n try {\n ast = parse(code);\n } catch {\n return null;\n }\n const pins: {at: number; name: string}[] = [];\n for (let node of ast.body) {\n if (node.type === 'ExportNamedDeclaration' && node.declaration)\n node = node.declaration;\n if (node.type !== 'VariableDeclaration') continue;\n for (const decl of node.declarations) {\n if (decl.id.type !== 'Identifier') continue;\n // `let Foo = Foo_1 = class Foo` — tsc's form when the class refers to itself.\n let init = decl.init;\n while (init && init.type === 'AssignmentExpression') init = init.right;\n if (init?.type === 'ClassExpression' && init.id?.name === decl.id.name) {\n pins.push({at: node.end, name: decl.id.name});\n }\n }\n }\n if (pins.length === 0) return null;\n let out = code;\n for (const {at, name} of pins.reverse()) {\n const pin = ` Object.defineProperty(${name}, \"name\", {value: ${JSON.stringify(name)}, configurable: true});`;\n out = out.slice(0, at) + pin + out.slice(at);\n }\n return out;\n}\n\nexport function pinCompiledClassNames(): Plugin {\n return {\n name: 'linked:pin-compiled-class-names',\n enforce: 'pre',\n transform(code, id) {\n if (!JS_ID.test(id.split('?', 1)[0])) return null;\n const pinned = pinDecoratedClassNames(code, (c) => this.parse(c));\n return pinned === null ? null : {code: pinned, map: null};\n },\n };\n}\n"]}
@@ -7,10 +7,13 @@ export interface ExposedShape {
7
7
  * renamed their class.
8
8
  *
9
9
  * A shape's IRI is built from its class name unless `@linkedShape({name})`
10
- * gives one. `keepNames` in Vite's own TypeScript transform protects source
11
- * files, but published `lib/` JavaScript never goes through that transform —
12
- * only through the define pass above. So a compiled shape is exposed exactly
13
- * when it has no explicit name and its module contains a trigger. This is how
10
+ * gives one. Source files are safe: esbuild lowers their decorators to an
11
+ * anonymous `let Foo = class {`, which takes its name from the binding. Only
12
+ * published `lib/` JavaScript carries the self-named class expression, so a
13
+ * compiled shape is exposed exactly when it has no explicit name and its module
14
+ * contains a trigger. `createViteConfig` pins these names
15
+ * (`plugins/pin-compiled-class-names.ts`), but other bundlers and hand-written
16
+ * Vite configs do not, so the explicit name is still the fix. This is how
14
17
  * `@_linked/server`'s `LinkedServer` and `LincdAPI` came to register as
15
18
  * `LinkedServer2` / `LincdAPI2`.
16
19
  */
@@ -1 +1 @@
1
- {"version":3,"file":"shapeNames.d.ts","sourceRoot":"","sources":["../../../src/utils/shapeNames.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,MAAM,EACd,aAAS,KACR,YAAY,EASd,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAC1B,aAAa,MAAM,KAClB,OAAO,CAAC,IAAI,GAAG,MAAM,CA2BvB,CAAC"}
1
+ {"version":3,"file":"shapeNames.d.ts","sourceRoot":"","sources":["../../../src/utils/shapeNames.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,MAAM,EACd,aAAS,KACR,YAAY,EASd,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAC1B,aAAa,MAAM,KAClB,OAAO,CAAC,IAAI,GAAG,MAAM,CA2BvB,CAAC"}
@@ -27,10 +27,13 @@ const DECORATED = /\b([A-Za-z_$][\w$]*) = __decorate\(\[([\s\S]*?)\], \1\)/g;
27
27
  * renamed their class.
28
28
  *
29
29
  * A shape's IRI is built from its class name unless `@linkedShape({name})`
30
- * gives one. `keepNames` in Vite's own TypeScript transform protects source
31
- * files, but published `lib/` JavaScript never goes through that transform —
32
- * only through the define pass above. So a compiled shape is exposed exactly
33
- * when it has no explicit name and its module contains a trigger. This is how
30
+ * gives one. Source files are safe: esbuild lowers their decorators to an
31
+ * anonymous `let Foo = class {`, which takes its name from the binding. Only
32
+ * published `lib/` JavaScript carries the self-named class expression, so a
33
+ * compiled shape is exposed exactly when it has no explicit name and its module
34
+ * contains a trigger. `createViteConfig` pins these names
35
+ * (`plugins/pin-compiled-class-names.ts`), but other bundlers and hand-written
36
+ * Vite configs do not, so the explicit name is still the fix. This is how
34
37
  * `@_linked/server`'s `LinkedServer` and `LincdAPI` came to register as
35
38
  * `LinkedServer2` / `LincdAPI2`.
36
39
  */
@@ -1 +1 @@
1
- {"version":3,"file":"shapeNames.js","sourceRoot":"","sources":["../../../src/utils/shapeNames.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAG,wCAAwC,CAAC;AAEhE,kEAAkE;AAClE,MAAM,SAAS,GAAG,0DAA0D,CAAC;AAO7E;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,MAAc,EACd,IAAI,GAAG,EAAE,EACO,EAAE;IAClB,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5C,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,KAAK,MAAM,CAAC,EAAE,SAAS,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QACnE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC;YAAE,SAAS;QAClD,IAAI,wCAAwC,CAAC,IAAI,CAAC,UAAU,CAAC;YAAE,SAAS;QACxE,KAAK,CAAC,IAAI,CAAC,EAAC,IAAI,EAAE,SAAS,EAAC,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,WAAmB,EACK,EAAE;IAC1B,MAAM,MAAM,G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ent":["import fs from 'fs';\nimport path from 'path';\n\n/**\n * Text that makes Vite run an extra `esbuild.transform` over a compiled module.\n *\n * Vite's `vite:define` plugin transforms any module containing a `define` key\n * (`process.env` and `import.meta.env` / `import.meta.hot` are its own keys in\n * a client build), and in dev it rewrites `process.env.NODE_ENV` in client\n * modules the same way. That pass does not set `keepNames`, and esbuild\n * renames the inner binding of the class expression tsc emits for a decorated\n * class: `let Foo = class Foo` becomes `class Foo2`.\n */\nconst RENAME_TRIGGER = /process\\.env|import\\.meta\\.(?:env|hot)/;\n\n/** `Foo = __decorate([ …decorators… ], Foo)`, as tsc emits it. */\nconst DECORATED = /\\b([A-Za-z_$][\\w$]*) = __decorate\\(\\[([\\s\\S]*?)\\], \\1\\)/g;\n\nexport interface ExposedShape {\n file: string;\n className: string;\n}\n\n/**\n * Shapes in one compiled module whose identity would change if a bundler\n * renamed their class.\n *\n * A shape's IRI is built from its class name unless `@linkedShape({name})`\n * gives one. `keepNames` in Vite's own TypeScript transform protects source\n * files, but published `lib/` JavaScript never goes through that transform —\n * only through the define pass above. So a compiled shape is exposed exactly\n * when it has no explicit name and its module contains a trigger. This is how\n * `@_linked/server`'s `LinkedServer` and `LincdAPI` came to register as\n * `LinkedServer2` / `LincdAPI2`.\n */\nexport const findRenameableShapes = (\n source: string,\n file = '',\n): ExposedShape[] => {\n if (!RENAME_TRIGGER.test(source)) return [];\n const found: ExposedShape[] = [];\n for (const [, className, decorators] of source.matchAll(DECORATED)) {\n if (!/\\blinkedShape\\b/.test(decorators)) continue;\n if (/\\blinkedShape\\(\\s*\\{[\\s\\S]*?\\bname\\s*:/.test(decorators)) continue;\n found.push({file, className});\n }\n return found;\n};\n\n/**\n * Build step: warn about every exposed shape in a package's compiled ESM.\n *\n * A warning, not a failure: it is only a hazard when a consumer's bundler\n * actually rewrites the module, and naming the shape is a change to the\n * package's source that its owner has to make.\n */\nexport const checkShapeNames = async (\n packagePath: string,\n): Promise<true | string> => {\n const libDir = path.join(packagePath, 'lib', 'esm');\n if (!fs.existsSync(libDir)) return true;\n const exposed: ExposedShape[] = [];\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.name.endsWith('.js')) {\n exposed.push(\n ...findRenameableShapes(\n fs.readFileSync(full, 'utf8'),\n path.relative(libDir, full),\n ),\n );\n }\n }\n };\n walk(libDir);\n if (exposed.length === 0) return true;\n const listed = exposed.map((s) => `${s.className} (${s.file})`).join(', ');\n return (\n `${exposed.length} shape(s) take their identity from a class name that a ` +\n `consumer's bundler may rename, because the module also reads process.env or ` +\n `import.meta.env: ${listed}. Give each an explicit name: ` +\n `@linkedShape({name: '<ClassName>'}).`\n );\n};\n"]}
1
+ {"version":3,"file":"shapeNames.js","sourceRoot":"","sources":["../../../src/utils/shapeNames.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAG,wCAAwC,CAAC;AAEhE,kEAAkE;AAClE,MAAM,SAAS,GAAG,0DAA0D,CAAC;AAO7E;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,MAAc,EACd,IAAI,GAAG,EAAE,EACO,EAAE;IAClB,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5C,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,KAAK,MAAM,CAAC,EAAE,SAAS,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QACnE,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC;YAAE,SAAS;QAClD,IAAI,wCAAwC,CAAC,IAAI,CAAC,UAAU,CAAC;YAAE,SAAS;QACxE,KAAK,CAA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AAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3E,OAAO,CACL,GAAG,OAAO,CAAC,MAAM,yDAAyD;QAC1E,8EAA8E;QAC9E,oBAAoB,MAAM,gCAAgC;QAC1D,sCAAsC,CACvC,CAAC;AACJ,CAAC,CAAA,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\n\n/**\n * Text that makes Vite run an extra `esbuild.transform` over a compiled module.\n *\n * Vite's `vite:define` plugin transforms any module containing a `define` key\n * (`process.env` and `import.meta.env` / `import.meta.hot` are its own keys in\n * a client build), and in dev it rewrites `process.env.NODE_ENV` in client\n * modules the same way. That pass does not set `keepNames`, and esbuild\n * renames the inner binding of the class expression tsc emits for a decorated\n * class: `let Foo = class Foo` becomes `class Foo2`.\n */\nconst RENAME_TRIGGER = /process\\.env|import\\.meta\\.(?:env|hot)/;\n\n/** `Foo = __decorate([ …decorators… ], Foo)`, as tsc emits it. */\nconst DECORATED = /\\b([A-Za-z_$][\\w$]*) = __decorate\\(\\[([\\s\\S]*?)\\], \\1\\)/g;\n\nexport interface ExposedShape {\n file: string;\n className: string;\n}\n\n/**\n * Shapes in one compiled module whose identity would change if a bundler\n * renamed their class.\n *\n * A shape's IRI is built from its class name unless `@linkedShape({name})`\n * gives one. Source files are safe: esbuild lowers their decorators to an\n * anonymous `let Foo = class {`, which takes its name from the binding. Only\n * published `lib/` JavaScript carries the self-named class expression, so a\n * compiled shape is exposed exactly when it has no explicit name and its module\n * contains a trigger. `createViteConfig` pins these names\n * (`plugins/pin-compiled-class-names.ts`), but other bundlers and hand-written\n * Vite configs do not, so the explicit name is still the fix. This is how\n * `@_linked/server`'s `LinkedServer` and `LincdAPI` came to register as\n * `LinkedServer2` / `LincdAPI2`.\n */\nexport const findRenameableShapes = (\n source: string,\n file = '',\n): ExposedShape[] => {\n if (!RENAME_TRIGGER.test(source)) return [];\n const found: ExposedShape[] = [];\n for (const [, className, decorators] of source.matchAll(DECORATED)) {\n if (!/\\blinkedShape\\b/.test(decorators)) continue;\n if (/\\blinkedShape\\(\\s*\\{[\\s\\S]*?\\bname\\s*:/.test(decorators)) continue;\n found.push({file, className});\n }\n return found;\n};\n\n/**\n * Build step: warn about every exposed shape in a package's compiled ESM.\n *\n * A warning, not a failure: it is only a hazard when a consumer's bundler\n * actually rewrites the module, and naming the shape is a change to the\n * package's source that its owner has to make.\n */\nexport const checkShapeNames = async (\n packagePath: string,\n): Promise<true | string> => {\n const libDir = path.join(packagePath, 'lib', 'esm');\n if (!fs.existsSync(libDir)) return true;\n const exposed: ExposedShape[] = [];\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.name.endsWith('.js')) {\n exposed.push(\n ...findRenameableShapes(\n fs.readFileSync(full, 'utf8'),\n path.relative(libDir, full),\n ),\n );\n }\n }\n };\n walk(libDir);\n if (exposed.length === 0) return true;\n const listed = exposed.map((s) => `${s.className} (${s.file})`).join(', ');\n return (\n `${exposed.length} shape(s) take their identity from a class name that a ` +\n `consumer's bundler may rename, because the module also reads process.env or ` +\n `import.meta.env: ${listed}. Give each an explicit name: ` +\n `@linkedShape({name: '<ClassName>'}).`\n );\n};\n"]}
@@ -126,6 +126,22 @@ export declare function discoverLinkedSourceDependencies(cwd?: string): Promise<
126
126
  * dependencies for.
127
127
  */
128
128
  export declare function discoverWorkspaces(extraGlobs?: string[], cwd?: string): Promise<WorkspaceEntry[]>;
129
+ /**
130
+ * Packages whose entry `linked start` hands to `vite.ssrLoadModule` by name
131
+ * (`@_linked/server/shapes/LinkedServer`, see `commands/start.ts`).
132
+ *
133
+ * Vite transforms an explicitly requested entry, and every file it reaches by
134
+ * RELATIVE import, whether or not the package is external. The same package's
135
+ * bare-specifier imports from anywhere else (the app's `src`, the storage
136
+ * config) are externalized to Node. Left external, the package is split across
137
+ * two loaders, and which copy a file ends up in depends on import order: a file
138
+ * the module runner has already evaluated is reused, one it has not is loaded
139
+ * by Node, and Node then loads that file's relative imports itself. Measured in
140
+ * CN: `package.js` and `ontologies/lincd-server.js` evaluated once by each
141
+ * loader, and `LocalFileStore.js` too once the package's `backend` was loaded.
142
+ * Bundling the package makes Vite the only loader for it.
143
+ */
144
+ export declare const SSR_ENTRY_PACKAGES: string[];
129
145
  /**
130
146
  * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those
131
147
  * package names are bundled by Vite; everything else in node_modules (including
@@ -134,6 +150,7 @@ export declare function discoverWorkspaces(extraGlobs?: string[], cwd?: string):
134
150
  * Installed packages that depend on a workspace (`dependents`, from
135
151
  * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.
136
152
  * Standalone (no workspaces): the context-holding framework packages are bundled.
153
+ * In both modes, `SSR_ENTRY_PACKAGES` are bundled.
137
154
  */
138
155
  export declare function ssrNoExternal(workspaces: {
139
156
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"vite-config.d.ts","sourceRoot":"","sources":["../../src/vite-config.ts"],"names":[],"mappings":"AAWA,OAAO,EAAC,YAAY,EAAC,MAAM,MAAM,CAAC;AAMlC,OAAO,KAAK,EAAC,MAAM,EAAa,MAAM,MAAM,CAAC;AAuB7C;;;;;;;;;;;;;;;GAeG;AACH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB,GAAI,IAAI,MAAM,KAAG,MAAM,GAAG,SAyDtD,CAAC;AAEF,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAQnD;AAED,MAAM,WAAW,uBAAuB;IACtC,qCAAqC;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,yBAAyB;IACzB,OAAO,CAAC,EAAE,UAAU,GAAG,kBAAkB,CAAC;IAC1C,iEAAiE;IACjE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0BAA0B;IAC1B,OAAO,CAAC,EAAE,MAAM,E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AACH,wBAAsB,gCAAgC,CACpD,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,cAAc,EAAE,CAAC,CAmC3B;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CACtC,UAAU,GAAE,MAAM,EAAO,EACzB,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,cAAc,EAAE,CAAC,CAyD3B;AAwCD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,kBAAkB,UAAsB,CAAC;AAEtD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAC3B,UAAU,EAAE;IAAC,IAAI,EAAE,MAAM,CAAA;CAAC,EAAE,EAC5B,UAAU,GAAE,MAAM,EAAO,GACxB,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAKrB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,IAAI,GAAE,IAAI,CAAC,uBAAuB,EAAE,QAAQ,GAAG,MAAM,CAAM,GAC1D,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAED,wBAAgB,gBAAgB,CAAC,IAAI,GAAE,uBAA4B,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAuXpG"}
@@ -24,6 +24,7 @@ import fsExtra from 'fs-extra';
24
24
  import path from 'node:path';
25
25
  import { generateScopedName } from './utils.js';
26
26
  import { parseWorkspacePatterns, isWorkspacePathNegated } from './workspace-globs.js';
27
+ import { pinCompiledClassNames } from './plugins/pin-compiled-class-names.js';
27
28
  /**
28
29
  * Framework packages that MUST be single-instance per runtime — they hold
29
30
  * module-level state (`@_linked/core`'s shape registry, `LinkedStorage`, the query
@@ -468,6 +469,22 @@ function resolveWorkspaceSpecifier(specifier, workspaces) {
468
469
  return null;
469
470
  });
470
471
  }
472
+ /**
473
+ * Packages whose entry `linked start` hands to `vite.ssrLoadModule` by name
474
+ * (`@_linked/server/shapes/LinkedServer`, see `commands/start.ts`).
475
+ *
476
+ * Vite transforms an explicitly requested entry, and every file it reaches by
477
+ * RELATIVE import, whether or not the package is external. The same package's
478
+ * bare-specifier imports from anywhere else (the app's `src`, the storage
479
+ * config) are externalized to Node. Left external, the package is split across
480
+ * two loaders, and which copy a file ends up in depends on import order: a file
481
+ * the module runner has already evaluated is reused, one it has not is loaded
482
+ * by Node, and Node then loads that file's relative imports itself. Measured in
483
+ * CN: `package.js` and `ontologies/lincd-server.js` evaluated once by each
484
+ * loader, and `LocalFileStore.js` too once the package's `backend` was loaded.
485
+ * Bundling the package makes Vite the only loader for it.
486
+ */
487
+ export const SSR_ENTRY_PACKAGES = ['@_linked/server'];
471
488
  /**
472
489
  * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those
473
490
  * package names are bundled by Vite; everything else in node_modules (including
@@ -476,11 +493,13 @@ function resolveWorkspaceSpecifier(specifier, workspaces) {
476
493
  * Installed packages that depend on a workspace (`dependents`, from
477
494
  * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.
478
495
  * Standalone (no workspaces): the context-holding framework packages are bundled.
496
+ * In both modes, `SSR_ENTRY_PACKAGES` are bundled.
479
497
  */
480
498
  export function ssrNoExternal(workspaces, dependents = []) {
481
- if (workspaces.length === 0)
482
- return [/^@_linked\/server-utils$/, /^@_linked\/react$/];
483
- return [...new Set([...workspaces.map((w) => w.name), ...dependents])];
499
+ if (workspaces.length === 0) {
500
+ return [/^@_linked\/server-utils$/, /^@_linked\/react$/, ...SSR_ENTRY_PACKAGES];
501
+ }
502
+ return [...new Set([...workspaces.map((w) => w.name), ...dependents, ...SSR_ENTRY_PACKAGES])];
484
503
  }
485
504
  /**
486
505
  * The `process.env.*` values inlined into the browser bundle — and only there.
@@ -615,6 +634,9 @@ export function createViteConfig(opts = {}) {
615
634
  },
616
635
  }
617
636
  : null,
637
+ // Published lib JS: keep decorated shape classes named `Foo`, not the
638
+ // `Foo2` Vite's esbuild re-prints would give them — see the plugin.
639
+ pinCompiledClassNames(),
618
640
  react({
619
641
  babel: {
620
642
  parserOpts: {
@@ -660,6 +682,10 @@ export function createViteConfig(opts = {}) {
660
682
  // `.../BackendAPIStore`, and every Server.call on that shape 501'd.
661
683
  // The same mangling made registration report `Shape undefined does not
662
684
  // extend base class`.
685
+ //
686
+ // Vite honours this in the minifier only: its per-file TypeScript
687
+ // transform and its define pass both run esbuild with keepNames off.
688
+ // `pinCompiledClassNames` above covers what those passes rename.
663
689
  keepNames: true,
664
690
  } }, (isStandalone
665
691
  ? {
@@ -719,8 +745,9 @@ export function createViteConfig(opts = {}) {
719
745
  // DIFFERENT module instances → two `AppContext` objects → `useAppContext()` sees
720
746
  // no provider (null) → "Cannot destructure 'isNativeApp'" and a blank "SSR timed
721
747
  // out". Bundling makes them one instance in Vite's SSR module graph (matching how
722
- // workspace mode bundles everything). Native-dep packages (`server`/`fuseki`) stay
723
- // external so their prebuilt binaries load via Node.
748
+ // workspace mode bundles everything). `fuseki` stays external; `server` is bundled
749
+ // because `start` loads its entry through Vite (`SSR_ENTRY_PACKAGES`). Their native
750
+ // dependencies (e.g. `sharp`) are separate packages and stay external either way.
724
751
  //
725
752
  // WORKSPACE: bundle ONLY the discovered source workspaces (they resolve to `src/`
726
753
  // for HMR). Published framework packages installed under node_modules (lib-only)
@@ -730,7 +757,8 @@ export function createViteConfig(opts = {}) {
730
757
  // as `@_linked/fuseki/shapes/FusekiStore` through native `import()`, which pulled
731
758
  // a SECOND Node-loaded core and split the shape registry. Installed packages
732
759
  // that depend on a workspace (e.g. published fuseki when core itself is a
733
- // workspace) are bundled too, so they import the Vite-loaded workspace.
760
+ // workspace) are bundled too, so they import the Vite-loaded workspace. The one
761
+ // published exception is `SSR_ENTRY_PACKAGES`, which Vite loads regardless.
734
762
  //
735
763
  // NOT DEV (a release build of the backend): nothing is force-bundled. The
736
764
  // compiled backend is loaded by Node next to the installed
@@ -1 +1 @@
1
- {"version":3,"file":"vite-config.js","sourceRoot":"","sources":["../../src/vite-config.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oEAAoE;AACpE,EAAE;AACF,+CAA+C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AyE;YACzE,0EAA0E;YAC1E,mEAAmE;YACnE,8CAA8C;YAC9C,YAAY,EAAE;gBACZ,MAAM,EAAE;oBACN,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC;iBAC3B;aACF,KAYE,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC;YACvB,CAAC,CAAC,EAAC,YAAY,EAAE,EAAC,OAAO,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAC,EAAC;YAC1D,CAAC,CAAC,YAAY,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;gBACrC,CAAC,CAAC,EAAC,YAAY,EAAE,EAAC,OAAO,EAAE,UAAU,EAAC,EAAC;gBACvC,CAAC,CAAC,EAAE,CAAC,CACV,CAAC;QAEF,sEAAsE;QACtE,IAAI,IAAI,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;YAChC,gEAAgE;YAChE,iEAAiE;YACjE,gEAAgE;YAChE,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAQ,MAAM,MAAM,CAAC,mBAA0B,CAAC,CAAC;gBAC/D,MAAM,cAAc,GAAG,MAAA,QAAQ,CAAC,OAAO,mCAAI,QAAQ,CAAC;gBACnD,MAAM,CAAC,OAAoB,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,IAAI,CACV,4DAA4D;oBAC1D,gEAAgE;oBAChE,sDAAsD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Vite config helper for linked apps. The one dev + build pipeline.\n//\n// Apps use this from their own vite.config.ts:\n//\n// import {createViteConfig} from '@_linked/cli/vite';\n// export default createViteConfig({port: 4040, cssMode: 'tailwind'});\n//\n// The helper preserves the dev-mode `generateScopedName` (readable\n// `_packageName_filename_className`) so CSS module class names match\n// what the previous bundler chain produced for trace/debug. Production\n// uses Vite's default scoping (content-hash, equivalent uniqueness).\nimport {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fsExtra from 'fs-extra';\nimport path from 'node:path';\nimport {generateScopedName} from './utils.js';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from './workspace-globs.js';\nimport type {Plugin, UserConfig} from 'vite';\n\n/**\n * Framework packages that MUST be single-instance per runtime — they hold\n * module-level state (`@_linked/core`'s shape registry, `LinkedStorage`, the query\n * context) or register shapes into it. Two copies in one runtime split that state\n * and mangle shape identity (`Person`→`Person2`). This ONE list is the single source\n * of truth for the standalone `optimizeDeps.exclude` (`linkedDeps`). In workspace mode\n * `ssr.noExternal` is keyed on the discovered source workspaces instead (see\n * `ssrNoExternal`), so published framework packages stay external and single-instance\n * under Node.\n */\nconst FRAMEWORK_PKG_PATTERNS: RegExp[] = [/^@_linked\\//, /^lincd-/];\nconst isFrameworkPkg = (name: string): boolean =>\n FRAMEWORK_PKG_PATTERNS.some((re) => re.test(name));\n\n/** Default dev server port, and Vite's default HMR websocket port. */\nconst DEFAULT_DEV_PORT = 4040;\nconst DEFAULT_HMR_PORT = 24678;\n/** Vite may not bind below 1024 without privileges; 65535 is the TCP ceiling. */\nconst MIN_HMR_PORT = 1024;\nconst MAX_HMR_PORT = 65535;\n\n/**\n * Derive an app's HMR websocket port from its dev port.\n *\n * Every `createViteConfig` app used to fall back to Vite's shared default\n * 24678, so any two dev servers running at once collided (\"Port 24678 is\n * already in use\") and HMR silently broke for the loser. Offsetting the HMR\n * port by the same amount the dev port is offset from its default keeps the\n * derivation trivial and means apps that already run on distinct dev ports get\n * distinct HMR ports for free.\n *\n * The input is untrusted (`process.env.PORT` is an arbitrary string), so\n * anything that is not a whole port number — `PORT=abc` yielding `NaN`, a\n * negative or out-of-range value — falls back to the dev port default. The\n * result is then clamped into the bindable range, since a far-out dev port\n * would otherwise derive an HMR port past 65535.\n */\n/**\n * Which manual chunk a module belongs in.\n *\n * Split large/common deps so route chunks don't all carry their own copy AND\n * the main entry doesn't end up at 5MB+. Each chunk becomes its own\n * `assets/<name>-<hash>.js` the browser caches independently — incremental\n * dev builds and cache wins on prod deploys both improve.\n *\n * Exported so the grouping can be asserted directly: getting it wrong does not\n * fail the build, it produces a bundle that throws on load in the browser.\n */\nexport const chunkForModuleId = (id: string): string | undefined => {\n if (!id.includes('node_modules')) {\n // Linked workspaces ship as @_linked/* / lincd-* — group all\n // linked-framework code into a single chunk.\n if (\n id.includes('/packages/core/') ||\n id.includes('/packages/react/') ||\n id.includes('/packages/server-utils/') ||\n id.includes('/packages/primitives/') ||\n id.includes('/packages/css/') ||\n /\\/packages\\/(auth|org|schema|fuseki|owl|xsd|dcat|dcmi|s3|sentry|ui)\\//.test(id)\n ) {\n return 'linked';\n }\n return undefined;\n }\n // Framework code installed from the registry rather than resolved to a\n // workspace. An app can hold both at once — a published `@_linked/server`\n // in node_modules next to workspace `@_linked/core` — and the two import\n // each other. Split across `linked` and `vendor` that is a cycle, and\n // Rollup's chosen order left a binding in its temporal dead zone:\n // `Cannot access 'Wo' before initialization` before the app rendered.\n // Same chunk, no cycle.\n if (/[\\\\/]node_modules[\\\\/](@_linked[\\\\/]|lincd-)/.test(id)) {\n return 'linked';\n }\n // React + React-DOM in their own chunk — every route uses them.\n //\n // react-router and @remix-run/router belong here too. Left in `vendor` they\n // made the two chunks import each other: react-router-dom re-exports\n // react-router, so react-vendor imported vendor, while vendor's own\n // top-level `React.createContext(...)` calls imported react-vendor. Rollup\n // has to pick an order for a cycle, and it ran vendor first — every\n // production build died on load with \"Cannot read properties of undefined\n // (reading 'createContext')\".\n if (\n /[\\\\/]node_modules[\\\\/](react|react-dom|react-router-dom|react-router|@remix-run[\\\\/]router|scheduler)[\\\\/]/.test(\n id\n )\n ) {\n return 'react-vendor';\n }\n // Heavy editor deps — only loaded on pages that need them, but worth\n // isolating so they don't get pulled into main.\n if (/[\\\\/]node_modules[\\\\/]@monaco-editor[\\\\/]/.test(id)) {\n return 'monaco';\n }\n // Charting/visualization\n if (/[\\\\/]node_modules[\\\\/](recharts|react-flow|@xyflow|d3-)[\\\\/]/.test(id)) {\n return 'viz';\n }\n // Animation\n if (/[\\\\/]node_modules[\\\\/]framer-motion[\\\\/]/.test(id)) {\n return 'motion';\n }\n // Catch-all for other node_modules in a vendor chunk\n return 'vendor';\n};\n\nexport function hmrPortFor(devPort: unknown): number {\n const parsed = Number(devPort);\n const validDevPort =\n Number.isFinite(parsed) && Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535\n ? parsed\n : DEFAULT_DEV_PORT;\n const derived = DEFAULT_HMR_PORT + (validDevPort - DEFAULT_DEV_PORT);\n return Math.min(MAX_HMR_PORT, Math.max(MIN_HMR_PORT, derived));\n}\n\nexport interface LinkedViteConfigOptions {\n /** Dev server port. Default 4040. */\n port?: number;\n /** Output dir for `vite build`. Default `public/bundles`. */\n outDir?: string;\n /** CSS pipeline mode. */\n cssMode?: 'tailwind' | 'css-modules-only';\n /** Entry file for the client bundle. Default `src/index.tsx`. */\n entry?: string;\n /** Extra Vite plugins. */\n plugins?: Plugin[];\n /** Extra PostCSS plugins (e.g. `postcss-media-to-container`). */\n postcssPlugins?: unknown[];\n /**\n * Extra `define` entries for the CLIENT environment only (used to bridge\n * `process.env.X` refs into the browser). Never applied server-side.\n */\n define?: Record<string, string>;\n /**\n * Extra workspace globs (trailing `/*`, or a direct package dir) resolved\n * RELATIVE TO the app's cwd, in ADDITION to the app's own `workspaces` field.\n *\n * For apps whose linked-package sources live OUTSIDE their own workspace tree\n * — e.g. an app consumes `packages/lincd.org/modules/*`, which sit one level\n * up (`../lincd.org/modules/*`) when the app runs inside the CN monorepo, and under\n * `packages/lincd.org/modules/*` when the app runs from its own root. Pass BOTH\n * candidate layouts; only globs whose parent dir actually exists are scanned,\n * so the same config works in either checkout. Each glob's packages are\n * registered as source workspaces (resolved to `src/` for HMR + single-instance),\n * exactly like the app's own `workspaces` field.\n */\n workspaceGlobs?: string[];\n}\n\ninterface WorkspaceEntry {\n name: string;\n srcDir: string;\n}\n\n// Resolve a dependency name to its installed package.json the way Node does:\n// look in `<dir>/node_modules/<name>`, then each parent directory's\n// node_modules, starting from the requiring package's directory. This finds\n// deps that npm/yarn workspaces HOISTED to the monorepo root (an app under\n// `services/api` whose dep lives in `<root>/node_modules`). The walk stops\n// after the nearest directory whose package.json declares `workspaces` (the\n// workspace root), or at the filesystem root. Returns null when the package\n// isn't installed (e.g. an optional dep) — we skip rather than throw.\nasync function isWorkspaceRoot(dir: string): Promise<boolean> {\n try {\n const json = await fsExtra.readJson(path.join(dir, 'package.json'));\n return !!json.workspaces;\n } catch {\n return false;\n }\n}\n\nasync function readInstalledPkg(\n name: string,\n fromDir: string,\n): Promise<{root: string; json: any} | null> {\n let dir = path.resolve(fromDir);\n while (true) {\n const root = path.join(dir, 'node_modules', name);\n const pkgJson = path.join(root, 'package.json');\n if (await fsExtra.pathExists(pkgJson)) {\n try {\n return {root, json: await fsExtra.readJson(pkgJson)};\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir || (await isWorkspaceRoot(dir))) return null;\n dir = parent;\n }\n}\n\n/**\n * Names of installed packages that depend, directly or transitively (via\n * `dependencies` / `peerDependencies`), on a discovered source workspace. Such a\n * package must also go through Vite SSR: if Node loaded it natively, it would\n * import its own Node-loaded copy of the workspace (e.g. published\n * `@_linked/fuseki` importing a workspace `@_linked/core`), splitting module\n * state. Vite rewrites the dynamic `import()` in code it transforms, so bundling\n * the dependents keeps one instance.\n *\n * Only the dependency closure of the app's `package.json` (dependencies +\n * devDependencies) and of the workspaces themselves is scanned. Packages are\n * resolved Node-style, keyed by real path, and unresolvable ones are ignored.\n * Workspace names are not included in the result.\n */\nexport async function workspaceDependents(\n workspaces: {name: string; srcDir?: string}[],\n cwd: string = process.cwd(),\n): Promise<string[]> {\n if (workspaces.length === 0) return [];\n const fs = await import('node:fs/promises');\n const wsNames = new Set(workspaces.map((w) => w.name));\n // realRoot -> {name, deps (realRoots)}\n const nodes = new Map<string, {name: string; deps: Set<string>}>();\n const realpath = async (p: string): Promise<string> => {\n try {\n return await fs.realpath(p);\n } catch {\n return path.resolve(p);\n }\n };\n\n const visit = async (root: string, json: any): Promise<string> => {\n const real = await realpath(root);\n if (nodes.has(real)) return real;\n const node = {name: json.name as string, deps: new Set<string>()};\n nodes.set(real, node);\n const names = new Set([\n ...Object.keys(json.dependencies ?? {}),\n ...Object.keys(json.peerDependencies ?? {}),\n ]);\n for (const dep of names) {\n const resolved = await readInstalledPkg(dep, real);\n if (resolved) node.deps.add(await visit(resolved.root, resolved.json));\n }\n return real;\n };\n\n // Seed: the app's direct deps, plus each workspace package's own deps.\n try {\n const appPkg = await fsExtra.readJson(path.join(cwd, 'package.json'));\n for (const dep of Object.keys({...appPkg.dependencies, ...appPkg.devDependencies})) {\n const resolved = await readInstalledPkg(dep, cwd);\n if (resolved) await visit(resolved.root, resolved.json);\n }\n } catch {}\n for (const ws of workspaces) {\n if (!ws.srcDir) continue;\n const root = path.dirname(ws.srcDir);\n try {\n await visit(root, await fsExtra.readJson(path.join(root, 'package.json')));\n } catch {}\n }\n\n // Walk reverse edges from every workspace node: everything reached depends on one.\n const dependentsOf = new Map<string, string[]>();\n for (const [key, node] of nodes) {\n for (const dep of node.deps) {\n if (!dependentsOf.has(dep)) dependentsOf.set(dep, []);\n dependentsOf.get(dep)!.push(key);\n }\n }\n const queue = [...nodes].filter(([, n]) => wsNames.has(n.name)).map(([k]) => k);\n const marked = new Set(queue);\n while (queue.length) {\n for (const parent of dependentsOf.get(queue.pop()!) ?? []) {\n if (!marked.has(parent)) {\n marked.add(parent);\n queue.push(parent);\n }\n }\n }\n const out = new Set<string>();\n for (const key of marked) {\n const name = nodes.get(key)!.name;\n if (name && !wsNames.has(name)) out.add(name);\n }\n return [...out].sort();\n}\n\n/**\n * Read a package root as a SOURCE install: `{name, srcDir}` iff it has a\n * package.json with a name and ships a `src/` dir. Published packages have only\n * `lib/` and are skipped — they resolve via their exports.\n */\nasync function readSourcePackage(root: string): Promise<WorkspaceEntry | null> {\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return null;\n const srcDir = path.join(root, 'src');\n if (!(await fsExtra.pathExists(srcDir))) return null;\n try {\n const json = await fsExtra.readJson(pkgPath);\n return json.name ? {name: json.name, srcDir} : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Linked packages installed as SOURCE, found by walking the app's\n * `dependencies` + `devDependencies` (and recursing through the `dependencies`\n * of each linked package found), keeping those marked `\"linkedPackage\": true`\n * — the same marker the CLI keys on (see cli-methods.ts) — and registering the\n * ones that ship `src/`.\n *\n * A dep ships `src/` when it is a symlinked workspace clone, a `link:`/`portal:`\n * dev install, or a LOCALIZED checkout (`packages-local/<pkg>`, in no workspace\n * glob). That's what lets a STANDALONE app (not itself a workspace root — e.g. a\n * per-branch clone under /apps) resolve a linked package's `.tsx` sources with\n * extension probing, instead of falling through to the package's\n * `development → ./src/*.ts` export (which misses `.tsx` like LinkedServer). A\n * prod/ejected app installs PUBLISHED packages (no `src/`) → not registered,\n * resolved via each package's `lib`.\n *\n * The marker — NOT the npm scope — drives discovery, so a user's own\n * custom-scope published linked package (e.g. `@acme/foo` with\n * `linkedPackage:true`) is picked up too, and linked packages present in\n * node_modules but not depended upon are ignored.\n *\n * Every root is REALPATHED before it is registered: `readInstalledPkg` returns\n * the `node_modules/<name>` symlink spelling, and Vite's resolver realpaths\n * every id it produces, so registering the symlink would give one file two\n * module ids — two instances of the same module.\n *\n * Shared by the Vite resolver table (`discoverWorkspaces`) and the `linked start`\n * HMR watch set, so the two cannot disagree about what is source.\n */\nexport async function discoverLinkedSourceDependencies(\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const pkgPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return [];\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n const walk = async (\n deps: Record<string, string> | undefined,\n fromDir: string,\n ): Promise<void> => {\n for (const name of Object.keys(deps ?? {})) {\n if (visited.has(name)) continue;\n visited.add(name);\n const resolved = await readInstalledPkg(name, fromDir);\n if (!resolved) continue;\n if (resolved.json.linkedPackage !== true) continue;\n let realRoot = resolved.root;\n try {\n realRoot = await fs.realpath(resolved.root);\n } catch {}\n const entry = await readSourcePackage(realRoot);\n if (entry && !seen.has(entry.name)) {\n seen.add(entry.name);\n out.push(entry);\n }\n // Recurse from the real location, so a symlinked clone resolves its own\n // dependencies from its source dir.\n await walk(resolved.json.dependencies, realRoot);\n }\n };\n const appPkg = await fsExtra.readJson(pkgPath);\n await walk(appPkg.dependencies, cwd);\n await walk(appPkg.devDependencies, cwd);\n return out;\n}\n\n/**\n * Walk the app's package.json `workspaces` field to build a lookup table\n * from npm name → absolute src/ directory. Used by the resolver plugin\n * to map bare specifiers like `@_linked/foo/bar` directly to source.\n *\n * Positive patterns are expanded by directory listing, so only a trailing `/*`\n * is honoured. NEGATED patterns (`\"!packages/core\"`) are honoured in full, with\n * npm's semantics — see ./workspace-globs.js. Skipping them would resolve a\n * package to an excluded directory that the package manager never installed\n * dependencies for.\n */\nexport async function discoverWorkspaces(\n extraGlobs: string[] = [],\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n // Register a package root iff it ships a `src/` dir (source install).\n const addFromRoot = async (root: string): Promise<void> => {\n const entry = await readSourcePackage(root);\n if (!entry || seen.has(entry.name)) return;\n seen.add(entry.name);\n out.push(entry);\n };\n\n // 1. The app's own `workspaces` globs — the monorepo-root case (CN, or any app\n // that is itself a workspace root). Only trailing `/*` patterns.\n const pkgPath = path.join(cwd, 'package.json');\n if (await fsExtra.pathExists(pkgPath)) {\n const pkg = await fsExtra.readJson(pkgPath);\n // Merge the app's own `workspaces` globs with any caller-supplied\n // `workspaceGlobs` (e.g. `../lincd.org/modules/*`). Non-existent parents\n // are skipped below, so passing both nested + standalone layouts is safe.\n // Either list may carry negations, so they are parsed together.\n const {patterns, negatedPatterns} = parseWorkspacePatterns([\n ...(Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? []),\n ...extraGlobs,\n ]);\n const addUnlessNegated = async (root: string): Promise<void> => {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) return;\n await addFromRoot(root);\n };\n for (const pattern of patterns) {\n const m = pattern.match(/^(.+?)\\/\\*$/);\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n for (const ent of await fs.readdir(parent, {withFileTypes: true})) {\n if (ent.isDirectory() || ent.isSymbolicLink()) {\n await addUnlessNegated(path.join(parent, ent.name));\n }\n }\n }\n } else {\n await addUnlessNegated(path.join(cwd, pattern));\n }\n }\n }\n\n // 2. Linked deps installed as source — including a localized checkout that is\n // in no workspace glob. Shared with the `linked start` watch set; see\n // discoverLinkedSourceDependencies above. Glob entries win on a name clash.\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (seen.has(entry.name)) continue;\n seen.add(entry.name);\n out.push(entry);\n }\n\n return out;\n}\n\n/**\n * Resolve a bare specifier like `@_linked/foo/bar`, `lincd-rdfs/Foo`, or\n * `pkg/utils/Bar.js` against the workspace lookup. Tries extensions in\n * order: .ts, .tsx, then the literal id (for files that already include\n * an extension or for non-TS assets). Returns null when the specifier\n * doesn't match any workspace package or no candidate exists on disk.\n */\nasync function resolveWorkspaceSpecifier(\n specifier: string,\n workspaces: WorkspaceEntry[],\n): Promise<string | null> {\n for (const ws of workspaces) {\n if (specifier === ws.name) {\n for (const ext of ['index.ts', 'index.tsx']) {\n const p = path.join(ws.srcDir, ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n return null;\n }\n if (specifier.startsWith(ws.name + '/')) {\n const subpath = specifier.slice(ws.name.length + 1);\n // Strip .js/.jsx suffix — workspace src uses TS published-output\n // convention (./Sibling.js) but we want the TS source.\n const base = subpath.replace(/\\.jsx?$/, '');\n for (const ext of ['.tsx', '.ts']) {\n const p = path.join(ws.srcDir, base + ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n // Files that already include an extension Vite handles (.css, .json,\n // .svg, etc.) — return the literal path under src.\n const literal = path.join(ws.srcDir, subpath);\n if (await fsExtra.pathExists(literal)) return literal;\n return null;\n }\n }\n return null;\n}\n\n/**\n * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those\n * package names are bundled by Vite; everything else in node_modules (including\n * published `@_linked/*`) is externalized to Node. Vite matches these entries\n * against the bare package name, so subpath imports (`pkg/shapes/Foo`) match too.\n * Installed packages that depend on a workspace (`dependents`, from\n * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.\n * Standalone (no workspaces): the context-holding framework packages are bundled.\n */\nexport function ssrNoExternal(\n workspaces: {name: string}[],\n dependents: string[] = [],\n): (string | RegExp)[] {\n if (workspaces.length === 0) return [/^@_linked\\/server-utils$/, /^@_linked\\/react$/];\n return [...new Set([...workspaces.map((w) => w.name), ...dependents])];\n}\n\n/**\n * The `process.env.*` values inlined into the browser bundle — and only there.\n * See the `environments.client.define` note in `createViteConfig` for why the\n * server environment must not receive them.\n */\nexport function clientDefine(\n opts: Pick<LinkedViteConfigOptions, 'define' | 'port'> = {},\n): Record<string, string> {\n return {\n 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),\n 'process.env.SITE_ROOT': JSON.stringify(\n process.env.SITE_ROOT ?? `http://localhost:${process.env.PORT ?? opts.port ?? 4040}`,\n ),\n // The app's display name, so client components (e.g. the header) can read it\n // like the SSR <title> does (server-utils Html reads process.env.APP_NAME). The\n // browser has no `process`, so inline it; falls back to a generic label when\n // unset so a bare checkout never renders `undefined`.\n 'process.env.APP_NAME': JSON.stringify(process.env.APP_NAME ?? 'Linked App'),\n ...(opts.define ?? {}),\n };\n}\n\nexport function createViteConfig(opts: LinkedViteConfigOptions = {}): ReturnType<typeof defineConfig> {\n return defineConfig(async ({mode}) => {\n const isDev = mode === 'development';\n const workspaces = isDev ? await discoverWorkspaces(opts.workspaceGlobs) : [];\n // STANDALONE = dev mode with no source-shipping workspaces discovered\n // (an app installed from npm outside the monorepo — its `@_linked/*` /\n // `lincd-*` deps are lib-only). discoverWorkspaces() only registers\n // packages that ship `src/` on disk, so `length === 0` is the exact\n // standalone signal used elsewhere in this file. In WORKSPACE mode\n // (CN monorepo or its workspace-member clones) this is false and none\n // of the standalone-gated branches below apply.\n const isStandalone = isDev && workspaces.length === 0;\n\n // The app's published framework deps — excluded from Vite's dep-optimizer below\n // (`optimizeDeps.exclude`) so the browser's native ESM graph loads ONE copy of each.\n // Without the exclude, esbuild inlines a duplicate `@_linked/core` into each\n // per-subpath chunk (`@_linked_schema_shapes_Person.js`,\n // `@_linked_core_utils_LinkedStorage.js`, …), duplicating framework classes\n // (`Person` → `Person2`/`3`), so their shapes register under mangled URIs that no\n // longer match the backend's (one clean copy via Node). These packages are ESM with\n // no bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // native-ESM serving needs no interop shim.\n const linkedDeps: string[] = [];\n if (isStandalone) {\n try {\n const appPkg = await fsExtra.readJson(path.join(process.cwd(), 'package.json'));\n const allDeps = {...appPkg.dependencies, ...appPkg.devDependencies};\n for (const name of Object.keys(allDeps)) {\n if (isFrameworkPkg(name)) linkedDeps.push(name);\n }\n } catch {\n /* best-effort — no package.json is fine */\n }\n }\n const config: UserConfig = {\n server: {\n port: opts.port ?? 4040,\n middlewareMode: true,\n // Unique HMR websocket port per app/worktree (PORT env override wins,\n // else opts.port) — see `hmrPortFor`. Apps can still override this with\n // their own `server.hmr` in mergeConfig.\n hmr: {port: hmrPortFor(process.env.PORT ?? opts.port)},\n },\n build: {\n outDir: opts.outDir ?? 'public/bundles',\n manifest: true,\n // Bump chunk-size warning so it doesn't fire on every build for\n // the linked vendor bundle. Real chunking happens via\n // manualChunks below.\n chunkSizeWarningLimit: 1000,\n rollupOptions: {\n input: opts.entry ?? 'src/index.tsx',\n output: {\n entryFileNames: 'assets/[name]-[hash].js',\n chunkFileNames: 'assets/[name]-[hash].js',\n assetFileNames: 'assets/[name]-[hash][extname]',\n manualChunks: chunkForModuleId,\n },\n },\n sourcemap: true,\n },\n plugins: [\n // Direct workspace specifier resolver.\n //\n // The package.json `\"./*\": { \"development\": \"./src/*.ts\" }` wildcard\n // can't express \"try .ts, fall back to .tsx\" (Node's exports spec\n // resolves to a single literal path). For React-heavy packages like\n // @_linked/primitives, @_linked/server-utils, and @_linked/auth,\n // most files are .tsx — the wildcard fails before any Vite plugin\n // gets a chance to fix it up.\n //\n // This plugin intercepts BARE workspace specifiers like\n // `@_linked/foo/bar` and `pkg-name/utils/Baz.js` BEFORE Vite's\n // package.json resolver runs, mapping them straight to source with\n // proper extension fallback (.tsx → .ts → literal). It also covers\n // the `./Sibling.js` published-output convention for imports made\n // from within workspace `src/` trees.\n isDev\n ? ({\n name: 'linked:resolve-workspace-ts',\n enforce: 'pre',\n async resolveId(id, importer) {\n if (id.startsWith('\\0')) return null;\n\n // Workspace-internal `./Sibling.js` → `.tsx` / `.ts` rewrite.\n if (\n importer &&\n importer.includes(`${path.sep}packages${path.sep}`) &&\n /\\.(jsx?)$/.test(id) &&\n (id.startsWith('.') || id.startsWith('/'))\n ) {\n const importerDir = path.dirname(importer);\n const base = path.resolve(importerDir, id);\n for (const ext of ['.tsx', '.ts']) {\n const candidate = base.replace(/\\.jsx?$/, ext);\n if (await fsExtra.pathExists(candidate)) return candidate;\n }\n }\n\n // Bare workspace specifier — resolve directly to src/.\n if (\n !id.startsWith('.') &&\n !id.startsWith('/') &&\n workspaces.length > 0\n ) {\n const resolved = await resolveWorkspaceSpecifier(id, workspaces);\n if (resolved) return resolved;\n }\n\n // STANDALONE (no workspaces): the linked packages are installed\n // from npm as lib-only (no `src`). We DON'T intercept them here —\n // instead the standalone `resolve.conditions` / `ssr.resolve.conditions`\n // (set on the config below, dropping Vite's `development` token)\n // let Vite's normal resolver pick each package's `import → lib/esm`\n // export. Bundling those lib files through the SSR runner works\n // (they're plain ESM); marking them external instead would leave a\n // bare specifier that `vite.ssrLoadModule` can't load\n // (\"Failed to load url @_linked/server/shapes/LinkedServer\").\n\n return null;\n },\n } as Plugin)\n : null,\n react({\n babel: {\n parserOpts: {\n plugins: ['decorators-legacy', 'classProperties'],\n },\n },\n }),\n // Dev-only: log every file the watcher sees change. Without this,\n // backend edits look silent (no JS rebuild step, no Node restart)\n // and it's hard to tell whether\n // Vite picked up the change at all.\n isDev\n ? ({\n name: 'linked:reload-log',\n configureServer(server) {\n server.watcher.on('change', (file) => {\n const rel = file.replace(process.cwd() + '/', '');\n console.log(`[linked] reloaded ${rel}`);\n });\n },\n } as Plugin)\n : null,\n ...(opts.plugins ?? []),\n ].filter(Boolean) as Plugin[],\n css: {\n modules: {\n generateScopedName: isDev ? generateScopedName : undefined,\n },\n postcss: opts.postcssPlugins\n ? {plugins: opts.postcssPlugins as any}\n : undefined,\n },\n esbuild: {\n tsconfigRaw: {\n compilerOptions: {\n experimentalDecorators: true,\n },\n },\n jsx: 'automatic',\n // A shape's IRI is built from its class name —\n // `getNodeShapeUri(packageName, constructor.name)` — so a minifier that\n // renames the class changes the shape's identity. In a production build\n // the client would ask the server for\n // `https://linked.cm/shape/server/za` while the server had registered\n // `.../BackendAPIStore`, and every Server.call on that shape 501'd.\n // The same mangling made registration report `Shape undefined does not\n // extend base class`.\n keepNames: true,\n },\n // STANDALONE resolve conditions.\n //\n // The published `@_linked/*` / `lincd-*` packages export\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // In dev, Vite expands its special `development|production` condition\n // token to `development`, so it resolves these to `./src/*.ts` — which\n // doesn't exist in a lib-only npm install → boot crash\n // (\"Failed to load @_linked/server/shapes/LinkedServer\").\n //\n // Dropping the dev/prod token from the condition list means Vite never\n // adds `development`; `import` (always appended last by Vite) wins, so\n // these packages resolve to `./lib/esm/*.js`. We start from Vite's\n // default SERVER conditions (`module`, `node`, `development|production`)\n // minus the dev/prod token. This governs BOTH the plugin pipeline\n // (`resolve.conditions`) and the SSR module runner used by\n // `ssrLoadModule('@_linked/server/shapes/LinkedServer')` in\n // commands/start.ts (`ssr.resolve.conditions`).\n //\n // WORKSPACE-GATED: only applied standalone. In monorepo dev the packages\n // ship `src`, and we WANT `development → src` for HMR — so we leave\n // conditions at Vite's defaults there (undefined = untouched), keeping\n // CN dev byte-for-byte unchanged.\n ...(isStandalone\n ? {\n resolve: {\n conditions: ['module', 'node'],\n // Dedupe the context-holding packages so the two `ssrLoadModule` loads\n // (LinkedServer + the app graph) resolve to ONE `server-utils`/`react`\n // instance — otherwise their `AppContext` objects differ and\n // `useAppContext()` returns null. Pairs with `ssr.noExternal` below.\n dedupe: ['@_linked/server-utils', '@_linked/react'],\n },\n }\n : {}),\n // `ssr.external` is a minimal allowlist of\n // npm deps that genuinely can't (or shouldn't) go through Vite's\n // SSR transform. Workspace packages (`@_linked/*`, `lincd-*`) are\n // DELIBERATELY removed so Vite resolves them via each package's\n // `development → ./src/*.ts` conditional export and HMR works on\n // source changes.\n //\n // \"Multiple LINCD\" warnings may resurface during the interim until\n // LINCD eradication completes (accepted).\n ssr: {\n // NOTE: Vite's `ssr.external` only accepts exact package-name strings\n // (not regex). Standalone `@_linked/*` / `lincd-*` are NOT force-listed\n // here — they auto-externalize (or bundle) and resolve via the\n // standalone `import → lib/esm` conditions set below.\n external: [\n 'react',\n 'react-dom',\n 'react-dom/server',\n 'react-router-dom',\n 'scheduler',\n 'express',\n ],\n // Vite 7 auto-externalizes node_modules packages for SSR (loading them\n // via Node → the `import`→`lib/esm` condition), which would bypass the\n // `linked:resolve-workspace-ts` resolver and create a SECOND module\n // instance of each workspace package (breaking the single-`src`-instance\n // invariant — `LinkedStorage` state set on one instance, read on the\n // other → \"No query dispatch configured\"). Force the workspace packages\n // to be BUNDLED so they resolve via each package's `development → src`.\n //\n // WORKSPACE-GATED: only force-bundle when workspaces are actually\n // present (the monorepo / CN + CN's workspace-member clones, where the\n // `@_linked/*` packages have `src` on disk). A STANDALONE app (CLI-\n // created, no workspaces) installs `@_linked/*` from npm as lib-only —\n // those have NO `src`, so bundling them via the `development → src`\n // condition fails (\"Failed to load @_linked/server/shapes/LinkedServer\").\n // Leaving them EXTERNAL lets Node resolve `import → lib/esm`. Single-\n // instance is not a concern standalone (one node_modules copy each) and\n // core's query dispatch is global-backed regardless.\n // STANDALONE: force-bundle the framework packages that hold React context /\n // shared singletons the SSR tree must agree on — `server-utils` (`AppContext`,\n // read by `AppRoot`) and `react`. If left external, LinkedServer's\n // `AppContextProvider` and the app's `AppRoot` (`useAppContext`) can resolve to\n // DIFFERENT module instances → two `AppContext` objects → `useAppContext()` sees\n // no provider (null) → \"Cannot destructure 'isNativeApp'\" and a blank \"SSR timed\n // out\". Bundling makes them one instance in Vite's SSR module graph (matching how\n // workspace mode bundles everything). Native-dep packages (`server`/`fuseki`) stay\n // external so their prebuilt binaries load via Node.\n //\n // WORKSPACE: bundle ONLY the discovered source workspaces (they resolve to `src/`\n // for HMR). Published framework packages installed under node_modules (lib-only)\n // stay EXTERNAL, so Vite-loaded source and Node-native `import()` share Node's\n // single instance of them. Force-bundling every `@_linked/*` here made Vite\n // evaluate its own `@_linked/core` while `loadStores` (core) loaded a store such\n // as `@_linked/fuseki/shapes/FusekiStore` through native `import()`, which pulled\n // a SECOND Node-loaded core and split the shape registry. Installed packages\n // that depend on a workspace (e.g. published fuseki when core itself is a\n // workspace) are bundled too, so they import the Vite-loaded workspace.\n //\n // NOT DEV (a release build of the backend): nothing is force-bundled. The\n // compiled backend is loaded by Node next to the installed\n // `@_linked/server`, so every framework package has to stay a bare import\n // that resolves to that same node_modules copy. `workspaces` is always\n // empty here, and handing that to `ssrNoExternal` used to select the\n // standalone list — which compiled a private `server-utils` into `lib/`,\n // so no app provider was `instanceof` the server's `ShapeProvider` and\n // `LinkedServer` dropped them all (\"exports two generic backend providers\").\n noExternal: isDev ? ssrNoExternal(workspaces, await workspaceDependents(workspaces)) : [],\n // STANDALONE: the SSR module runner (`vite.ssrLoadModule`, used to\n // load LinkedServer + the app graph in commands/start.ts) has its OWN\n // condition list, defaulting to `resolve.conditions`. Set it\n // explicitly so `development` is excluded there too and the lib-only\n // packages resolve via `import → lib/esm`. Omitted (defaults kept) in\n // workspace mode so monorepo SSR still resolves `development → src`.\n ...(isStandalone\n ? {resolve: {conditions: ['module', 'node']}}\n : {}),\n },\n // Client-only, deliberately: these go on the `client` environment, not the\n // top-level `define`, because a top-level `define` is inherited by the SSR\n // environment too.\n //\n // The browser needs them. `@_linked/server-utils`'s `Server.ts` reads\n // `process.env.SITE_ROOT` to target the backend; the browser has no\n // `process`, and Vite (unlike a bundler's EnvironmentPlugin) doesn't\n // auto-inline `process.env.X`, so SITE_ROOT is defined here — always the\n // app's own origin, defaulted to `http://localhost:<port>` (an explicit\n // `SITE_ROOT` env, e.g. from `.env-cmdrc`, still wins). NODE_ENV is a\n // common client guard, so it is defined too.\n //\n // The server must NOT get them, for two reasons:\n // - it reads `process.env` at runtime, so an inlined build-time value is\n // wrong there (a release backend would carry the build machine's\n // SITE_ROOT rather than the deployment's);\n // - worse, every `define` key is a trigger. Vite's `vite:define` plugin\n // runs `esbuild.transform` — without `keepNames` — over any SSR module\n // whose text contains a key. esbuild renames the inner binding of a\n // tsc-emitted decorated class (`let LinkedServer = class LinkedServer`\n // becomes `class LinkedServer2`), and a shape's IRI is built from its\n // class name, so `@_linked/server`'s `LinkedServer` and `LincdAPI`\n // registered as `LinkedServer2` / `LincdAPI2` in dev. Without user keys\n // the SSR environment has none of its own (`keepProcessEnv` is on for\n // it), so nothing server-side is rewritten.\n //\n // Only these SPECIFIC tokens, never a whole-object `process.env`\n // replacement: in a client build Vite already maps any other\n // `process.env.X` to `{}.X` (undefined), which is what client code expects.\n //\n // Apps expose their OWN frontend env vars through the `define` option,\n // which lands here too:\n // createViteConfig({ define: {\n // 'process.env.MY_PUBLIC_KEY': JSON.stringify(process.env.MY_PUBLIC_KEY),\n // }})\n // (only reference PUBLIC vars in client code — a defined secret would be\n // inlined into the browser bundle). An app that puts a top-level `define`\n // in its own config reintroduces both problems for the server; use\n // `environments.client.define` there as well.\n environments: {\n client: {\n define: clientDefine(opts),\n },\n },\n // WORKSPACE mode: exclude the source-shipping workspace packages (@_linked/*,\n // lincd-*) from esbuild's dep pre-bundler. They resolve to `src/` via the\n // `linked:resolve-workspace-ts` plugin; in a workspace-member CLONE they'd\n // otherwise resolve via `node_modules` SYMLINKS and esbuild fails on their\n // subpath `exports` (\"No known conditions for ./shapes/SHACL …\").\n // STANDALONE mode: exclude the published `@_linked/*` / `lincd-*` deps from\n // esbuild's pre-bundler so the browser's native ESM graph loads ONE copy of\n // `@_linked/core` (no per-subpath duplication → stable class names → shape URIs\n // match the backend — see `linkedDeps` above). These packages are ESM with no\n // bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // serving them as native ESM needs no `optimizeDeps.include` interop shim.\n ...(workspaces.length > 0\n ? {optimizeDeps: {exclude: workspaces.map((w) => w.name)}}\n : isStandalone && linkedDeps.length > 0\n ? {optimizeDeps: {exclude: linkedDeps}}\n : {}),\n };\n\n // Tailwind plugin (only if explicitly enabled — adds a heavy plugin).\n if (opts.cssMode === 'tailwind') {\n // Try ESM dynamic import first (works when @tailwindcss/vite is\n // installed in the app or hoisted). Surface a CLEAR warning when\n // it's not — the app needs the dep for theme variables to load.\n try {\n const tailwind: any = await import('@tailwindcss/vite' as any);\n const tailwindPlugin = tailwind.default ?? tailwind;\n (config.plugins as Plugin[]).push(tailwindPlugin());\n } catch (err) {\n console.warn(\n '[createViteConfig] cssMode=tailwind but @tailwindcss/vite ' +\n 'could not be loaded. Theme variables won\\'t apply at runtime. ' +\n 'Add `@tailwindcss/vite` to your app\\'s package.json.',\n );\n }\n }\n\n return config;\n });\n}\n"]}
1
+ {"version":3,"file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gBACnD,MAAM,CAAC,OAAoB,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,IAAI,CACV,4DAA4D;oBAC1D,gEAAgE;oBAChE,sDAAsD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Vite config helper for linked apps. The one dev + build pipeline.\n//\n// Apps use this from their own vite.config.ts:\n//\n// import {createViteConfig} from '@_linked/cli/vite';\n// export default createViteConfig({port: 4040, cssMode: 'tailwind'});\n//\n// The helper preserves the dev-mode `generateScopedName` (readable\n// `_packageName_filename_className`) so CSS module class names match\n// what the previous bundler chain produced for trace/debug. Production\n// uses Vite's default scoping (content-hash, equivalent uniqueness).\nimport {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fsExtra from 'fs-extra';\nimport path from 'node:path';\nimport {generateScopedName} from './utils.js';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from './workspace-globs.js';\nimport {pinCompiledClassNames} from './plugins/pin-compiled-class-names.js';\nimport type {Plugin, UserConfig} from 'vite';\n\n/**\n * Framework packages that MUST be single-instance per runtime — they hold\n * module-level state (`@_linked/core`'s shape registry, `LinkedStorage`, the query\n * context) or register shapes into it. Two copies in one runtime split that state\n * and mangle shape identity (`Person`→`Person2`). This ONE list is the single source\n * of truth for the standalone `optimizeDeps.exclude` (`linkedDeps`). In workspace mode\n * `ssr.noExternal` is keyed on the discovered source workspaces instead (see\n * `ssrNoExternal`), so published framework packages stay external and single-instance\n * under Node.\n */\nconst FRAMEWORK_PKG_PATTERNS: RegExp[] = [/^@_linked\\//, /^lincd-/];\nconst isFrameworkPkg = (name: string): boolean =>\n FRAMEWORK_PKG_PATTERNS.some((re) => re.test(name));\n\n/** Default dev server port, and Vite's default HMR websocket port. */\nconst DEFAULT_DEV_PORT = 4040;\nconst DEFAULT_HMR_PORT = 24678;\n/** Vite may not bind below 1024 without privileges; 65535 is the TCP ceiling. */\nconst MIN_HMR_PORT = 1024;\nconst MAX_HMR_PORT = 65535;\n\n/**\n * Derive an app's HMR websocket port from its dev port.\n *\n * Every `createViteConfig` app used to fall back to Vite's shared default\n * 24678, so any two dev servers running at once collided (\"Port 24678 is\n * already in use\") and HMR silently broke for the loser. Offsetting the HMR\n * port by the same amount the dev port is offset from its default keeps the\n * derivation trivial and means apps that already run on distinct dev ports get\n * distinct HMR ports for free.\n *\n * The input is untrusted (`process.env.PORT` is an arbitrary string), so\n * anything that is not a whole port number — `PORT=abc` yielding `NaN`, a\n * negative or out-of-range value — falls back to the dev port default. The\n * result is then clamped into the bindable range, since a far-out dev port\n * would otherwise derive an HMR port past 65535.\n */\n/**\n * Which manual chunk a module belongs in.\n *\n * Split large/common deps so route chunks don't all carry their own copy AND\n * the main entry doesn't end up at 5MB+. Each chunk becomes its own\n * `assets/<name>-<hash>.js` the browser caches independently — incremental\n * dev builds and cache wins on prod deploys both improve.\n *\n * Exported so the grouping can be asserted directly: getting it wrong does not\n * fail the build, it produces a bundle that throws on load in the browser.\n */\nexport const chunkForModuleId = (id: string): string | undefined => {\n if (!id.includes('node_modules')) {\n // Linked workspaces ship as @_linked/* / lincd-* — group all\n // linked-framework code into a single chunk.\n if (\n id.includes('/packages/core/') ||\n id.includes('/packages/react/') ||\n id.includes('/packages/server-utils/') ||\n id.includes('/packages/primitives/') ||\n id.includes('/packages/css/') ||\n /\\/packages\\/(auth|org|schema|fuseki|owl|xsd|dcat|dcmi|s3|sentry|ui)\\//.test(id)\n ) {\n return 'linked';\n }\n return undefined;\n }\n // Framework code installed from the registry rather than resolved to a\n // workspace. An app can hold both at once — a published `@_linked/server`\n // in node_modules next to workspace `@_linked/core` — and the two import\n // each other. Split across `linked` and `vendor` that is a cycle, and\n // Rollup's chosen order left a binding in its temporal dead zone:\n // `Cannot access 'Wo' before initialization` before the app rendered.\n // Same chunk, no cycle.\n if (/[\\\\/]node_modules[\\\\/](@_linked[\\\\/]|lincd-)/.test(id)) {\n return 'linked';\n }\n // React + React-DOM in their own chunk — every route uses them.\n //\n // react-router and @remix-run/router belong here too. Left in `vendor` they\n // made the two chunks import each other: react-router-dom re-exports\n // react-router, so react-vendor imported vendor, while vendor's own\n // top-level `React.createContext(...)` calls imported react-vendor. Rollup\n // has to pick an order for a cycle, and it ran vendor first — every\n // production build died on load with \"Cannot read properties of undefined\n // (reading 'createContext')\".\n if (\n /[\\\\/]node_modules[\\\\/](react|react-dom|react-router-dom|react-router|@remix-run[\\\\/]router|scheduler)[\\\\/]/.test(\n id\n )\n ) {\n return 'react-vendor';\n }\n // Heavy editor deps — only loaded on pages that need them, but worth\n // isolating so they don't get pulled into main.\n if (/[\\\\/]node_modules[\\\\/]@monaco-editor[\\\\/]/.test(id)) {\n return 'monaco';\n }\n // Charting/visualization\n if (/[\\\\/]node_modules[\\\\/](recharts|react-flow|@xyflow|d3-)[\\\\/]/.test(id)) {\n return 'viz';\n }\n // Animation\n if (/[\\\\/]node_modules[\\\\/]framer-motion[\\\\/]/.test(id)) {\n return 'motion';\n }\n // Catch-all for other node_modules in a vendor chunk\n return 'vendor';\n};\n\nexport function hmrPortFor(devPort: unknown): number {\n const parsed = Number(devPort);\n const validDevPort =\n Number.isFinite(parsed) && Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535\n ? parsed\n : DEFAULT_DEV_PORT;\n const derived = DEFAULT_HMR_PORT + (validDevPort - DEFAULT_DEV_PORT);\n return Math.min(MAX_HMR_PORT, Math.max(MIN_HMR_PORT, derived));\n}\n\nexport interface LinkedViteConfigOptions {\n /** Dev server port. Default 4040. */\n port?: number;\n /** Output dir for `vite build`. Default `public/bundles`. */\n outDir?: string;\n /** CSS pipeline mode. */\n cssMode?: 'tailwind' | 'css-modules-only';\n /** Entry file for the client bundle. Default `src/index.tsx`. */\n entry?: string;\n /** Extra Vite plugins. */\n plugins?: Plugin[];\n /** Extra PostCSS plugins (e.g. `postcss-media-to-container`). */\n postcssPlugins?: unknown[];\n /**\n * Extra `define` entries for the CLIENT environment only (used to bridge\n * `process.env.X` refs into the browser). Never applied server-side.\n */\n define?: Record<string, string>;\n /**\n * Extra workspace globs (trailing `/*`, or a direct package dir) resolved\n * RELATIVE TO the app's cwd, in ADDITION to the app's own `workspaces` field.\n *\n * For apps whose linked-package sources live OUTSIDE their own workspace tree\n * — e.g. an app consumes `packages/lincd.org/modules/*`, which sit one level\n * up (`../lincd.org/modules/*`) when the app runs inside the CN monorepo, and under\n * `packages/lincd.org/modules/*` when the app runs from its own root. Pass BOTH\n * candidate layouts; only globs whose parent dir actually exists are scanned,\n * so the same config works in either checkout. Each glob's packages are\n * registered as source workspaces (resolved to `src/` for HMR + single-instance),\n * exactly like the app's own `workspaces` field.\n */\n workspaceGlobs?: string[];\n}\n\ninterface WorkspaceEntry {\n name: string;\n srcDir: string;\n}\n\n// Resolve a dependency name to its installed package.json the way Node does:\n// look in `<dir>/node_modules/<name>`, then each parent directory's\n// node_modules, starting from the requiring package's directory. This finds\n// deps that npm/yarn workspaces HOISTED to the monorepo root (an app under\n// `services/api` whose dep lives in `<root>/node_modules`). The walk stops\n// after the nearest directory whose package.json declares `workspaces` (the\n// workspace root), or at the filesystem root. Returns null when the package\n// isn't installed (e.g. an optional dep) — we skip rather than throw.\nasync function isWorkspaceRoot(dir: string): Promise<boolean> {\n try {\n const json = await fsExtra.readJson(path.join(dir, 'package.json'));\n return !!json.workspaces;\n } catch {\n return false;\n }\n}\n\nasync function readInstalledPkg(\n name: string,\n fromDir: string,\n): Promise<{root: string; json: any} | null> {\n let dir = path.resolve(fromDir);\n while (true) {\n const root = path.join(dir, 'node_modules', name);\n const pkgJson = path.join(root, 'package.json');\n if (await fsExtra.pathExists(pkgJson)) {\n try {\n return {root, json: await fsExtra.readJson(pkgJson)};\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir || (await isWorkspaceRoot(dir))) return null;\n dir = parent;\n }\n}\n\n/**\n * Names of installed packages that depend, directly or transitively (via\n * `dependencies` / `peerDependencies`), on a discovered source workspace. Such a\n * package must also go through Vite SSR: if Node loaded it natively, it would\n * import its own Node-loaded copy of the workspace (e.g. published\n * `@_linked/fuseki` importing a workspace `@_linked/core`), splitting module\n * state. Vite rewrites the dynamic `import()` in code it transforms, so bundling\n * the dependents keeps one instance.\n *\n * Only the dependency closure of the app's `package.json` (dependencies +\n * devDependencies) and of the workspaces themselves is scanned. Packages are\n * resolved Node-style, keyed by real path, and unresolvable ones are ignored.\n * Workspace names are not included in the result.\n */\nexport async function workspaceDependents(\n workspaces: {name: string; srcDir?: string}[],\n cwd: string = process.cwd(),\n): Promise<string[]> {\n if (workspaces.length === 0) return [];\n const fs = await import('node:fs/promises');\n const wsNames = new Set(workspaces.map((w) => w.name));\n // realRoot -> {name, deps (realRoots)}\n const nodes = new Map<string, {name: string; deps: Set<string>}>();\n const realpath = async (p: string): Promise<string> => {\n try {\n return await fs.realpath(p);\n } catch {\n return path.resolve(p);\n }\n };\n\n const visit = async (root: string, json: any): Promise<string> => {\n const real = await realpath(root);\n if (nodes.has(real)) return real;\n const node = {name: json.name as string, deps: new Set<string>()};\n nodes.set(real, node);\n const names = new Set([\n ...Object.keys(json.dependencies ?? {}),\n ...Object.keys(json.peerDependencies ?? {}),\n ]);\n for (const dep of names) {\n const resolved = await readInstalledPkg(dep, real);\n if (resolved) node.deps.add(await visit(resolved.root, resolved.json));\n }\n return real;\n };\n\n // Seed: the app's direct deps, plus each workspace package's own deps.\n try {\n const appPkg = await fsExtra.readJson(path.join(cwd, 'package.json'));\n for (const dep of Object.keys({...appPkg.dependencies, ...appPkg.devDependencies})) {\n const resolved = await readInstalledPkg(dep, cwd);\n if (resolved) await visit(resolved.root, resolved.json);\n }\n } catch {}\n for (const ws of workspaces) {\n if (!ws.srcDir) continue;\n const root = path.dirname(ws.srcDir);\n try {\n await visit(root, await fsExtra.readJson(path.join(root, 'package.json')));\n } catch {}\n }\n\n // Walk reverse edges from every workspace node: everything reached depends on one.\n const dependentsOf = new Map<string, string[]>();\n for (const [key, node] of nodes) {\n for (const dep of node.deps) {\n if (!dependentsOf.has(dep)) dependentsOf.set(dep, []);\n dependentsOf.get(dep)!.push(key);\n }\n }\n const queue = [...nodes].filter(([, n]) => wsNames.has(n.name)).map(([k]) => k);\n const marked = new Set(queue);\n while (queue.length) {\n for (const parent of dependentsOf.get(queue.pop()!) ?? []) {\n if (!marked.has(parent)) {\n marked.add(parent);\n queue.push(parent);\n }\n }\n }\n const out = new Set<string>();\n for (const key of marked) {\n const name = nodes.get(key)!.name;\n if (name && !wsNames.has(name)) out.add(name);\n }\n return [...out].sort();\n}\n\n/**\n * Read a package root as a SOURCE install: `{name, srcDir}` iff it has a\n * package.json with a name and ships a `src/` dir. Published packages have only\n * `lib/` and are skipped — they resolve via their exports.\n */\nasync function readSourcePackage(root: string): Promise<WorkspaceEntry | null> {\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return null;\n const srcDir = path.join(root, 'src');\n if (!(await fsExtra.pathExists(srcDir))) return null;\n try {\n const json = await fsExtra.readJson(pkgPath);\n return json.name ? {name: json.name, srcDir} : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Linked packages installed as SOURCE, found by walking the app's\n * `dependencies` + `devDependencies` (and recursing through the `dependencies`\n * of each linked package found), keeping those marked `\"linkedPackage\": true`\n * — the same marker the CLI keys on (see cli-methods.ts) — and registering the\n * ones that ship `src/`.\n *\n * A dep ships `src/` when it is a symlinked workspace clone, a `link:`/`portal:`\n * dev install, or a LOCALIZED checkout (`packages-local/<pkg>`, in no workspace\n * glob). That's what lets a STANDALONE app (not itself a workspace root — e.g. a\n * per-branch clone under /apps) resolve a linked package's `.tsx` sources with\n * extension probing, instead of falling through to the package's\n * `development → ./src/*.ts` export (which misses `.tsx` like LinkedServer). A\n * prod/ejected app installs PUBLISHED packages (no `src/`) → not registered,\n * resolved via each package's `lib`.\n *\n * The marker — NOT the npm scope — drives discovery, so a user's own\n * custom-scope published linked package (e.g. `@acme/foo` with\n * `linkedPackage:true`) is picked up too, and linked packages present in\n * node_modules but not depended upon are ignored.\n *\n * Every root is REALPATHED before it is registered: `readInstalledPkg` returns\n * the `node_modules/<name>` symlink spelling, and Vite's resolver realpaths\n * every id it produces, so registering the symlink would give one file two\n * module ids — two instances of the same module.\n *\n * Shared by the Vite resolver table (`discoverWorkspaces`) and the `linked start`\n * HMR watch set, so the two cannot disagree about what is source.\n */\nexport async function discoverLinkedSourceDependencies(\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const pkgPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return [];\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n const walk = async (\n deps: Record<string, string> | undefined,\n fromDir: string,\n ): Promise<void> => {\n for (const name of Object.keys(deps ?? {})) {\n if (visited.has(name)) continue;\n visited.add(name);\n const resolved = await readInstalledPkg(name, fromDir);\n if (!resolved) continue;\n if (resolved.json.linkedPackage !== true) continue;\n let realRoot = resolved.root;\n try {\n realRoot = await fs.realpath(resolved.root);\n } catch {}\n const entry = await readSourcePackage(realRoot);\n if (entry && !seen.has(entry.name)) {\n seen.add(entry.name);\n out.push(entry);\n }\n // Recurse from the real location, so a symlinked clone resolves its own\n // dependencies from its source dir.\n await walk(resolved.json.dependencies, realRoot);\n }\n };\n const appPkg = await fsExtra.readJson(pkgPath);\n await walk(appPkg.dependencies, cwd);\n await walk(appPkg.devDependencies, cwd);\n return out;\n}\n\n/**\n * Walk the app's package.json `workspaces` field to build a lookup table\n * from npm name → absolute src/ directory. Used by the resolver plugin\n * to map bare specifiers like `@_linked/foo/bar` directly to source.\n *\n * Positive patterns are expanded by directory listing, so only a trailing `/*`\n * is honoured. NEGATED patterns (`\"!packages/core\"`) are honoured in full, with\n * npm's semantics — see ./workspace-globs.js. Skipping them would resolve a\n * package to an excluded directory that the package manager never installed\n * dependencies for.\n */\nexport async function discoverWorkspaces(\n extraGlobs: string[] = [],\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n // Register a package root iff it ships a `src/` dir (source install).\n const addFromRoot = async (root: string): Promise<void> => {\n const entry = await readSourcePackage(root);\n if (!entry || seen.has(entry.name)) return;\n seen.add(entry.name);\n out.push(entry);\n };\n\n // 1. The app's own `workspaces` globs — the monorepo-root case (CN, or any app\n // that is itself a workspace root). Only trailing `/*` patterns.\n const pkgPath = path.join(cwd, 'package.json');\n if (await fsExtra.pathExists(pkgPath)) {\n const pkg = await fsExtra.readJson(pkgPath);\n // Merge the app's own `workspaces` globs with any caller-supplied\n // `workspaceGlobs` (e.g. `../lincd.org/modules/*`). Non-existent parents\n // are skipped below, so passing both nested + standalone layouts is safe.\n // Either list may carry negations, so they are parsed together.\n const {patterns, negatedPatterns} = parseWorkspacePatterns([\n ...(Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? []),\n ...extraGlobs,\n ]);\n const addUnlessNegated = async (root: string): Promise<void> => {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) return;\n await addFromRoot(root);\n };\n for (const pattern of patterns) {\n const m = pattern.match(/^(.+?)\\/\\*$/);\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n for (const ent of await fs.readdir(parent, {withFileTypes: true})) {\n if (ent.isDirectory() || ent.isSymbolicLink()) {\n await addUnlessNegated(path.join(parent, ent.name));\n }\n }\n }\n } else {\n await addUnlessNegated(path.join(cwd, pattern));\n }\n }\n }\n\n // 2. Linked deps installed as source — including a localized checkout that is\n // in no workspace glob. Shared with the `linked start` watch set; see\n // discoverLinkedSourceDependencies above. Glob entries win on a name clash.\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (seen.has(entry.name)) continue;\n seen.add(entry.name);\n out.push(entry);\n }\n\n return out;\n}\n\n/**\n * Resolve a bare specifier like `@_linked/foo/bar`, `lincd-rdfs/Foo`, or\n * `pkg/utils/Bar.js` against the workspace lookup. Tries extensions in\n * order: .ts, .tsx, then the literal id (for files that already include\n * an extension or for non-TS assets). Returns null when the specifier\n * doesn't match any workspace package or no candidate exists on disk.\n */\nasync function resolveWorkspaceSpecifier(\n specifier: string,\n workspaces: WorkspaceEntry[],\n): Promise<string | null> {\n for (const ws of workspaces) {\n if (specifier === ws.name) {\n for (const ext of ['index.ts', 'index.tsx']) {\n const p = path.join(ws.srcDir, ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n return null;\n }\n if (specifier.startsWith(ws.name + '/')) {\n const subpath = specifier.slice(ws.name.length + 1);\n // Strip .js/.jsx suffix — workspace src uses TS published-output\n // convention (./Sibling.js) but we want the TS source.\n const base = subpath.replace(/\\.jsx?$/, '');\n for (const ext of ['.tsx', '.ts']) {\n const p = path.join(ws.srcDir, base + ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n // Files that already include an extension Vite handles (.css, .json,\n // .svg, etc.) — return the literal path under src.\n const literal = path.join(ws.srcDir, subpath);\n if (await fsExtra.pathExists(literal)) return literal;\n return null;\n }\n }\n return null;\n}\n\n/**\n * Packages whose entry `linked start` hands to `vite.ssrLoadModule` by name\n * (`@_linked/server/shapes/LinkedServer`, see `commands/start.ts`).\n *\n * Vite transforms an explicitly requested entry, and every file it reaches by\n * RELATIVE import, whether or not the package is external. The same package's\n * bare-specifier imports from anywhere else (the app's `src`, the storage\n * config) are externalized to Node. Left external, the package is split across\n * two loaders, and which copy a file ends up in depends on import order: a file\n * the module runner has already evaluated is reused, one it has not is loaded\n * by Node, and Node then loads that file's relative imports itself. Measured in\n * CN: `package.js` and `ontologies/lincd-server.js` evaluated once by each\n * loader, and `LocalFileStore.js` too once the package's `backend` was loaded.\n * Bundling the package makes Vite the only loader for it.\n */\nexport const SSR_ENTRY_PACKAGES = ['@_linked/server'];\n\n/**\n * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those\n * package names are bundled by Vite; everything else in node_modules (including\n * published `@_linked/*`) is externalized to Node. Vite matches these entries\n * against the bare package name, so subpath imports (`pkg/shapes/Foo`) match too.\n * Installed packages that depend on a workspace (`dependents`, from\n * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.\n * Standalone (no workspaces): the context-holding framework packages are bundled.\n * In both modes, `SSR_ENTRY_PACKAGES` are bundled.\n */\nexport function ssrNoExternal(\n workspaces: {name: string}[],\n dependents: string[] = [],\n): (string | RegExp)[] {\n if (workspaces.length === 0) {\n return [/^@_linked\\/server-utils$/, /^@_linked\\/react$/, ...SSR_ENTRY_PACKAGES];\n }\n return [...new Set([...workspaces.map((w) => w.name), ...dependents, ...SSR_ENTRY_PACKAGES])];\n}\n\n/**\n * The `process.env.*` values inlined into the browser bundle — and only there.\n * See the `environments.client.define` note in `createViteConfig` for why the\n * server environment must not receive them.\n */\nexport function clientDefine(\n opts: Pick<LinkedViteConfigOptions, 'define' | 'port'> = {},\n): Record<string, string> {\n return {\n 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),\n 'process.env.SITE_ROOT': JSON.stringify(\n process.env.SITE_ROOT ?? `http://localhost:${process.env.PORT ?? opts.port ?? 4040}`,\n ),\n // The app's display name, so client components (e.g. the header) can read it\n // like the SSR <title> does (server-utils Html reads process.env.APP_NAME). The\n // browser has no `process`, so inline it; falls back to a generic label when\n // unset so a bare checkout never renders `undefined`.\n 'process.env.APP_NAME': JSON.stringify(process.env.APP_NAME ?? 'Linked App'),\n ...(opts.define ?? {}),\n };\n}\n\nexport function createViteConfig(opts: LinkedViteConfigOptions = {}): ReturnType<typeof defineConfig> {\n return defineConfig(async ({mode}) => {\n const isDev = mode === 'development';\n const workspaces = isDev ? await discoverWorkspaces(opts.workspaceGlobs) : [];\n // STANDALONE = dev mode with no source-shipping workspaces discovered\n // (an app installed from npm outside the monorepo — its `@_linked/*` /\n // `lincd-*` deps are lib-only). discoverWorkspaces() only registers\n // packages that ship `src/` on disk, so `length === 0` is the exact\n // standalone signal used elsewhere in this file. In WORKSPACE mode\n // (CN monorepo or its workspace-member clones) this is false and none\n // of the standalone-gated branches below apply.\n const isStandalone = isDev && workspaces.length === 0;\n\n // The app's published framework deps — excluded from Vite's dep-optimizer below\n // (`optimizeDeps.exclude`) so the browser's native ESM graph loads ONE copy of each.\n // Without the exclude, esbuild inlines a duplicate `@_linked/core` into each\n // per-subpath chunk (`@_linked_schema_shapes_Person.js`,\n // `@_linked_core_utils_LinkedStorage.js`, …), duplicating framework classes\n // (`Person` → `Person2`/`3`), so their shapes register under mangled URIs that no\n // longer match the backend's (one clean copy via Node). These packages are ESM with\n // no bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // native-ESM serving needs no interop shim.\n const linkedDeps: string[] = [];\n if (isStandalone) {\n try {\n const appPkg = await fsExtra.readJson(path.join(process.cwd(), 'package.json'));\n const allDeps = {...appPkg.dependencies, ...appPkg.devDependencies};\n for (const name of Object.keys(allDeps)) {\n if (isFrameworkPkg(name)) linkedDeps.push(name);\n }\n } catch {\n /* best-effort — no package.json is fine */\n }\n }\n const config: UserConfig = {\n server: {\n port: opts.port ?? 4040,\n middlewareMode: true,\n // Unique HMR websocket port per app/worktree (PORT env override wins,\n // else opts.port) — see `hmrPortFor`. Apps can still override this with\n // their own `server.hmr` in mergeConfig.\n hmr: {port: hmrPortFor(process.env.PORT ?? opts.port)},\n },\n build: {\n outDir: opts.outDir ?? 'public/bundles',\n manifest: true,\n // Bump chunk-size warning so it doesn't fire on every build for\n // the linked vendor bundle. Real chunking happens via\n // manualChunks below.\n chunkSizeWarningLimit: 1000,\n rollupOptions: {\n input: opts.entry ?? 'src/index.tsx',\n output: {\n entryFileNames: 'assets/[name]-[hash].js',\n chunkFileNames: 'assets/[name]-[hash].js',\n assetFileNames: 'assets/[name]-[hash][extname]',\n manualChunks: chunkForModuleId,\n },\n },\n sourcemap: true,\n },\n plugins: [\n // Direct workspace specifier resolver.\n //\n // The package.json `\"./*\": { \"development\": \"./src/*.ts\" }` wildcard\n // can't express \"try .ts, fall back to .tsx\" (Node's exports spec\n // resolves to a single literal path). For React-heavy packages like\n // @_linked/primitives, @_linked/server-utils, and @_linked/auth,\n // most files are .tsx — the wildcard fails before any Vite plugin\n // gets a chance to fix it up.\n //\n // This plugin intercepts BARE workspace specifiers like\n // `@_linked/foo/bar` and `pkg-name/utils/Baz.js` BEFORE Vite's\n // package.json resolver runs, mapping them straight to source with\n // proper extension fallback (.tsx → .ts → literal). It also covers\n // the `./Sibling.js` published-output convention for imports made\n // from within workspace `src/` trees.\n isDev\n ? ({\n name: 'linked:resolve-workspace-ts',\n enforce: 'pre',\n async resolveId(id, importer) {\n if (id.startsWith('\\0')) return null;\n\n // Workspace-internal `./Sibling.js` → `.tsx` / `.ts` rewrite.\n if (\n importer &&\n importer.includes(`${path.sep}packages${path.sep}`) &&\n /\\.(jsx?)$/.test(id) &&\n (id.startsWith('.') || id.startsWith('/'))\n ) {\n const importerDir = path.dirname(importer);\n const base = path.resolve(importerDir, id);\n for (const ext of ['.tsx', '.ts']) {\n const candidate = base.replace(/\\.jsx?$/, ext);\n if (await fsExtra.pathExists(candidate)) return candidate;\n }\n }\n\n // Bare workspace specifier — resolve directly to src/.\n if (\n !id.startsWith('.') &&\n !id.startsWith('/') &&\n workspaces.length > 0\n ) {\n const resolved = await resolveWorkspaceSpecifier(id, workspaces);\n if (resolved) return resolved;\n }\n\n // STANDALONE (no workspaces): the linked packages are installed\n // from npm as lib-only (no `src`). We DON'T intercept them here —\n // instead the standalone `resolve.conditions` / `ssr.resolve.conditions`\n // (set on the config below, dropping Vite's `development` token)\n // let Vite's normal resolver pick each package's `import → lib/esm`\n // export. Bundling those lib files through the SSR runner works\n // (they're plain ESM); marking them external instead would leave a\n // bare specifier that `vite.ssrLoadModule` can't load\n // (\"Failed to load url @_linked/server/shapes/LinkedServer\").\n\n return null;\n },\n } as Plugin)\n : null,\n // Published lib JS: keep decorated shape classes named `Foo`, not the\n // `Foo2` Vite's esbuild re-prints would give them — see the plugin.\n pinCompiledClassNames(),\n react({\n babel: {\n parserOpts: {\n plugins: ['decorators-legacy', 'classProperties'],\n },\n },\n }),\n // Dev-only: log every file the watcher sees change. Without this,\n // backend edits look silent (no JS rebuild step, no Node restart)\n // and it's hard to tell whether\n // Vite picked up the change at all.\n isDev\n ? ({\n name: 'linked:reload-log',\n configureServer(server) {\n server.watcher.on('change', (file) => {\n const rel = file.replace(process.cwd() + '/', '');\n console.log(`[linked] reloaded ${rel}`);\n });\n },\n } as Plugin)\n : null,\n ...(opts.plugins ?? []),\n ].filter(Boolean) as Plugin[],\n css: {\n modules: {\n generateScopedName: isDev ? generateScopedName : undefined,\n },\n postcss: opts.postcssPlugins\n ? {plugins: opts.postcssPlugins as any}\n : undefined,\n },\n esbuild: {\n tsconfigRaw: {\n compilerOptions: {\n experimentalDecorators: true,\n },\n },\n jsx: 'automatic',\n // A shape's IRI is built from its class name —\n // `getNodeShapeUri(packageName, constructor.name)` — so a minifier that\n // renames the class changes the shape's identity. In a production build\n // the client would ask the server for\n // `https://linked.cm/shape/server/za` while the server had registered\n // `.../BackendAPIStore`, and every Server.call on that shape 501'd.\n // The same mangling made registration report `Shape undefined does not\n // extend base class`.\n //\n // Vite honours this in the minifier only: its per-file TypeScript\n // transform and its define pass both run esbuild with keepNames off.\n // `pinCompiledClassNames` above covers what those passes rename.\n keepNames: true,\n },\n // STANDALONE resolve conditions.\n //\n // The published `@_linked/*` / `lincd-*` packages export\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // In dev, Vite expands its special `development|production` condition\n // token to `development`, so it resolves these to `./src/*.ts` — which\n // doesn't exist in a lib-only npm install → boot crash\n // (\"Failed to load @_linked/server/shapes/LinkedServer\").\n //\n // Dropping the dev/prod token from the condition list means Vite never\n // adds `development`; `import` (always appended last by Vite) wins, so\n // these packages resolve to `./lib/esm/*.js`. We start from Vite's\n // default SERVER conditions (`module`, `node`, `development|production`)\n // minus the dev/prod token. This governs BOTH the plugin pipeline\n // (`resolve.conditions`) and the SSR module runner used by\n // `ssrLoadModule('@_linked/server/shapes/LinkedServer')` in\n // commands/start.ts (`ssr.resolve.conditions`).\n //\n // WORKSPACE-GATED: only applied standalone. In monorepo dev the packages\n // ship `src`, and we WANT `development → src` for HMR — so we leave\n // conditions at Vite's defaults there (undefined = untouched), keeping\n // CN dev byte-for-byte unchanged.\n ...(isStandalone\n ? {\n resolve: {\n conditions: ['module', 'node'],\n // Dedupe the context-holding packages so the two `ssrLoadModule` loads\n // (LinkedServer + the app graph) resolve to ONE `server-utils`/`react`\n // instance — otherwise their `AppContext` objects differ and\n // `useAppContext()` returns null. Pairs with `ssr.noExternal` below.\n dedupe: ['@_linked/server-utils', '@_linked/react'],\n },\n }\n : {}),\n // `ssr.external` is a minimal allowlist of\n // npm deps that genuinely can't (or shouldn't) go through Vite's\n // SSR transform. Workspace packages (`@_linked/*`, `lincd-*`) are\n // DELIBERATELY removed so Vite resolves them via each package's\n // `development → ./src/*.ts` conditional export and HMR works on\n // source changes.\n //\n // \"Multiple LINCD\" warnings may resurface during the interim until\n // LINCD eradication completes (accepted).\n ssr: {\n // NOTE: Vite's `ssr.external` only accepts exact package-name strings\n // (not regex). Standalone `@_linked/*` / `lincd-*` are NOT force-listed\n // here — they auto-externalize (or bundle) and resolve via the\n // standalone `import → lib/esm` conditions set below.\n external: [\n 'react',\n 'react-dom',\n 'react-dom/server',\n 'react-router-dom',\n 'scheduler',\n 'express',\n ],\n // Vite 7 auto-externalizes node_modules packages for SSR (loading them\n // via Node → the `import`→`lib/esm` condition), which would bypass the\n // `linked:resolve-workspace-ts` resolver and create a SECOND module\n // instance of each workspace package (breaking the single-`src`-instance\n // invariant — `LinkedStorage` state set on one instance, read on the\n // other → \"No query dispatch configured\"). Force the workspace packages\n // to be BUNDLED so they resolve via each package's `development → src`.\n //\n // WORKSPACE-GATED: only force-bundle when workspaces are actually\n // present (the monorepo / CN + CN's workspace-member clones, where the\n // `@_linked/*` packages have `src` on disk). A STANDALONE app (CLI-\n // created, no workspaces) installs `@_linked/*` from npm as lib-only —\n // those have NO `src`, so bundling them via the `development → src`\n // condition fails (\"Failed to load @_linked/server/shapes/LinkedServer\").\n // Leaving them EXTERNAL lets Node resolve `import → lib/esm`. Single-\n // instance is not a concern standalone (one node_modules copy each) and\n // core's query dispatch is global-backed regardless.\n // STANDALONE: force-bundle the framework packages that hold React context /\n // shared singletons the SSR tree must agree on — `server-utils` (`AppContext`,\n // read by `AppRoot`) and `react`. If left external, LinkedServer's\n // `AppContextProvider` and the app's `AppRoot` (`useAppContext`) can resolve to\n // DIFFERENT module instances → two `AppContext` objects → `useAppContext()` sees\n // no provider (null) → \"Cannot destructure 'isNativeApp'\" and a blank \"SSR timed\n // out\". Bundling makes them one instance in Vite's SSR module graph (matching how\n // workspace mode bundles everything). `fuseki` stays external; `server` is bundled\n // because `start` loads its entry through Vite (`SSR_ENTRY_PACKAGES`). Their native\n // dependencies (e.g. `sharp`) are separate packages and stay external either way.\n //\n // WORKSPACE: bundle ONLY the discovered source workspaces (they resolve to `src/`\n // for HMR). Published framework packages installed under node_modules (lib-only)\n // stay EXTERNAL, so Vite-loaded source and Node-native `import()` share Node's\n // single instance of them. Force-bundling every `@_linked/*` here made Vite\n // evaluate its own `@_linked/core` while `loadStores` (core) loaded a store such\n // as `@_linked/fuseki/shapes/FusekiStore` through native `import()`, which pulled\n // a SECOND Node-loaded core and split the shape registry. Installed packages\n // that depend on a workspace (e.g. published fuseki when core itself is a\n // workspace) are bundled too, so they import the Vite-loaded workspace. The one\n // published exception is `SSR_ENTRY_PACKAGES`, which Vite loads regardless.\n //\n // NOT DEV (a release build of the backend): nothing is force-bundled. The\n // compiled backend is loaded by Node next to the installed\n // `@_linked/server`, so every framework package has to stay a bare import\n // that resolves to that same node_modules copy. `workspaces` is always\n // empty here, and handing that to `ssrNoExternal` used to select the\n // standalone list — which compiled a private `server-utils` into `lib/`,\n // so no app provider was `instanceof` the server's `ShapeProvider` and\n // `LinkedServer` dropped them all (\"exports two generic backend providers\").\n noExternal: isDev ? ssrNoExternal(workspaces, await workspaceDependents(workspaces)) : [],\n // STANDALONE: the SSR module runner (`vite.ssrLoadModule`, used to\n // load LinkedServer + the app graph in commands/start.ts) has its OWN\n // condition list, defaulting to `resolve.conditions`. Set it\n // explicitly so `development` is excluded there too and the lib-only\n // packages resolve via `import → lib/esm`. Omitted (defaults kept) in\n // workspace mode so monorepo SSR still resolves `development → src`.\n ...(isStandalone\n ? {resolve: {conditions: ['module', 'node']}}\n : {}),\n },\n // Client-only, deliberately: these go on the `client` environment, not the\n // top-level `define`, because a top-level `define` is inherited by the SSR\n // environment too.\n //\n // The browser needs them. `@_linked/server-utils`'s `Server.ts` reads\n // `process.env.SITE_ROOT` to target the backend; the browser has no\n // `process`, and Vite (unlike a bundler's EnvironmentPlugin) doesn't\n // auto-inline `process.env.X`, so SITE_ROOT is defined here — always the\n // app's own origin, defaulted to `http://localhost:<port>` (an explicit\n // `SITE_ROOT` env, e.g. from `.env-cmdrc`, still wins). NODE_ENV is a\n // common client guard, so it is defined too.\n //\n // The server must NOT get them, for two reasons:\n // - it reads `process.env` at runtime, so an inlined build-time value is\n // wrong there (a release backend would carry the build machine's\n // SITE_ROOT rather than the deployment's);\n // - worse, every `define` key is a trigger. Vite's `vite:define` plugin\n // runs `esbuild.transform` — without `keepNames` — over any SSR module\n // whose text contains a key. esbuild renames the inner binding of a\n // tsc-emitted decorated class (`let LinkedServer = class LinkedServer`\n // becomes `class LinkedServer2`), and a shape's IRI is built from its\n // class name, so `@_linked/server`'s `LinkedServer` and `LincdAPI`\n // registered as `LinkedServer2` / `LincdAPI2` in dev. Without user keys\n // the SSR environment has none of its own (`keepProcessEnv` is on for\n // it), so nothing server-side is rewritten.\n //\n // Only these SPECIFIC tokens, never a whole-object `process.env`\n // replacement: in a client build Vite already maps any other\n // `process.env.X` to `{}.X` (undefined), which is what client code expects.\n //\n // Apps expose their OWN frontend env vars through the `define` option,\n // which lands here too:\n // createViteConfig({ define: {\n // 'process.env.MY_PUBLIC_KEY': JSON.stringify(process.env.MY_PUBLIC_KEY),\n // }})\n // (only reference PUBLIC vars in client code — a defined secret would be\n // inlined into the browser bundle). An app that puts a top-level `define`\n // in its own config reintroduces both problems for the server; use\n // `environments.client.define` there as well.\n environments: {\n client: {\n define: clientDefine(opts),\n },\n },\n // WORKSPACE mode: exclude the source-shipping workspace packages (@_linked/*,\n // lincd-*) from esbuild's dep pre-bundler. They resolve to `src/` via the\n // `linked:resolve-workspace-ts` plugin; in a workspace-member CLONE they'd\n // otherwise resolve via `node_modules` SYMLINKS and esbuild fails on their\n // subpath `exports` (\"No known conditions for ./shapes/SHACL …\").\n // STANDALONE mode: exclude the published `@_linked/*` / `lincd-*` deps from\n // esbuild's pre-bundler so the browser's native ESM graph loads ONE copy of\n // `@_linked/core` (no per-subpath duplication → stable class names → shape URIs\n // match the backend — see `linkedDeps` above). These packages are ESM with no\n // bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // serving them as native ESM needs no `optimizeDeps.include` interop shim.\n ...(workspaces.length > 0\n ? {optimizeDeps: {exclude: workspaces.map((w) => w.name)}}\n : isStandalone && linkedDeps.length > 0\n ? {optimizeDeps: {exclude: linkedDeps}}\n : {}),\n };\n\n // Tailwind plugin (only if explicitly enabled — adds a heavy plugin).\n if (opts.cssMode === 'tailwind') {\n // Try ESM dynamic import first (works when @tailwindcss/vite is\n // installed in the app or hoisted). Surface a CLEAR warning when\n // it's not — the app needs the dep for theme variables to load.\n try {\n const tailwind: any = await import('@tailwindcss/vite' as any);\n const tailwindPlugin = tailwind.default ?? tailwind;\n (config.plugins as Plugin[]).push(tailwindPlugin());\n } catch (err) {\n console.warn(\n '[createViteConfig] cssMode=tailwind but @tailwindcss/vite ' +\n 'could not be loaded. Theme variables won\\'t apply at runtime. ' +\n 'Add `@tailwindcss/vite` to your app\\'s package.json.',\n );\n }\n }\n\n return config;\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@_linked/cli",
3
- "version": "1.28.1",
3
+ "version": "1.28.2",
4
4
  "packageManager": "npm@11.19.1",
5
5
  "description": "Command line tools for the @_linked/* packages and apps",
6
6
  "main": "lib/esm/index.js",