@_linked/server 3.6.1 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"linkedDependencies.js","sourceRoot":"","sources":["../../../src/utils/linkedDependencies.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAsB7B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAS;IAC3C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACzD,OAAO,IAAI,CAAC,aAAa,KAAK,IAAI,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,IAAS;IACtC,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QACrE,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC;IACzB,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC9B,oEAAoE;QACpE,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;QAC1E,OAAO,GAAG,IAAI,GAAG,CAAC;IACpB,CAAC;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,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IACrC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;QACvC,CAAC,CAAC,UAAU;QACZ,CAAC,CAAC,UAAU;YACV,CAAC,CAAC,CAAC,UAAU,CAAC;YACd,CAAC,CAAC,EAAE,CAAC;IACT,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAC5B,OAAO,KAAK,KAAK,QAAQ;QACvB,CAAC,CAAC,KAAK,KAAK,OAAO;QACnB,CAAC,CAAC,KAAK,YAAY,MAAM;YACvB,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;YACrB,CAAC,CAAC,KAAK,CACZ,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,eAAe,CAAC,IAAS;;IACvC,OAAO,CACL,MAAA,MAAA,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,0CAAE,GAAG,0CAAE,UAAU,mCAC7B,MAAA,MAAA,MAAA,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,0CAAE,YAAY,0CAAE,GAAG,0CAAE,OAAO,0CAAE,UAAU,CACrD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAe,EACf,OAAY;;IAEZ,OAAO,CACL,MAAA,yBAAyB,CAAC,OAAO,EAAE,OAAO,CAAC,mCAC3C,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE;QACpC,aAAa;QACb,GAAG,sBAAsB;KAC1B,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * A linked package found in the app's dependency tree, wherever it is\n * installed: a workspace member, a localized checkout, or a registry install.\n */\nexport interface LinkedDependency {\n packageName: string;\n /**\n * Realpath of the package root whose backend the server loads: the copy the\n * app itself resolves when that copy is a linked package, otherwise the\n * first copy the walk found.\n */\n path: string;\n /**\n * Every distinct installed copy of this package in the tree (realpaths),\n * in the order the walk found them. More than one means the install is not\n * deduplicated; only `path`'s backend is ever loaded.\n */\n copies: { path: string; version?: string }[];\n}\n\n/**\n * A package whose backend providers the server loads at boot: one whose\n * package.json declares `\"linkedPackage\": true`. That flag is the only test —\n * not the package's scope. `@_linked/localize` is in the `@_linked` scope and\n * is a CLI tool, not a linked package; a custom-scope package with the flag is\n * a linked package. The CLI's workspace discovery uses the same flag.\n *\n * The legacy `\"lincd\": true` flag is deliberately NOT enough. Those packages\n * import the old `lincd` core, and loading them at boot is what produced\n * \"Multiple versions of LINCD are loaded\" before boot loading was narrowed to\n * workspace members.\n */\nexport function isLinkedPackageJson(json: any): boolean {\n if (!json || typeof json.name !== 'string') return false;\n return json.linkedPackage === true;\n}\n\n/**\n * Find an installed package the way Node does: `<dir>/node_modules/<name>`,\n * then each parent directory's `node_modules`. Returns null when it is not\n * installed (an optional dependency, say) rather than throwing.\n */\n/**\n * Whether a package has a JavaScript entry the server can import: `main`,\n * `module`, or an `exports` map with a root (`.`) entry or a single string.\n * A linked package can be pure CSS (`@_linked/css`); importing that whole\n * fails with \"Failed to resolve entry\", so the server skips it.\n */\nexport function hasModuleEntry(json: any): boolean {\n if (!json) return false;\n if (typeof json.main === 'string' || typeof json.module === 'string') {\n return true;\n }\n const exp = json.exports;\n if (typeof exp === 'string') return true;\n if (exp && typeof exp === 'object') {\n const keys = Object.keys(exp);\n // Conditions only ({import, require, ...}) describe the root entry.\n if (keys.length > 0 && keys.every((k) => !k.startsWith('.'))) return true;\n return '.' in exp;\n }\n return false;\n}\n\nexport function readInstalledPackage(\n name: string,\n fromDir: string\n): { 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 pkgJsonPath = path.join(root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n return { root, json: JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')) };\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Every linked package reachable from the app's `dependencies`, each one AFTER\n * the linked packages it depends on. Providers register middleware in the\n * order they are indexed, so a package's middleware must not run before that\n * of a package it builds on (e.g. anything reading `request.linkedAuth` after\n * @_linked/auth's JWT middleware).\n *\n * Only linked packages are recursed into — the same rule the workspace-only\n * filter used — so the walk reads a few dozen package.json files, not the\n * whole of node_modules. Each package's dependencies are resolved from its\n * REAL location, so a symlinked workspace or localized checkout resolves its\n * own dependencies the way Node will when it loads it — which is how a\n * package installed only nested (`owl/node_modules/@_linked/rdfs`) is found.\n *\n * The walk is keyed by real path, not name, so every installed copy of a\n * package is recorded (`copies`). The copy whose backend is loaded (`path`)\n * is the one the app itself resolves, so it is the same module instance the\n * app's own imports reach; when the app cannot resolve the package at all\n * (it is only installed nested) it is the first copy found.\n */\nexport function discoverLinkedDependencies(\n appDir: string,\n appPackageJson: any\n): LinkedDependency[] {\n const out: LinkedDependency[] = [];\n const byName = new Map<string, LinkedDependency>();\n const visitedRoots = new Set<string>();\n const appName = appPackageJson?.name;\n\n const visit = (name: string, fromDir: string) => {\n if (name === appName) return;\n const installed = readInstalledPackage(name, fromDir);\n if (!installed || !isLinkedPackageJson(installed.json)) return;\n const realRoot = realpathOr(installed.root);\n if (visitedRoots.has(realRoot)) return;\n visitedRoots.add(realRoot);\n let entry = byName.get(name);\n if (!entry) {\n entry = { packageName: name, path: realRoot, copies: [] };\n byName.set(name, entry);\n }\n entry.copies.push({ path: realRoot, version: installed.json.version });\n for (const dep of Object.keys(installed.json.dependencies ?? {})) {\n visit(dep, realRoot);\n }\n // Pushed after its dependencies, once per name: the first copy found\n // fixes the package's place in the order.\n if (!out.includes(entry)) out.push(entry);\n };\n\n for (const name of Object.keys(appPackageJson?.dependencies ?? {})) {\n visit(name, appDir);\n }\n\n for (const entry of out) {\n if (entry.copies.length < 2) continue;\n const fromApp = readInstalledPackage(entry.packageName, appDir);\n if (fromApp && isLinkedPackageJson(fromApp.json)) {\n const appCopy = realpathOr(fromApp.root);\n if (entry.copies.some((c) => c.path === appCopy)) entry.path = appCopy;\n }\n }\n return out;\n}\n\nfunction realpathOr(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n/**\n * The conditions a backend entry is resolved with on the Node path. These are\n * the ones Node's ESM loader applies to `import()` — so the file found is the\n * file a bare `import('<pkg>/backend')` from the app would load, and Node's\n * module cache (keyed by real file URL) hands both the same instance.\n * `development` is deliberately absent: it is a Vite/bundler condition, and a\n * production Node runtime never applies it.\n */\nexport const NODE_IMPORT_CONDITIONS = ['import', 'node', 'default'] as const;\n\n/**\n * The absolute path of a package's backend entry file, or null when the\n * package has no backend entry or the file it names does not exist.\n *\n * With `exports`, this follows Node's PACKAGE_EXPORTS_RESOLVE for the\n * `./backend` subpath: an exact `./backend` key wins; otherwise the `./*`-style\n * pattern with the longest matching prefix; condition objects (nested or not)\n * pick the first key that is one of `conditions` or `default`; arrays take the\n * first target that resolves. A package that has `exports` but nothing\n * matching `./backend` has no backend — exactly as Node would refuse to\n * import it.\n *\n * Without `exports`, the legacy layout: `<root>/backend.js`,\n * `<root>/backend/index.js`, and the layout linked packages build to — a\n * `backend.js` next to `main` (`lib/esm/backend.js`).\n *\n * Hand-written rather than via `resolve.exports`: that package also stops at\n * a path and leaves the existence check to the caller, the subset needed is\n * ~50 lines, and the server keeps one less dependency in every app's install.\n */\nexport function resolveBackendEntry(\n pkgRoot: string,\n pkgJson: any,\n conditions: readonly string[] = NODE_IMPORT_CONDITIONS\n): string | null {\n const exists = (rel: string) => packageFile(pkgRoot, rel);\n const exportsField = pkgJson?.exports;\n if (exportsField === undefined || exportsField === null) {\n const candidates = ['backend.js', 'backend/index.js'];\n if (typeof pkgJson?.main === 'string') {\n candidates.push(path.join(path.dirname(pkgJson.main), 'backend.js'));\n }\n candidates.push('lib/esm/backend.js');\n for (const rel of candidates) {\n const file = exists(rel);\n if (file) return file;\n }\n return null;\n }\n return resolveBackendExport(exportsField, conditions, exists);\n}\n\n/** `<pkgRoot>/<rel>` when it is a file inside the package, else null. */\nfunction packageFile(pkgRoot: string, rel: string): string | null {\n const file = path.resolve(pkgRoot, rel);\n // Never let an export target escape the package.\n if (!file.startsWith(path.resolve(pkgRoot) + path.sep)) return null;\n try {\n return fs.statSync(file).isFile() ? file : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The `./backend` subpath of an `exports` map, resolved per Node's\n * PACKAGE_EXPORTS_RESOLVE (see resolveBackendEntry). `probe` turns a matched\n * `./`-relative target into a file, or null when it does not resolve.\n */\nfunction resolveBackendExport(\n exportsField: any,\n conditions: readonly string[],\n probe: (rel: string) => string | null\n): string | null {\n // `\"exports\": \"./x.js\"`, an array, or a condition object at the top level\n // are all sugar for the \".\" subpath only.\n if (\n typeof exportsField !== 'object' ||\n Array.isArray(exportsField) ||\n !Object.keys(exportsField).some((k) => k.startsWith('.'))\n ) {\n return null;\n }\n\n const subpath = './backend';\n let target: any;\n let patternMatch: string | null = null;\n if (Object.prototype.hasOwnProperty.call(exportsField, subpath)) {\n target = exportsField[subpath];\n } else {\n let bestKey: string | null = null;\n for (const key of Object.keys(exportsField)) {\n const star = key.indexOf('*');\n if (star === -1 || key.indexOf('*', star + 1) !== -1) continue;\n const prefix = key.slice(0, star);\n const suffix = key.slice(star + 1);\n if (\n subpath !== prefix &&\n subpath.length >= key.length &&\n subpath.startsWith(prefix) &&\n subpath.endsWith(suffix) &&\n (bestKey === null || patternKeyCompare(bestKey, key) > 0)\n ) {\n bestKey = key;\n patternMatch = subpath.slice(prefix.length, subpath.length - suffix.length);\n }\n }\n if (bestKey === null) return null;\n target = exportsField[bestKey];\n }\n\n const resolveTarget = (t: any): string | null => {\n if (typeof t === 'string') {\n if (!t.startsWith('./')) return null;\n const rel = patternMatch === null ? t : t.split('*').join(patternMatch);\n return probe(rel);\n }\n if (Array.isArray(t)) {\n for (const item of t) {\n const file = resolveTarget(item);\n if (file) return file;\n }\n return null;\n }\n if (t && typeof t === 'object') {\n for (const key of Object.keys(t)) {\n if (key === 'default' || conditions.includes(key)) {\n // Node takes the first matching condition even if its target fails\n // to resolve; it does not fall through to later keys.\n return resolveTarget(t[key]);\n }\n }\n }\n return null;\n };\n return resolveTarget(target);\n}\n\n/**\n * The SOURCE file a dev Vite runner loads for `<pkg>/backend` when the\n * package is a source package — its real root has a `src/` directory, which is\n * what makes `linked`'s Vite config register it as a workspace (cli\n * `discoverWorkspaces` / `readSourcePackage`). Null when the package has no\n * `src/` or no source backend; the caller then falls back to\n * resolveBackendEntry (a built `lib/` copy, or nothing).\n *\n * Mirrors the cli's `resolveWorkspaceSpecifier` for the `./backend` subpath,\n * which runs BEFORE `exports`: `src/backend.tsx`, `src/backend.ts`, then the\n * package's own `exports` under `import`/`default` with a `./lib/esm/X.js`\n * target mapped to `src/X.tsx` / `src/X.ts` (any other `./lib/esm/` target to\n * the same path under src). So an unbuilt workspace, whose `exports` name only\n * `lib/esm`, still has its backend found, and a built one reports the src file\n * Vite actually evaluates rather than its stale `lib/`.\n *\n * Only meaningful when the dev Vite runner owns the package; Node (production,\n * external packages) loads `lib/` and never sees src.\n */\nexport function resolveSourceBackendEntry(\n pkgRoot: string,\n pkgJson: any\n): string | null {\n try {\n if (!fs.statSync(path.join(pkgRoot, 'src')).isDirectory()) return null;\n } catch {\n return null;\n }\n for (const rel of ['src/backend.tsx', 'src/backend.ts']) {\n const file = packageFile(pkgRoot, rel);\n if (file) return file;\n }\n const exportsField = pkgJson?.exports;\n if (exportsField === undefined || exportsField === null) return null;\n const libPrefix = './lib/esm/';\n return resolveBackendExport(exportsField, ['import'], (rel) => {\n if (!rel.startsWith(libPrefix)) return null;\n const sub = rel.slice(libPrefix.length);\n if (/\\.jsx?$/.test(sub)) {\n const base = 'src/' + sub.replace(/\\.jsx?$/, '');\n return packageFile(pkgRoot, base + '.tsx') ?? packageFile(pkgRoot, base + '.ts');\n }\n return packageFile(pkgRoot, 'src/' + sub);\n });\n}\n\n/** Node's PATTERN_KEY_COMPARE: < 0 means `a` is the more specific pattern. */\nfunction patternKeyCompare(a: string, b: string): number {\n const aBase = a.indexOf('*');\n const bBase = b.indexOf('*');\n const baseA = aBase === -1 ? a.length : aBase + 1;\n const baseB = bBase === -1 ? b.length : bBase + 1;\n if (baseA > baseB) return -1;\n if (baseB > baseA) return 1;\n if (aBase === -1) return 1;\n if (bBase === -1) return -1;\n if (a.length > b.length) return -1;\n if (b.length > a.length) return 1;\n return 0;\n}\n\n/**\n * Whether the dev SSR runner BUNDLES `pkgName` (it is in Vite's\n * `ssr.noExternal`) rather than handing it to Node.\n *\n * This decides which loader a package's backend must be loaded with. A module\n * has to be evaluated by the same loader that evaluates the package everywhere\n * else in the SSR graph, or it runs twice:\n *\n * - `vite.ssrLoadModule('<external pkg>/backend')` transforms that entry and\n * its relative imports even though the package is external, while the app's\n * bare imports of the same package are evaluated by Node — two copies of the\n * package's module state.\n * - a plain `import()` of a BUNDLED package goes to Node, while the app's\n * imports of it are evaluated by Vite — the same split the other way round.\n *\n * Vite matches `noExternal` entries against the bare package name, so a\n * subpath (`pkg/backend`) is covered by an entry for `pkg`.\n */\nexport function isBundledBySsr(pkgName: string, noExternal: unknown): boolean {\n if (noExternal === true) return true;\n const entries = Array.isArray(noExternal)\n ? noExternal\n : noExternal\n ? [noExternal]\n : [];\n return entries.some((entry) =>\n typeof entry === 'string'\n ? entry === pkgName\n : entry instanceof RegExp\n ? entry.test(pkgName)\n : false\n );\n}\n\n/** The dev SSR runner's resolved `noExternal`, wherever this Vite keeps it. */\nexport function ssrNoExternalOf(vite: any): unknown {\n return (\n vite?.config?.ssr?.noExternal ??\n vite?.config?.environments?.ssr?.resolve?.noExternal\n );\n}\n\n/**\n * The backend entry of a package the dev Vite runner owns (see isBundledBySsr):\n * its source backend when it is a source package (resolveSourceBackendEntry),\n * otherwise what `exports` names under the `development` condition and Node's\n * import conditions. A registry install has no src/, so it resolves exactly\n * as before.\n */\nexport function resolveDevBackendEntry(\n pkgRoot: string,\n pkgJson: any\n): string | null {\n return (\n resolveSourceBackendEntry(pkgRoot, pkgJson) ??\n resolveBackendEntry(pkgRoot, pkgJson, [\n 'development',\n ...NODE_IMPORT_CONDITIONS,\n ])\n );\n}\n"]}
1
+ {"version":3,"file":"linkedDependencies.js","sourceRoot":"","sources":["../../../src/utils/linkedDependencies.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAsB7B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAS;IAC3C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACzD,OAAO,IAAI,CAAC,aAAa,KAAK,IAAI,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,IAAS;IACtC,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QACrE,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC;IACzB,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC9B,oEAAoE;QACpE,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAAE,OAAO,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,CAAC;YACd,CAAC,CAAC,EAAE,CAAC;IACT,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAC5B,OAAO,KAAK,KAAK,QAAQ;QACvB,CAAC,CAAC,KAAK,KAAK,OAAO;QACnB,CAAC,CAAC,KAAK,YAAY,MAAM;YACvB,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;YACrB,CAAC,CAAC,KAAK,CACZ,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,eAAe,CAAC,IAAS;;IACvC,OAAO,CACL,MAAA,MAAA,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,0CAAE,GAAG,0CAAE,UAAU,mCAC7B,MAAA,MAAA,MAAA,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,0CAAE,YAAY,0CAAE,GAAG,0CAAE,OAAO,0CAAE,UAAU,CACrD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAe,EACf,OAAY;;IAEZ,OAAO,CACL,MAAA,yBAAyB,CAAC,OAAO,EAAE,OAAO,CAAC,mCAC3C,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE;QACpC,aAAa;QACb,GAAG,sBAAsB;KAC1B,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * A linked package found in the app's dependency tree, wherever it is\n * installed: a workspace member, a localized checkout, or a registry install.\n */\nexport interface LinkedDependency {\n packageName: string;\n /**\n * Realpath of the package root whose backend the server loads: the copy the\n * app itself resolves when that copy is a linked package, otherwise the\n * first copy the walk found.\n */\n path: string;\n /**\n * Every distinct installed copy of this package in the tree (realpaths),\n * in the order the walk found them. More than one means the install is not\n * deduplicated; only `path`'s backend is ever loaded.\n */\n copies: { path: string; version?: string }[];\n}\n\n/**\n * A package whose backend providers the server loads at boot: one whose\n * package.json declares `\"linkedPackage\": true`. That flag is the only test —\n * not the package's scope. `@_linked/localize` is in the `@_linked` scope and\n * is a CLI tool, not a linked package; a custom-scope package with the flag is\n * a linked package. The CLI's workspace discovery uses the same flag.\n *\n * The legacy `\"lincd\": true` flag is deliberately NOT enough. Those packages\n * import the old `lincd` core, and loading them at boot is what produced\n * \"Multiple versions of LINCD are loaded\" before boot loading was narrowed to\n * workspace members.\n */\nexport function isLinkedPackageJson(json: any): boolean {\n if (!json || typeof json.name !== 'string') return false;\n return json.linkedPackage === true;\n}\n\n/**\n * Find an installed package the way Node does: `<dir>/node_modules/<name>`,\n * then each parent directory's `node_modules`. Returns null when it is not\n * installed (an optional dependency, say) rather than throwing.\n */\n/**\n * Whether a package has a JavaScript entry the server can import: `main`,\n * `module`, or an `exports` map with a root (`.`) entry or a single string.\n * A linked package can be pure CSS (`@_linked/css`); importing that whole\n * fails with \"Failed to resolve entry\", so the server skips it.\n */\nexport function hasModuleEntry(json: any): boolean {\n if (!json) return false;\n if (typeof json.main === 'string' || typeof json.module === 'string') {\n return true;\n }\n const exp = json.exports;\n if (typeof exp === 'string') return true;\n if (exp && typeof exp === 'object') {\n const keys = Object.keys(exp);\n // Conditions only ({import, require, ...}) describe the root entry.\n if (keys.length > 0 && keys.every((k) => !k.startsWith('.'))) return true;\n return '.' in exp;\n }\n return false;\n}\n\nexport function readInstalledPackage(\n name: string,\n fromDir: string\n): { 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 pkgJsonPath = path.join(root, 'package.json');\n if (fs.existsSync(pkgJsonPath)) {\n try {\n return { root, json: JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')) };\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Every linked package reachable from the app's `dependencies`, each one AFTER\n * the linked packages it depends on. Providers register middleware in the\n * order they are indexed, so a package's middleware must not run before that\n * of a package it builds on (e.g. anything reading `request.linkedAuth` after\n * @_linked/auth's JWT middleware).\n *\n * Only linked packages are recursed into — the same rule the workspace-only\n * filter used — so the walk reads a few dozen package.json files, not the\n * whole of node_modules. Each package's dependencies are resolved from its\n * REAL location, so a symlinked workspace or localized checkout resolves its\n * own dependencies the way Node will when it loads it — which is how a\n * package installed only nested (`owl/node_modules/@_linked/rdfs`) is found.\n *\n * The walk is keyed by real path, not name, so every installed copy of a\n * package is recorded (`copies`). The copy whose backend is loaded (`path`)\n * is the one the app itself resolves, so it is the same module instance the\n * app's own imports reach; when the app cannot resolve the package at all\n * (it is only installed nested) it is the first copy found.\n */\nexport function discoverLinkedDependencies(\n appDir: string,\n appPackageJson: any\n): LinkedDependency[] {\n const out: LinkedDependency[] = [];\n const byName = new Map<string, LinkedDependency>();\n const visitedRoots = new Set<string>();\n const appName = appPackageJson?.name;\n\n const visit = (name: string, fromDir: string) => {\n if (name === appName) return;\n const installed = readInstalledPackage(name, fromDir);\n if (!installed || !isLinkedPackageJson(installed.json)) return;\n const realRoot = realpathOr(installed.root);\n if (visitedRoots.has(realRoot)) return;\n visitedRoots.add(realRoot);\n let entry = byName.get(name);\n if (!entry) {\n entry = { packageName: name, path: realRoot, copies: [] };\n byName.set(name, entry);\n }\n entry.copies.push({ path: realRoot, version: installed.json.version });\n for (const dep of Object.keys(installed.json.dependencies ?? {})) {\n visit(dep, realRoot);\n }\n // Pushed after its dependencies, once per name: the first copy found\n // fixes the package's place in the order.\n if (!out.includes(entry)) out.push(entry);\n };\n\n for (const name of Object.keys(appPackageJson?.dependencies ?? {})) {\n visit(name, appDir);\n }\n\n for (const entry of out) {\n if (entry.copies.length < 2) continue;\n const fromApp = readInstalledPackage(entry.packageName, appDir);\n if (fromApp && isLinkedPackageJson(fromApp.json)) {\n const appCopy = realpathOr(fromApp.root);\n if (entry.copies.some((c) => c.path === appCopy)) entry.path = appCopy;\n }\n }\n return out;\n}\n\n/**\n * Package name → the names of its direct `dependencies` and `peerDependencies`, for the app\n * (`appPackageJson`) and every package in `packageDirs` (name → package root, as discovery\n * found it). The shape check scopes its direction-I errors with it. A package whose\n * `package.json` cannot be read is left out.\n */\nexport function readDependencyLists(\n packageDirs: Iterable<[string, string]>,\n appPackageJson?: any\n): Record<string, string[]> {\n const lists: Record<string, string[]> = {};\n const add = (name: unknown, json: any) => {\n if (typeof name !== 'string' || !name) return;\n lists[name] = [\n ...new Set([\n ...Object.keys(json?.dependencies ?? {}),\n ...Object.keys(json?.peerDependencies ?? {}),\n ]),\n ].sort();\n };\n if (appPackageJson) add(appPackageJson.name, appPackageJson);\n for (const [name, dir] of packageDirs) {\n try {\n add(name, JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')));\n } catch {}\n }\n return lists;\n}\n\nfunction realpathOr(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n/**\n * The conditions a backend entry is resolved with on the Node path. These are\n * the ones Node's ESM loader applies to `import()` — so the file found is the\n * file a bare `import('<pkg>/backend')` from the app would load, and Node's\n * module cache (keyed by real file URL) hands both the same instance.\n * `development` is deliberately absent: it is a Vite/bundler condition, and a\n * production Node runtime never applies it.\n */\nexport const NODE_IMPORT_CONDITIONS = ['import', 'node', 'default'] as const;\n\n/**\n * The absolute path of a package's backend entry file, or null when the\n * package has no backend entry or the file it names does not exist.\n *\n * With `exports`, this follows Node's PACKAGE_EXPORTS_RESOLVE for the\n * `./backend` subpath: an exact `./backend` key wins; otherwise the `./*`-style\n * pattern with the longest matching prefix; condition objects (nested or not)\n * pick the first key that is one of `conditions` or `default`; arrays take the\n * first target that resolves. A package that has `exports` but nothing\n * matching `./backend` has no backend — exactly as Node would refuse to\n * import it.\n *\n * Without `exports`, the legacy layout: `<root>/backend.js`,\n * `<root>/backend/index.js`, and the layout linked packages build to — a\n * `backend.js` next to `main` (`lib/esm/backend.js`).\n *\n * Hand-written rather than via `resolve.exports`: that package also stops at\n * a path and leaves the existence check to the caller, the subset needed is\n * ~50 lines, and the server keeps one less dependency in every app's install.\n */\nexport function resolveBackendEntry(\n pkgRoot: string,\n pkgJson: any,\n conditions: readonly string[] = NODE_IMPORT_CONDITIONS\n): string | null {\n const exists = (rel: string) => packageFile(pkgRoot, rel);\n const exportsField = pkgJson?.exports;\n if (exportsField === undefined || exportsField === null) {\n const candidates = ['backend.js', 'backend/index.js'];\n if (typeof pkgJson?.main === 'string') {\n candidates.push(path.join(path.dirname(pkgJson.main), 'backend.js'));\n }\n candidates.push('lib/esm/backend.js');\n for (const rel of candidates) {\n const file = exists(rel);\n if (file) return file;\n }\n return null;\n }\n return resolveBackendExport(exportsField, conditions, exists);\n}\n\n/** `<pkgRoot>/<rel>` when it is a file inside the package, else null. */\nfunction packageFile(pkgRoot: string, rel: string): string | null {\n const file = path.resolve(pkgRoot, rel);\n // Never let an export target escape the package.\n if (!file.startsWith(path.resolve(pkgRoot) + path.sep)) return null;\n try {\n return fs.statSync(file).isFile() ? file : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The `./backend` subpath of an `exports` map, resolved per Node's\n * PACKAGE_EXPORTS_RESOLVE (see resolveBackendEntry). `probe` turns a matched\n * `./`-relative target into a file, or null when it does not resolve.\n */\nfunction resolveBackendExport(\n exportsField: any,\n conditions: readonly string[],\n probe: (rel: string) => string | null\n): string | null {\n // `\"exports\": \"./x.js\"`, an array, or a condition object at the top level\n // are all sugar for the \".\" subpath only.\n if (\n typeof exportsField !== 'object' ||\n Array.isArray(exportsField) ||\n !Object.keys(exportsField).some((k) => k.startsWith('.'))\n ) {\n return null;\n }\n\n const subpath = './backend';\n let target: any;\n let patternMatch: string | null = null;\n if (Object.prototype.hasOwnProperty.call(exportsField, subpath)) {\n target = exportsField[subpath];\n } else {\n let bestKey: string | null = null;\n for (const key of Object.keys(exportsField)) {\n const star = key.indexOf('*');\n if (star === -1 || key.indexOf('*', star + 1) !== -1) continue;\n const prefix = key.slice(0, star);\n const suffix = key.slice(star + 1);\n if (\n subpath !== prefix &&\n subpath.length >= key.length &&\n subpath.startsWith(prefix) &&\n subpath.endsWith(suffix) &&\n (bestKey === null || patternKeyCompare(bestKey, key) > 0)\n ) {\n bestKey = key;\n patternMatch = subpath.slice(prefix.length, subpath.length - suffix.length);\n }\n }\n if (bestKey === null) return null;\n target = exportsField[bestKey];\n }\n\n const resolveTarget = (t: any): string | null => {\n if (typeof t === 'string') {\n if (!t.startsWith('./')) return null;\n const rel = patternMatch === null ? t : t.split('*').join(patternMatch);\n return probe(rel);\n }\n if (Array.isArray(t)) {\n for (const item of t) {\n const file = resolveTarget(item);\n if (file) return file;\n }\n return null;\n }\n if (t && typeof t === 'object') {\n for (const key of Object.keys(t)) {\n if (key === 'default' || conditions.includes(key)) {\n // Node takes the first matching condition even if its target fails\n // to resolve; it does not fall through to later keys.\n return resolveTarget(t[key]);\n }\n }\n }\n return null;\n };\n return resolveTarget(target);\n}\n\n/**\n * The SOURCE file a dev Vite runner loads for `<pkg>/backend` when the\n * package is a source package — its real root has a `src/` directory, which is\n * what makes `linked`'s Vite config register it as a workspace (cli\n * `discoverWorkspaces` / `readSourcePackage`). Null when the package has no\n * `src/` or no source backend; the caller then falls back to\n * resolveBackendEntry (a built `lib/` copy, or nothing).\n *\n * Mirrors the cli's `resolveWorkspaceSpecifier` for the `./backend` subpath,\n * which runs BEFORE `exports`: `src/backend.tsx`, `src/backend.ts`, then the\n * package's own `exports` under `import`/`default` with a `./lib/esm/X.js`\n * target mapped to `src/X.tsx` / `src/X.ts` (any other `./lib/esm/` target to\n * the same path under src). So an unbuilt workspace, whose `exports` name only\n * `lib/esm`, still has its backend found, and a built one reports the src file\n * Vite actually evaluates rather than its stale `lib/`.\n *\n * Only meaningful when the dev Vite runner owns the package; Node (production,\n * external packages) loads `lib/` and never sees src.\n */\nexport function resolveSourceBackendEntry(\n pkgRoot: string,\n pkgJson: any\n): string | null {\n try {\n if (!fs.statSync(path.join(pkgRoot, 'src')).isDirectory()) return null;\n } catch {\n return null;\n }\n for (const rel of ['src/backend.tsx', 'src/backend.ts']) {\n const file = packageFile(pkgRoot, rel);\n if (file) return file;\n }\n const exportsField = pkgJson?.exports;\n if (exportsField === undefined || exportsField === null) return null;\n const libPrefix = './lib/esm/';\n return resolveBackendExport(exportsField, ['import'], (rel) => {\n if (!rel.startsWith(libPrefix)) return null;\n const sub = rel.slice(libPrefix.length);\n if (/\\.jsx?$/.test(sub)) {\n const base = 'src/' + sub.replace(/\\.jsx?$/, '');\n return packageFile(pkgRoot, base + '.tsx') ?? packageFile(pkgRoot, base + '.ts');\n }\n return packageFile(pkgRoot, 'src/' + sub);\n });\n}\n\n/** Node's PATTERN_KEY_COMPARE: < 0 means `a` is the more specific pattern. */\nfunction patternKeyCompare(a: string, b: string): number {\n const aBase = a.indexOf('*');\n const bBase = b.indexOf('*');\n const baseA = aBase === -1 ? a.length : aBase + 1;\n const baseB = bBase === -1 ? b.length : bBase + 1;\n if (baseA > baseB) return -1;\n if (baseB > baseA) return 1;\n if (aBase === -1) return 1;\n if (bBase === -1) return -1;\n if (a.length > b.length) return -1;\n if (b.length > a.length) return 1;\n return 0;\n}\n\n/**\n * Whether the dev SSR runner BUNDLES `pkgName` (it is in Vite's\n * `ssr.noExternal`) rather than handing it to Node.\n *\n * This decides which loader a package's backend must be loaded with. A module\n * has to be evaluated by the same loader that evaluates the package everywhere\n * else in the SSR graph, or it runs twice:\n *\n * - `vite.ssrLoadModule('<external pkg>/backend')` transforms that entry and\n * its relative imports even though the package is external, while the app's\n * bare imports of the same package are evaluated by Node — two copies of the\n * package's module state.\n * - a plain `import()` of a BUNDLED package goes to Node, while the app's\n * imports of it are evaluated by Vite — the same split the other way round.\n *\n * Vite matches `noExternal` entries against the bare package name, so a\n * subpath (`pkg/backend`) is covered by an entry for `pkg`.\n */\nexport function isBundledBySsr(pkgName: string, noExternal: unknown): boolean {\n if (noExternal === true) return true;\n const entries = Array.isArray(noExternal)\n ? noExternal\n : noExternal\n ? [noExternal]\n : [];\n return entries.some((entry) =>\n typeof entry === 'string'\n ? entry === pkgName\n : entry instanceof RegExp\n ? entry.test(pkgName)\n : false\n );\n}\n\n/** The dev SSR runner's resolved `noExternal`, wherever this Vite keeps it. */\nexport function ssrNoExternalOf(vite: any): unknown {\n return (\n vite?.config?.ssr?.noExternal ??\n vite?.config?.environments?.ssr?.resolve?.noExternal\n );\n}\n\n/**\n * The backend entry of a package the dev Vite runner owns (see isBundledBySsr):\n * its source backend when it is a source package (resolveSourceBackendEntry),\n * otherwise what `exports` names under the `development` condition and Node's\n * import conditions. A registry install has no src/, so it resolves exactly\n * as before.\n */\nexport function resolveDevBackendEntry(\n pkgRoot: string,\n pkgJson: any\n): string | null {\n return (\n resolveSourceBackendEntry(pkgRoot, pkgJson) ??\n resolveBackendEntry(pkgRoot, pkgJson, [\n 'development',\n ...NODE_IMPORT_CONDITIONS,\n ])\n );\n}\n"]}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Ontology sync and the shape check, as the server runs them before its shape sync: at boot and
3
+ * when the host asks for a re-sync (`POST /admin/sync-shapes`).
4
+ *
5
+ * - The ontology sync (core `syncOntologies`) writes each registered package's ontology data into
6
+ * its own named graph of the app's default dataset (`{package IRI}/graph/ontology`, with a
7
+ * record in the graph registry that marks it as a hierarchy source), skipping a package whose
8
+ * stored hash matches, so the store's RDFS view infers the class hierarchy. A store without
9
+ * graph queries (it answers `unsupported-query-kind`, or has no `graphQuery`) gets core's
10
+ * earlier sync of the `rdfs:subClassOf` triples into the default graph instead. The graphs the
11
+ * sync wrote or dropped are observed on core's query dispatch and reported by name.
12
+ * - The shape check (core `checkShapeHierarchy`) compares the registered shapes with that
13
+ * hierarchy. A running app is never stopped by it: its findings are logged and counted.
14
+ * - The in-memory class hierarchy (core `loadOntologyHierarchy`) is loaded also when the sync
15
+ * is off; the sync loads it itself when it runs.
16
+ * - Before either, every linked package directory the server discovered registers its ontologies
17
+ * (core `registerInstalledOntologies`): a package the app only deep-imports shape files from
18
+ * never evaluates its register modules, so its data would be missing from both. A source
19
+ * package without built register modules (a workspace package in dev) registers through
20
+ * `importModule` (Vite's `ssrLoadModule`), when the caller passes one.
21
+ *
22
+ * The four core modules (`ontology/syncOntologies`, `shapes/checkShapeHierarchy`,
23
+ * `ontology/hierarchy`, `ontology/registerInstalled`) are server only and not in core's index, so
24
+ * {@link loadOntologyCore} imports them by their fixed subpaths when the phase runs; the core
25
+ * this server depends on has all of them. Kept apart from `LinkedServer` so the order and the failure handling can be tested without
26
+ * booting a server.
27
+ */
28
+ import type { BootOrphanScope } from './syncShapes.js';
29
+ /** The subset of core's ontology and shape-check API this module calls. */
30
+ export interface OntologyCore {
31
+ syncOntologies(ds: unknown, options: {
32
+ orphanScope: BootOrphanScope;
33
+ }): Promise<{
34
+ written: string[];
35
+ skipped: string[];
36
+ pruned: string[];
37
+ }>;
38
+ checkShapeHierarchy(options: {
39
+ dependencies?: Record<string, string[]>;
40
+ }): Promise<Array<{
41
+ kind: string;
42
+ severity: 'error' | 'warning';
43
+ shape?: string;
44
+ iri?: string;
45
+ message: string;
46
+ }>>;
47
+ /** Loads the in-memory class hierarchy. Optional so a test double can leave it out. */
48
+ loadOntologyHierarchy?: () => Promise<unknown>;
49
+ /**
50
+ * Calls `onGraph` for every graph query on `ds` that succeeds until the returned function is
51
+ * called (core's `subscribeQueryDispatch`). Optional so a test double can leave it out.
52
+ */
53
+ observeGraphQueries?: (ds: unknown, onGraph: (query: {
54
+ kind: string;
55
+ graph: string;
56
+ }, settled: Promise<unknown>) => void) => () => void;
57
+ /**
58
+ * Registers the ontologies of the installed packages in the given directories. Optional so a
59
+ * test double can leave it out.
60
+ */
61
+ registerInstalledOntologies?: (packageDirs: string[], options?: {
62
+ importModule?: (file: string) => Promise<unknown>;
63
+ }) => Promise<string[]>;
64
+ }
65
+ /** What the ontology sync and the shape check did, as `POST /admin/sync-shapes` reports it. */
66
+ export interface OntologyPhaseResult {
67
+ /**
68
+ * Packages whose ontology graph (or, on a store without graph queries, hierarchy) was written,
69
+ * packages left as they were (unchanged or unreadable), and the graphs the sync wrote and
70
+ * dropped (empty on a store without graph queries).
71
+ */
72
+ ontologies: {
73
+ written: string[];
74
+ skipped: string[];
75
+ graphs?: string[];
76
+ droppedGraphs?: string[];
77
+ };
78
+ /** The shape check's findings, counted by severity. */
79
+ shapeCheck: {
80
+ errors: number;
81
+ warnings: number;
82
+ };
83
+ /** The first error the sync or the check threw; the phase went on without it. */
84
+ failure?: Error;
85
+ }
86
+ /**
87
+ * Whether the server syncs shapes (and so ontologies) into its app data: off when `linked.config`
88
+ * sets `syncShapesOnBoot: false` or the environment sets `LINKED_SYNC_SHAPES_ON_BOOT=false`. One
89
+ * switch for both syncs, at boot and on the host's request.
90
+ */
91
+ export declare function shapeSyncOn(env: Record<string, string | undefined>, configFlag: unknown): boolean;
92
+ /**
93
+ * Whether the boot syncs ontologies: when shape sync is on ({@link shapeSyncOn}) and the
94
+ * environment does not opt out with `LINKED_SYNC_ONTOLOGIES_ON_BOOT=false`.
95
+ */
96
+ export declare function bootSyncsOntologies(env: Record<string, string | undefined>, configFlag?: unknown): boolean;
97
+ /**
98
+ * Import core's ontology sync, shape check, hierarchy loader and installed packages'
99
+ * registration.
100
+ */
101
+ export declare function loadOntologyCore(): Promise<OntologyCore>;
102
+ /**
103
+ * The package directories whose ontologies register before the sync: every linked package
104
+ * discovered in the app's dependency tree, then the app's own workspace packages (a CN clone's
105
+ * `packages/<slug>-ont` is one no package imports, so the dependency walk never reaches it).
106
+ * Order kept, duplicates dropped.
107
+ */
108
+ export declare function ontologyPackageDirs(linkedPackageDirs: Iterable<string>, workspacePackageDirs: Iterable<string>): string[];
109
+ /**
110
+ * In dev, the loader for source register modules: Vite's `ssrLoadModule`, so a workspace package
111
+ * that was never built registers on the core the SSR graph uses. Undefined without Vite (a built
112
+ * app), where source packages are skipped.
113
+ */
114
+ export declare function sourceModuleImporter(vite: {
115
+ ssrLoadModule?: (url: string) => Promise<unknown>;
116
+ } | undefined | null): ((file: string) => Promise<unknown>) | undefined;
117
+ /**
118
+ * Register the ontologies of the installed linked packages in `packageDirs` (package roots), sync
119
+ * the registered ontologies into `ds` (when `sync` is set and there is a dataset), then run the
120
+ * shape check. Never throws: a failed registration is logged and the phase goes on; a failed sync is logged and returned as `failure`, and the
121
+ * check still runs; a failed check likewise. Logs one line for the sync, one summary line for
122
+ * the check and one line per finding.
123
+ */
124
+ export declare function runOntologyPhase(ds: unknown, { core, sync, orphanScope, dependencies, packageDirs, importModule, log, warn, }: {
125
+ core: OntologyCore;
126
+ sync: boolean;
127
+ orphanScope: BootOrphanScope;
128
+ dependencies?: Record<string, string[]>;
129
+ /** Every linked package directory the server discovered (transitively). */
130
+ packageDirs?: string[];
131
+ /**
132
+ * Imports a source register module (`src/ontologies/*.register.ts`) of a package directory
133
+ * without built ones; in dev, Vite's `ssrLoadModule`.
134
+ */
135
+ importModule?: (file: string) => Promise<unknown>;
136
+ log?: (message: string) => void;
137
+ warn?: (message: string, err?: unknown) => void;
138
+ }): Promise<OntologyPhaseResult>;
139
+ /**
140
+ * The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology
141
+ * phase failed. The ontology phase's failure is then thrown, so the route answers with it, as
142
+ * it does for a failed shape sync.
143
+ */
144
+ export declare function syncOntologiesThenShapes<T extends object>(ontologyPhase: () => Promise<OntologyPhaseResult>, shapeSync: () => Promise<T>): Promise<T & Pick<OntologyPhaseResult, 'ontologies' | 'shapeCheck'>>;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Whether the server syncs shapes (and so ontologies) into its app data: off when `linked.config`
3
+ * sets `syncShapesOnBoot: false` or the environment sets `LINKED_SYNC_SHAPES_ON_BOOT=false`. One
4
+ * switch for both syncs, at boot and on the host's request.
5
+ */
6
+ export function shapeSyncOn(env, configFlag) {
7
+ return configFlag !== false && env.LINKED_SYNC_SHAPES_ON_BOOT !== 'false';
8
+ }
9
+ /**
10
+ * Whether the boot syncs ontologies: when shape sync is on ({@link shapeSyncOn}) and the
11
+ * environment does not opt out with `LINKED_SYNC_ONTOLOGIES_ON_BOOT=false`.
12
+ */
13
+ export function bootSyncsOntologies(env, configFlag) {
14
+ return shapeSyncOn(env, configFlag) && env.LINKED_SYNC_ONTOLOGIES_ON_BOOT !== 'false';
15
+ }
16
+ /**
17
+ * Import core's ontology sync, shape check, hierarchy loader and installed packages'
18
+ * registration.
19
+ */
20
+ export async function loadOntologyCore() {
21
+ const sync = await import('@_linked/core/ontology/syncOntologies');
22
+ const check = await import('@_linked/core/shapes/checkShapeHierarchy');
23
+ const hierarchy = await import('@_linked/core/ontology/hierarchy');
24
+ const registerInstalled = await import('@_linked/core/ontology/registerInstalled');
25
+ const dispatch = await import('@_linked/core/queries/queryDispatch');
26
+ return {
27
+ syncOntologies: (ds, options) => sync.syncOntologies(ds, options),
28
+ checkShapeHierarchy: (options) => check.checkShapeHierarchy(options),
29
+ loadOntologyHierarchy: () => hierarchy.loadOntologyHierarchy(),
30
+ registerInstalledOntologies: (packageDirs, options) => registerInstalled.registerInstalledOntologies(packageDirs, options),
31
+ observeGraphQueries: (ds, onGraph) => dispatch.subscribeQueryDispatch((event) => {
32
+ if (event.kind === 'graph' && event.target === ds)
33
+ onGraph(event.query, event.result);
34
+ }),
35
+ };
36
+ }
37
+ /**
38
+ * The package directories whose ontologies register before the sync: every linked package
39
+ * discovered in the app's dependency tree, then the app's own workspace packages (a CN clone's
40
+ * `packages/<slug>-ont` is one no package imports, so the dependency walk never reaches it).
41
+ * Order kept, duplicates dropped.
42
+ */
43
+ export function ontologyPackageDirs(linkedPackageDirs, workspacePackageDirs) {
44
+ return [...new Set([...linkedPackageDirs, ...workspacePackageDirs])];
45
+ }
46
+ /**
47
+ * In dev, the loader for source register modules: Vite's `ssrLoadModule`, so a workspace package
48
+ * that was never built registers on the core the SSR graph uses. Undefined without Vite (a built
49
+ * app), where source packages are skipped.
50
+ */
51
+ export function sourceModuleImporter(vite) {
52
+ const ssrLoadModule = vite === null || vite === void 0 ? void 0 : vite.ssrLoadModule;
53
+ return typeof ssrLoadModule === 'function' ? (file) => ssrLoadModule.call(vite, file) : undefined;
54
+ }
55
+ const asError = (err) => (err instanceof Error ? err : new Error(String(err)));
56
+ const list = (names) => (names.length ? names.join(', ') : 'none');
57
+ /**
58
+ * Register the ontologies of the installed linked packages in `packageDirs` (package roots), sync
59
+ * the registered ontologies into `ds` (when `sync` is set and there is a dataset), then run the
60
+ * shape check. Never throws: a failed registration is logged and the phase goes on; a failed sync is logged and returned as `failure`, and the
61
+ * check still runs; a failed check likewise. Logs one line for the sync, one summary line for
62
+ * the check and one line per finding.
63
+ */
64
+ export async function runOntologyPhase(ds, { core, sync, orphanScope, dependencies, packageDirs = [], importModule, log = console.log, warn = console.warn, }) {
65
+ var _a, _b;
66
+ const result = {
67
+ ontologies: { written: [], skipped: [], graphs: [], droppedGraphs: [] },
68
+ shapeCheck: { errors: 0, warnings: 0 },
69
+ };
70
+ if (core.registerInstalledOntologies && packageDirs.length) {
71
+ try {
72
+ if (importModule)
73
+ await core.registerInstalledOntologies(packageDirs, { importModule });
74
+ else
75
+ await core.registerInstalledOntologies(packageDirs);
76
+ }
77
+ catch (err) {
78
+ warn("[LinkedServer] registering the installed packages' ontologies failed:", err);
79
+ }
80
+ }
81
+ let hierarchyLoaded = false;
82
+ if (sync && ds) {
83
+ const written = new Set();
84
+ const dropped = new Set();
85
+ const pending = [];
86
+ const stop = (_a = core.observeGraphQueries) === null || _a === void 0 ? void 0 : _a.call(core, ds, (query, settled) => {
87
+ pending.push(settled.then(() => (query.kind === 'graph_drop' ? dropped : written).add(query.graph), () => undefined));
88
+ });
89
+ try {
90
+ const sync = await core.syncOntologies(ds, { orphanScope });
91
+ await Promise.all(pending);
92
+ const graphs = [...written].sort();
93
+ const droppedGraphs = [...dropped].sort();
94
+ result.ontologies = { written: sync.written, skipped: sync.skipped, graphs, droppedGraphs };
95
+ hierarchyLoaded = true;
96
+ const defaultGraph = !!stop && sync.written.length > 0 && graphs.length === 0;
97
+ log(`[LinkedServer] ontology sync${defaultGraph ? ' (default graph: the store has no graph queries)' : ''}: ` +
98
+ `written ${list(sync.written)}; skipped ${list(sync.skipped)}` +
99
+ (orphanScope === 'all' ? `; pruned ${list(sync.pruned)}` : '') +
100
+ (graphs.length ? `; graphs written ${list(graphs)}` : '') +
101
+ (droppedGraphs.length ? `; graphs dropped ${list(droppedGraphs)}` : ''));
102
+ }
103
+ catch (err) {
104
+ result.failure = asError(err);
105
+ warn('[LinkedServer] ontology sync failed:', err);
106
+ }
107
+ finally {
108
+ stop === null || stop === void 0 ? void 0 : stop();
109
+ }
110
+ }
111
+ if (!hierarchyLoaded && core.loadOntologyHierarchy) {
112
+ try {
113
+ await core.loadOntologyHierarchy();
114
+ }
115
+ catch (err) {
116
+ warn('[LinkedServer] loading the class hierarchy failed:', err);
117
+ }
118
+ }
119
+ try {
120
+ const findings = await core.checkShapeHierarchy({ dependencies });
121
+ const errors = findings.filter((f) => f.severity === 'error').length;
122
+ result.shapeCheck = { errors, warnings: findings.length - errors };
123
+ log(`[LinkedServer] shape check: ${errors} error(s), ${findings.length - errors} warning(s)`);
124
+ for (const f of findings)
125
+ warn(`[LinkedServer] shape check ${f.severity} (${f.kind}): ${f.message}`);
126
+ }
127
+ catch (err) {
128
+ (_b = result.failure) !== null && _b !== void 0 ? _b : (result.failure = asError(err));
129
+ warn('[LinkedServer] shape check failed:', err);
130
+ }
131
+ return result;
132
+ }
133
+ /**
134
+ * The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology
135
+ * phase failed. The ontology phase's failure is then thrown, so the route answers with it, as
136
+ * it does for a failed shape sync.
137
+ */
138
+ export async function syncOntologiesThenShapes(ontologyPhase, shapeSync) {
139
+ const { ontologies, shapeCheck, failure } = await ontologyPhase();
140
+ const shapes = await shapeSync();
141
+ if (failure)
142
+ throw failure;
143
+ return { ...shapes, ontologies, shapeCheck };
144
+ }
145
+ //# sourceMappingURL=ontologySync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ontologySync.js","sourceRoot":"","sources":["../../../src/utils/ontologySync.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AIG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,aAAiD,EACjD,SAA2B;IAE3B,MAAM,EAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAC,GAAG,MAAM,aAAa,EAAE,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAC;IACjC,IAAI,OAAO;QAAE,MAAM,OAAO,CAAC;IAC3B,OAAO,EAAC,GAAG,MAAM,EAAE,UAAU,EAAE,UAAU,EAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Ontology sync and the shape check, as the server runs them before its shape sync: at boot and\n * when the host asks for a re-sync (`POST /admin/sync-shapes`).\n *\n * - The ontology sync (core `syncOntologies`) writes each registered package's ontology data into\n * its own named graph of the app's default dataset (`{package IRI}/graph/ontology`, with a\n * record in the graph registry that marks it as a hierarchy source), skipping a package whose\n * stored hash matches, so the store's RDFS view infers the class hierarchy. A store without\n * graph queries (it answers `unsupported-query-kind`, or has no `graphQuery`) gets core's\n * earlier sync of the `rdfs:subClassOf` triples into the default graph instead. The graphs the\n * sync wrote or dropped are observed on core's query dispatch and reported by name.\n * - The shape check (core `checkShapeHierarchy`) compares the registered shapes with that\n * hierarchy. A running app is never stopped by it: its findings are logged and counted.\n * - The in-memory class hierarchy (core `loadOntologyHierarchy`) is loaded also when the sync\n * is off; the sync loads it itself when it runs.\n * - Before either, every linked package directory the server discovered registers its ontologies\n * (core `registerInstalledOntologies`): a package the app only deep-imports shape files from\n * never evaluates its register modules, so its data would be missing from both. A source\n * package without built register modules (a workspace package in dev) registers through\n * `importModule` (Vite's `ssrLoadModule`), when the caller passes one.\n *\n * The four core modules (`ontology/syncOntologies`, `shapes/checkShapeHierarchy`,\n * `ontology/hierarchy`, `ontology/registerInstalled`) are server only and not in core's index, so\n * {@link loadOntologyCore} imports them by their fixed subpaths when the phase runs; the core\n * this server depends on has all of them. Kept apart from `LinkedServer` so the order and the failure handling can be tested without\n * booting a server.\n */\nimport type {BootOrphanScope} from './syncShapes.js';\n\n/** The subset of core's ontology and shape-check API this module calls. */\nexport interface OntologyCore {\n syncOntologies(\n ds: unknown,\n options: {orphanScope: BootOrphanScope},\n ): Promise<{written: string[]; skipped: string[]; pruned: string[]}>;\n checkShapeHierarchy(options: {dependencies?: Record<string, string[]>}): Promise<\n Array<{kind: string; severity: 'error' | 'warning'; shape?: string; iri?: string; message: string}>\n >;\n /** Loads the in-memory class hierarchy. Optional so a test double can leave it out. */\n loadOntologyHierarchy?: () => Promise<unknown>;\n /**\n * Calls `onGraph` for every graph query on `ds` that succeeds until the returned function is\n * called (core's `subscribeQueryDispatch`). Optional so a test double can leave it out.\n */\n observeGraphQueries?: (\n ds: unknown,\n onGraph: (query: {kind: string; graph: string}, settled: Promise<unknown>) => void,\n ) => () => void;\n /**\n * Registers the ontologies of the installed packages in the given directories. Optional so a\n * test double can leave it out.\n */\n registerInstalledOntologies?: (\n packageDirs: string[],\n options?: {importModule?: (file: string) => Promise<unknown>},\n ) => Promise<string[]>;\n}\n\n/** What the ontology sync and the shape check did, as `POST /admin/sync-shapes` reports it. */\nexport interface OntologyPhaseResult {\n /**\n * Packages whose ontology graph (or, on a store without graph queries, hierarchy) was written,\n * packages left as they were (unchanged or unreadable), and the graphs the sync wrote and\n * dropped (empty on a store without graph queries).\n */\n ontologies: {written: string[]; skipped: string[]; graphs?: string[]; droppedGraphs?: string[]};\n /** The shape check's findings, counted by severity. */\n shapeCheck: {errors: number; warnings: number};\n /** The first error the sync or the check threw; the phase went on without it. */\n failure?: Error;\n}\n\n/**\n * Whether the server syncs shapes (and so ontologies) into its app data: off when `linked.config`\n * sets `syncShapesOnBoot: false` or the environment sets `LINKED_SYNC_SHAPES_ON_BOOT=false`. One\n * switch for both syncs, at boot and on the host's request.\n */\nexport function shapeSyncOn(\n env: Record<string, string | undefined>,\n configFlag: unknown,\n): boolean {\n return configFlag !== false && env.LINKED_SYNC_SHAPES_ON_BOOT !== 'false';\n}\n\n/**\n * Whether the boot syncs ontologies: when shape sync is on ({@link shapeSyncOn}) and the\n * environment does not opt out with `LINKED_SYNC_ONTOLOGIES_ON_BOOT=false`.\n */\nexport function bootSyncsOntologies(\n env: Record<string, string | undefined>,\n configFlag?: unknown,\n): boolean {\n return shapeSyncOn(env, configFlag) && env.LINKED_SYNC_ONTOLOGIES_ON_BOOT !== 'false';\n}\n\n/**\n * Import core's ontology sync, shape check, hierarchy loader and installed packages'\n * registration.\n */\nexport async function loadOntologyCore(): Promise<OntologyCore> {\n const sync = await import('@_linked/core/ontology/syncOntologies');\n const check = await import('@_linked/core/shapes/checkShapeHierarchy');\n const hierarchy = await import('@_linked/core/ontology/hierarchy');\n const registerInstalled = await import('@_linked/core/ontology/registerInstalled');\n const dispatch = await import('@_linked/core/queries/queryDispatch');\n return {\n syncOntologies: (ds, options) =>\n sync.syncOntologies(ds as Parameters<typeof sync.syncOntologies>[0], options),\n checkShapeHierarchy: (options) => check.checkShapeHierarchy(options),\n loadOntologyHierarchy: () => hierarchy.loadOntologyHierarchy(),\n registerInstalledOntologies: (packageDirs, options) =>\n registerInstalled.registerInstalledOntologies(packageDirs, options),\n observeGraphQueries: (ds, onGraph) =>\n dispatch.subscribeQueryDispatch((event) => {\n if (event.kind === 'graph' && event.target === ds) onGraph(event.query, event.result);\n }),\n };\n}\n\n/**\n * The package directories whose ontologies register before the sync: every linked package\n * discovered in the app's dependency tree, then the app's own workspace packages (a CN clone's\n * `packages/<slug>-ont` is one no package imports, so the dependency walk never reaches it).\n * Order kept, duplicates dropped.\n */\nexport function ontologyPackageDirs(\n linkedPackageDirs: Iterable<string>,\n workspacePackageDirs: Iterable<string>,\n): string[] {\n return [...new Set([...linkedPackageDirs, ...workspacePackageDirs])];\n}\n\n/**\n * In dev, the loader for source register modules: Vite's `ssrLoadModule`, so a workspace package\n * that was never built registers on the core the SSR graph uses. Undefined without Vite (a built\n * app), where source packages are skipped.\n */\nexport function sourceModuleImporter(\n vite: {ssrLoadModule?: (url: string) => Promise<unknown>} | undefined | null,\n): ((file: string) => Promise<unknown>) | undefined {\n const ssrLoadModule = vite?.ssrLoadModule;\n return typeof ssrLoadModule === 'function' ? (file) => ssrLoadModule.call(vite, file) : undefined;\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));\nconst list = (names: string[]) => (names.length ? names.join(', ') : 'none');\n\n/**\n * Register the ontologies of the installed linked packages in `packageDirs` (package roots), sync\n * the registered ontologies into `ds` (when `sync` is set and there is a dataset), then run the\n * shape check. Never throws: a failed registration is logged and the phase goes on; a failed sync is logged and returned as `failure`, and the\n * check still runs; a failed check likewise. Logs one line for the sync, one summary line for\n * the check and one line per finding.\n */\nexport async function runOntologyPhase(\n ds: unknown,\n {\n core,\n sync,\n orphanScope,\n dependencies,\n packageDirs = [],\n importModule,\n log = console.log,\n warn = console.warn,\n }: {\n core: OntologyCore;\n sync: boolean;\n orphanScope: BootOrphanScope;\n dependencies?: Record<string, string[]>;\n /** Every linked package directory the server discovered (transitively). */\n packageDirs?: string[];\n /**\n * Imports a source register module (`src/ontologies/*.register.ts`) of a package directory\n * without built ones; in dev, Vite's `ssrLoadModule`.\n */\n importModule?: (file: string) => Promise<unknown>;\n log?: (message: string) => void;\n warn?: (message: string, err?: unknown) => void;\n },\n): Promise<OntologyPhaseResult> {\n const result: OntologyPhaseResult = {\n ontologies: {written: [], skipped: [], graphs: [], droppedGraphs: []},\n shapeCheck: {errors: 0, warnings: 0},\n };\n\n if (core.registerInstalledOntologies && packageDirs.length) {\n try {\n if (importModule) await core.registerInstalledOntologies(packageDirs, {importModule});\n else await core.registerInstalledOntologies(packageDirs);\n } catch (err) {\n warn(\"[LinkedServer] registering the installed packages' ontologies failed:\", err);\n }\n }\n\n let hierarchyLoaded = false;\n if (sync && ds) {\n const written = new Set<string>();\n const dropped = new Set<string>();\n const pending: Promise<unknown>[] = [];\n const stop = core.observeGraphQueries?.(ds, (query, settled) => {\n pending.push(\n settled.then(\n () => (query.kind === 'graph_drop' ? dropped : written).add(query.graph),\n () => undefined,\n ),\n );\n });\n try {\n const sync = await core.syncOntologies(ds, {orphanScope});\n await Promise.all(pending);\n const graphs = [...written].sort();\n const droppedGraphs = [...dropped].sort();\n result.ontologies = {written: sync.written, skipped: sync.skipped, graphs, droppedGraphs};\n hierarchyLoaded = true;\n const defaultGraph = !!stop && sync.written.length > 0 && graphs.length === 0;\n log(\n `[LinkedServer] ontology sync${defaultGraph ? ' (default graph: the store has no graph queries)' : ''}: ` +\n `written ${list(sync.written)}; skipped ${list(sync.skipped)}` +\n (orphanScope === 'all' ? `; pruned ${list(sync.pruned)}` : '') +\n (graphs.length ? `; graphs written ${list(graphs)}` : '') +\n (droppedGraphs.length ? `; graphs dropped ${list(droppedGraphs)}` : ''),\n );\n } catch (err) {\n result.failure = asError(err);\n warn('[LinkedServer] ontology sync failed:', err);\n } finally {\n stop?.();\n }\n }\n if (!hierarchyLoaded && core.loadOntologyHierarchy) {\n try {\n await core.loadOntologyHierarchy();\n } catch (err) {\n warn('[LinkedServer] loading the class hierarchy failed:', err);\n }\n }\n\n try {\n const findings = await core.checkShapeHierarchy({dependencies});\n const errors = findings.filter((f) => f.severity === 'error').length;\n result.shapeCheck = {errors, warnings: findings.length - errors};\n log(`[LinkedServer] shape check: ${errors} error(s), ${findings.length - errors} warning(s)`);\n for (const f of findings) warn(`[LinkedServer] shape check ${f.severity} (${f.kind}): ${f.message}`);\n } catch (err) {\n result.failure ??= asError(err);\n warn('[LinkedServer] shape check failed:', err);\n }\n return result;\n}\n\n/**\n * The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology\n * phase failed. The ontology phase's failure is then thrown, so the route answers with it, as\n * it does for a failed shape sync.\n */\nexport async function syncOntologiesThenShapes<T extends object>(\n ontologyPhase: () => Promise<OntologyPhaseResult>,\n shapeSync: () => Promise<T>,\n): Promise<T & Pick<OntologyPhaseResult, 'ontologies' | 'shapeCheck'>> {\n const {ontologies, shapeCheck, failure} = await ontologyPhase();\n const shapes = await shapeSync();\n if (failure) throw failure;\n return {...shapes, ontologies, shapeCheck};\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { type GraphQuery } from '@_linked/core/queries/graphQuery';
1
2
  import type { ShapeCatalog } from '@_linked/core/utils/ShapeCatalog';
2
3
  import { type QueryOperation } from '@_linked/server-utils/utils/QueryAccess';
3
4
  /**
@@ -63,3 +64,23 @@ export declare function lowerForAccessCheck(builder: any): unknown;
63
64
  export declare function authorizeGenericQuery(operation: QueryOperation, query: unknown, builder: any, endpoint: string): Promise<void>;
64
65
  /** Check a raw SPARQL query against the `rawQueries` setting (see utils/rawQueries). */
65
66
  export declare function authorizeRawQuery(query: unknown, endpoint: string): Promise<void>;
67
+ /**
68
+ * The graph query `json` describes, checked with core's `parseGraphQuery`; `undefined` when it is
69
+ * not a valid graph query (the access check then refuses it with 400).
70
+ */
71
+ export declare function toGraphQuery(json: unknown): GraphQuery | undefined;
72
+ /**
73
+ * Check a graph query against the `graph` rule of the store `LinkedStorage.graphQuery` routes its
74
+ * record class to (`QueryAccess`, operation `graph`): no rule, or `'none'`, refuses it (403, 401
75
+ * without a session); a malformed one answers 400. `ir` is {@link toGraphQuery}'s result. No
76
+ * catalog is resolved for a graph query (its record shapes are core's built-ins), so the check
77
+ * resolves the store in the global registry, where `LinkedStorage.graphQuery` then runs it.
78
+ */
79
+ export declare function authorizeGraphQuery(query: unknown, ir: GraphQuery | undefined, endpoint: string): Promise<void>;
80
+ /**
81
+ * A store's graph query refusal (`GraphQueryError`) as the answer the caller gets: a
82
+ * `ServerCallError` with the refusal's status and message and its `code`, which the call route
83
+ * sends as `{error, code}` (`RemoteDataset` turns it back into a `GraphQueryError`). Any other
84
+ * error is returned as is.
85
+ */
86
+ export declare function graphQueryCallError(err: unknown): unknown;
@@ -10,6 +10,11 @@
10
10
  * module turns the incoming query into the builder the store runs and the IR
11
11
  * the rules read.
12
12
  *
13
+ * Graph queries (`graph_create`, `graph_replace`, `graph_patch`, `graph_drop`) arrive as plain
14
+ * data on `/call/@_linked/server/graphQuery`: {@link toGraphQuery} checks the JSON, the store's
15
+ * `graph` rule decides ({@link authorizeGraphQuery}), and a refusal of the store goes back with
16
+ * its code ({@link graphQueryCallError}).
17
+ *
13
18
  * The host can supply the shape catalog a request's query is decoded in
14
19
  * (`setQueryCatalogResolver`), so one server can resolve the same shape IRI
15
20
  * differently per request (for example per project branch).
@@ -18,6 +23,7 @@
18
23
  * the ground up (see QueryAccess).
19
24
  */
20
25
  import { fromJSON } from '@_linked/core';
26
+ import { isGraphQueryError, parseGraphQuery, } from '@_linked/core/queries/graphQuery';
21
27
  import { lower } from '@_linked/core/queries/lower';
22
28
  import { checkQueryAccess, } from '@_linked/server-utils/utils/QueryAccess';
23
29
  import { ServerCallError } from '@_linked/server-utils/utils/ServerCallError';
@@ -174,4 +180,52 @@ export async function authorizeRawQuery(query, endpoint) {
174
180
  endpoint,
175
181
  });
