@_linked/server 2.14.2 → 2.15.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @\_linked/server
2
2
 
3
+ ## 2.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#117](https://github.com/linked-fw/server/pull/117) [`05d29f1`](https://github.com/linked-fw/server/commit/05d29f11fa634436de4c5c8f9940790a90e3a222) Thanks [@flyon](https://github.com/flyon)! - Boot-time shape sync no longer deletes store shapes the app did not register.
8
+
9
+ `LinkedServer` materializes the app's registered shapes into its app-data on every boot. It called
10
+ core `syncShapes(appData)` with no options, so on the cores where `orphanScope` defaults to `'all'`
11
+ it also deleted every NodeShape in the dataset that the process had not registered. An app whose
12
+ backend imports no shapes — the Create Now app template — therefore deleted every NodeShape in its
13
+ app-data on boot, including shapes Create Now put there with `bindShape` / `enableCapability`; one
14
+ that deep-imported a single shape file deleted the rest of that package.
15
+
16
+ Boot sync now passes `{orphanScope: 'none'}` explicitly, so it is additive whatever core version the
17
+ app resolves. An operator who wants the old pruning can set `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true`
18
+ (that exact value; anything else leaves pruning off). Each boot logs one line naming the mode that
19
+ ran. The helpers are exported from `@_linked/server/utils/syncShapes`.
20
+
21
+ ## 2.14.3
22
+
23
+ ### Patch Changes
24
+
25
+ - [#113](https://github.com/linked-fw/server/pull/113) [`add9285`](https://github.com/linked-fw/server/commit/add928543ce3b0d68319384490b46527b8878e14) Thanks [@flyon](https://github.com/flyon)! - Add `shapes/index`, a side-effect-only module that registers every shape this package defines, and have the package entry import it instead of listing shapes one by one. Hosts and consumers can now load `@_linked/server/shapes/index` to get the package's full shape set registered without pulling in anything else, and a shape added later is picked up by the entry automatically.
26
+
3
27
  ## 2.14.2
4
28
 
5
29
  ### Patch Changes
@@ -1,9 +1,7 @@
1
1
  import './types.js';
2
2
  import './ontologies/lincd-server.register.js';
3
- import './shapes/LinkedServer.js';
4
- import './shapes/LincdAPI.js';
3
+ import './shapes/index.js';
5
4
  import './shapes/quadstores/BackendAPIStore.js';
6
5
  import './shapes/filestores/LocalFileStore.js';
7
- import './shapes/LincdWebApp.js';
8
6
  import './utils/accessUrl.js';
9
7
  export type { RouteConfig, RoutesConfig, RoutesModule, } from '@_linked/server-utils/types/RouteConfig';
package/lib/esm/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import './types.js';
2
2
  import './ontologies/lincd-server.register.js';
3
3
  //SHAPES FIRST
4
- import './shapes/LinkedServer.js';
5
- import './shapes/LincdAPI.js';
4
+ import './shapes/index.js';
5
+ // Not shapes (plain store classes); kept so the entry's module graph is unchanged.
6
6
  import './shapes/quadstores/BackendAPIStore.js';
7
7
  import './shapes/filestores/LocalFileStore.js';
8
- import './shapes/LincdWebApp.js';
9
8
  //THEN COMPONENTS
10
9
  import './utils/accessUrl.js';
11
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,CAAC;AACpB,OAAO,uCAAuC,CAAC;AAE/C,cAAc;AACd,OAAO,0BAA0B,CAAC;AAClC,OAAO,sBAAsB,CAAC;AAC9B,OAAO,wCAAwC,CAAC;AAChD,OAAO,uCAAuC,CAAC;AAC/C,OAAO,yBAAyB,CAAC;AAEjC,iBAAiB;AACjB,OAAO,sBAAsB,CAAC","sourcesContent":["import './types.js';\nimport './ontologies/lincd-server.register.js';\n\n//SHAPES FIRST\nimport './shapes/LinkedServer.js';\nimport './shapes/LincdAPI.js';\nimport './shapes/quadstores/BackendAPIStore.js';\nimport './shapes/filestores/LocalFileStore.js';\nimport './shapes/LincdWebApp.js';\n\n//THEN COMPONENTS\nimport './utils/accessUrl.js';\n\n//TYPES — re-exported from @_linked/server-utils (canonical location)\nexport type {\n RouteConfig,\n RoutesConfig,\n RoutesModule,\n} from '@_linked/server-utils/types/RouteConfig';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,CAAC;AACpB,OAAO,uCAAuC,CAAC;AAE/C,cAAc;AACd,OAAO,mBAAmB,CAAC;AAC3B,mFAAmF;AACnF,OAAO,wCAAwC,CAAC;AAChD,OAAO,uCAAuC,CAAC;AAE/C,iBAAiB;AACjB,OAAO,sBAAsB,CAAC","sourcesContent":["import './types.js';\nimport './ontologies/lincd-server.register.js';\n\n//SHAPES FIRST\nimport './shapes/index.js';\n// Not shapes (plain store classes); kept so the entry's module graph is unchanged.\nimport './shapes/quadstores/BackendAPIStore.js';\nimport './shapes/filestores/LocalFileStore.js';\n\n//THEN COMPONENTS\nimport './utils/accessUrl.js';\n\n//TYPES — re-exported from @_linked/server-utils (canonical location)\nexport type {\n RouteConfig,\n RoutesConfig,\n RoutesModule,\n} from '@_linked/server-utils/types/RouteConfig';\n"]}
@@ -54,15 +54,18 @@ export declare class LinkedServer extends Shape {
54
54
  * Materialize this server's registered shapes into the RDF store as SHACL
55
55
  * (core `syncShapes` → pure `sh:NodeShape` + property shapes), so a running
56
56
  * app's app-data holds the shapes its instances validate/query against
57
- * (plan-010 T1e.2). This is the canonical, uniform reuse+create mechanism:
58
- * whatever shapes the app package registers (published re-exports + generated)
59
- * get materialized on boot (and re-run on shape-file HMR).
57
+ * (plan-010 T1e.2). Whatever shapes the app package registers (published
58
+ * re-exports + generated) get written on boot (and re-run on shape-file HMR).
59
+ *
60
+ * Additive only: store shapes this process did not register are left alone
61
+ * unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true` — see
62
+ * `bootOrphanScope` in utils/syncShapes for why.
60
63
  *
61
64
  * Gated to servers whose DEFAULT dataset is a **concrete** materializable store
62
65
  * (detected via `rawQuery`) — i.e. an app pointing at its app-data FusekiStore.
63
- * CN's default is the context-routing `AppDataRouter` (no `rawQuery`; a bare
64
- * `syncShapes` orphan-read would throw with no active project), so CN is skipped
65
- * here — it materializes its own pinned native shapes in its storage config.
66
+ * CN's default is the context-routing `AppDataRouter` (no `rawQuery`), so CN is
67
+ * skipped here — it materializes its own pinned native shapes in its storage
68
+ * config.
66
69
  */
67
70
  private materializeShapesIntoStore;
68
71
  start(): Promise<this>;
@@ -51,6 +51,7 @@ import { resolveBootstrapEntry, resolveViteMainEntry, resolveViteServingMode, }
51
51
  import { resolveRouteAssets } from '../utils/routeAssets.js';
52
52
  import { resolveRouteComponent, ssrCssInlineUrls, ssrCssScope, } from '../utils/ssrCss.js';
53
53
  import { indexShapesIntoMemory } from '../utils/Shapes.js';
54
+ import { materializeShapes } from '../utils/syncShapes.js';
54
55
  import { installSpaFallback, repinSpaFallback, } from '../utils/spaFallback.js';
55
56
  import { LincdAPI } from './LincdAPI.js';
56
57
  //prevent errors in node.js when (s)css files are imported in js
@@ -193,15 +194,18 @@ let LinkedServer = class LinkedServer extends Shape {
193
194
  * Materialize this server's registered shapes into the RDF store as SHACL
194
195
  * (core `syncShapes` → pure `sh:NodeShape` + property shapes), so a running
195
196
  * app's app-data holds the shapes its instances validate/query against
196
- * (plan-010 T1e.2). This is the canonical, uniform reuse+create mechanism:
197
- * whatever shapes the app package registers (published re-exports + generated)
198
- * get materialized on boot (and re-run on shape-file HMR).
197
+ * (plan-010 T1e.2). Whatever shapes the app package registers (published
198
+ * re-exports + generated) get written on boot (and re-run on shape-file HMR).
199
+ *
200
+ * Additive only: store shapes this process did not register are left alone
201
+ * unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true` — see
202
+ * `bootOrphanScope` in utils/syncShapes for why.
199
203
  *
200
204
  * Gated to servers whose DEFAULT dataset is a **concrete** materializable store
201
205
  * (detected via `rawQuery`) — i.e. an app pointing at its app-data FusekiStore.
202
- * CN's default is the context-routing `AppDataRouter` (no `rawQuery`; a bare
203
- * `syncShapes` orphan-read would throw with no active project), so CN is skipped
204
- * here — it materializes its own pinned native shapes in its storage config.
206
+ * CN's default is the context-routing `AppDataRouter` (no `rawQuery`), so CN is
207
+ * skipped here — it materializes its own pinned native shapes in its storage
208
+ * config.
205
209
  */
206
210
  async materializeShapesIntoStore() {
207
211
  var _a;
@@ -221,16 +225,8 @@ let LinkedServer = class LinkedServer extends Shape {
221
225
  try {
222
226
  const { syncShapes } = await import('@_linked/core');
223
227
  // Explicit target: materialize EVERY registered shape into the app's own
224
- // data store regardless of per-shape routing/pins — syncShapes(ds) threads
225
- // ds through the orphan-read + every delete→recreate. (No reliance on
226
- // "whatever the default resolves to per shape".)
227
- const thunks = await syncShapes(appData);
228
- // Batched (not all-at-once) so we don't overwhelm Fuseki — the API hands
229
- // back unexecuted thunks precisely so the caller paces them.
230
- for (let i = 0; i < thunks.length; i += 8) {
231
- await Promise.all(thunks.slice(i, i + 8).map((run) => run()));
232
- }
233
- console.log(`[LinkedServer] materialized ${thunks.length} shape(s) into app-data`);
228
+ // data store regardless of per-shape routing/pins.
229
+ await materializeShapes(appData, syncShapes);
234
230
  }
235
231
  catch (err) {
236
232
  console.warn('[LinkedServer] shape materialization failed (non-fatal):', err);
@@ -1 +1 @@
1
- {"version":3,"file":"LinkedServer.js","sourceRoot":"","sources":["../../../src/shapes/LinkedServer.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AACb,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAqC,MAAM,SAAS,CAAC;AAC5D,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,QAAQ,MAAM,IAAI,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAElC,oEAAoE;AACpE,oEAAoE;AACpE,oEAAoE;AACpE,0BAA0B;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cA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C;YACF,MAAM,IAAI,eAAe,CAAC,GAAG,EAAE,mBAAmB,GAAG,IAAI,MAAM,EAAE,CAAC,CAAC;QACrE,CAAC;QAED,IAAI,CAAC;YACH,4BAA4B;YAC5B,sEAAsE;YACtE,wJAAwJ;YACxJ,+DAA+D;YAC/D,IAAI,OAAO,IAAI,QAAQ,EAAE,CAAC;gBACxB,mDAAmD;gBACnD,oFAAoF;gBACpF,MAAM,OAAO,CAAC,OAAO,CACnB,sBAAsB,CAAC,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CACtD,CAAC;YACJ,CAAC;YACD,sBAAsB;YACtB,uBAAuB;YAEvB,wEAAwE;YACxE,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAC5B,sBAAsB,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,sBAAsB,EAAE,IAAI,CAAC,CACnE,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,IAAI,CACV,wBAAwB,MAAM,kBAC5B,MAAM,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC,WAAW,CAAC,IAC5D,eAAe,GAAG,KAAK,EACvB,CAAC,CACF,CAAC;YAEF,gBAAgB;YAChB,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YAC1B,gFAAgF;YAChF,MAAM,CAAC,CAAC;QACV,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;;AA79DD;;GAEG;AACI,wBAAW,GAAG,WAAW,CAAC,WAAW,AAA1B,CAA2B;AAJlC,YAAY;IADxB,WAAW,CAAC,EAAC,IAAI,EAAE,cAAc,EAAC,CAAC;;GACvB,YAAY,CA+9DxB","sourcesContent":["'use strict';\nimport chalk from 'chalk';\nimport { timingSafeEqual } from 'crypto';\nimport events from 'events';\nimport express, { Express as ExpressServer } from 'express';\nimport fetchCookie from 'fetch-cookie';\nimport * as fsNative from 'fs';\nimport * as fs from 'fs/promises';\nimport { Server as HttpServer } from 'http';\n// Plan-011: imports from @_linked/cli now go through ./lifecycle (a\n// dynamic-import-free file) so Vite's SSR module graph doesn't pull\n// in the legacy webpack flow and emit dozens of unanalyzable-import\n// warnings on every boot.\nimport { getLincdPackages } from '@_linked/cli/lifecycle';\nimport { getPackageJSON } from '@_linked/cli/utils';\nimport type { LinkedConfig } from '@_linked/cli/interfaces';\nimport { AppContextProvider } from '@_linked/server-utils/components/AppContext';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { JSONParser } from '@_linked/server-utils/utils/JSONParser';\nimport { JSONWriter } from '@_linked/server-utils/utils/JSONWriter';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport { ServerCallError } from '@_linked/server-utils/utils/ServerCallError';\nimport { ShapeProvider } from '@_linked/server-utils/utils/ShapeProvider';\nimport { Shape } from '@_linked/core/shapes/Shape';\nimport { LinkedErrorLogging } from '@_linked/core/utils/LinkedErrorLogging';\nimport {\n FileStorePurposes,\n LinkedFileStorage,\n} from '@_linked/core/utils/LinkedFileStorage';\nimport type { IFileStore } from '@_linked/core/interfaces/IFileStore';\nimport { getResizedImagesStore } from '../utils/resizedImagesPurpose.js';\nimport { LinkedStorage } from '@_linked/core/utils/LinkedStorage';\nimport { autoLoadOntologyData } from '@_linked/core/utils/Package';\nimport {\n getShapeClass,\n getSuperShapesClasses,\n} from '@_linked/core/utils/ShapeClass';\nimport path from 'path';\nimport {pathToFileURL} from 'node:url';\nimport process from 'process';\nimport * as React from 'react';\nimport { renderToPipeableStream, renderToStaticMarkup } from 'react-dom/server';\nimport { StaticRouter } from 'react-router-dom/server.js';\nimport { rimraf } from 'rimraf';\nimport sharp from 'sharp';\nimport {\n findStoredKey,\n resolveResizeSource,\n} from '../utils/resizeSource.js';\nimport { Transform } from 'stream';\nimport { CookieJar } from 'tough-cookie';\nimport { lincdServer } from '../ontologies/lincd-server.js';\nimport { linkedShape } from '../package.js';\nimport {\n resolveStaticAccessURL,\n staticAssetURL,\n} from '../utils/releaseManifest.js';\nimport {\n resolveBootstrapEntry,\n resolveViteMainEntry,\n resolveViteServingMode,\n} from '../utils/bootstrapEntry.js';\nimport { resolveRouteAssets } from '../utils/routeAssets.js';\nimport {\n resolveRouteComponent,\n ssrCssInlineUrls,\n ssrCssScope,\n} from '../utils/ssrCss.js';\nimport { indexShapesIntoMemory } from '../utils/Shapes.js';\nimport {\n installSpaFallback,\n repinSpaFallback,\n} from '../utils/spaFallback.js';\nimport { LincdAPI } from './LincdAPI.js';\nimport type { RoutesConfig, RouteConfig } from '../types/RouteConfig.js';\n\n//prevent errors in node.js when (s)css files are imported in js\nconst isProduction = process.env.NODE_ENV === 'production';\nconst isDevelopment = process.env.NODE_ENV === 'development';\n\ndeclare var globalThis: any;\n// Install a global fetch that persists cookies across redirects using a CookieJar.\n// This ensures server-side requests behave more like browsers when handling Set-Cookie + redirects.\nconst __lincdCookieJar = new CookieJar();\n// Wrap native fetch with fetch-cookie so it reads/writes cookies in the jar.\nconst __lincdFetchWithCookies = fetchCookie(fetch, __lincdCookieJar);\n\n// Expose (optionally) for debugging/tests; not required by app logic.\n(globalThis as any).__lincdCookieJar = __lincdCookieJar;\n\n// Set the global fetch used throughout the server code path\n(globalThis as any).fetch = __lincdFetchWithCookies;\n\nprocess.on('uncaughtException', (err) => {\n console.warn(chalk.red('Asynchronous error caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err);\n});\nprocess.on('unhandledRejection', (err) => {\n console.warn(chalk.red('Unhandled rejection caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err as Error);\n});\n\nprocess.on('warning', (e) => console.warn(e.stack));\n\n//allow more listeners for when we have many concurrent users\nevents.EventEmitter.prototype.setMaxListeners(500);\n\n// const jsdom = require(\"jsdom\");\n// const { JSDOM } = jsdom;\n// const { document } = (new JSDOM(`...`)).window;\n//\n// global['document'] = document;\nglobal['reactStaticRenderer'] = renderToStaticMarkup;\n\nautoLoadOntologyData(true);\n\n// Named explicitly: tsc emits `let X = class X`, and any later esbuild pass over that JS (Vite's\n// SSR `define` replacement runs one on every file mentioning a defined `process.env.*`) renames\n// the inner binding to `X2`, which would otherwise become this shape's IRI.\n@linkedShape({name: 'LinkedServer'})\nexport class LinkedServer extends Shape {\n /**\n * indicates that instances of this shape need to have this rdf.type\n */\n static targetClass = lincdServer.LincdServer;\n private config: LinkedConfig;\n private cachedPaths: Map<string, string> = new Map();\n private assets: { [key: string]: string } & {\n manifest?: Record<string, string>;\n };\n /**\n * Whether pages are served by the live Vite dev server rather than a\n * `vite build` on disk. Decided once in `start()` — see\n * utils/bootstrapEntry `resolveViteServingMode`.\n */\n private viteDevServer = false;\n /**\n * Base URL every asset this build produced is served from — resolved once in\n * `start()` and kept so per-request route chunks land on the same base as\n * the entry tags. Empty means origin-relative (development, and any app\n * serving its own bundles).\n */\n private staticAccessURL: string = '';\n /**\n * Whether `assets['main.js']` came from a Vite build. Vite always emits the\n * entry as an ES module, so it has to be bootstrapped with\n * `bootstrapModules`; a legacy webpack bundle is a classic script and must\n * keep `bootstrapScripts`.\n */\n private mainEntryIsModule = false;\n protected server: ExpressServer;\n protected httpServer: HttpServer;\n private package: any;\n private cacheWebpack: boolean;\n private cssMode = 'scss-modules';\n private analyse: boolean = false;\n private shapeProviders: Map<string, ShapeProvider[]> = new Map();\n private genericProviders: Map<string, BackendProvider> = new Map();\n //from resizedFileName to full resized path (CDN or similar)\n private resizePathsMap: Map<string, string> = new Map();\n private api: LincdAPI;\n\n /**\n * yarn linked start sends the contents of linked.config.js as an object to this constructor\n * @param n\n */\n constructor(config?: LinkedConfig | string | { id?: string }) {\n super(\n typeof config === 'string' || (config && 'id' in config)\n ? config\n : undefined\n );\n if (config && typeof config !== 'string' && !('id' in config)) {\n // The absence of `id` is the runtime discriminator for a LinkedConfig;\n // the widened `{id?: string}` member of the union keeps TS from narrowing\n // to it on that check alone.\n this.config = config as LinkedConfig;\n }\n\n this.api = new LincdAPI({ id: process.env.SITE_ROOT + '/api' });\n\n //Ensure the Server utility (for Server.call()) directly accesses\n // this server on the backend instead of going through a network call\n Server.setLocalServer(this);\n }\n\n /*async getLincdDependencies(): Promise<string[]> {\n\t\tlet lincdDependencies = [];\n\t\tlet dependencies = this.package.dependencies;\n\n\t\tawait Promise.all(\n\t\t\tObject.keys(dependencies).map((dependencyPkgName) => {\n\t\t\t\tlet modulePackageJson = getModulePackageJSON(dependencyPkgName);\n\t\t\t\tif (modulePackageJson['lincd']) {\n\t\t\t\t\tlincdDependencies.push(modulePackageJson.name);\n\t\t\t\t}\n\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\n\t\t\t\t// let packagePath;\n\t\t\t\t// try {\n\t\t\t\t// packagePath = require.resolve(`${dependencyPkgName}`);\n\t\t\t\t// } catch (err) {\n\t\t\t\t// console.warn('Could not find package ' + dependencyPkgName+'. Error: '+err.toString());\n\t\t\t\t// return;\n\t\t\t\t// }\n\t\t\t\t// packagePath = path.dirname(packagePath) + '/package.json'\n\t\t\t\t// return fs\n\t\t\t\t// .readFile(packagePath, 'utf-8')\n\t\t\t\t// .then((res) => {\n\t\t\t\t// let pkg = JSON.parse(res);\n\t\t\t\t// if (pkg['lincd']) {\n\t\t\t\t// lincdDependencies.push(pkg.name);\n\t\t\t\t// }\n\t\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\t\t\t\t\t// })\n\t\t\t\t\t// .catch((err) => {\n\t\t\t\t\t// console.log('Could not read package.json file: '+err);\n\t\t\t\t\t// });\n\t\t\t}),\n\t\t);\n\t\treturn lincdDependencies;\n\t}*/\n get app() {\n return this.server;\n }\n\n initPackage() {\n this.package = JSON.parse(\n fsNative.readFileSync(\n path.resolve(process.cwd(), 'package.json'),\n 'utf-8'\n )\n );\n }\n async initOnly() {\n await this.initOntologies();\n await this.initStores();\n\n this.initPackage();\n\n this.server = express();\n\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n return this;\n }\n\n /**\n * Materialize this server's registered shapes into the RDF store as SHACL\n * (core `syncShapes` → pure `sh:NodeShape` + property shapes), so a running\n * app's app-data holds the shapes its instances validate/query against\n * (plan-010 T1e.2). This is the canonical, uniform reuse+create mechanism:\n * whatever shapes the app package registers (published re-exports + generated)\n * get materialized on boot (and re-run on shape-file HMR).\n *\n * Gated to servers whose DEFAULT dataset is a **concrete** materializable store\n * (detected via `rawQuery`) — i.e. an app pointing at its app-data FusekiStore.\n * CN's default is the context-routing `AppDataRouter` (no `rawQuery`; a bare\n * `syncShapes` orphan-read would throw with no active project), so CN is skipped\n * here — it materializes its own pinned native shapes in its storage config.\n */\n private async materializeShapesIntoStore(): Promise<void> {\n // Opt-out via `linked.config` `syncShapesOnBoot` (default true); env\n // LINKED_SYNC_SHAPES_ON_BOOT overrides for deployment. CN sets\n // `syncShapesOnBoot: false` in its own linked.config — its default dataset is\n // a context-router that can't materialize context-free, and it syncs its own\n // pinned shapes separately (linked.backend.storage.js).\n const configFlag = (this.config as any)?.syncShapesOnBoot;\n const envFlag = process.env.LINKED_SYNC_SHAPES_ON_BOOT;\n if (configFlag === false || envFlag === 'false') {\n return;\n }\n const appData = LinkedStorage.getDefaultDataset();\n if (!appData) return;\n try {\n const {syncShapes} = await import('@_linked/core');\n // Explicit target: materialize EVERY registered shape into the app's own\n // data store regardless of per-shape routing/pins — syncShapes(ds) threads\n // ds through the orphan-read + every delete→recreate. (No reliance on\n // \"whatever the default resolves to per shape\".)\n const thunks = await syncShapes(appData as any);\n // Batched (not all-at-once) so we don't overwhelm Fuseki — the API hands\n // back unexecuted thunks precisely so the caller paces them.\n for (let i = 0; i < thunks.length; i += 8) {\n await Promise.all(thunks.slice(i, i + 8).map((run) => run()));\n }\n console.log(\n `[LinkedServer] materialized ${thunks.length} shape(s) into app-data`,\n );\n } catch (err) {\n console.warn('[LinkedServer] shape materialization failed (non-fatal):', err);\n }\n }\n\n // async serveData(req,res) {\n // let nodeURI = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n //\n // let store = LinkedStorage.getDatasets().find(store => {\n // return nodeURI.includes(store.namedNode.uri)\n // })\n // }\n\n async start() {\n this.initPackage();\n // Static assets should come from the static store URL (versioned path),\n // not the upload store URL. An explicit STATIC_ACCESS_URL still wins;\n // otherwise the release manifest `linked build-app` wrote next to the\n // bundle says which published release this build is, so a deployment no\n // longer has to repeat that URL by hand. See utils/releaseManifest.\n // In development we deliberately use a relative path so bundle URLs work\n // regardless of which PORT the dev server bound to (browsers resolve\n // relative URLs against window.location.origin). Hardcoding SITE_ROOT\n // baked :4000 into every SSR'd HTML page.\n const isDevAssets = process.env.NODE_ENV === 'development';\n const staticAccessURL = resolveStaticAccessURL({\n isDevAssets,\n appRoot: process.cwd(),\n fileStoreAccessURL: LinkedFileStorage.accessURL,\n });\n this.staticAccessURL = staticAccessURL;\n const staticAsset = (assetPath: string) =>\n staticAssetURL(staticAccessURL, assetPath);\n\n // Bundle/manifest read (plan-011: Vite is the only supported build).\n // Vite manifest lives at public/bundles/.vite/manifest.json.\n this.assets = {\n 'main.js':\n staticAsset('/bundles/main.bundle.js') + '?v=' + this.package.version,\n 'main.css': staticAsset('/bundles/main.css'),\n };\n // Dev or built, decided once and reused by the render path — see\n // utils/bootstrapEntry. In development the build manifest is not read:\n // one left on disk by an earlier `vite build` would otherwise swap in\n // stale built CSS while Vite serves the live styles.\n const servingMode = resolveViteServingMode({\n viteConfig: (this.config.server as any)?.vite,\n nodeEnv: process.env.NODE_ENV,\n readManifest: () => {\n try {\n const viteManifestPath = path.resolve(\n process.cwd(),\n 'public/bundles/.vite/manifest.json'\n );\n if (!fsNative.existsSync(viteManifestPath)) return null;\n return JSON.parse(fsNative.readFileSync(viteManifestPath, 'utf-8'));\n } catch (err) {\n console.warn('Could not load bundle manifest:', err);\n return null;\n }\n },\n });\n this.viteDevServer = servingMode.viteDevServer;\n if (servingMode.manifest) {\n const viteManifest = servingMode.manifest as Record<string, any>;\n this.assets.manifest = viteManifest;\n // Resolve main entry per Vite manifest shape:\n // { \"src/index.tsx\": { file: \"assets/main-<hash>.js\", css: [...] } }\n const mainEntry = resolveViteMainEntry(viteManifest);\n if (mainEntry?.file) {\n this.assets['main.js'] = staticAsset(`/bundles/${mainEntry.file}`);\n this.mainEntryIsModule = true;\n }\n if (mainEntry?.css?.[0]) {\n this.assets['main.css'] = staticAsset(`/bundles/${mainEntry.css[0]}`);\n }\n }\n // Vite dev marker: the HTML renderer skips pre-built CSS/JS link tags,\n // because Vite handles asset injection itself.\n if (this.viteDevServer) {\n this.assets['__viteDev'] = '1';\n }\n\n const isProduction = process.env.NODE_ENV === 'production';\n if (!isProduction && this.config.cssMode === 'tailwind') {\n this.assets['tailwind-cdn'] = 'https://cdn.tailwindcss.com';\n }\n\n //for multicore we use PM2, and each instance needs to listen to port 0.\n // whilst the main thread will listen to env.PORT automatically\n // const PORT = this.config.multiCore ? 0 : process.env.PORT || 3000;\n // const publicPort = process.env.PORT || 3000;\n //update: back to original setup. multicore handles itself inside @semantu/multicore\n const PORT = parseInt(process.env.PORT) || 4000;\n this.server = express();\n\n const dirName = path.resolve(process.cwd(), 'frontend');\n\n await this.initOntologies();\n //TODO: when we do not keep all data in memory (and thus do not need to rely on in memory data for page requests), we can possibly remove await here, since all stores handle their own initialisation before executing commands\n await this.initStores();\n\n this.initGarbageCollection();\n // this.app.use((req, res, next) => {\n // console.log('start request');\n // next();\n // });\n // before controllers\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n\n //START OF EXPRESS ROUTES AND MIDDLEWARE\n\n //use cors\n // var corsOptions = {\n // origin: ['http://localhost:4001', 'https://www.mynd.site'],\n // optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204\n // };\n // //accept JSON bodies\n // this.server.use(bodyParser.json({limit: '50mb'}));\n this.server.use(express.json({ limit: '50mb' }));\n\n // this.server.use(cors(corsOptions));\n //\n // //compress server output with gzip,\n //UPDATE ive set level to 2 (low compression fast speed) because responses were taking too long (98% of server time was used by compress)\n // this.server.use(compress({level: 2}));\n\n await this.callGenericBackendProvidersMethod('setupBeforeControllers');\n\n // Vite middleware (plan 010): when the user app starts via Vite\n // (`linked start --vite`), the orchestrator passes the Vite handle\n // through config.server.viteMiddleware. We mount it and skip the\n // entire webpack-dev-middleware setup below.\n const viteMiddleware = (this.config.server as any)?.viteMiddleware;\n if (viteMiddleware) {\n this.server.use(viteMiddleware);\n }\n\n // Plan-011: legacy webpack-dev-middleware branch removed. Under Vite\n // (the only supported dev path now) `viteMiddleware` is set, which\n // previously forced `skipBuild = true` and made this whole block\n // dead. Removing it ends the static dependency on @_linked/cli/\n // config-webpack-app (full of dynamic imports Vite couldn't analyze)\n // and shrinks LinkedServer's import surface considerably.\n\n // //map URL routes to file paths\n const oneYear = 1000 * 60 * 60 * 24 * 365; // in milliseconds\n const oneMonth = 1000 * 60 * 60 * 24 * 30; // in milliseconds\n this.server.use(\n '/public',\n express.static('./public', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n\n this.server.use(\n '/uploads',\n express.static('./data/uploads', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/', express.static('./public/root'));\n this.server.use(\n '/favicon.ico',\n express.static('./public/favicon.ico', {\n maxAge: oneMonth, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/.well-known', express.static('./public/.well-known'));\n\n // this.server.post('/data',this.handleErrorsJson(async (req,res) => this.serveData(req, res)));\n this.server.get('/resized/*', async (req, res) => {\n this.resizeImage(req, res);\n });\n\n // Scoped-package variants (@scope/pkg). Register BEFORE the unscoped\n // routes — Express `:pkg` won't consume slashes, so a call to\n // `/call/@_linked/auth/signinDev` would otherwise fall through to the\n // 3-segment `:pkg/:shape/:method` route and be misinterpreted as a\n // shape-method call (pkg=`@_linked`, shape=`auth`). These handlers\n // recognise the `@scope/pkg` prefix and rebuild the full package name\n // before dispatching to the same handler used for unscoped packages.\n this.server.post(\n '/call/@:scope/:pkg/:method',\n this.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return this.processBackendMethodCall(req, res);\n })\n );\n this.server.post(\n '/call/@:scope/:pkg/:shape/:method',\n this.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return this.processShapeMethodCall(req, res);\n })\n );\n this.server.post(\n '/call/:pkg/:method',\n this.handleErrorsJson(async (req, res) =>\n this.processBackendMethodCall(req, res)\n )\n );\n this.server.post(\n '/call/:pkg/:shape/:method',\n this.handleErrorsJson(async (req, res) =>\n this.processShapeMethodCall(req, res)\n )\n );\n this.server.post(\n '/api/:method/:action?',\n this.handleErrorsJson(async (req, res) =>\n this.processAPICall(req, res, 'post')\n )\n );\n this.server.get(\n '/api/:method/:action?',\n this.handleErrorsJson(async (req, res) =>\n this.processAPICall(req, res, 'get')\n )\n );\n // this.server.post(\n // '/api/query/:method',\n // this.handleErrorsJson(async (req, res) => this.processQuery(req, res)),\n // );\n\n // now that all the middleware is defined, we initialise the providers, before we define a catch-all route\n // before catch all\n // await this.initBackendProviders();\n await this.callGenericBackendProvidersMethod(\n 'setupBeforeCatchAllControllers'\n );\n\n // HEAD catch-all for maintenance/health check (client fetches SITE_ROOT with method: HEAD)\n this.server.head('__health', (_req, res) => {\n res.sendStatus(200);\n });\n\n // CN control channel (plan-010 T1b.3). Present only when CN spawned this\n // process with a shared secret (CN_APP_ADMIN_SECRET); a standalone app run\n // without the secret leaves the channel closed (404). Auth is the\n // x-cn-admin-secret header matching that env value.\n const adminSecret = process.env.CN_APP_ADMIN_SECRET;\n // Constant-time compare so the secret can't be recovered by timing the 401\n // response. timingSafeEqual requires equal-length buffers, so guard length.\n const secretMatches = (provided: string | undefined): boolean => {\n if (!adminSecret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(adminSecret);\n return a.length === b.length && timingSafeEqual(a, b);\n };\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!adminSecret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!secretMatches(req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n this.server.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n this.server.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n // CN's provisioner respawns on exit (see ChildProcessProvisioner).\n setTimeout(() => process.exit(0), 50);\n });\n\n // after controller\n await this.callGenericBackendProvidersMethod('setupAfterControllers');\n\n // The SPA catch-all goes on LAST. `setupAfterControllers` is a documented\n // hook for providers to register their own routes, so installing the\n // catch-all before it would shadow every GET route registered there —\n // answering them with the client shell at status 200.\n // An API-only backend (`linked start --api-only`) has no app to render:\n // without the catch-all, page requests get express's plain 404.\n if (!(this.config.server as any)?.apiOnly) {\n this.installSpaFallback();\n }\n\n //remove http(s):// and remove port :[port]\n const HOST = process.env.SITE_ROOT.replace(/https?:\\/\\//, '').replace(\n /:\\d+$/,\n ''\n );\n\n //backlog of 1024 means maximum of 1024 connections in the queue (higher than default)\n this.httpServer = this.server.listen({ port: PORT, backlog: 1024 }, () => {\n console.log(`Up and running at http://localhost:${PORT}`);\n // open(`http://localhost:${PORT}`)\n });\n // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n this.httpServer.keepAliveTimeout = 60_000;\n // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363\n this.httpServer.headersTimeout = 61_000;\n\n this.httpServer.on('error', function (error) {\n if (error['syscall'] !== 'listen') {\n throw error;\n }\n const isPipe = (portOrPipe) => Number.isNaN(portOrPipe);\n const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;\n switch (error['code']) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n default:\n throw error;\n }\n });\n return this;\n }\n\n async initOntologies() {}\n\n /**\n *\n * @returns\n * @todo Check if default file store is set, if not, set it\n */\n async initStores() {\n return Promise.all(\n LinkedStorage.getDatasets().map((store) => {\n return store.init ? store.init() : Promise.resolve();\n })\n );\n }\n\n // get generic backend providers for handle controller methods\n async callGenericBackendProvidersMethod(method: string, ...args: any[]) {\n for (let genericProvider of this.genericProviders.values()) {\n if (!genericProvider || !genericProvider[method]) {\n continue;\n }\n if (typeof genericProvider[method] == 'function') {\n await Promise.resolve(genericProvider[method](...args));\n }\n }\n }\n\n /**\n * Removes temporary nodes from memory if they've been seen twice\n * Current interval is once per hour.\n * So after 2 hours temporary nodes are removed.\n */\n initGarbageCollection() {\n // let seenLastTime:NodeSet<NamedNode> = null;\n // setInterval(() => {\n //\n // let tempNodes = new NodeSet<NamedNode>();\n // NamedNode.getAllNamedNodes().forEach(n => {\n // if(n.isTemporaryNode) {\n // if(seenLastTime && seenLastTime.has(n))\n // {\n // n.remove();\n // } else {\n // tempNodes.add(n);\n // }\n // }\n // })\n // seenLastTime = tempNodes;\n // }, 1000 * 10); //every 10 sec\n // // }, 1000 * 60 * 60); //every hour\n }\n async initBackendProviders() {\n //get all local workspace lincd packages, then filter to only those\n //in this app's dependency tree. This avoids loading npm-installed\n //legacy packages that may use an old version of the core.\n const allLocalPackages = getLincdPackages();\n const localPackageMap = new Map<\n string,\n { packageName: string; path: string }\n >(allLocalPackages.map((pkg) => [pkg.packageName, pkg]));\n const relevantPackages = this.filterPackagesByDependencyTree(\n localPackageMap,\n this.package\n );\n for (let [pkgName, pkg] of relevantPackages) {\n await this.indexPackageBackendProviders(pkgName);\n await this.indexLincdPackage(pkgName);\n }\n\n try {\n await fs\n .readFile(path.join(process.cwd(), 'package.json'), 'utf-8')\n .then(async (contents) => {\n let pkg = JSON.parse(contents);\n // Route through default ${pkg}/backend resolution. The app's\n // package.json `exports`./backend field handles dev vs prod:\n // \"exports\": {\n // \"./backend\": {\n // \"development\": \"./src/backend.ts\",\n // \"default\": \"./lib/esm/backend.js\"\n // }\n // }\n // Removed plan-010 D10: the source-direct\n // path.join(cwd, 'src', 'backend.ts') override that forced TS\n // runtime loading. Vite SSR's ssrLoadModule handles the\n // transform; production runs from lib/esm/.\n await this.indexPackageBackendProviders(pkg.name, false);\n });\n } catch (err) {\n console.warn(err);\n }\n }\n\n /**\n * Filters local workspace packages to only those reachable from the app's\n * dependency tree. Mirrors the logic used by `buildAll` in lincd-cli.\n */\n private filterPackagesByDependencyTree(\n allPackages: Map<string, { packageName: string; path: string }>,\n appPackageJson: any\n ): Map<string, { packageName: string; path: string }> {\n const relevantPackages = new Map<\n string,\n { packageName: string; path: string }\n >();\n const packagesToCheck = new Set<string>();\n const processedPackages = new Set<string>();\n\n // Start with direct dependencies from the app\n if (appPackageJson.dependencies) {\n for (const dep of Object.keys(appPackageJson.dependencies)) {\n if (allPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n\n // Recursively follow each package's dependencies\n while (packagesToCheck.size > 0) {\n const packageName = packagesToCheck.values().next().value;\n packagesToCheck.delete(packageName);\n if (processedPackages.has(packageName)) {\n continue;\n }\n processedPackages.add(packageName);\n const packageDetails = allPackages.get(packageName);\n if (packageDetails) {\n relevantPackages.set(packageName, packageDetails);\n const pkg = getPackageJSON(packageDetails.path);\n if (pkg?.dependencies) {\n for (const dep of Object.keys(pkg.dependencies)) {\n if (allPackages.has(dep) && !processedPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n }\n }\n\n return relevantPackages;\n }\n\n async resizeImage(req, res) {\n //check if the w or h query parameters are set\n let width = req.query.w;\n let height = req.query.h;\n //if not\n if (!width && !height) {\n //redirect to the original image\n res.redirect(req.originalUrl.replace('/resized', '/uploads'));\n return;\n }\n\n let imageFileName = req.query.src; // example: https://cdnurl.com/uploads/1710814765388-935b511c9_cropped.jpeg\n const accessURL = LinkedFileStorage.accessURL;\n\n if (imageFileName) {\n // `src` may only name an image this app already stores. Before this check\n // the value went straight to fetch(), which made the route an open proxy\n // into its own network -- cloud metadata, localhost, private ranges -- and\n // the response was then written into the PUBLIC file store and the caller\n // redirected to it, so anything reachable was persisted, not just leaked.\n //\n // resolveResizeSource compares parsed origins (a startsWith check is\n // defeated by https://cdn.example.com.evil.com) and hands back the key,\n // which must also exist in the store before anything is requested.\n const source = resolveResizeSource(imageFileName, accessURL);\n\n if (!source.allowed) {\n res.status(400).send({ error: 'Unsupported image source' });\n return;\n }\n\n // Two candidates, because the stores disagree on whether the public URL\n // includes the upload mount -- see resolveResizeSource. Fail-closed: if\n // neither shape is held, nothing is fetched.\n const storedKey = await findStoredKey(source.keys, (key) =>\n LinkedFileStorage.fileExists(key)\n );\n\n if (!storedKey) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // extract the base name and extension from the key the store actually\n // holds, not from the URL path.\n //\n // These differ: LocalFileStore serves `accessURL + /uploads/ + key`, so\n // deriving the destination from the URL gave it an extra `uploads/`\n // segment and resized files landed in data/uploads/uploads/resized/.\n // S3FileStore serves the key directly, so for it the two are the same --\n // which is why this went unnoticed. Deriving from the key is correct for\n // both.\n const { name, ext } = path.parse(storedKey);\n\n // Sharp READS svg but cannot WRITE it, so an SVG source is rasterized to\n // PNG below. The cache key has to say so: storing PNG bytes under a `.svg`\n // key would also mean serving them as `image/svg+xml`, since the cache-hit\n // branch types the response from this extension.\n const outputExt = ext.toLowerCase() === '.svg' ? '.png' : ext;\n\n // append the width and height parameters to the base name\n // example: 935b511c9_cropped_w190.jpeg or 935b511c9_cropped_w190h190.jpeg\n //\n // The underscore is emitted once, before either dimension, rather than as\n // part of the width segment. With it inside the width, a height-only\n // request produced `logoh30.jpeg` here while the local branch below --\n // which has always written the separator unconditionally -- produced\n // `logo_h30.jpeg` for the same request. The two halves of one route\n // disagreed on the cache key.\n const newName = `${name}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }`;\n\n // the destination key, alongside the original\n // example: uploads/935b511c9_cropped.jpeg -> uploads/resized/935b511c9_cropped_w190.jpeg\n // and for a LocalFileStore key: photo.jpg -> resized/photo_w190.jpg\n const keyDir = path.dirname(storedKey);\n const newPathname = path.join(\n keyDir === '.' ? '' : keyDir,\n 'resized',\n `${newName}${outputExt}`\n );\n\n const resizedImageFileName = newPathname.startsWith('/')\n ? newPathname.slice(1)\n : newPathname;\n\n if (this.resizePathsMap.has(resizedImageFileName)) {\n res.redirect(this.resizePathsMap.get(resizedImageFileName));\n return;\n }\n\n // check if the resized image already exists in the CDN\n const imageExists: boolean = await LinkedFileStorage.fileExists(\n resizedImageFileName\n );\n\n // if exists, redirect to the resized image\n if (imageExists) {\n const resizedPathOnCdn: string = accessURL + '/' + resizedImageFileName;\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n } else {\n console.log(\n `${process.pid} - ${\n process.env.PORT\n }: Resizing image: ${imageFileName} to ${width} x ${height || ''}`\n );\n //in multicore development, we need to access the site from 127.0.0.1, and so all requests need to go there\n // // if (process.env.NODE_ENV === 'development' && process.env.NUM_WORKER_PROCESSES) {\n // // imageFileName = imageFileName.replace('localhost', '127.0.0.1');\n // // }\n\n // Read the bytes out of the store rather than fetching its public URL.\n //\n // Once `src` has to name an image the store already holds, fetching is\n // a round-trip to ask a web server for a file this process can open --\n // over the loopback interface, for a LocalFileStore. Reading directly\n // is faster, and it means the route makes no outbound request at all:\n // there is no origin to re-check after a redirect, no timeout to tune\n // and no response size to cap, because there is no response.\n const image = await LinkedFileStorage.getFile(storedKey);\n\n // if image is null or empty, return 404\n if (!image?.length) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // get the format of the image\n let format;\n try {\n format = await sharp(image)\n .metadata()\n .then((meta) => meta.format);\n } catch (err) {\n console.warn('Unsupported image format: ' + err);\n res.status(400).send({ error: 'Unsupported image format' });\n return;\n }\n\n // Sharp reads SVG but has no SVG encoder, so `.toFormat('svg')` throws\n // and every resize of an SVG failed. Rasterize to PNG instead — lossless,\n // and it matches the `.png` cache key chosen above.\n const outputFormat = format === 'svg' ? 'png' : format;\n\n // set the output options based on the format for quality and compression\n let outputOptions;\n switch (outputFormat) {\n case 'jpeg':\n outputOptions = { quality: 90 };\n break;\n case 'png':\n outputOptions = { compressionLevel: 9 };\n break;\n case 'webp':\n outputOptions = { quality: 90 };\n break;\n // add more formats here\n default:\n outputOptions = {};\n }\n\n // resize the image\n const resizedImage: Buffer = await sharp(image)\n .resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n )\n .toFormat(outputFormat, outputOptions)\n .toBuffer()\n .catch((err) => {\n console.warn('Could not resize image: ' + err);\n return null;\n });\n\n // if resizedImage is null, return 500\n if (!resizedImage) {\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // upload the resized image to the CDN\n const resizedPathOnCdn = await LinkedFileStorage.saveFile(\n newPathname,\n resizedImage\n );\n\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n }\n } else {\n imageFileName = req.originalUrl.split('/resized/')[1]?.split('?')[0];\n }\n\n // Both halves of this route now read and write through LinkedFileStorage.\n //\n // This branch used to hardcode <cwd>/data/uploads for both, which meant it\n // could only ever work for a LocalFileStore: an app configured with S3 kept\n // its uploads in the bucket, so every request here looked on a local disk\n // that had nothing on it and 404'd. Going through the store also removes the\n // need to create the cache directory by hand -- LocalFileStore.saveFile\n // makes its own parent folders, which is why the mkdirSync that used to sit\n // here (commented out, so it silently did nothing) is gone rather than\n // restored.\n const [trueFileName, ...extensions] = imageFileName.split('.');\n const sourceExtension = extensions.join('.');\n\n // Same rasterization as the branch above: sharp reads SVG but cannot write\n // it. `extension` is what the cached derivative actually IS, and is what\n // `sendStoredFile` types the response with, so it has to be the OUTPUT\n // format rather than the source's.\n const extension =\n sourceExtension.toLowerCase() === 'svg' ? 'png' : sourceExtension;\n\n const resizedKey = path.join(\n path.dirname(imageFileName) === '.' ? '' : path.dirname(imageFileName),\n 'resized',\n `${path.basename(trueFileName)}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }.${extension}`\n );\n\n // The resize cache is its own purpose, so an app can keep derivatives on a\n // local disk while its uploads live in S3, or share one store for both.\n // Unconfigured, it falls back to the default store, which is the previous\n // behaviour for anyone who never thinks about it.\n const cacheStore = getResizedImagesStore();\n const sendStoredFile = async (store: IFileStore, key: string) => {\n const bytes = await store.getFile(key);\n if (!bytes) {\n return false;\n }\n res.type(extension || 'bin').send(bytes);\n return true;\n };\n\n if (await cacheStore.fileExists(resizedKey)) {\n if (await sendStoredFile(cacheStore, resizedKey)) {\n return;\n }\n }\n\n const uploadsStore = LinkedFileStorage.getStore(FileStorePurposes.uploads);\n const original = await uploadsStore.getFile(imageFileName);\n\n if (!original) {\n console.warn('Could not find original image at ' + imageFileName);\n res.status(404).send({ error: 'Could not find original image' });\n return;\n }\n\n let resized: Buffer;\n try {\n const pipeline = sharp(original).resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n );\n // Without this, sharp writes in the INPUT format, which for an SVG source\n // means asking for an encoder it does not have.\n resized = await (sourceExtension.toLowerCase() === 'svg'\n ? pipeline.png({ compressionLevel: 9 })\n : pipeline\n ).toBuffer();\n } catch (err) {\n console.warn('Could not resize image: ' + err);\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // preventDuplicates: false because this is a cache keyed by name. Letting\n // the store pick a fresh name on collision would write a second copy for\n // every request and never hit the cache.\n //\n // A failure here is logged, not fatal: the resize succeeded, so the caller\n // still gets its image and only the caching is lost. It used to be\n // swallowed and then followed by sendFile on a file that was never written,\n // which turned a cache miss into a 404 with nothing in the response to say\n // why -- and, on the error path, into a second send after the 500.\n try {\n await cacheStore.saveFile(resizedKey, resized, {\n preventDuplicates: false,\n });\n } catch (err) {\n console.warn('Could not cache resized image at ' + resizedKey + ': ' + err);\n }\n\n res.type(extension || 'bin').send(resized);\n }\n\n async indexLincdPackage(pkg: string, warnIfNotFound: boolean = false) {\n if (pkg === this.package.name) {\n return;\n }\n try {\n // console.log(`🔍 Loading package: ${pkg}`);\n // console.log(\n // `🔍 Module resolution for ${pkg}:`,\n //@ts-ignore\n // await import.meta.resolve(pkg)\n // );\n // plan-011 §P6 — prefer Vite's SSR loader so workspace packages register\n // on the SINGLE @_linked/core instance the rest of the SSR graph uses.\n // The bare Node `import()` fallback resolves `default`→lib, evaluating a\n // SECOND core copy (benign post-§P1, but a needless second instance).\n // Node import stays as the fallback when Vite isn't active (production /\n // Node-only CLI commands). Mirrors indexPackageBackendProviders.\n const vite: any = (this.config.server as any)?.vite;\n if (vite && typeof vite.ssrLoadModule === 'function') {\n await vite.ssrLoadModule(pkg);\n } else {\n // @vite-ignore — dynamic specifier is intentional: this checks\n // whether `pkg` is resolvable at runtime, then catches the error.\n // eslint-disable-next-line no-unsanitized/method\n await import(/* @vite-ignore */ pkg);\n }\n // console.log(`✅ Successfully loaded: ${pkg}`);\n } catch (e) {\n let providerNotFound =\n e.code === 'MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find package '${pkg}'`) !== -1;\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n chalk.magenta(\n `Could not load package ${pkg}`,\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n )\n );\n }\n } else {\n console.warn(\n chalk.red(\n `Error loading '${pkg}' ${\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n }: ${e.message}\\n`\n ),\n e.stack\n );\n }\n }\n }\n async indexPackageBackendProviders(\n pkg: string,\n warnIfNotFound: boolean = false,\n backendIndexFilePath?: string\n ) {\n if (!backendIndexFilePath) {\n backendIndexFilePath = `${pkg}/backend`;\n }\n let backendProviderExports;\n let genericBackendProvider;\n let shapeProviders = [];\n // Plan-010 phase 4/5: when Vite SSR is active, route module loading\n // through vite.ssrLoadModule. This handles the case where the user app\n // is the consuming workspace itself (self-reference like\n // @semantu/create-now/backend), which Node's ESM resolver can't resolve\n // from inside an installed package like @_linked/server.\n const vite: any = (this.config.server as any)?.vite;\n const loadModule = async (specifier: string) => {\n if (vite && typeof vite.ssrLoadModule === 'function') {\n // For the user app's own backend, resolve to ./src/backend.ts directly.\n // Vite reads the app's package.json exports.development condition.\n if (specifier === `${this.package.name}/backend`) {\n return await vite.ssrLoadModule('/src/backend.ts');\n }\n // Plan-011: ssr.external is now an npm-only allowlist. Workspace\n // packages MUST go through Vite's SSR loader so they share the\n // same module instance as everything else in the SSR call graph\n // (otherwise we get duplicate React contexts, duplicate Linked\n // package registrations, etc).\n //\n // Pre-check whether the specifier actually resolves before\n // calling ssrLoadModule — many packages have no `/backend`\n // export, and ssrLoadModule logs a \"Failed to load url\" error\n // INTERNALLY before throwing, which spams stdout even when the\n // surrounding catch handles it. pluginContainer.resolveId is\n // quiet: it returns null when no plugin can resolve the id.\n try {\n const resolved = await vite.pluginContainer?.resolveId?.(specifier);\n if (!resolved) {\n // Synthesise the same error shape the catch expects so the\n // \"no backend export, that's fine\" branch fires.\n const err: any = new Error(\n `Failed to load url ${specifier} (resolved id: ${specifier}). Does the file exist?`,\n );\n throw err;\n }\n } catch (e: any) {\n // If the pre-check itself errored (e.g. plugin threw on a\n // pkg name it doesn't know), let the call below surface the\n // real error path.\n if (!e?.message?.includes('Failed to load url')) {\n // fall through to ssrLoadModule which will throw + log\n } else {\n throw e;\n }\n }\n return await vite.ssrLoadModule(specifier);\n }\n // No-vite path (e.g. production runtime).\n //\n // The app's own backend cannot be imported by name here. A self-reference\n // resolves only from inside the package that declares it, and this code\n // lives in node_modules/@_linked/server — so Node reports\n // `Cannot find package '<app>'` and every one of the app's Providers\n // silently fails to register. The Vite branch above already works around\n // this; the compiled runtime needs the same treatment, by path.\n if (specifier === `${this.package.name}/backend`) {\n const compiled = path.join(process.cwd(), 'lib', 'backend.js');\n const source = path.join(process.cwd(), 'src', 'backend.ts');\n const target = fsNative.existsSync(compiled) ? compiled : source;\n return await import(/* @vite-ignore */ pathToFileURL(target).href);\n }\n // Fall back to Node's resolver. The dynamic specifier is intentional.\n return await import(/* @vite-ignore */ specifier);\n };\n await loadModule(backendIndexFilePath)\n .then((backendProviderExports) => {\n //instantiate the exported provider classes and add them to the right place\n Object.keys(backendProviderExports).forEach((key) => {\n let providerClass = backendProviderExports[key];\n //always send an instance of the express server\n //TODO: do not create an instance, just save the class and instantiate it when needed\n let provider = new providerClass(this.server, this);\n if (provider instanceof ShapeProvider) {\n shapeProviders.push(provider);\n if (!Object.getOwnPropertyNames(provider).includes('shape')) {\n console.warn(\n chalk.red(`${\n Object.getPrototypeOf(provider).constructor.name\n } in package ${pkg}\n is not properly linked to a shape. Use public shape = SomeShape.`)\n );\n }\n } else {\n if (genericBackendProvider) {\n console.warn(\n `Package ${pkg} exports two generic backend providers. Only one will work`\n );\n } else {\n genericBackendProvider = provider;\n }\n }\n });\n })\n .catch((e) => {\n // Recognize \"no /backend export\" failures across two loader\n // shapes:\n // Node's import() → ERR_MODULE_NOT_FOUND + \"Cannot find module 'X/backend'\"\n // Vite's ssrLoadModule() → \"Failed to load url X/backend\"\n // package `exports` without a ./backend entry (Node + Vite)\n // → 'Missing \"./backend\" specifier in \"X\" package'\n // In either case, missing /backend on a package that doesn't\n // ship a backend is expected; loud-error only on REAL load\n // failures (syntax error inside an existing backend.ts, etc).\n const nodeMatch = e.message.match(/module \\'([^\\']+)'/);\n const viteMatch = e.message.match(/Failed to load url ([^\\s]+)/);\n const matchedSpec = nodeMatch?.[1] ?? viteMatch?.[1];\n const notExported = /Missing \"\\.\\/backend\" specifier in \"[^\"]+\" package/.test(\n e.message\n );\n let providerNotFound =\n notExported ||\n (!!matchedSpec &&\n matchedSpec.includes('/backend') &&\n ((e.code === 'ERR_MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find module`) !== -1) ||\n e.message.indexOf('Failed to load url') !== -1));\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n chalk.magenta(`Could not find backend file of package ${pkg}. \n Check:\\n\n - Make sure backend.ts exists and is included in tsconfig.json\\n\n - Make sure the package name in src/package.ts matches the package name in package.json`)\n );\n }\n } else {\n console.warn(\n chalk.red(\n `Could not load backend file of module '${pkg}' from ${process.cwd()}:\\n`\n ),\n e.stack\n );\n }\n genericBackendProvider = null;\n });\n this.genericProviders.set(pkg, genericBackendProvider);\n this.shapeProviders.set(pkg, shapeProviders);\n return { backendProviderExports, shapeProviders };\n }\n\n /**\n * Plan-011 phase 2 — HMR re-index entry point.\n *\n * Called by the CLI orchestrator's Vite watcher whenever a `.ts`/`.tsx`\n * file inside a workspace package changes. Disposes the package's\n * existing providers (so routes, listeners, timers don't accumulate),\n * drops them from the registry, and re-runs indexPackageBackendProviders\n * to pick up the freshly-imported module.\n *\n * Dispose calls have a 5 s soft timeout. A hanging dispose logs a\n * warning and is abandoned so HMR doesn't stall the whole dev loop.\n */\n /**\n * Install the client-shell catch-all as the last ordinary layer on the\n * router stack. See utils/spaFallback.ts for why ordering has to be\n * re-asserted rather than assumed.\n */\n private installSpaFallback(): void {\n installSpaFallback(\n this.server,\n this.handleErrors(async (req, res) => {\n //make sure the frontend bundle has finished building\n // await this.waitForWebpack();\n this.render(req, res);\n })\n );\n }\n\n async onSourceChange(pkg: string): Promise<void> {\n const disposeWithTimeout = async (p: any, label: string) => {\n if (!p?.dispose) return;\n try {\n await Promise.race([\n Promise.resolve().then(() => p.dispose()),\n new Promise((_, reject) =>\n setTimeout(\n () => reject(new Error(`dispose timeout after 5s`)),\n 5000\n )\n ),\n ]);\n } catch (err: any) {\n console.warn(\n chalk.yellow(`[linked] ${label} dispose failed: ${err.message}`)\n );\n }\n };\n\n const generic = this.genericProviders.get(pkg);\n if (generic) {\n await disposeWithTimeout(generic, `${pkg} generic provider`);\n this.genericProviders.delete(pkg);\n }\n\n const shapeProvs = this.shapeProviders.get(pkg) ?? [];\n for (const p of shapeProvs) {\n await disposeWithTimeout(\n p,\n `${pkg} ${Object.getPrototypeOf(p)?.constructor?.name ?? 'shape provider'}`\n );\n }\n this.shapeProviders.delete(pkg);\n\n await this.indexPackageBackendProviders(pkg, true);\n\n // Run the boot lifecycle on the FRESHLY-loaded provider so it\n // re-registers its Express routes/middleware after dispose. Without\n // this, dispose() tears the old routes off and the new instance is\n // constructed but never gets a chance to register the replacements.\n const fresh = this.genericProviders.get(pkg);\n if (fresh?.setupBeforeControllers) {\n try {\n await fresh.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n chalk.yellow(\n `[linked] ${pkg} setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n const freshShapes = this.shapeProviders.get(pkg) ?? [];\n for (const p of freshShapes) {\n if (p?.setupBeforeControllers) {\n try {\n await p.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n chalk.yellow(\n `[linked] ${pkg} shape-provider setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n }\n\n // Providers just re-registered their routes, which express can only APPEND\n // — i.e. behind the catch-all installed at boot. Put it back at the end so\n // those routes stay reachable. Safe here: every registration above has\n // completed, so no provider is mid-capture of its own layer indices.\n repinSpaFallback(this.server);\n }\n\n async processBackendMethodCall(request, response) {\n this.noCache(response);\n await this.initRequest(request, response);\n let { pkg, method } = request.params;\n let { args } = JSONParser.parseObject<{ args }>(request.body);\n\n return this.callBackendMethod(pkg, method, args, request, response).then(\n (result) => {\n //some methods of backend providers may choose to work with request/response directly and will not return anything\n //so only if a result is returned\n if (typeof result !== 'undefined') {\n //do we convert it to JSON and send it to the frontend\n this.sendJson(response, result);\n } else {\n //in other cases, we still need to close the request and send an empty response\n if (!response.headersSent) {\n this.sendJson(response, null);\n }\n }\n }\n );\n }\n\n noCache(response) {\n response.setHeader('Surrogate-Control', 'no-store');\n response.setHeader(\n 'Cache-Control',\n 'no-store, no-cache, must-revalidate, proxy-revalidate'\n );\n response.setHeader('Expires', '0');\n }\n async processAPICall(\n request,\n response,\n method: 'get' | 'post' | 'put' | 'delete'\n ) {\n this.noCache(response);\n const result = await this.api.process(request, response, method);\n }\n // async processQuery(request, response) {\n //\n // this.api.process(request, response);\n // }\n async processShapeMethodCall(request, response) {\n this.noCache(response);\n // console.log('process shape call');\n // response.on('finish', function() {\n // console.log('shape method call request finish');\n // });\n //\n // response.on('close', function() {\n // console.log('close');\n // });\n //\n // response.on('end', function() {\n // console.log('end');\n // });\n //\n // response.on('header', function() {\n // console.log('header');\n // console.log(response.statusCode);\n // });\n\n await this.initRequest(request, response);\n let { pkg, shape, method } = request.params;\n let { shapeURI, instanceNode, args } = JSONParser.parseObject<{\n shapeURI: string;\n instanceNode: { id: string } | null;\n args: any[];\n }>(request.body);\n\n if (!shapeURI) {\n if (request.query?.shapeURI) {\n shapeURI = request.query?.shapeURI;\n } else {\n response.status(500).send({\n error: 'Invalid server call request: ' + request.originalUrl,\n });\n console.warn(\n chalk.red('Invalid server call request: ' + request.originalUrl)\n );\n return;\n }\n }\n return this.callShapeMethod(\n pkg,\n method,\n shapeURI,\n instanceNode,\n args,\n request,\n response\n ).then((result) => {\n //we return json if something was returned or, if nothing was returned, we still close the request if the method has not accessed response itself already to send things over\n if (typeof result !== 'undefined' || !response.headersSent) {\n this.sendJson(response, result);\n }\n });\n }\n\n async callShapeMethod(\n pkg: string,\n method: string,\n shapeURI: string,\n instanceNode: { id: string } | null,\n args: any[],\n request,\n response\n ) {\n //- index module providers if not done yet\n if (!this.shapeProviders.has(pkg)) {\n await this.indexPackageBackendProviders(pkg, true);\n }\n\n let packageShapeProviders = this.shapeProviders.get(pkg);\n\n let findProviderForShape = (nodeShapeId: string) => {\n return packageShapeProviders.find((provider) => {\n //access the static shape (which is a linkedShape() / Shape class)\n //then access the SHACL NodeShape of that shape class, and its id\n return (\n provider instanceof ShapeProvider &&\n provider.shape?.shape?.id === nodeShapeId\n );\n });\n };\n\n let providerMethodFailed = false;\n try {\n //- find matching provider\n let shapeClass = getShapeClass(shapeURI);\n let shapeProvider: ShapeProvider = shapeClass?.shape\n ? findProviderForShape(shapeClass.shape.id)\n : undefined;\n if (!shapeProvider && shapeClass) {\n let superShapeClasses = getSuperShapesClasses(\n shapeClass as unknown as typeof Shape\n );\n for (let superShapeClass of superShapeClasses) {\n let superShapeProvider = findProviderForShape(\n superShapeClass.shape?.id\n );\n if (superShapeProvider) {\n shapeProvider = superShapeProvider;\n break;\n }\n }\n }\n // No provider for this shape (e.g. it isn't registered on this side).\n // Framework packages are kept single-instance by the cli vite-config's\n // `optimizeDeps.exclude`, so a mismatch here signals a real\n // misconfiguration. Answer 501 (via handleErrorsJson) rather than an empty\n // 200; direct backend callers get a rejected ServerCallError.\n if (!shapeProvider) {\n console.warn(\n `[LinkedServer] callShapeMethod: no provider for '${shapeURI}' ` +\n `(pkg '${pkg}', method '${method}').`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n\n if (shapeProvider) {\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //give the provider a chance to prepare for this request\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(shapeProvider.initRequest(request, response));\n }\n\n //see if the shapeProvider implements the called method\n if (shapeProvider[method]) {\n //prepare the first argument\n //we want to convert the instance node into an instance of the shape that this shapeProvider provides for\n //let's find the shape class\n if (shapeProvider.shape) {\n //instance nodes are not always sent. A shape can also call a shape provider from a static method without a shape instance.\n if (instanceNode) {\n let providerShapeClass = shapeProvider.shape;\n let instance = new (providerShapeClass as any)({\n id: instanceNode.id,\n });\n\n //always send instanceNode as first argument to static provider methods\n args.unshift(instance);\n }\n\n try {\n //call the method with the given arguments\n let result = await Promise.resolve(\n shapeProvider[method].apply(shapeProvider, args)\n );\n return result;\n } catch (e) {\n console.warn(\n `Error whilst calling ${\n Object.getPrototypeOf(shapeProvider).constructor.name\n }.${method}(): `,\n e\n );\n // Rethrow so the HTTP route answers with an error status (via\n // handleErrorsJson) instead of `200 null`, and direct backend\n // callers get a rejected promise.\n providerMethodFailed = true;\n throw e;\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not define its own 'static shape' property. Please connect the provider to a shape.`\n );\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not have a method called ${method}`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n }\n } catch (err) {\n if (!providerMethodFailed && !ServerCallError.is(err)) {\n console.warn(`Error whilst trying to access provider of ${pkg}: `, err);\n }\n throw err;\n }\n return null;\n }\n\n handleErrors(fn) {\n return async function (req, res, next) {\n try {\n return await fn(req, res);\n } catch (x) {\n console.log(x);\n next(x);\n }\n };\n }\n\n handleErrorsJson(fn) {\n return async (req, res, next) => {\n try {\n return await fn(req, res);\n } catch (err) {\n // A ServerCallError (e.g. 501 for a call no provider handles) carries\n // its own status and a message that is safe to send to the client.\n if (ServerCallError.is(err)) {\n return this.sendError(res, err.status, err.message);\n }\n this.sendError(\n res,\n 500,\n 'internal server error' + (isDevelopment ? ': ' + err?.stack : ''),\n 'internal server error: ' + err?.stack\n );\n }\n };\n }\n\n sendError(res, statusCode = 500, message, logMessage?: string) {\n res?.status(statusCode);\n if (message) {\n res?.send({ error: message });\n console.warn(chalk.red(logMessage || message));\n }\n }\n\n /**\n * The stylesheets a dev (Vite) page render needs, inlined into\n * `<style id=\"ssr-css\">` so the first paint is styled before Vite's client\n * injects the same CSS.\n *\n * Scoped to what the app module and the matched routes' pages import\n * statically (see utils/ssrCss `ssrCssScope`). The dev server preloads every\n * page into the module graph, so the whole graph is every page's CSS —\n * megabytes per request in a large app. When the scope cannot be\n * established (no routes config, a route rendered through a function, a\n * module not found) it falls back to the whole graph.\n *\n * Ids are kept in the combined graph's order, so the cascade order of what\n * remains is unchanged.\n */\n private async collectViteSsrCss(\n vite: any,\n App: unknown,\n matchedRoutes: RouteConfig[] | null,\n ): Promise<string> {\n if (!vite?.moduleGraph?.idToModuleMap) return '';\n // Note: Tailwind v4 `@theme` directives in app theme CSS files are\n // NOT processed at SSR collection time — the @tailwindcss/vite\n // plugin expands them at production build only. In dev mode, the\n // theme variables (—color-primary-*, etc.) are injected by Vite's\n // runtime AFTER client hydration, which causes a brief flash of\n // unthemed content (logos render black until ~hydration+200ms).\n // Production (vite build) is unaffected — the static main.css\n // contains expanded :root variables.\n let scope: Set<string> | null = null;\n const ssrGraph = vite.environments?.ssr?.moduleGraph;\n if (ssrGraph?.idToModuleMap && App && matchedRoutes) {\n const pages: unknown[] = [];\n let known = true;\n for (const route of matchedRoutes) {\n const component = await resolveRouteComponent(route);\n if (component === undefined) {\n known = false;\n break;\n }\n if (component !== null) pages.push(component);\n }\n if (known) {\n scope = ssrCssScope(ssrGraph.idToModuleMap.values(), {\n app: App,\n pages,\n });\n }\n }\n // Read only now: resolving a lazy route above can load its page, and the\n // combined graph's id map is a view built when it is read.\n const graphIds = [\n ...(vite.moduleGraph.idToModuleMap as Map<string, unknown>).keys(),\n ];\n const ids = scope ? graphIds.filter((id) => scope!.has(id)) : graphIds;\n // Only real stylesheets, once per file — see utils/ssrCss.\n const inlineUrls = ssrCssInlineUrls(ids, {\n publicDir: vite.config?.publicDir,\n });\n const cssChunks: string[] = [];\n for (const inlineUrl of inlineUrls) {\n try {\n const cssModule = await vite.ssrLoadModule(inlineUrl);\n if (typeof cssModule?.default === 'string') {\n cssChunks.push(cssModule.default);\n }\n } catch {/* skip */}\n }\n return cssChunks.join('\\n');\n }\n\n async render(req, res) {\n res.socket.on('error', (error) => {\n console.error('Fatal socket error', error);\n });\n\n //when render() is called, the request is always an 'initial page request', and the server which will return HTML (so this is a SSR request)\n //in that case we send data back to the frontend in a <script> tag.\n //We initiate that object here\n if (req['frontendData'] == null) {\n req['frontendData'] = {};\n }\n\n //if we are caching this page\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n //if there is a cach for this path, send it\n if (this.cachedPaths.has(req.url)) {\n // console.log(req.url + ': Returning cached path');\n const html = this.cachedPaths.get(req.url);\n // res.setHeader('Content-Type', 'text/html; charset=utf-8');\n // res.setHeader('Content-Length', Buffer.byteLength(html, 'utf8').toString());\n // res.status(200).end(html);\n res.send(html);\n return;\n }\n }\n\n let didError = false;\n\n let App = this.config.server?.loadAppComponent\n ? await this.config.server.loadAppComponent()\n : null;\n\n // Vite dev CSS collection (plan-010 iteration 1 — gap A):\n // 1. Preload the matched route's module via ssrLoadModule so all\n // page-level dependencies (SigninLayout, CreateAccount, etc.)\n // enter Vite's moduleGraph BEFORE we collect CSS. Without this,\n // only App's eager imports are in the graph and lazy routes'\n // CSS would be missing — page renders unstyled until hydration.\n // 2. Once the route is matched, collect the CSS the app and that route's\n // page import (collectViteSsrCss), each loaded via `?inline` (Vite\n // returns the processed CSS as the default export).\n // 3. Inject as inline <style> in HTML head (Html.tsx).\n const vite: any = (this.config.server as any)?.vite;\n // Vite SSR module preload (plan-010 iter1 gap A):\n // Pages are loaded lazily via React.lazy — their modules only enter\n // Vite's moduleGraph after the lazy resolves. For SSR CSS collection\n // we need the page modules in the graph BEFORE the first render of\n // each route. The orchestrator passes a preloadPagesFn that lists\n // all page files (typically via `import.meta.glob`); we call\n // ssrLoadModule on each path once. After the first render of a\n // session everything is cached.\n const preloadPagesFn: any = (this.config.server as any)?.viteSsrPreload;\n if (vite?.ssrLoadModule && preloadPagesFn && !(this as any)._viteSsrPreloaded) {\n try {\n const pagePaths: string[] = await preloadPagesFn();\n for (const p of pagePaths) {\n try {\n await vite.ssrLoadModule(p);\n } catch {/* skip — page may not exist or have ssr errors */}\n }\n } catch {/* ignore */}\n (this as any)._viteSsrPreloaded = true;\n }\n\n await this.initRequest(req, res);\n let { requestLD, requestObject } = await this.getRequestData(req, res);\n\n //on the backend we need to inform the hook of the request-data value\n //on the frontend it will be read from the HTML\n // setRequestData(requestObject);\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n let stream;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timedout = false;\n // const timeout = setTimeout(() => {\n // stream.abort(`${req.url}: ⏱ SSR stream took too long — force abort`);\n // if (!res.headersSent) {\n // res.statusCode = 500;\n // res.end('SSR timed out');\n // }\n // timedout = true;\n // }, 8_000);\n\n let manifest = this.assets.manifest || {};\n let preloadScripts: string[] = [];\n let preloadStyles: string[] = [];\n let matchedRouteKey: string | null = null;\n // Null until the routes config has loaded: without it, what renders is unknown.\n let matchedRoutes: RouteConfig[] | null = null;\n // Plan-010 Vite dev mode: skip preload resolution entirely. Vite\n // handles dynamic import() at runtime — there are no pre-built\n // chunks to preload, and the webpack-shape fallback would pick up\n // stale bundles on disk (public/bundles/*.bundle.js from a prior\n // webpack build) and link them, breaking hydration.\n // The same decision start() made for the `__viteDev` marker. This used\n // to be re-derived from `latestManifest`, which nothing ever set, so it\n // answered \"dev\" whenever Vite was attached — even when start() had\n // chosen the build — and the page mixed built CSS with the dev preamble.\n const usingViteDev = this.viteDevServer;\n\n // Load routes config if available and extract preload chunks for the current route\n if (this.config.server?.loadRoutes) {\n try {\n const routesModule = await this.config.server.loadRoutes();\n const ROUTES: RoutesConfig =\n routesModule.ROUTES ||\n routesModule.default?.ROUTES ||\n (routesModule as RoutesConfig);\n\n // Match the current request path to a route\n let matchedRoute: RouteConfig | null = null;\n const allMatches: RouteConfig[] = [];\n for (const [key, route] of Object.entries(ROUTES)) {\n if (!route?.path) continue;\n const pathPattern = route.path\n .replace(/:\\w+\\??/g, '([^/]+)')\n .replace(/\\*/g, '.*');\n const regex = new RegExp('^' + pathPattern + '$');\n if (regex.test(req.path)) {\n // Every match, not only the first: React Router may pick a more\n // specific route than this first-match loop, and the dev CSS\n // scope must cover whichever page actually renders.\n allMatches.push(route);\n if (!matchedRoute) {\n matchedRoute = route;\n matchedRouteKey = key;\n }\n }\n }\n matchedRoutes = allMatches;\n\n // If we found a matching route with preloadChunks, resolve them to URLs (both JS and CSS).\n // Manifest format detection: Vite manifest entries are objects with .file/.css; webpack\n // manifest entries are bare strings. Try Vite shape first, fall back to webpack.\n // Skip entirely in Vite dev mode — no pre-built chunks exist; Vite handles dynamic\n // imports at runtime.\n if (\n !usingViteDev &&\n matchedRoute?.preloadChunks &&\n Array.isArray(matchedRoute.preloadChunks)\n ) {\n // Both lists are built on the base the entry tags use, so a release\n // served from a CDN preloads its route chunks from that release\n // rather than from this app server. See utils/routeAssets.\n const routeAssets = resolveRouteAssets(\n manifest,\n matchedRoute.preloadChunks,\n this.staticAccessURL,\n );\n preloadScripts = routeAssets.scripts;\n preloadStyles = routeAssets.styles;\n }\n } catch (err) {\n console.warn('Failed to resolve preload chunks:', err);\n }\n }\n\n // Add matched route key to request object for Html component\n req['matchedRouteKey'] = matchedRouteKey;\n\n const ssrCss = await this.collectViteSsrCss(vite, App, matchedRoutes);\n // Per request, and not enumerable: Html reads `assets.__viteSsrCss` for\n // the inline <style>, but also serialises the whole assets object into\n // `assetManifest` for the client, which never uses it. Enumerable, the\n // collected CSS — megabytes in a large app — went into every page twice.\n // A per-request copy also keeps one render's CSS out of another's.\n const assets = { ...this.assets };\n if (ssrCss) {\n Object.defineProperty(assets, '__viteSsrCss', {\n value: ssrCss,\n enumerable: false,\n });\n }\n\n stream = renderToPipeableStream(\n <React.StrictMode>\n <StaticRouter location={req.url}>\n <AppContextProvider\n assets={assets}\n requestLD={requestLD}\n requestObject={requestObject}\n preloadScripts={preloadScripts}\n preloadStyles={preloadStyles}\n expressRequest={req}\n expressResponse={res}\n >\n <App />\n </AppContextProvider>\n </StaticRouter>\n </React.StrictMode>,\n {\n // How the client entry boots — dev preamble, ES module, or classic\n // script. See utils/bootstrapEntry.\n ...resolveBootstrapEntry({\n viteDevServer: usingViteDev,\n mainEntryIsModule: this.mainEntryIsModule,\n mainEntry: this.assets['main.js'],\n }),\n onShellReady: function () {\n res.statusCode = didError ? 500 : 200;\n res.setHeader('Content-type', 'text/html');\n\n // Create a caching transform stream à la mxstbr.com/thoughts/streaming-ssr\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n const bufferedChunks: Buffer[] = [];\n\n const cacheStream = new Transform({\n transform(chunk, _enc, cb) {\n bufferedChunks.push(chunk); // keep a copy\n cb(null, chunk); // forward unchanged\n },\n flush: (cb) => {\n const html = Buffer.concat(bufferedChunks).toString('utf8');\n this.cachedPaths.set(req.url, html);\n if (this.config.server.cacheTimeout) {\n setTimeout(\n () => this.cachedPaths.delete(req.url),\n this.config.server.cacheTimeout\n );\n }\n clearTimeout(timeout); // rendering finished → stop timer\n cb();\n },\n });\n\n // Pipe the caching stream into the real response\n cacheStream.pipe(res);\n\n // React may **only be piped once**, so pipe it to the cacheStream\n stream.pipe(cacheStream);\n } else {\n stream.pipe(res);\n }\n }.bind(this),\n onShellError(x) {\n didError = true;\n console.error(x);\n // Respond NOW. Without this the socket stays open until the 10s\n // watchdog below fires, turning every render-time crash into an\n // opaque \"SSR timed out\" with the real error buried in the log.\n clearTimeout(timeout);\n if (res.headersSent) {\n res.end();\n return;\n }\n res.statusCode = 500;\n res.setHeader('Content-type', 'text/plain');\n res.end(\n 'SSR render failed before the shell was ready:\\n\\n' +\n ((x as any)?.stack ?? (x as any)?.message ?? String(x))\n );\n },\n }\n );\n\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n timeout = setTimeout(() => {\n stream.abort('⏱ SSR stream took too long — force abort');\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end('SSR timed out');\n }\n }, 10_000);\n\n res.on('close', () => {\n clearTimeout(timeout); // if you're using a safety timeout\n });\n }\n\n //If we ever need to use multiple webpack entry-points and different bundle names, then uncomment this\n /*getWebpackAssets()\n\t{\n\t\t// const { devMiddleware } = res.locals.webpack;\n\t\t// const outputFileSystem = devMiddleware.outputFileSystem;\n\t\t// const jsonWebpackStats = devMiddleware.stats.toJson();\n\t\t// const { assetsByChunkName, outputPath } = jsonWebpackStats;\n\t\t//\n\t\t// let normalizedAssets = normalizeAssets(assetsByChunkName.main);\n\t\t// let cssAssets = normalizedAssets\n\t\t// .filter((path) => path.endsWith(\".css\"))\n\t\t// .map((filePath) => outputFileSystem.readFileSync(path.join(outputPath, filePath)))\n\t\t// .join(\"\\n\");\n\t\t//\n\t\t// let jsAssets = normalizeAssets(assetsByChunkName.main)\n\t\t// .filter((path) => path.endsWith(\".js\"))\n\t\t// .map((path) => `<script src=\"${path}\"></script>`)\n\t\t// .join(\"\\n\")}\n\t}*/\n\n sendJson(res, obj) {\n let jsonObject = JSONWriter.toJsObject(obj);\n res.json(jsonObject);\n }\n\n async initRequest(request, response) {\n // initialise the request for all providers, do it synchroniously, one after the other\n let p = Promise.resolve();\n [...this.genericProviders.values()]\n .filter(Boolean)\n .forEach((backendProvider) => {\n p = p\n .then(() => {\n return backendProvider.initRequest(request, response);\n })\n .catch((err) => {\n console.warn(\n `Error during initRequest for provider ${\n Object.getPrototypeOf(backendProvider).constructor.name\n }: `,\n err\n );\n });\n });\n\n return p;\n }\n\n async getRequestData(\n request,\n response\n ): Promise<{ requestLD: string; requestObject: string }> {\n // Phase 1: providers return plain JSON data via supplyDataForRequest.\n // requestLD is kept as empty string for now — SSR data seeding will be\n // reworked in Phase 2/3 to inject query results instead of graph data.\n let requestData: Record<string, any> = {};\n await Promise.all(\n [...this.genericProviders.values()].map((backendProvider) => {\n if (backendProvider) {\n return Promise.resolve(\n backendProvider.supplyDataForRequest(request, response, requestData)\n ).catch((err) => {\n console.warn(\n `Error requesting page-request data from ${\n Object.getPrototypeOf(backendProvider).constructor.name\n }: `,\n err\n );\n });\n }\n })\n );\n\n let requestLD = '';\n let requestObject = JSONWriter.stringify(request['frontendData']);\n return { requestLD, requestObject };\n }\n\n async callBackendMethod(\n pkg: string,\n method: string,\n args: any[],\n request,\n response\n ) {\n if (!this.genericProviders.has(pkg)) {\n await this.indexPackageBackendProviders(pkg, true);\n }\n\n //retrieve the indexed provider class and create a new instance for this request\n let genericBackendProvider = this.genericProviders.get(pkg);\n\n let result;\n if (!genericBackendProvider) {\n console.warn(\n `${chalk.magenta(\n pkg\n )} does not have a generic backend provider. If you can edit this package, make sure 'backend.ts' is included in 'tsconfig.json' and that it exports a provider.`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n //test if there is a matching method in the backend provider\n if (!genericBackendProvider[method]) {\n console.warn(\n `Generic provider '${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n }' of ${pkg} does not have a method called ${method}`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n\n try {\n //TODO: remove init request.\n //TODO: refactor this.request and this.response to a request parameter\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //initialise the request for this specific provider\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(\n genericBackendProvider.initRequest(request, response)\n );\n }\n // args.push(request);\n // args.push(response);\n\n //call the method with the given arguments and return the result as json\n result = await Promise.resolve(\n genericBackendProvider[method].apply(genericBackendProvider, args)\n );\n } catch (e) {\n console.warn(\n `Error whilst calling ${method}() in provider ${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n } of package ${pkg}:\\n`,\n e\n );\n\n // error logging\n LinkedErrorLogging.log(e);\n // Rethrow so the HTTP route answers with an error status instead of `200 null`.\n throw e;\n }\n return result;\n }\n}\n"]}
1
+ {"version":3,"file":"LinkedServer.js","sourceRoot":"","sources":["../../../src/shapes/LinkedServer.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AACb,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;A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mBAAmB,GAAG,IAAI,MAAM,EAAE,CAAC,CAAC;QACrE,CAAC;QAED,IAAI,CAAC;YACH,4BAA4B;YAC5B,sEAAsE;YACtE,wJAAwJ;YACxJ,+DAA+D;YAC/D,IAAI,OAAO,IAAI,QAAQ,EAAE,CAAC;gBACxB,mDAAmD;gBACnD,oFAAoF;gBACpF,MAAM,OAAO,CAAC,OAAO,CACnB,sBAAsB,CAAC,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CACtD,CAAC;YACJ,CAAC;YACD,sBAAsB;YACtB,uBAAuB;YAEvB,wEAAwE;YACxE,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAC5B,sBAAsB,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,sBAAsB,EAAE,IAAI,CAAC,CACnE,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,IAAI,CACV,wBAAwB,MAAM,kBAC5B,MAAM,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC,WAAW,CAAC,IAC5D,eAAe,GAAG,KAAK,EACvB,CAAC,CACF,CAAC;YAEF,gBAAgB;YAChB,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YAC1B,gFAAgF;YAChF,MAAM,CAAC,CAAC;QACV,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;;AAt9DD;;GAEG;AACI,wBAAW,GAAG,WAAW,CAAC,WAAW,AAA1B,CAA2B;AAJlC,YAAY;IADxB,WAAW,CAAC,EAAC,IAAI,EAAE,cAAc,EAAC,CAAC;;GACvB,YAAY,CAw9DxB","sourcesContent":["'use strict';\nimport chalk from 'chalk';\nimport { timingSafeEqual } from 'crypto';\nimport events from 'events';\nimport express, { Express as ExpressServer } from 'express';\nimport fetchCookie from 'fetch-cookie';\nimport * as fsNative from 'fs';\nimport * as fs from 'fs/promises';\nimport { Server as HttpServer } from 'http';\n// Plan-011: imports from @_linked/cli now go through ./lifecycle (a\n// dynamic-import-free file) so Vite's SSR module graph doesn't pull\n// in the legacy webpack flow and emit dozens of unanalyzable-import\n// warnings on every boot.\nimport { getLincdPackages } from '@_linked/cli/lifecycle';\nimport { getPackageJSON } from '@_linked/cli/utils';\nimport type { LinkedConfig } from '@_linked/cli/interfaces';\nimport { AppContextProvider } from '@_linked/server-utils/components/AppContext';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { JSONParser } from '@_linked/server-utils/utils/JSONParser';\nimport { JSONWriter } from '@_linked/server-utils/utils/JSONWriter';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport { ServerCallError } from '@_linked/server-utils/utils/ServerCallError';\nimport { ShapeProvider } from '@_linked/server-utils/utils/ShapeProvider';\nimport { Shape } from '@_linked/core/shapes/Shape';\nimport { LinkedErrorLogging } from '@_linked/core/utils/LinkedErrorLogging';\nimport {\n FileStorePurposes,\n LinkedFileStorage,\n} from '@_linked/core/utils/LinkedFileStorage';\nimport type { IFileStore } from '@_linked/core/interfaces/IFileStore';\nimport { getResizedImagesStore } from '../utils/resizedImagesPurpose.js';\nimport { LinkedStorage } from '@_linked/core/utils/LinkedStorage';\nimport { autoLoadOntologyData } from '@_linked/core/utils/Package';\nimport {\n getShapeClass,\n getSuperShapesClasses,\n} from '@_linked/core/utils/ShapeClass';\nimport path from 'path';\nimport {pathToFileURL} from 'node:url';\nimport process from 'process';\nimport * as React from 'react';\nimport { renderToPipeableStream, renderToStaticMarkup } from 'react-dom/server';\nimport { StaticRouter } from 'react-router-dom/server.js';\nimport { rimraf } from 'rimraf';\nimport sharp from 'sharp';\nimport {\n findStoredKey,\n resolveResizeSource,\n} from '../utils/resizeSource.js';\nimport { Transform } from 'stream';\nimport { CookieJar } from 'tough-cookie';\nimport { lincdServer } from '../ontologies/lincd-server.js';\nimport { linkedShape } from '../package.js';\nimport {\n resolveStaticAccessURL,\n staticAssetURL,\n} from '../utils/releaseManifest.js';\nimport {\n resolveBootstrapEntry,\n resolveViteMainEntry,\n resolveViteServingMode,\n} from '../utils/bootstrapEntry.js';\nimport { resolveRouteAssets } from '../utils/routeAssets.js';\nimport {\n resolveRouteComponent,\n ssrCssInlineUrls,\n ssrCssScope,\n} from '../utils/ssrCss.js';\nimport { indexShapesIntoMemory } from '../utils/Shapes.js';\nimport { materializeShapes } from '../utils/syncShapes.js';\nimport {\n installSpaFallback,\n repinSpaFallback,\n} from '../utils/spaFallback.js';\nimport { LincdAPI } from './LincdAPI.js';\nimport type { RoutesConfig, RouteConfig } from '../types/RouteConfig.js';\n\n//prevent errors in node.js when (s)css files are imported in js\nconst isProduction = process.env.NODE_ENV === 'production';\nconst isDevelopment = process.env.NODE_ENV === 'development';\n\ndeclare var globalThis: any;\n// Install a global fetch that persists cookies across redirects using a CookieJar.\n// This ensures server-side requests behave more like browsers when handling Set-Cookie + redirects.\nconst __lincdCookieJar = new CookieJar();\n// Wrap native fetch with fetch-cookie so it reads/writes cookies in the jar.\nconst __lincdFetchWithCookies = fetchCookie(fetch, __lincdCookieJar);\n\n// Expose (optionally) for debugging/tests; not required by app logic.\n(globalThis as any).__lincdCookieJar = __lincdCookieJar;\n\n// Set the global fetch used throughout the server code path\n(globalThis as any).fetch = __lincdFetchWithCookies;\n\nprocess.on('uncaughtException', (err) => {\n console.warn(chalk.red('Asynchronous error caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err);\n});\nprocess.on('unhandledRejection', (err) => {\n console.warn(chalk.red('Unhandled rejection caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err as Error);\n});\n\nprocess.on('warning', (e) => console.warn(e.stack));\n\n//allow more listeners for when we have many concurrent users\nevents.EventEmitter.prototype.setMaxListeners(500);\n\n// const jsdom = require(\"jsdom\");\n// const { JSDOM } = jsdom;\n// const { document } = (new JSDOM(`...`)).window;\n//\n// global['document'] = document;\nglobal['reactStaticRenderer'] = renderToStaticMarkup;\n\nautoLoadOntologyData(true);\n\n// Named explicitly: tsc emits `let X = class X`, and any later esbuild pass over that JS (Vite's\n// SSR `define` replacement runs one on every file mentioning a defined `process.env.*`) renames\n// the inner binding to `X2`, which would otherwise become this shape's IRI.\n@linkedShape({name: 'LinkedServer'})\nexport class LinkedServer extends Shape {\n /**\n * indicates that instances of this shape need to have this rdf.type\n */\n static targetClass = lincdServer.LincdServer;\n private config: LinkedConfig;\n private cachedPaths: Map<string, string> = new Map();\n private assets: { [key: string]: string } & {\n manifest?: Record<string, string>;\n };\n /**\n * Whether pages are served by the live Vite dev server rather than a\n * `vite build` on disk. Decided once in `start()` — see\n * utils/bootstrapEntry `resolveViteServingMode`.\n */\n private viteDevServer = false;\n /**\n * Base URL every asset this build produced is served from — resolved once in\n * `start()` and kept so per-request route chunks land on the same base as\n * the entry tags. Empty means origin-relative (development, and any app\n * serving its own bundles).\n */\n private staticAccessURL: string = '';\n /**\n * Whether `assets['main.js']` came from a Vite build. Vite always emits the\n * entry as an ES module, so it has to be bootstrapped with\n * `bootstrapModules`; a legacy webpack bundle is a classic script and must\n * keep `bootstrapScripts`.\n */\n private mainEntryIsModule = false;\n protected server: ExpressServer;\n protected httpServer: HttpServer;\n private package: any;\n private cacheWebpack: boolean;\n private cssMode = 'scss-modules';\n private analyse: boolean = false;\n private shapeProviders: Map<string, ShapeProvider[]> = new Map();\n private genericProviders: Map<string, BackendProvider> = new Map();\n //from resizedFileName to full resized path (CDN or similar)\n private resizePathsMap: Map<string, string> = new Map();\n private api: LincdAPI;\n\n /**\n * yarn linked start sends the contents of linked.config.js as an object to this constructor\n * @param n\n */\n constructor(config?: LinkedConfig | string | { id?: string }) {\n super(\n typeof config === 'string' || (config && 'id' in config)\n ? config\n : undefined\n );\n if (config && typeof config !== 'string' && !('id' in config)) {\n // The absence of `id` is the runtime discriminator for a LinkedConfig;\n // the widened `{id?: string}` member of the union keeps TS from narrowing\n // to it on that check alone.\n this.config = config as LinkedConfig;\n }\n\n this.api = new LincdAPI({ id: process.env.SITE_ROOT + '/api' });\n\n //Ensure the Server utility (for Server.call()) directly accesses\n // this server on the backend instead of going through a network call\n Server.setLocalServer(this);\n }\n\n /*async getLincdDependencies(): Promise<string[]> {\n\t\tlet lincdDependencies = [];\n\t\tlet dependencies = this.package.dependencies;\n\n\t\tawait Promise.all(\n\t\t\tObject.keys(dependencies).map((dependencyPkgName) => {\n\t\t\t\tlet modulePackageJson = getModulePackageJSON(dependencyPkgName);\n\t\t\t\tif (modulePackageJson['lincd']) {\n\t\t\t\t\tlincdDependencies.push(modulePackageJson.name);\n\t\t\t\t}\n\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\n\t\t\t\t// let packagePath;\n\t\t\t\t// try {\n\t\t\t\t// packagePath = require.resolve(`${dependencyPkgName}`);\n\t\t\t\t// } catch (err) {\n\t\t\t\t// console.warn('Could not find package ' + dependencyPkgName+'. Error: '+err.toString());\n\t\t\t\t// return;\n\t\t\t\t// }\n\t\t\t\t// packagePath = path.dirname(packagePath) + '/package.json'\n\t\t\t\t// return fs\n\t\t\t\t// .readFile(packagePath, 'utf-8')\n\t\t\t\t// .then((res) => {\n\t\t\t\t// let pkg = JSON.parse(res);\n\t\t\t\t// if (pkg['lincd']) {\n\t\t\t\t// lincdDependencies.push(pkg.name);\n\t\t\t\t// }\n\t\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\t\t\t\t\t// })\n\t\t\t\t\t// .catch((err) => {\n\t\t\t\t\t// console.log('Could not read package.json file: '+err);\n\t\t\t\t\t// });\n\t\t\t}),\n\t\t);\n\t\treturn lincdDependencies;\n\t}*/\n get app() {\n return this.server;\n }\n\n initPackage() {\n this.package = JSON.parse(\n fsNative.readFileSync(\n path.resolve(process.cwd(), 'package.json'),\n 'utf-8'\n )\n );\n }\n async initOnly() {\n await this.initOntologies();\n await this.initStores();\n\n this.initPackage();\n\n this.server = express();\n\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n return this;\n }\n\n /**\n * Materialize this server's registered shapes into the RDF store as SHACL\n * (core `syncShapes` → pure `sh:NodeShape` + property shapes), so a running\n * app's app-data holds the shapes its instances validate/query against\n * (plan-010 T1e.2). Whatever shapes the app package registers (published\n * re-exports + generated) get written on boot (and re-run on shape-file HMR).\n *\n * Additive only: store shapes this process did not register are left alone\n * unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true` — see\n * `bootOrphanScope` in utils/syncShapes for why.\n *\n * Gated to servers whose DEFAULT dataset is a **concrete** materializable store\n * (detected via `rawQuery`) — i.e. an app pointing at its app-data FusekiStore.\n * CN's default is the context-routing `AppDataRouter` (no `rawQuery`), so CN is\n * skipped here — it materializes its own pinned native shapes in its storage\n * config.\n */\n private async materializeShapesIntoStore(): Promise<void> {\n // Opt-out via `linked.config` `syncShapesOnBoot` (default true); env\n // LINKED_SYNC_SHAPES_ON_BOOT overrides for deployment. CN sets\n // `syncShapesOnBoot: false` in its own linked.config — its default dataset is\n // a context-router that can't materialize context-free, and it syncs its own\n // pinned shapes separately (linked.backend.storage.js).\n const configFlag = (this.config as any)?.syncShapesOnBoot;\n const envFlag = process.env.LINKED_SYNC_SHAPES_ON_BOOT;\n if (configFlag === false || envFlag === 'false') {\n return;\n }\n const appData = LinkedStorage.getDefaultDataset();\n if (!appData) return;\n try {\n const {syncShapes} = await import('@_linked/core');\n // Explicit target: materialize EVERY registered shape into the app's own\n // data store regardless of per-shape routing/pins.\n await materializeShapes(appData, syncShapes as any);\n } catch (err) {\n console.warn('[LinkedServer] shape materialization failed (non-fatal):', err);\n }\n }\n\n // async serveData(req,res) {\n // let nodeURI = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n //\n // let store = LinkedStorage.getDatasets().find(store => {\n // return nodeURI.includes(store.namedNode.uri)\n // })\n // }\n\n async start() {\n this.initPackage();\n // Static assets should come from the static store URL (versioned path),\n // not the upload store URL. An explicit STATIC_ACCESS_URL still wins;\n // otherwise the release manifest `linked build-app` wrote next to the\n // bundle says which published release this build is, so a deployment no\n // longer has to repeat that URL by hand. See utils/releaseManifest.\n // In development we deliberately use a relative path so bundle URLs work\n // regardless of which PORT the dev server bound to (browsers resolve\n // relative URLs against window.location.origin). Hardcoding SITE_ROOT\n // baked :4000 into every SSR'd HTML page.\n const isDevAssets = process.env.NODE_ENV === 'development';\n const staticAccessURL = resolveStaticAccessURL({\n isDevAssets,\n appRoot: process.cwd(),\n fileStoreAccessURL: LinkedFileStorage.accessURL,\n });\n this.staticAccessURL = staticAccessURL;\n const staticAsset = (assetPath: string) =>\n staticAssetURL(staticAccessURL, assetPath);\n\n // Bundle/manifest read (plan-011: Vite is the only supported build).\n // Vite manifest lives at public/bundles/.vite/manifest.json.\n this.assets = {\n 'main.js':\n staticAsset('/bundles/main.bundle.js') + '?v=' + this.package.version,\n 'main.css': staticAsset('/bundles/main.css'),\n };\n // Dev or built, decided once and reused by the render path — see\n // utils/bootstrapEntry. In development the build manifest is not read:\n // one left on disk by an earlier `vite build` would otherwise swap in\n // stale built CSS while Vite serves the live styles.\n const servingMode = resolveViteServingMode({\n viteConfig: (this.config.server as any)?.vite,\n nodeEnv: process.env.NODE_ENV,\n readManifest: () => {\n try {\n const viteManifestPath = path.resolve(\n process.cwd(),\n 'public/bundles/.vite/manifest.json'\n );\n if (!fsNative.existsSync(viteManifestPath)) return null;\n return JSON.parse(fsNative.readFileSync(viteManifestPath, 'utf-8'));\n } catch (err) {\n console.warn('Could not load bundle manifest:', err);\n return null;\n }\n },\n });\n this.viteDevServer = servingMode.viteDevServer;\n if (servingMode.manifest) {\n const viteManifest = servingMode.manifest as Record<string, any>;\n this.assets.manifest = viteManifest;\n // Resolve main entry per Vite manifest shape:\n // { \"src/index.tsx\": { file: \"assets/main-<hash>.js\", css: [...] } }\n const mainEntry = resolveViteMainEntry(viteManifest);\n if (mainEntry?.file) {\n this.assets['main.js'] = staticAsset(`/bundles/${mainEntry.file}`);\n this.mainEntryIsModule = true;\n }\n if (mainEntry?.css?.[0]) {\n this.assets['main.css'] = staticAsset(`/bundles/${mainEntry.css[0]}`);\n }\n }\n // Vite dev marker: the HTML renderer skips pre-built CSS/JS link tags,\n // because Vite handles asset injection itself.\n if (this.viteDevServer) {\n this.assets['__viteDev'] = '1';\n }\n\n const isProduction = process.env.NODE_ENV === 'production';\n if (!isProduction && this.config.cssMode === 'tailwind') {\n this.assets['tailwind-cdn'] = 'https://cdn.tailwindcss.com';\n }\n\n //for multicore we use PM2, and each instance needs to listen to port 0.\n // whilst the main thread will listen to env.PORT automatically\n // const PORT = this.config.multiCore ? 0 : process.env.PORT || 3000;\n // const publicPort = process.env.PORT || 3000;\n //update: back to original setup. multicore handles itself inside @semantu/multicore\n const PORT = parseInt(process.env.PORT) || 4000;\n this.server = express();\n\n const dirName = path.resolve(process.cwd(), 'frontend');\n\n await this.initOntologies();\n //TODO: when we do not keep all data in memory (and thus do not need to rely on in memory data for page requests), we can possibly remove await here, since all stores handle their own initialisation before executing commands\n await this.initStores();\n\n this.initGarbageCollection();\n // this.app.use((req, res, next) => {\n // console.log('start request');\n // next();\n // });\n // before controllers\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n\n //START OF EXPRESS ROUTES AND MIDDLEWARE\n\n //use cors\n // var corsOptions = {\n // origin: ['http://localhost:4001', 'https://www.mynd.site'],\n // optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204\n // };\n // //accept JSON bodies\n // this.server.use(bodyParser.json({limit: '50mb'}));\n this.server.use(express.json({ limit: '50mb' }));\n\n // this.server.use(cors(corsOptions));\n //\n // //compress server output with gzip,\n //UPDATE ive set level to 2 (low compression fast speed) because responses were taking too long (98% of server time was used by compress)\n // this.server.use(compress({level: 2}));\n\n await this.callGenericBackendProvidersMethod('setupBeforeControllers');\n\n // Vite middleware (plan 010): when the user app starts via Vite\n // (`linked start --vite`), the orchestrator passes the Vite handle\n // through config.server.viteMiddleware. We mount it and skip the\n // entire webpack-dev-middleware setup below.\n const viteMiddleware = (this.config.server as any)?.viteMiddleware;\n if (viteMiddleware) {\n this.server.use(viteMiddleware);\n }\n\n // Plan-011: legacy webpack-dev-middleware branch removed. Under Vite\n // (the only supported dev path now) `viteMiddleware` is set, which\n // previously forced `skipBuild = true` and made this whole block\n // dead. Removing it ends the static dependency on @_linked/cli/\n // config-webpack-app (full of dynamic imports Vite couldn't analyze)\n // and shrinks LinkedServer's import surface considerably.\n\n // //map URL routes to file paths\n const oneYear = 1000 * 60 * 60 * 24 * 365; // in milliseconds\n const oneMonth = 1000 * 60 * 60 * 24 * 30; // in milliseconds\n this.server.use(\n '/public',\n express.static('./public', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n\n this.server.use(\n '/uploads',\n express.static('./data/uploads', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/', express.static('./public/root'));\n this.server.use(\n '/favicon.ico',\n express.static('./public/favicon.ico', {\n maxAge: oneMonth, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/.well-known', express.static('./public/.well-known'));\n\n // this.server.post('/data',this.handleErrorsJson(async (req,res) => this.serveData(req, res)));\n this.server.get('/resized/*', async (req, res) => {\n this.resizeImage(req, res);\n });\n\n // Scoped-package variants (@scope/pkg). Register BEFORE the unscoped\n // routes — Express `:pkg` won't consume slashes, so a call to\n // `/call/@_linked/auth/signinDev` would otherwise fall through to the\n // 3-segment `:pkg/:shape/:method` route and be misinterpreted as a\n // shape-method call (pkg=`@_linked`, shape=`auth`). These handlers\n // recognise the `@scope/pkg` prefix and rebuild the full package name\n // before dispatching to the same handler used for unscoped packages.\n this.server.post(\n '/call/@:scope/:pkg/:method',\n this.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return this.processBackendMethodCall(req, res);\n })\n );\n this.server.post(\n '/call/@:scope/:pkg/:shape/:method',\n this.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return this.processShapeMethodCall(req, res);\n })\n );\n this.server.post(\n '/call/:pkg/:method',\n this.handleErrorsJson(async (req, res) =>\n this.processBackendMethodCall(req, res)\n )\n );\n this.server.post(\n '/call/:pkg/:shape/:method',\n this.handleErrorsJson(async (req, res) =>\n this.processShapeMethodCall(req, res)\n )\n );\n this.server.post(\n '/api/:method/:action?',\n this.handleErrorsJson(async (req, res) =>\n this.processAPICall(req, res, 'post')\n )\n );\n this.server.get(\n '/api/:method/:action?',\n this.handleErrorsJson(async (req, res) =>\n this.processAPICall(req, res, 'get')\n )\n );\n // this.server.post(\n // '/api/query/:method',\n // this.handleErrorsJson(async (req, res) => this.processQuery(req, res)),\n // );\n\n // now that all the middleware is defined, we initialise the providers, before we define a catch-all route\n // before catch all\n // await this.initBackendProviders();\n await this.callGenericBackendProvidersMethod(\n 'setupBeforeCatchAllControllers'\n );\n\n // HEAD catch-all for maintenance/health check (client fetches SITE_ROOT with method: HEAD)\n this.server.head('__health', (_req, res) => {\n res.sendStatus(200);\n });\n\n // CN control channel (plan-010 T1b.3). Present only when CN spawned this\n // process with a shared secret (CN_APP_ADMIN_SECRET); a standalone app run\n // without the secret leaves the channel closed (404). Auth is the\n // x-cn-admin-secret header matching that env value.\n const adminSecret = process.env.CN_APP_ADMIN_SECRET;\n // Constant-time compare so the secret can't be recovered by timing the 401\n // response. timingSafeEqual requires equal-length buffers, so guard length.\n const secretMatches = (provided: string | undefined): boolean => {\n if (!adminSecret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(adminSecret);\n return a.length === b.length && timingSafeEqual(a, b);\n };\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!adminSecret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!secretMatches(req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n this.server.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n this.server.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n // CN's provisioner respawns on exit (see ChildProcessProvisioner).\n setTimeout(() => process.exit(0), 50);\n });\n\n // after controller\n await this.callGenericBackendProvidersMethod('setupAfterControllers');\n\n // The SPA catch-all goes on LAST. `setupAfterControllers` is a documented\n // hook for providers to register their own routes, so installing the\n // catch-all before it would shadow every GET route registered there —\n // answering them with the client shell at status 200.\n // An API-only backend (`linked start --api-only`) has no app to render:\n // without the catch-all, page requests get express's plain 404.\n if (!(this.config.server as any)?.apiOnly) {\n this.installSpaFallback();\n }\n\n //remove http(s):// and remove port :[port]\n const HOST = process.env.SITE_ROOT.replace(/https?:\\/\\//, '').replace(\n /:\\d+$/,\n ''\n );\n\n //backlog of 1024 means maximum of 1024 connections in the queue (higher than default)\n this.httpServer = this.server.listen({ port: PORT, backlog: 1024 }, () => {\n console.log(`Up and running at http://localhost:${PORT}`);\n // open(`http://localhost:${PORT}`)\n });\n // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n this.httpServer.keepAliveTimeout = 60_000;\n // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363\n this.httpServer.headersTimeout = 61_000;\n\n this.httpServer.on('error', function (error) {\n if (error['syscall'] !== 'listen') {\n throw error;\n }\n const isPipe = (portOrPipe) => Number.isNaN(portOrPipe);\n const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;\n switch (error['code']) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n default:\n throw error;\n }\n });\n return this;\n }\n\n async initOntologies() {}\n\n /**\n *\n * @returns\n * @todo Check if default file store is set, if not, set it\n */\n async initStores() {\n return Promise.all(\n LinkedStorage.getDatasets().map((store) => {\n return store.init ? store.init() : Promise.resolve();\n })\n );\n }\n\n // get generic backend providers for handle controller methods\n async callGenericBackendProvidersMethod(method: string, ...args: any[]) {\n for (let genericProvider of this.genericProviders.values()) {\n if (!genericProvider || !genericProvider[method]) {\n continue;\n }\n if (typeof genericProvider[method] == 'function') {\n await Promise.resolve(genericProvider[method](...args));\n }\n }\n }\n\n /**\n * Removes temporary nodes from memory if they've been seen twice\n * Current interval is once per hour.\n * So after 2 hours temporary nodes are removed.\n */\n initGarbageCollection() {\n // let seenLastTime:NodeSet<NamedNode> = null;\n // setInterval(() => {\n //\n // let tempNodes = new NodeSet<NamedNode>();\n // NamedNode.getAllNamedNodes().forEach(n => {\n // if(n.isTemporaryNode) {\n // if(seenLastTime && seenLastTime.has(n))\n // {\n // n.remove();\n // } else {\n // tempNodes.add(n);\n // }\n // }\n // })\n // seenLastTime = tempNodes;\n // }, 1000 * 10); //every 10 sec\n // // }, 1000 * 60 * 60); //every hour\n }\n async initBackendProviders() {\n //get all local workspace lincd packages, then filter to only those\n //in this app's dependency tree. This avoids loading npm-installed\n //legacy packages that may use an old version of the core.\n const allLocalPackages = getLincdPackages();\n const localPackageMap = new Map<\n string,\n { packageName: string; path: string }\n >(allLocalPackages.map((pkg) => [pkg.packageName, pkg]));\n const relevantPackages = this.filterPackagesByDependencyTree(\n localPackageMap,\n this.package\n );\n for (let [pkgName, pkg] of relevantPackages) {\n await this.indexPackageBackendProviders(pkgName);\n await this.indexLincdPackage(pkgName);\n }\n\n try {\n await fs\n .readFile(path.join(process.cwd(), 'package.json'), 'utf-8')\n .then(async (contents) => {\n let pkg = JSON.parse(contents);\n // Route through default ${pkg}/backend resolution. The app's\n // package.json `exports`./backend field handles dev vs prod:\n // \"exports\": {\n // \"./backend\": {\n // \"development\": \"./src/backend.ts\",\n // \"default\": \"./lib/esm/backend.js\"\n // }\n // }\n // Removed plan-010 D10: the source-direct\n // path.join(cwd, 'src', 'backend.ts') override that forced TS\n // runtime loading. Vite SSR's ssrLoadModule handles the\n // transform; production runs from lib/esm/.\n await this.indexPackageBackendProviders(pkg.name, false);\n });\n } catch (err) {\n console.warn(err);\n }\n }\n\n /**\n * Filters local workspace packages to only those reachable from the app's\n * dependency tree. Mirrors the logic used by `buildAll` in lincd-cli.\n */\n private filterPackagesByDependencyTree(\n allPackages: Map<string, { packageName: string; path: string }>,\n appPackageJson: any\n ): Map<string, { packageName: string; path: string }> {\n const relevantPackages = new Map<\n string,\n { packageName: string; path: string }\n >();\n const packagesToCheck = new Set<string>();\n const processedPackages = new Set<string>();\n\n // Start with direct dependencies from the app\n if (appPackageJson.dependencies) {\n for (const dep of Object.keys(appPackageJson.dependencies)) {\n if (allPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n\n // Recursively follow each package's dependencies\n while (packagesToCheck.size > 0) {\n const packageName = packagesToCheck.values().next().value;\n packagesToCheck.delete(packageName);\n if (processedPackages.has(packageName)) {\n continue;\n }\n processedPackages.add(packageName);\n const packageDetails = allPackages.get(packageName);\n if (packageDetails) {\n relevantPackages.set(packageName, packageDetails);\n const pkg = getPackageJSON(packageDetails.path);\n if (pkg?.dependencies) {\n for (const dep of Object.keys(pkg.dependencies)) {\n if (allPackages.has(dep) && !processedPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n }\n }\n\n return relevantPackages;\n }\n\n async resizeImage(req, res) {\n //check if the w or h query parameters are set\n let width = req.query.w;\n let height = req.query.h;\n //if not\n if (!width && !height) {\n //redirect to the original image\n res.redirect(req.originalUrl.replace('/resized', '/uploads'));\n return;\n }\n\n let imageFileName = req.query.src; // example: https://cdnurl.com/uploads/1710814765388-935b511c9_cropped.jpeg\n const accessURL = LinkedFileStorage.accessURL;\n\n if (imageFileName) {\n // `src` may only name an image this app already stores. Before this check\n // the value went straight to fetch(), which made the route an open proxy\n // into its own network -- cloud metadata, localhost, private ranges -- and\n // the response was then written into the PUBLIC file store and the caller\n // redirected to it, so anything reachable was persisted, not just leaked.\n //\n // resolveResizeSource compares parsed origins (a startsWith check is\n // defeated by https://cdn.example.com.evil.com) and hands back the key,\n // which must also exist in the store before anything is requested.\n const source = resolveResizeSource(imageFileName, accessURL);\n\n if (!source.allowed) {\n res.status(400).send({ error: 'Unsupported image source' });\n return;\n }\n\n // Two candidates, because the stores disagree on whether the public URL\n // includes the upload mount -- see resolveResizeSource. Fail-closed: if\n // neither shape is held, nothing is fetched.\n const storedKey = await findStoredKey(source.keys, (key) =>\n LinkedFileStorage.fileExists(key)\n );\n\n if (!storedKey) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // extract the base name and extension from the key the store actually\n // holds, not from the URL path.\n //\n // These differ: LocalFileStore serves `accessURL + /uploads/ + key`, so\n // deriving the destination from the URL gave it an extra `uploads/`\n // segment and resized files landed in data/uploads/uploads/resized/.\n // S3FileStore serves the key directly, so for it the two are the same --\n // which is why this went unnoticed. Deriving from the key is correct for\n // both.\n const { name, ext } = path.parse(storedKey);\n\n // Sharp READS svg but cannot WRITE it, so an SVG source is rasterized to\n // PNG below. The cache key has to say so: storing PNG bytes under a `.svg`\n // key would also mean serving them as `image/svg+xml`, since the cache-hit\n // branch types the response from this extension.\n const outputExt = ext.toLowerCase() === '.svg' ? '.png' : ext;\n\n // append the width and height parameters to the base name\n // example: 935b511c9_cropped_w190.jpeg or 935b511c9_cropped_w190h190.jpeg\n //\n // The underscore is emitted once, before either dimension, rather than as\n // part of the width segment. With it inside the width, a height-only\n // request produced `logoh30.jpeg` here while the local branch below --\n // which has always written the separator unconditionally -- produced\n // `logo_h30.jpeg` for the same request. The two halves of one route\n // disagreed on the cache key.\n const newName = `${name}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }`;\n\n // the destination key, alongside the original\n // example: uploads/935b511c9_cropped.jpeg -> uploads/resized/935b511c9_cropped_w190.jpeg\n // and for a LocalFileStore key: photo.jpg -> resized/photo_w190.jpg\n const keyDir = path.dirname(storedKey);\n const newPathname = path.join(\n keyDir === '.' ? '' : keyDir,\n 'resized',\n `${newName}${outputExt}`\n );\n\n const resizedImageFileName = newPathname.startsWith('/')\n ? newPathname.slice(1)\n : newPathname;\n\n if (this.resizePathsMap.has(resizedImageFileName)) {\n res.redirect(this.resizePathsMap.get(resizedImageFileName));\n return;\n }\n\n // check if the resized image already exists in the CDN\n const imageExists: boolean = await LinkedFileStorage.fileExists(\n resizedImageFileName\n );\n\n // if exists, redirect to the resized image\n if (imageExists) {\n const resizedPathOnCdn: string = accessURL + '/' + resizedImageFileName;\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n } else {\n console.log(\n `${process.pid} - ${\n process.env.PORT\n }: Resizing image: ${imageFileName} to ${width} x ${height || ''}`\n );\n //in multicore development, we need to access the site from 127.0.0.1, and so all requests need to go there\n // // if (process.env.NODE_ENV === 'development' && process.env.NUM_WORKER_PROCESSES) {\n // // imageFileName = imageFileName.replace('localhost', '127.0.0.1');\n // // }\n\n // Read the bytes out of the store rather than fetching its public URL.\n //\n // Once `src` has to name an image the store already holds, fetching is\n // a round-trip to ask a web server for a file this process can open --\n // over the loopback interface, for a LocalFileStore. Reading directly\n // is faster, and it means the route makes no outbound request at all:\n // there is no origin to re-check after a redirect, no timeout to tune\n // and no response size to cap, because there is no response.\n const image = await LinkedFileStorage.getFile(storedKey);\n\n // if image is null or empty, return 404\n if (!image?.length) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // get the format of the image\n let format;\n try {\n format = await sharp(image)\n .metadata()\n .then((meta) => meta.format);\n } catch (err) {\n console.warn('Unsupported image format: ' + err);\n res.status(400).send({ error: 'Unsupported image format' });\n return;\n }\n\n // Sharp reads SVG but has no SVG encoder, so `.toFormat('svg')` throws\n // and every resize of an SVG failed. Rasterize to PNG instead — lossless,\n // and it matches the `.png` cache key chosen above.\n const outputFormat = format === 'svg' ? 'png' : format;\n\n // set the output options based on the format for quality and compression\n let outputOptions;\n switch (outputFormat) {\n case 'jpeg':\n outputOptions = { quality: 90 };\n break;\n case 'png':\n outputOptions = { compressionLevel: 9 };\n break;\n case 'webp':\n outputOptions = { quality: 90 };\n break;\n // add more formats here\n default:\n outputOptions = {};\n }\n\n // resize the image\n const resizedImage: Buffer = await sharp(image)\n .resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n )\n .toFormat(outputFormat, outputOptions)\n .toBuffer()\n .catch((err) => {\n console.warn('Could not resize image: ' + err);\n return null;\n });\n\n // if resizedImage is null, return 500\n if (!resizedImage) {\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // upload the resized image to the CDN\n const resizedPathOnCdn = await LinkedFileStorage.saveFile(\n newPathname,\n resizedImage\n );\n\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n }\n } else {\n imageFileName = req.originalUrl.split('/resized/')[1]?.split('?')[0];\n }\n\n // Both halves of this route now read and write through LinkedFileStorage.\n //\n // This branch used to hardcode <cwd>/data/uploads for both, which meant it\n // could only ever work for a LocalFileStore: an app configured with S3 kept\n // its uploads in the bucket, so every request here looked on a local disk\n // that had nothing on it and 404'd. Going through the store also removes the\n // need to create the cache directory by hand -- LocalFileStore.saveFile\n // makes its own parent folders, which is why the mkdirSync that used to sit\n // here (commented out, so it silently did nothing) is gone rather than\n // restored.\n const [trueFileName, ...extensions] = imageFileName.split('.');\n const sourceExtension = extensions.join('.');\n\n // Same rasterization as the branch above: sharp reads SVG but cannot write\n // it. `extension` is what the cached derivative actually IS, and is what\n // `sendStoredFile` types the response with, so it has to be the OUTPUT\n // format rather than the source's.\n const extension =\n sourceExtension.toLowerCase() === 'svg' ? 'png' : sourceExtension;\n\n const resizedKey = path.join(\n path.dirname(imageFileName) === '.' ? '' : path.dirname(imageFileName),\n 'resized',\n `${path.basename(trueFileName)}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }.${extension}`\n );\n\n // The resize cache is its own purpose, so an app can keep derivatives on a\n // local disk while its uploads live in S3, or share one store for both.\n // Unconfigured, it falls back to the default store, which is the previous\n // behaviour for anyone who never thinks about it.\n const cacheStore = getResizedImagesStore();\n const sendStoredFile = async (store: IFileStore, key: string) => {\n const bytes = await store.getFile(key);\n if (!bytes) {\n return false;\n }\n res.type(extension || 'bin').send(bytes);\n return true;\n };\n\n if (await cacheStore.fileExists(resizedKey)) {\n if (await sendStoredFile(cacheStore, resizedKey)) {\n return;\n }\n }\n\n const uploadsStore = LinkedFileStorage.getStore(FileStorePurposes.uploads);\n const original = await uploadsStore.getFile(imageFileName);\n\n if (!original) {\n console.warn('Could not find original image at ' + imageFileName);\n res.status(404).send({ error: 'Could not find original image' });\n return;\n }\n\n let resized: Buffer;\n try {\n const pipeline = sharp(original).resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n );\n // Without this, sharp writes in the INPUT format, which for an SVG source\n // means asking for an encoder it does not have.\n resized = await (sourceExtension.toLowerCase() === 'svg'\n ? pipeline.png({ compressionLevel: 9 })\n : pipeline\n ).toBuffer();\n } catch (err) {\n console.warn('Could not resize image: ' + err);\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // preventDuplicates: false because this is a cache keyed by name. Letting\n // the store pick a fresh name on collision would write a second copy for\n // every request and never hit the cache.\n //\n // A failure here is logged, not fatal: the resize succeeded, so the caller\n // still gets its image and only the caching is lost. It used to be\n // swallowed and then followed by sendFile on a file that was never written,\n // which turned a cache miss into a 404 with nothing in the response to say\n // why -- and, on the error path, into a second send after the 500.\n try {\n await cacheStore.saveFile(resizedKey, resized, {\n preventDuplicates: false,\n });\n } catch (err) {\n console.warn('Could not cache resized image at ' + resizedKey + ': ' + err);\n }\n\n res.type(extension || 'bin').send(resized);\n }\n\n async indexLincdPackage(pkg: string, warnIfNotFound: boolean = false) {\n if (pkg === this.package.name) {\n return;\n }\n try {\n // console.log(`🔍 Loading package: ${pkg}`);\n // console.log(\n // `🔍 Module resolution for ${pkg}:`,\n //@ts-ignore\n // await import.meta.resolve(pkg)\n // );\n // plan-011 §P6 — prefer Vite's SSR loader so workspace packages register\n // on the SINGLE @_linked/core instance the rest of the SSR graph uses.\n // The bare Node `import()` fallback resolves `default`→lib, evaluating a\n // SECOND core copy (benign post-§P1, but a needless second instance).\n // Node import stays as the fallback when Vite isn't active (production /\n // Node-only CLI commands). Mirrors indexPackageBackendProviders.\n const vite: any = (this.config.server as any)?.vite;\n if (vite && typeof vite.ssrLoadModule === 'function') {\n await vite.ssrLoadModule(pkg);\n } else {\n // @vite-ignore — dynamic specifier is intentional: this checks\n // whether `pkg` is resolvable at runtime, then catches the error.\n // eslint-disable-next-line no-unsanitized/method\n await import(/* @vite-ignore */ pkg);\n }\n // console.log(`✅ Successfully loaded: ${pkg}`);\n } catch (e) {\n let providerNotFound =\n e.code === 'MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find package '${pkg}'`) !== -1;\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n chalk.magenta(\n `Could not load package ${pkg}`,\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n )\n );\n }\n } else {\n console.warn(\n chalk.red(\n `Error loading '${pkg}' ${\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n }: ${e.message}\\n`\n ),\n e.stack\n );\n }\n }\n }\n async indexPackageBackendProviders(\n pkg: string,\n warnIfNotFound: boolean = false,\n backendIndexFilePath?: string\n ) {\n if (!backendIndexFilePath) {\n backendIndexFilePath = `${pkg}/backend`;\n }\n let backendProviderExports;\n let genericBackendProvider;\n let shapeProviders = [];\n // Plan-010 phase 4/5: when Vite SSR is active, route module loading\n // through vite.ssrLoadModule. This handles the case where the user app\n // is the consuming workspace itself (self-reference like\n // @semantu/create-now/backend), which Node's ESM resolver can't resolve\n // from inside an installed package like @_linked/server.\n const vite: any = (this.config.server as any)?.vite;\n const loadModule = async (specifier: string) => {\n if (vite && typeof vite.ssrLoadModule === 'function') {\n // For the user app's own backend, resolve to ./src/backend.ts directly.\n // Vite reads the app's package.json exports.development condition.\n if (specifier === `${this.package.name}/backend`) {\n return await vite.ssrLoadModule('/src/backend.ts');\n }\n // Plan-011: ssr.external is now an npm-only allowlist. Workspace\n // packages MUST go through Vite's SSR loader so they share the\n // same module instance as everything else in the SSR call graph\n // (otherwise we get duplicate React contexts, duplicate Linked\n // package registrations, etc).\n //\n // Pre-check whether the specifier actually resolves before\n // calling ssrLoadModule — many packages have no `/backend`\n // export, and ssrLoadModule logs a \"Failed to load url\" error\n // INTERNALLY before throwing, which spams stdout even when the\n // surrounding catch handles it. pluginContainer.resolveId is\n // quiet: it returns null when no plugin can resolve the id.\n try {\n const resolved = await vite.pluginContainer?.resolveId?.(specifier);\n if (!resolved) {\n // Synthesise the same error shape the catch expects so the\n // \"no backend export, that's fine\" branch fires.\n const err: any = new Error(\n `Failed to load url ${specifier} (resolved id: ${specifier}). Does the file exist?`,\n );\n throw err;\n }\n } catch (e: any) {\n // If the pre-check itself errored (e.g. plugin threw on a\n // pkg name it doesn't know), let the call below surface the\n // real error path.\n if (!e?.message?.includes('Failed to load url')) {\n // fall through to ssrLoadModule which will throw + log\n } else {\n throw e;\n }\n }\n return await vite.ssrLoadModule(specifier);\n }\n // No-vite path (e.g. production runtime).\n //\n // The app's own backend cannot be imported by name here. A self-reference\n // resolves only from inside the package that declares it, and this code\n // lives in node_modules/@_linked/server — so Node reports\n // `Cannot find package '<app>'` and every one of the app's Providers\n // silently fails to register. The Vite branch above already works around\n // this; the compiled runtime needs the same treatment, by path.\n if (specifier === `${this.package.name}/backend`) {\n const compiled = path.join(process.cwd(), 'lib', 'backend.js');\n const source = path.join(process.cwd(), 'src', 'backend.ts');\n const target = fsNative.existsSync(compiled) ? compiled : source;\n return await import(/* @vite-ignore */ pathToFileURL(target).href);\n }\n // Fall back to Node's resolver. The dynamic specifier is intentional.\n return await import(/* @vite-ignore */ specifier);\n };\n await loadModule(backendIndexFilePath)\n .then((backendProviderExports) => {\n //instantiate the exported provider classes and add them to the right place\n Object.keys(backendProviderExports).forEach((key) => {\n let providerClass = backendProviderExports[key];\n //always send an instance of the express server\n //TODO: do not create an instance, just save the class and instantiate it when needed\n let provider = new providerClass(this.server, this);\n if (provider instanceof ShapeProvider) {\n shapeProviders.push(provider);\n if (!Object.getOwnPropertyNames(provider).includes('shape')) {\n console.warn(\n chalk.red(`${\n Object.getPrototypeOf(provider).constructor.name\n } in package ${pkg}\n is not properly linked to a shape. Use public shape = SomeShape.`)\n );\n }\n } else {\n if (genericBackendProvider) {\n console.warn(\n `Package ${pkg} exports two generic backend providers. Only one will work`\n );\n } else {\n genericBackendProvider = provider;\n }\n }\n });\n })\n .catch((e) => {\n // Recognize \"no /backend export\" failures across two loader\n // shapes:\n // Node's import() → ERR_MODULE_NOT_FOUND + \"Cannot find module 'X/backend'\"\n // Vite's ssrLoadModule() → \"Failed to load url X/backend\"\n // package `exports` without a ./backend entry (Node + Vite)\n // → 'Missing \"./backend\" specifier in \"X\" package'\n // In either case, missing /backend on a package that doesn't\n // ship a backend is expected; loud-error only on REAL load\n // failures (syntax error inside an existing backend.ts, etc).\n const nodeMatch = e.message.match(/module \\'([^\\']+)'/);\n const viteMatch = e.message.match(/Failed to load url ([^\\s]+)/);\n const matchedSpec = nodeMatch?.[1] ?? viteMatch?.[1];\n const notExported = /Missing \"\\.\\/backend\" specifier in \"[^\"]+\" package/.test(\n e.message\n );\n let providerNotFound =\n notExported ||\n (!!matchedSpec &&\n matchedSpec.includes('/backend') &&\n ((e.code === 'ERR_MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find module`) !== -1) ||\n e.message.indexOf('Failed to load url') !== -1));\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n chalk.magenta(`Could not find backend file of package ${pkg}. \n Check:\\n\n - Make sure backend.ts exists and is included in tsconfig.json\\n\n - Make sure the package name in src/package.ts matches the package name in package.json`)\n );\n }\n } else {\n console.warn(\n chalk.red(\n `Could not load backend file of module '${pkg}' from ${process.cwd()}:\\n`\n ),\n e.stack\n );\n }\n genericBackendProvider = null;\n });\n this.genericProviders.set(pkg, genericBackendProvider);\n this.shapeProviders.set(pkg, shapeProviders);\n return { backendProviderExports, shapeProviders };\n }\n\n /**\n * Plan-011 phase 2 — HMR re-index entry point.\n *\n * Called by the CLI orchestrator's Vite watcher whenever a `.ts`/`.tsx`\n * file inside a workspace package changes. Disposes the package's\n * existing providers (so routes, listeners, timers don't accumulate),\n * drops them from the registry, and re-runs indexPackageBackendProviders\n * to pick up the freshly-imported module.\n *\n * Dispose calls have a 5 s soft timeout. A hanging dispose logs a\n * warning and is abandoned so HMR doesn't stall the whole dev loop.\n */\n /**\n * Install the client-shell catch-all as the last ordinary layer on the\n * router stack. See utils/spaFallback.ts for why ordering has to be\n * re-asserted rather than assumed.\n */\n private installSpaFallback(): void {\n installSpaFallback(\n this.server,\n this.handleErrors(async (req, res) => {\n //make sure the frontend bundle has finished building\n // await this.waitForWebpack();\n this.render(req, res);\n })\n );\n }\n\n async onSourceChange(pkg: string): Promise<void> {\n const disposeWithTimeout = async (p: any, label: string) => {\n if (!p?.dispose) return;\n try {\n await Promise.race([\n Promise.resolve().then(() => p.dispose()),\n new Promise((_, reject) =>\n setTimeout(\n () => reject(new Error(`dispose timeout after 5s`)),\n 5000\n )\n ),\n ]);\n } catch (err: any) {\n console.warn(\n chalk.yellow(`[linked] ${label} dispose failed: ${err.message}`)\n );\n }\n };\n\n const generic = this.genericProviders.get(pkg);\n if (generic) {\n await disposeWithTimeout(generic, `${pkg} generic provider`);\n this.genericProviders.delete(pkg);\n }\n\n const shapeProvs = this.shapeProviders.get(pkg) ?? [];\n for (const p of shapeProvs) {\n await disposeWithTimeout(\n p,\n `${pkg} ${Object.getPrototypeOf(p)?.constructor?.name ?? 'shape provider'}`\n );\n }\n this.shapeProviders.delete(pkg);\n\n await this.indexPackageBackendProviders(pkg, true);\n\n // Run the boot lifecycle on the FRESHLY-loaded provider so it\n // re-registers its Express routes/middleware after dispose. Without\n // this, dispose() tears the old routes off and the new instance is\n // constructed but never gets a chance to register the replacements.\n const fresh = this.genericProviders.get(pkg);\n if (fresh?.setupBeforeControllers) {\n try {\n await fresh.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n chalk.yellow(\n `[linked] ${pkg} setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n const freshShapes = this.shapeProviders.get(pkg) ?? [];\n for (const p of freshShapes) {\n if (p?.setupBeforeControllers) {\n try {\n await p.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n chalk.yellow(\n `[linked] ${pkg} shape-provider setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n }\n\n // Providers just re-registered their routes, which express can only APPEND\n // — i.e. behind the catch-all installed at boot. Put it back at the end so\n // those routes stay reachable. Safe here: every registration above has\n // completed, so no provider is mid-capture of its own layer indices.\n repinSpaFallback(this.server);\n }\n\n async processBackendMethodCall(request, response) {\n this.noCache(response);\n await this.initRequest(request, response);\n let { pkg, method } = request.params;\n let { args } = JSONParser.parseObject<{ args }>(request.body);\n\n return this.callBackendMethod(pkg, method, args, request, response).then(\n (result) => {\n //some methods of backend providers may choose to work with request/response directly and will not return anything\n //so only if a result is returned\n if (typeof result !== 'undefined') {\n //do we convert it to JSON and send it to the frontend\n this.sendJson(response, result);\n } else {\n //in other cases, we still need to close the request and send an empty response\n if (!response.headersSent) {\n this.sendJson(response, null);\n }\n }\n }\n );\n }\n\n noCache(response) {\n response.setHeader('Surrogate-Control', 'no-store');\n response.setHeader(\n 'Cache-Control',\n 'no-store, no-cache, must-revalidate, proxy-revalidate'\n );\n response.setHeader('Expires', '0');\n }\n async processAPICall(\n request,\n response,\n method: 'get' | 'post' | 'put' | 'delete'\n ) {\n this.noCache(response);\n const result = await this.api.process(request, response, method);\n }\n // async processQuery(request, response) {\n //\n // this.api.process(request, response);\n // }\n async processShapeMethodCall(request, response) {\n this.noCache(response);\n // console.log('process shape call');\n // response.on('finish', function() {\n // console.log('shape method call request finish');\n // });\n //\n // response.on('close', function() {\n // console.log('close');\n // });\n //\n // response.on('end', function() {\n // console.log('end');\n // });\n //\n // response.on('header', function() {\n // console.log('header');\n // console.log(response.statusCode);\n // });\n\n await this.initRequest(request, response);\n let { pkg, shape, method } = request.params;\n let { shapeURI, instanceNode, args } = JSONParser.parseObject<{\n shapeURI: string;\n instanceNode: { id: string } | null;\n args: any[];\n }>(request.body);\n\n if (!shapeURI) {\n if (request.query?.shapeURI) {\n shapeURI = request.query?.shapeURI;\n } else {\n response.status(500).send({\n error: 'Invalid server call request: ' + request.originalUrl,\n });\n console.warn(\n chalk.red('Invalid server call request: ' + request.originalUrl)\n );\n return;\n }\n }\n return this.callShapeMethod(\n pkg,\n method,\n shapeURI,\n instanceNode,\n args,\n request,\n response\n ).then((result) => {\n //we return json if something was returned or, if nothing was returned, we still close the request if the method has not accessed response itself already to send things over\n if (typeof result !== 'undefined' || !response.headersSent) {\n this.sendJson(response, result);\n }\n });\n }\n\n async callShapeMethod(\n pkg: string,\n method: string,\n shapeURI: string,\n instanceNode: { id: string } | null,\n args: any[],\n request,\n response\n ) {\n //- index module providers if not done yet\n if (!this.shapeProviders.has(pkg)) {\n await this.indexPackageBackendProviders(pkg, true);\n }\n\n let packageShapeProviders = this.shapeProviders.get(pkg);\n\n let findProviderForShape = (nodeShapeId: string) => {\n return packageShapeProviders.find((provider) => {\n //access the static shape (which is a linkedShape() / Shape class)\n //then access the SHACL NodeShape of that shape class, and its id\n return (\n provider instanceof ShapeProvider &&\n provider.shape?.shape?.id === nodeShapeId\n );\n });\n };\n\n let providerMethodFailed = false;\n try {\n //- find matching provider\n let shapeClass = getShapeClass(shapeURI);\n let shapeProvider: ShapeProvider = shapeClass?.shape\n ? findProviderForShape(shapeClass.shape.id)\n : undefined;\n if (!shapeProvider && shapeClass) {\n let superShapeClasses = getSuperShapesClasses(\n shapeClass as unknown as typeof Shape\n );\n for (let superShapeClass of superShapeClasses) {\n let superShapeProvider = findProviderForShape(\n superShapeClass.shape?.id\n );\n if (superShapeProvider) {\n shapeProvider = superShapeProvider;\n break;\n }\n }\n }\n // No provider for this shape (e.g. it isn't registered on this side).\n // Framework packages are kept single-instance by the cli vite-config's\n // `optimizeDeps.exclude`, so a mismatch here signals a real\n // misconfiguration. Answer 501 (via handleErrorsJson) rather than an empty\n // 200; direct backend callers get a rejected ServerCallError.\n if (!shapeProvider) {\n console.warn(\n `[LinkedServer] callShapeMethod: no provider for '${shapeURI}' ` +\n `(pkg '${pkg}', method '${method}').`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n\n if (shapeProvider) {\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //give the provider a chance to prepare for this request\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(shapeProvider.initRequest(request, response));\n }\n\n //see if the shapeProvider implements the called method\n if (shapeProvider[method]) {\n //prepare the first argument\n //we want to convert the instance node into an instance of the shape that this shapeProvider provides for\n //let's find the shape class\n if (shapeProvider.shape) {\n //instance nodes are not always sent. A shape can also call a shape provider from a static method without a shape instance.\n if (instanceNode) {\n let providerShapeClass = shapeProvider.shape;\n let instance = new (providerShapeClass as any)({\n id: instanceNode.id,\n });\n\n //always send instanceNode as first argument to static provider methods\n args.unshift(instance);\n }\n\n try {\n //call the method with the given arguments\n let result = await Promise.resolve(\n shapeProvider[method].apply(shapeProvider, args)\n );\n return result;\n } catch (e) {\n console.warn(\n `Error whilst calling ${\n Object.getPrototypeOf(shapeProvider).constructor.name\n }.${method}(): `,\n e\n );\n // Rethrow so the HTTP route answers with an error status (via\n // handleErrorsJson) instead of `200 null`, and direct backend\n // callers get a rejected promise.\n providerMethodFailed = true;\n throw e;\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not define its own 'static shape' property. Please connect the provider to a shape.`\n );\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not have a method called ${method}`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n }\n } catch (err) {\n if (!providerMethodFailed && !ServerCallError.is(err)) {\n console.warn(`Error whilst trying to access provider of ${pkg}: `, err);\n }\n throw err;\n }\n return null;\n }\n\n handleErrors(fn) {\n return async function (req, res, next) {\n try {\n return await fn(req, res);\n } catch (x) {\n console.log(x);\n next(x);\n }\n };\n }\n\n handleErrorsJson(fn) {\n return async (req, res, next) => {\n try {\n return await fn(req, res);\n } catch (err) {\n // A ServerCallError (e.g. 501 for a call no provider handles) carries\n // its own status and a message that is safe to send to the client.\n if (ServerCallError.is(err)) {\n return this.sendError(res, err.status, err.message);\n }\n this.sendError(\n res,\n 500,\n 'internal server error' + (isDevelopment ? ': ' + err?.stack : ''),\n 'internal server error: ' + err?.stack\n );\n }\n };\n }\n\n sendError(res, statusCode = 500, message, logMessage?: string) {\n res?.status(statusCode);\n if (message) {\n res?.send({ error: message });\n console.warn(chalk.red(logMessage || message));\n }\n }\n\n /**\n * The stylesheets a dev (Vite) page render needs, inlined into\n * `<style id=\"ssr-css\">` so the first paint is styled before Vite's client\n * injects the same CSS.\n *\n * Scoped to what the app module and the matched routes' pages import\n * statically (see utils/ssrCss `ssrCssScope`). The dev server preloads every\n * page into the module graph, so the whole graph is every page's CSS —\n * megabytes per request in a large app. When the scope cannot be\n * established (no routes config, a route rendered through a function, a\n * module not found) it falls back to the whole graph.\n *\n * Ids are kept in the combined graph's order, so the cascade order of what\n * remains is unchanged.\n */\n private async collectViteSsrCss(\n vite: any,\n App: unknown,\n matchedRoutes: RouteConfig[] | null,\n ): Promise<string> {\n if (!vite?.moduleGraph?.idToModuleMap) return '';\n // Note: Tailwind v4 `@theme` directives in app theme CSS files are\n // NOT processed at SSR collection time — the @tailwindcss/vite\n // plugin expands them at production build only. In dev mode, the\n // theme variables (—color-primary-*, etc.) are injected by Vite's\n // runtime AFTER client hydration, which causes a brief flash of\n // unthemed content (logos render black until ~hydration+200ms).\n // Production (vite build) is unaffected — the static main.css\n // contains expanded :root variables.\n let scope: Set<string> | null = null;\n const ssrGraph = vite.environments?.ssr?.moduleGraph;\n if (ssrGraph?.idToModuleMap && App && matchedRoutes) {\n const pages: unknown[] = [];\n let known = true;\n for (const route of matchedRoutes) {\n const component = await resolveRouteComponent(route);\n if (component === undefined) {\n known = false;\n break;\n }\n if (component !== null) pages.push(component);\n }\n if (known) {\n scope = ssrCssScope(ssrGraph.idToModuleMap.values(), {\n app: App,\n pages,\n });\n }\n }\n // Read only now: resolving a lazy route above can load its page, and the\n // combined graph's id map is a view built when it is read.\n const graphIds = [\n ...(vite.moduleGraph.idToModuleMap as Map<string, unknown>).keys(),\n ];\n const ids = scope ? graphIds.filter((id) => scope!.has(id)) : graphIds;\n // Only real stylesheets, once per file — see utils/ssrCss.\n const inlineUrls = ssrCssInlineUrls(ids, {\n publicDir: vite.config?.publicDir,\n });\n const cssChunks: string[] = [];\n for (const inlineUrl of inlineUrls) {\n try {\n const cssModule = await vite.ssrLoadModule(inlineUrl);\n if (typeof cssModule?.default === 'string') {\n cssChunks.push(cssModule.default);\n }\n } catch {/* skip */}\n }\n return cssChunks.join('\\n');\n }\n\n async render(req, res) {\n res.socket.on('error', (error) => {\n console.error('Fatal socket error', error);\n });\n\n //when render() is called, the request is always an 'initial page request', and the server which will return HTML (so this is a SSR request)\n //in that case we send data back to the frontend in a <script> tag.\n //We initiate that object here\n if (req['frontendData'] == null) {\n req['frontendData'] = {};\n }\n\n //if we are caching this page\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n //if there is a cach for this path, send it\n if (this.cachedPaths.has(req.url)) {\n // console.log(req.url + ': Returning cached path');\n const html = this.cachedPaths.get(req.url);\n // res.setHeader('Content-Type', 'text/html; charset=utf-8');\n // res.setHeader('Content-Length', Buffer.byteLength(html, 'utf8').toString());\n // res.status(200).end(html);\n res.send(html);\n return;\n }\n }\n\n let didError = false;\n\n let App = this.config.server?.loadAppComponent\n ? await this.config.server.loadAppComponent()\n : null;\n\n // Vite dev CSS collection (plan-010 iteration 1 — gap A):\n // 1. Preload the matched route's module via ssrLoadModule so all\n // page-level dependencies (SigninLayout, CreateAccount, etc.)\n // enter Vite's moduleGraph BEFORE we collect CSS. Without this,\n // only App's eager imports are in the graph and lazy routes'\n // CSS would be missing — page renders unstyled until hydration.\n // 2. Once the route is matched, collect the CSS the app and that route's\n // page import (collectViteSsrCss), each loaded via `?inline` (Vite\n // returns the processed CSS as the default export).\n // 3. Inject as inline <style> in HTML head (Html.tsx).\n const vite: any = (this.config.server as any)?.vite;\n // Vite SSR module preload (plan-010 iter1 gap A):\n // Pages are loaded lazily via React.lazy — their modules only enter\n // Vite's moduleGraph after the lazy resolves. For SSR CSS collection\n // we need the page modules in the graph BEFORE the first render of\n // each route. The orchestrator passes a preloadPagesFn that lists\n // all page files (typically via `import.meta.glob`); we call\n // ssrLoadModule on each path once. After the first render of a\n // session everything is cached.\n const preloadPagesFn: any = (this.config.server as any)?.viteSsrPreload;\n if (vite?.ssrLoadModule && preloadPagesFn && !(this as any)._viteSsrPreloaded) {\n try {\n const pagePaths: string[] = await preloadPagesFn();\n for (const p of pagePaths) {\n try {\n await vite.ssrLoadModule(p);\n } catch {/* skip — page may not exist or have ssr errors */}\n }\n } catch {/* ignore */}\n (this as any)._viteSsrPreloaded = true;\n }\n\n await this.initRequest(req, res);\n let { requestLD, requestObject } = await this.getRequestData(req, res);\n\n //on the backend we need to inform the hook of the request-data value\n //on the frontend it will be read from the HTML\n // setRequestData(requestObject);\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n let stream;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timedout = false;\n // const timeout = setTimeout(() => {\n // stream.abort(`${req.url}: ⏱ SSR stream took too long — force abort`);\n // if (!res.headersSent) {\n // res.statusCode = 500;\n // res.end('SSR timed out');\n // }\n // timedout = true;\n // }, 8_000);\n\n let manifest = this.assets.manifest || {};\n let preloadScripts: string[] = [];\n let preloadStyles: string[] = [];\n let matchedRouteKey: string | null = null;\n // Null until the routes config has loaded: without it, what renders is unknown.\n let matchedRoutes: RouteConfig[] | null = null;\n // Plan-010 Vite dev mode: skip preload resolution entirely. Vite\n // handles dynamic import() at runtime — there are no pre-built\n // chunks to preload, and the webpack-shape fallback would pick up\n // stale bundles on disk (public/bundles/*.bundle.js from a prior\n // webpack build) and link them, breaking hydration.\n // The same decision start() made for the `__viteDev` marker. This used\n // to be re-derived from `latestManifest`, which nothing ever set, so it\n // answered \"dev\" whenever Vite was attached — even when start() had\n // chosen the build — and the page mixed built CSS with the dev preamble.\n const usingViteDev = this.viteDevServer;\n\n // Load routes config if available and extract preload chunks for the current route\n if (this.config.server?.loadRoutes) {\n try {\n const routesModule = await this.config.server.loadRoutes();\n const ROUTES: RoutesConfig =\n routesModule.ROUTES ||\n routesModule.default?.ROUTES ||\n (routesModule as RoutesConfig);\n\n // Match the current request path to a route\n let matchedRoute: RouteConfig | null = null;\n const allMatches: RouteConfig[] = [];\n for (const [key, route] of Object.entries(ROUTES)) {\n if (!route?.path) continue;\n const pathPattern = route.path\n .replace(/:\\w+\\??/g, '([^/]+)')\n .replace(/\\*/g, '.*');\n const regex = new RegExp('^' + pathPattern + '$');\n if (regex.test(req.path)) {\n // Every match, not only the first: React Router may pick a more\n // specific route than this first-match loop, and the dev CSS\n // scope must cover whichever page actually renders.\n allMatches.push(route);\n if (!matchedRoute) {\n matchedRoute = route;\n matchedRouteKey = key;\n }\n }\n }\n matchedRoutes = allMatches;\n\n // If we found a matching route with preloadChunks, resolve them to URLs (both JS and CSS).\n // Manifest format detection: Vite manifest entries are objects with .file/.css; webpack\n // manifest entries are bare strings. Try Vite shape first, fall back to webpack.\n // Skip entirely in Vite dev mode — no pre-built chunks exist; Vite handles dynamic\n // imports at runtime.\n if (\n !usingViteDev &&\n matchedRoute?.preloadChunks &&\n Array.isArray(matchedRoute.preloadChunks)\n ) {\n // Both lists are built on the base the entry tags use, so a release\n // served from a CDN preloads its route chunks from that release\n // rather than from this app server. See utils/routeAssets.\n const routeAssets = resolveRouteAssets(\n manifest,\n matchedRoute.preloadChunks,\n this.staticAccessURL,\n );\n preloadScripts = routeAssets.scripts;\n preloadStyles = routeAssets.styles;\n }\n } catch (err) {\n console.warn('Failed to resolve preload chunks:', err);\n }\n }\n\n // Add matched route key to request object for Html component\n req['matchedRouteKey'] = matchedRouteKey;\n\n const ssrCss = await this.collectViteSsrCss(vite, App, matchedRoutes);\n // Per request, and not enumerable: Html reads `assets.__viteSsrCss` for\n // the inline <style>, but also serialises the whole assets object into\n // `assetManifest` for the client, which never uses it. Enumerable, the\n // collected CSS — megabytes in a large app — went into every page twice.\n // A per-request copy also keeps one render's CSS out of another's.\n const assets = { ...this.assets };\n if (ssrCss) {\n Object.defineProperty(assets, '__viteSsrCss', {\n value: ssrCss,\n enumerable: false,\n });\n }\n\n stream = renderToPipeableStream(\n <React.StrictMode>\n <StaticRouter location={req.url}>\n <AppContextProvider\n assets={assets}\n requestLD={requestLD}\n requestObject={requestObject}\n preloadScripts={preloadScripts}\n preloadStyles={preloadStyles}\n expressRequest={req}\n expressResponse={res}\n >\n <App />\n </AppContextProvider>\n </StaticRouter>\n </React.StrictMode>,\n {\n // How the client entry boots — dev preamble, ES module, or classic\n // script. See utils/bootstrapEntry.\n ...resolveBootstrapEntry({\n viteDevServer: usingViteDev,\n mainEntryIsModule: this.mainEntryIsModule,\n mainEntry: this.assets['main.js'],\n }),\n onShellReady: function () {\n res.statusCode = didError ? 500 : 200;\n res.setHeader('Content-type', 'text/html');\n\n // Create a caching transform stream à la mxstbr.com/thoughts/streaming-ssr\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n const bufferedChunks: Buffer[] = [];\n\n const cacheStream = new Transform({\n transform(chunk, _enc, cb) {\n bufferedChunks.push(chunk); // keep a copy\n cb(null, chunk); // forward unchanged\n },\n flush: (cb) => {\n const html = Buffer.concat(bufferedChunks).toString('utf8');\n this.cachedPaths.set(req.url, html);\n if (this.config.server.cacheTimeout) {\n setTimeout(\n () => this.cachedPaths.delete(req.url),\n this.config.server.cacheTimeout\n );\n }\n clearTimeout(timeout); // rendering finished → stop timer\n cb();\n },\n });\n\n // Pipe the caching stream into the real response\n cacheStream.pipe(res);\n\n // React may **only be piped once**, so pipe it to the cacheStream\n stream.pipe(cacheStream);\n } else {\n stream.pipe(res);\n }\n }.bind(this),\n onShellError(x) {\n didError = true;\n console.error(x);\n // Respond NOW. Without this the socket stays open until the 10s\n // watchdog below fires, turning every render-time crash into an\n // opaque \"SSR timed out\" with the real error buried in the log.\n clearTimeout(timeout);\n if (res.headersSent) {\n res.end();\n return;\n }\n res.statusCode = 500;\n res.setHeader('Content-type', 'text/plain');\n res.end(\n 'SSR render failed before the shell was ready:\\n\\n' +\n ((x as any)?.stack ?? (x as any)?.message ?? String(x))\n );\n },\n }\n );\n\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n timeout = setTimeout(() => {\n stream.abort('⏱ SSR stream took too long — force abort');\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end('SSR timed out');\n }\n }, 10_000);\n\n res.on('close', () => {\n clearTimeout(timeout); // if you're using a safety timeout\n });\n }\n\n //If we ever need to use multiple webpack entry-points and different bundle names, then uncomment this\n /*getWebpackAssets()\n\t{\n\t\t// const { devMiddleware } = res.locals.webpack;\n\t\t// const outputFileSystem = devMiddleware.outputFileSystem;\n\t\t// const jsonWebpackStats = devMiddleware.stats.toJson();\n\t\t// const { assetsByChunkName, outputPath } = jsonWebpackStats;\n\t\t//\n\t\t// let normalizedAssets = normalizeAssets(assetsByChunkName.main);\n\t\t// let cssAssets = normalizedAssets\n\t\t// .filter((path) => path.endsWith(\".css\"))\n\t\t// .map((filePath) => outputFileSystem.readFileSync(path.join(outputPath, filePath)))\n\t\t// .join(\"\\n\");\n\t\t//\n\t\t// let jsAssets = normalizeAssets(assetsByChunkName.main)\n\t\t// .filter((path) => path.endsWith(\".js\"))\n\t\t// .map((path) => `<script src=\"${path}\"></script>`)\n\t\t// .join(\"\\n\")}\n\t}*/\n\n sendJson(res, obj) {\n let jsonObject = JSONWriter.toJsObject(obj);\n res.json(jsonObject);\n }\n\n async initRequest(request, response) {\n // initialise the request for all providers, do it synchroniously, one after the other\n let p = Promise.resolve();\n [...this.genericProviders.values()]\n .filter(Boolean)\n .forEach((backendProvider) => {\n p = p\n .then(() => {\n return backendProvider.initRequest(request, response);\n })\n .catch((err) => {\n console.warn(\n `Error during initRequest for provider ${\n Object.getPrototypeOf(backendProvider).constructor.name\n }: `,\n err\n );\n });\n });\n\n return p;\n }\n\n async getRequestData(\n request,\n response\n ): Promise<{ requestLD: string; requestObject: string }> {\n // Phase 1: providers return plain JSON data via supplyDataForRequest.\n // requestLD is kept as empty string for now — SSR data seeding will be\n // reworked in Phase 2/3 to inject query results instead of graph data.\n let requestData: Record<string, any> = {};\n await Promise.all(\n [...this.genericProviders.values()].map((backendProvider) => {\n if (backendProvider) {\n return Promise.resolve(\n backendProvider.supplyDataForRequest(request, response, requestData)\n ).catch((err) => {\n console.warn(\n `Error requesting page-request data from ${\n Object.getPrototypeOf(backendProvider).constructor.name\n }: `,\n err\n );\n });\n }\n })\n );\n\n let requestLD = '';\n let requestObject = JSONWriter.stringify(request['frontendData']);\n return { requestLD, requestObject };\n }\n\n async callBackendMethod(\n pkg: string,\n method: string,\n args: any[],\n request,\n response\n ) {\n if (!this.genericProviders.has(pkg)) {\n await this.indexPackageBackendProviders(pkg, true);\n }\n\n //retrieve the indexed provider class and create a new instance for this request\n let genericBackendProvider = this.genericProviders.get(pkg);\n\n let result;\n if (!genericBackendProvider) {\n console.warn(\n `${chalk.magenta(\n pkg\n )} does not have a generic backend provider. If you can edit this package, make sure 'backend.ts' is included in 'tsconfig.json' and that it exports a provider.`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n //test if there is a matching method in the backend provider\n if (!genericBackendProvider[method]) {\n console.warn(\n `Generic provider '${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n }' of ${pkg} does not have a method called ${method}`\n );\n throw new ServerCallError(501, `No provider for ${pkg}/${method}`);\n }\n\n try {\n //TODO: remove init request.\n //TODO: refactor this.request and this.response to a request parameter\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //initialise the request for this specific provider\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(\n genericBackendProvider.initRequest(request, response)\n );\n }\n // args.push(request);\n // args.push(response);\n\n //call the method with the given arguments and return the result as json\n result = await Promise.resolve(\n genericBackendProvider[method].apply(genericBackendProvider, args)\n );\n } catch (e) {\n console.warn(\n `Error whilst calling ${method}() in provider ${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n } of package ${pkg}:\\n`,\n e\n );\n\n // error logging\n LinkedErrorLogging.log(e);\n // Rethrow so the HTTP route answers with an error status instead of `200 null`.\n throw e;\n }\n return result;\n }\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import '../ontologies/lincd-server.register.js';
2
+ import './LinkedServer.js';
3
+ import './LincdAPI.js';
4
+ import './LincdWebApp.js';
@@ -0,0 +1,8 @@
1
+ // Registers every shape this package defines. Side-effect imports only: a
2
+ // consumer (or the host app) can load this one module to get the full set of
3
+ // shapes registered, without pulling in components, providers or other exports.
4
+ import '../ontologies/lincd-server.register.js';
5
+ import './LinkedServer.js';
6
+ import './LincdAPI.js';
7
+ import './LincdWebApp.js';
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/shapes/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,6EAA6E;AAC7E,gFAAgF;AAChF,OAAO,wCAAwC,CAAC;AAEhD,OAAO,mBAAmB,CAAC;AAC3B,OAAO,eAAe,CAAC;AACvB,OAAO,kBAAkB,CAAC","sourcesContent":["// Registers every shape this package defines. Side-effect imports only: a\n// consumer (or the host app) can load this one module to get the full set of\n// shapes registered, without pulling in components, providers or other exports.\nimport '../ontologies/lincd-server.register.js';\n\nimport './LinkedServer.js';\nimport './LincdAPI.js';\nimport './LincdWebApp.js';\n"]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Boot-time shape materialization: write the shapes this process registered into
3
+ * its app-data dataset as SHACL, via core `syncShapes`.
4
+ *
5
+ * Kept apart from `LinkedServer` so the orphan policy can be tested without
6
+ * booting a server.
7
+ */
8
+ /** The orphan policies a booting server may run with. */
9
+ export type BootOrphanScope = 'all' | 'none';
10
+ /** The subset of core's `syncShapes` this module calls. */
11
+ export type SyncShapesFn = (ds: unknown, options: {
12
+ orphanScope: BootOrphanScope;
13
+ }) => Promise<Array<() => Promise<void>>>;
14
+ /**
15
+ * The orphan policy for boot-time sync.
16
+ *
17
+ * `'none'` unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true`.
18
+ *
19
+ * Boot sync must not delete store shapes the process did not register, because
20
+ * the registry is routinely a subset of what the dataset holds: shapes are
21
+ * deep-importable one file at a time, an app's backend may import no shapes at
22
+ * all, and an app-data dataset also holds shapes other writers put there (Create
23
+ * Now's `bindShape` / `enableCapability`). With pruning on, an app whose backend
24
+ * imports no shapes deletes every NodeShape in its app-data on each boot.
25
+ * `'ownedNamespaces'` is deliberately not offered: a namespace is a whole
26
+ * package, so a deep import of one shape file still prunes the rest of it.
27
+ */
28
+ export declare function bootOrphanScope(env?: Record<string, string | undefined>): BootOrphanScope;
29
+ /**
30
+ * Plan and run a sync of every registered shape into `ds`, in batches of 8 so
31
+ * Fuseki is not flooded. The orphan policy is always passed explicitly — an app
32
+ * may be running a core whose `syncShapes` still defaults to pruning.
33
+ *
34
+ * Logs one line naming the policy that ran.
35
+ */
36
+ export declare function materializeShapes(ds: unknown, syncShapes: SyncShapesFn, { env, log, }?: {
37
+ env?: Record<string, string | undefined>;
38
+ log?: (message: string) => void;
39
+ }): Promise<{
40
+ count: number;
41
+ orphanScope: BootOrphanScope;
42
+ }>;
@@ -1 +1,47 @@
1
+ /**
2
+ * Boot-time shape materialization: write the shapes this process registered into
3
+ * its app-data dataset as SHACL, via core `syncShapes`.
4
+ *
5
+ * Kept apart from `LinkedServer` so the orphan policy can be tested without
6
+ * booting a server.
7
+ */
8
+ /**
9
+ * The orphan policy for boot-time sync.
10
+ *
11
+ * `'none'` unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true`.
12
+ *
13
+ * Boot sync must not delete store shapes the process did not register, because
14
+ * the registry is routinely a subset of what the dataset holds: shapes are
15
+ * deep-importable one file at a time, an app's backend may import no shapes at
16
+ * all, and an app-data dataset also holds shapes other writers put there (Create
17
+ * Now's `bindShape` / `enableCapability`). With pruning on, an app whose backend
18
+ * imports no shapes deletes every NodeShape in its app-data on each boot.
19
+ * `'ownedNamespaces'` is deliberately not offered: a namespace is a whole
20
+ * package, so a deep import of one shape file still prunes the rest of it.
21
+ */
22
+ export function bootOrphanScope(env = process.env) {
23
+ return env.LINKED_SYNC_SHAPES_PRUNE_ORPHANS === 'true' ? 'all' : 'none';
24
+ }
25
+ /**
26
+ * Plan and run a sync of every registered shape into `ds`, in batches of 8 so
27
+ * Fuseki is not flooded. The orphan policy is always passed explicitly — an app
28
+ * may be running a core whose `syncShapes` still defaults to pruning.
29
+ *
30
+ * Logs one line naming the policy that ran.
31
+ */
32
+ export async function materializeShapes(ds, syncShapes, { env = process.env, log = console.log, } = {}) {
33
+ const orphanScope = bootOrphanScope(env);
34
+ const thunks = await syncShapes(ds, { orphanScope });
35
+ for (let i = 0; i < thunks.length; i += 8) {
36
+ await Promise.all(thunks.slice(i, i + 8).map((run) => run()));
37
+ }
38
+ log(orphanScope === 'all'
39
+ ? `[LinkedServer] synced shapes into app-data with orphanScope 'all' ` +
40
+ `(LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true): ${thunks.length} operation(s), ` +
41
+ `store shapes not registered in this process were deleted`
42
+ : `[LinkedServer] synced shapes into app-data with orphanScope 'none': ` +
43
+ `${thunks.length} shape(s) written, no store shapes deleted ` +
44
+ `(set LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true to prune)`);
45
+ return { count: thunks.length, orphanScope };
46
+ }
1
47
  //# sourceMappingURL=syncShapes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"syncShapes.js","sourceRoot":"","sources":["../../../src/utils/syncShapes.ts"],"names":[],"mappings":"","sourcesContent":[""]}
1
+ {"version":3,"file":"syncShapes.js","sourceRoot":"","sources":["../../../src/utils/syncShapes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,eAAe,CAC7B,MAA0C,OAAO,CAAC,GAAG;IAErD,OAAO,GAAG,CAAC,gCAAgC,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;AAC1E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,EAAW,EACX,UAAwB,EACxB,EACE,GAAG,GAAG,OAAO,CAAC,GAAG,EACjB,GAAG,GAAG,OAAO,CAAC,GAAG,MAIf,EAAE;IAEN,MAAM,WAAW,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACzC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,EAAE,EAAE,EAAC,WAAW,EAAC,CAAC,CAAC;IACnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1C,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IAChE,CAAC;IACD,GAAG,CACD,WAAW,KAAK,KAAK;QACnB,CAAC,CAAC,oEAAoE;YAClE,4CAA4C,MAAM,CAAC,MAAM,iBAAiB;YAC1E,0DAA0D;QAC9D,CAAC,CAAC,sEAAsE;YACpE,GAAG,MAAM,CAAC,MAAM,6CAA6C;YAC7D,sDAAsD,CAC7D,CAAC;IACF,OAAO,EAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Boot-time shape materialization: write the shapes this process registered into\n * its app-data dataset as SHACL, via core `syncShapes`.\n *\n * Kept apart from `LinkedServer` so the orphan policy can be tested without\n * booting a server.\n */\n\n/** The orphan policies a booting server may run with. */\nexport type BootOrphanScope = 'all' | 'none';\n\n/** The subset of core's `syncShapes` this module calls. */\nexport type SyncShapesFn = (\n ds: unknown,\n options: {orphanScope: BootOrphanScope},\n) => Promise<Array<() => Promise<void>>>;\n\n/**\n * The orphan policy for boot-time sync.\n *\n * `'none'` unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true`.\n *\n * Boot sync must not delete store shapes the process did not register, because\n * the registry is routinely a subset of what the dataset holds: shapes are\n * deep-importable one file at a time, an app's backend may import no shapes at\n * all, and an app-data dataset also holds shapes other writers put there (Create\n * Now's `bindShape` / `enableCapability`). With pruning on, an app whose backend\n * imports no shapes deletes every NodeShape in its app-data on each boot.\n * `'ownedNamespaces'` is deliberately not offered: a namespace is a whole\n * package, so a deep import of one shape file still prunes the rest of it.\n */\nexport function bootOrphanScope(\n env: Record<string, string | undefined> = process.env,\n): BootOrphanScope {\n return env.LINKED_SYNC_SHAPES_PRUNE_ORPHANS === 'true' ? 'all' : 'none';\n}\n\n/**\n * Plan and run a sync of every registered shape into `ds`, in batches of 8 so\n * Fuseki is not flooded. The orphan policy is always passed explicitly — an app\n * may be running a core whose `syncShapes` still defaults to pruning.\n *\n * Logs one line naming the policy that ran.\n */\nexport async function materializeShapes(\n ds: unknown,\n syncShapes: SyncShapesFn,\n {\n env = process.env,\n log = console.log,\n }: {\n env?: Record<string, string | undefined>;\n log?: (message: string) => void;\n } = {},\n): Promise<{count: number; orphanScope: BootOrphanScope}> {\n const orphanScope = bootOrphanScope(env);\n const thunks = await syncShapes(ds, {orphanScope});\n for (let i = 0; i < thunks.length; i += 8) {\n await Promise.all(thunks.slice(i, i + 8).map((run) => run()));\n }\n log(\n orphanScope === 'all'\n ? `[LinkedServer] synced shapes into app-data with orphanScope 'all' ` +\n `(LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true): ${thunks.length} operation(s), ` +\n `store shapes not registered in this process were deleted`\n : `[LinkedServer] synced shapes into app-data with orphanScope 'none': ` +\n `${thunks.length} shape(s) written, no store shapes deleted ` +\n `(set LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true to prune)`,\n );\n return {count: thunks.length, orphanScope};\n}\n"]}
package/package.json CHANGED
@@ -10,8 +10,8 @@
10
10
  "type": "git",
11
11
  "url": "git+https://github.com/linked-fw/server.git"
12
12
  },
13
- "version": "2.14.2",
14
- "packageManager": "npm@11.19.1",
13
+ "version": "2.15.0",
14
+ "packageManager": "npm@11.20.0",
15
15
  "linkedPackage": true,
16
16
  "type": "module",
17
17
  "main": "lib/esm/index.js",
@@ -64,8 +64,8 @@
64
64
  "webpack-hot-middleware": "^2.26.1"
65
65
  },
66
66
  "devDependencies": {
67
- "@changesets/changelog-github": "^0.5.2",
68
- "@changesets/cli": "^2.29.8",
67
+ "@changesets/changelog-github": "^1.0.0",
68
+ "@changesets/cli": "^3.0.0",
69
69
  "@jest/globals": "^29.7.0",
70
70
  "@types/jest": "^29.5.14",
71
71
  "@types/node": "^20.12.7",