176
182
  }
183
+ /**
184
+ * The graph query `json` describes, checked with core's `parseGraphQuery`; `undefined` when it is
185
+ * not a valid graph query (the access check then refuses it with 400).
186
+ */
187
+ export function toGraphQuery(json) {
188
+ try {
189
+ return parseGraphQuery(json);
190
+ }
191
+ catch (_a) {
192
+ return undefined;
193
+ }
194
+ }
195
+ /**
196
+ * Check a graph query against the `graph` rule of the store `LinkedStorage.graphQuery` routes its
197
+ * record class to (`QueryAccess`, operation `graph`): no rule, or `'none'`, refuses it (403, 401
198
+ * without a session); a malformed one answers 400. `ir` is {@link toGraphQuery}'s result. No
199
+ * catalog is resolved for a graph query (its record shapes are core's built-ins), so the check
200
+ * resolves the store in the global registry, where `LinkedStorage.graphQuery` then runs it.
201
+ */
202
+ export async function authorizeGraphQuery(query, ir, endpoint) {
203
+ await checkQueryAccess({
204
+ operation: 'graph',
205
+ query,
206
+ ir,
207
+ mode: getRpcExposureMode(),
208
+ endpoint,
209
+ });
210
+ }
211
+ /** The HTTP status each graph query refusal is answered with. */
212
+ const GRAPH_REFUSAL_STATUS = {
213
+ 'unsupported-query-kind': 501,
214
+ 'graph-name-read-only': 400,
215
+ 'graph-not-registered': 409,
216
+ 'graph-exists': 409,
217
+ };
218
+ /**
219
+ * A store's graph query refusal (`GraphQueryError`) as the answer the caller gets: a
220
+ * `ServerCallError` with the refusal's status and message and its `code`, which the call route
221
+ * sends as `{error, code}` (`RemoteDataset` turns it back into a `GraphQueryError`). Any other
222
+ * error is returned as is.
223
+ */
224
+ export function graphQueryCallError(err) {
225
+ var _a;
226
+ if (!isGraphQueryError(err))
227
+ return err;
228
+ const status = (_a = GRAPH_REFUSAL_STATUS[err.code]) !== null && _a !== void 0 ? _a : 400;
229
+ return Object.assign(new ServerCallError(status, err.message, { cause: err }), { code: err.code });
230
+ }
177
231
  //# sourceMappingURL=queryPlane.js.map