@nicia-ai/typegraph 0.66.1 → 0.67.1
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 +24 -0
- package/README.md +15 -0
- package/dist/backend/drizzle/engine/index.cjs +6 -6
- package/dist/backend/drizzle/engine/index.js +1 -1
- package/dist/backend/postgres/index.cjs +15 -15
- package/dist/backend/postgres/index.js +1 -1
- package/dist/backend/postgres/pglite-store.cjs +1 -1
- package/dist/backend/postgres/pglite-store.js +1 -1
- package/dist/backend/postgres/pglite.cjs +3 -3
- package/dist/backend/postgres/pglite.js +2 -2
- package/dist/backend/sqlite/index.cjs +14 -14
- package/dist/backend/sqlite/index.js +1 -1
- package/dist/backend/sqlite/libsql.cjs +6 -6
- package/dist/backend/sqlite/libsql.js +1 -1
- package/dist/backend/sqlite/local-store.cjs +1 -1
- package/dist/backend/sqlite/local-store.js +1 -1
- package/dist/backend/sqlite/local.cjs +3 -3
- package/dist/backend/sqlite/local.js +2 -2
- package/dist/{chunk-TR7QTODF.js → chunk-55DGFZYC.js} +3 -3
- package/dist/{chunk-TR7QTODF.js.map → chunk-55DGFZYC.js.map} +1 -1
- package/dist/{chunk-WB55URNM.js → chunk-6CKSTY2D.js} +7 -3
- package/dist/chunk-6CKSTY2D.js.map +1 -0
- package/dist/{chunk-ZONDBN6H.js → chunk-6DY26DPE.js} +3 -3
- package/dist/{chunk-ZONDBN6H.js.map → chunk-6DY26DPE.js.map} +1 -1
- package/dist/{chunk-YHMXF7OZ.js → chunk-6J3VUPI6.js} +3 -3
- package/dist/{chunk-YHMXF7OZ.js.map → chunk-6J3VUPI6.js.map} +1 -1
- package/dist/{chunk-MN325MG4.cjs → chunk-7MQL7FEN.cjs} +11 -2
- package/dist/chunk-7MQL7FEN.cjs.map +1 -0
- package/dist/{chunk-WWSYGZED.cjs → chunk-E6XL3KMZ.cjs} +6 -6
- package/dist/{chunk-WWSYGZED.cjs.map → chunk-E6XL3KMZ.cjs.map} +1 -1
- package/dist/{chunk-SSDHR2C2.js → chunk-EFSXK3DW.js} +3 -3
- package/dist/{chunk-SSDHR2C2.js.map → chunk-EFSXK3DW.js.map} +1 -1
- package/dist/{chunk-2DJKHZQ4.js → chunk-EORFWD6O.js} +11 -2
- package/dist/chunk-EORFWD6O.js.map +1 -0
- package/dist/{chunk-Y4X6ODVY.cjs → chunk-FS2GVO2T.cjs} +56 -56
- package/dist/{chunk-Y4X6ODVY.cjs.map → chunk-FS2GVO2T.cjs.map} +1 -1
- package/dist/{chunk-K7YACILO.cjs → chunk-GXHEGNI6.cjs} +9 -9
- package/dist/{chunk-K7YACILO.cjs.map → chunk-GXHEGNI6.cjs.map} +1 -1
- package/dist/{chunk-BX42F7IJ.cjs → chunk-SSDLQPMY.cjs} +7 -2
- package/dist/chunk-SSDLQPMY.cjs.map +1 -0
- package/dist/{chunk-ANMCKLZQ.cjs → chunk-ZRIXU33S.cjs} +12 -12
- package/dist/{chunk-ANMCKLZQ.cjs.map → chunk-ZRIXU33S.cjs.map} +1 -1
- package/dist/graph-merge/index.cjs +500 -26
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +384 -2
- package/dist/graph-merge/index.d.ts +384 -2
- package/dist/graph-merge/index.js +485 -15
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/index.cjs +63 -63
- package/dist/index.js +3 -3
- package/dist/{local-store-impl-ERPNYOCL.js → local-store-impl-CCMWTLGY.js} +6 -6
- package/dist/{local-store-impl-ERPNYOCL.js.map → local-store-impl-CCMWTLGY.js.map} +1 -1
- package/dist/{local-store-impl-OUINMCYI.cjs → local-store-impl-GI6S4J6B.cjs} +9 -9
- package/dist/{local-store-impl-OUINMCYI.cjs.map → local-store-impl-GI6S4J6B.cjs.map} +1 -1
- package/dist/{pglite-store-impl-Z3SOOP75.cjs → pglite-store-impl-HAPAJUIO.cjs} +9 -9
- package/dist/{pglite-store-impl-Z3SOOP75.cjs.map → pglite-store-impl-HAPAJUIO.cjs.map} +1 -1
- package/dist/{pglite-store-impl-DUJBQZS5.js → pglite-store-impl-HDLFOZWS.js} +6 -6
- package/dist/{pglite-store-impl-DUJBQZS5.js.map → pglite-store-impl-HDLFOZWS.js.map} +1 -1
- package/dist/schema/index.cjs +27 -27
- package/dist/schema/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-2DJKHZQ4.js.map +0 -1
- package/dist/chunk-BX42F7IJ.cjs.map +0 -1
- package/dist/chunk-MN325MG4.cjs.map +0 -1
- package/dist/chunk-WB55URNM.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk7MQL7FEN_cjs = require('./chunk-7MQL7FEN.cjs');
|
|
4
4
|
var chunkI7SBZJI2_cjs = require('./chunk-I7SBZJI2.cjs');
|
|
5
5
|
var chunk6JRVV2SS_cjs = require('./chunk-6JRVV2SS.cjs');
|
|
6
6
|
var chunk7XYPLAPL_cjs = require('./chunk-7XYPLAPL.cjs');
|
|
@@ -20,7 +20,7 @@ async function loadDefaultPgvectorExtension() {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
async function createLocalPgliteBackend(options = {}) {
|
|
23
|
-
const tables2 = options.tables ??
|
|
23
|
+
const tables2 = options.tables ?? chunk7MQL7FEN_cjs.tables;
|
|
24
24
|
const vectorExtension = options.vector === false ? void 0 : options.vector ?? await loadDefaultPgvectorExtension();
|
|
25
25
|
const vectorEnabled = vectorExtension !== void 0;
|
|
26
26
|
const client = await pglite.PGlite.create({
|
|
@@ -28,10 +28,10 @@ async function createLocalPgliteBackend(options = {}) {
|
|
|
28
28
|
...vectorExtension === void 0 ? {} : { extensions: { vector: vectorExtension } }
|
|
29
29
|
});
|
|
30
30
|
try {
|
|
31
|
-
const migrationSql = vectorEnabled ?
|
|
31
|
+
const migrationSql = vectorEnabled ? chunk7MQL7FEN_cjs.generatePostgresMigrationSQL(tables2, options.fulltext) : chunk7MQL7FEN_cjs.generateVectorlessPostgresMigrationSQL(tables2, options.fulltext);
|
|
32
32
|
await client.exec(migrationSql);
|
|
33
33
|
const db = pglite$1.drizzle(client);
|
|
34
|
-
const backend =
|
|
34
|
+
const backend = chunk7MQL7FEN_cjs.createPostgresBackend(db, {
|
|
35
35
|
...options.schemaProvisioning === void 0 ? {} : { schemaProvisioning: options.schemaProvisioning },
|
|
36
36
|
tables: tables2,
|
|
37
37
|
...vectorEnabled ? {} : { vector: false },
|
|
@@ -51,5 +51,5 @@ async function createLocalPgliteBackend(options = {}) {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
exports.createLocalPgliteBackend = createLocalPgliteBackend;
|
|
54
|
-
//# sourceMappingURL=chunk-
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
//# sourceMappingURL=chunk-E6XL3KMZ.cjs.map
|
|
55
|
+
//# sourceMappingURL=chunk-E6XL3KMZ.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/postgres/pglite.ts"],"names":["ConfigurationError","tables","PGlite","generatePostgresMigrationSQL","generateVectorlessPostgresMigrationSQL","drizzle","createPostgresBackend","wrapWithManagedClose","markBundledRootAutocommitEligible","closeAfterFailure"],"mappings":";;;;;;;;;AAsJA,eAAe,4BAAA,GAAmD;AAChE,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAU,MAAM,OAAO,+BAA+B,CAAA;AAC5D,IAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,EACjB,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,2PAAA;AAAA,MAIA,EAAE,OAAA,EAAS,QAAA,EAAU,UAAA,EAAY,+BAAA,EAAgC;AAAA,MACjE,EAAE,OAAO,KAAA;AAAM,KACjB;AAAA,EACF;AACF;AAoBA,eAAsB,wBAAA,CACpB,OAAA,GAAqC,EAAC,EACH;AACnC,EAAA,MAAMC,OAAAA,GA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MAAM,OAAO,KAAA,EAAM;AAAA,IACrB,CAAC,CAAA;AAED,IAAA,OAAO;AAAA,MACL,OAAA,EAASC,oDAAkC,cAAc,CAAA;AAAA,MACzD,EAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,OAAOC,mCAAA,CAAkB,QAAQ,KAAK,CAAA;AAAA,EACxC;AACF","file":"chunk-WWSYGZED.cjs","sourcesContent":["/**\n * Local PGlite backend — Postgres-in-WASM, running in-process.\n *\n * [PGlite](https://pglite.dev/) is a full Postgres compiled to WebAssembly\n * that runs inside the Node/Bun/Deno/browser process with no server and no\n * native addon. This is the batteries-included Postgres analog of\n * `createLocalSqliteBackend`: it constructs a PGlite instance, loads the\n * pgvector extension, runs the schema DDL, and returns a ready\n * `{ backend, db }` pair whose `close()` disposes the engine.\n *\n * `@electric-sql/pglite` is an optional peer dependency. Vector support\n * additionally needs `@electric-sql/pglite-pgvector` (PGlite ≥ 0.5 ships\n * pgvector as a separate package). Install what you need:\n *\n * ```bash\n * pnpm add @electric-sql/pglite @electric-sql/pglite-pgvector\n * ```\n *\n * @example In-memory database (default, vector enabled)\n * ```typescript\n * import { createLocalPgliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/postgres/pglite\";\n *\n * const { backend } = await createLocalPgliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example Persistent on-disk database\n * ```typescript\n * const { backend, db } = await createLocalPgliteBackend({ dataDir: \"./pgdata\" });\n * ```\n *\n * @example No vector support (skip the pgvector extension)\n * ```typescript\n * const { backend } = await createLocalPgliteBackend({ vector: false });\n * ```\n *\n * PGlite is single-connection and serial: there is no pooling, so concurrent\n * `store.transaction()` calls queue rather than run in parallel.\n */\nimport { type Extension, PGlite } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { type FulltextStrategy } from \"../../query/dialect/fulltext-strategy\";\nimport { markBundledRootAutocommitEligible } from \"../capabilities/autocommit-single-statement\";\nimport { wrapWithManagedClose } from \"../derive-backend\";\nexport type { GraphIdentityConfig } from \"../../core/define-graph\";\nimport {\n generatePostgresMigrationSQL,\n generateVectorlessPostgresMigrationSQL,\n} from \"../drizzle/ddl\";\nimport { type AnyPgTransaction } from \"../drizzle/execution\";\nexport type { AnyPgDatabase, AnyPgTransaction } from \"../drizzle/execution\";\nimport {\n createPostgresBackend,\n type PostgresTables,\n tables as defaultTables,\n} from \"../drizzle/postgres\";\nimport {\n type AdapterBackend,\n closeAfterFailure,\n type SchemaProvisioning,\n} from \"../types\";\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a local PGlite backend.\n */\nexport type LocalPgliteBackendOptions = Readonly<{\n /**\n * PGlite data directory. Omit for an in-memory database (the default).\n * Accepts any PGlite data-dir spec: a filesystem path (`\"./pgdata\"`),\n * `\"memory://\"`, or a browser/runtime-specific scheme such as\n * `\"idb://my-db\"`.\n */\n dataDir?: string;\n\n /**\n * Custom table definitions. Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n\n /**\n * Controls the pgvector stack:\n *\n * - **omitted (default)** — load pgvector from `@electric-sql/pglite-pgvector`\n * and run `CREATE EXTENSION vector`, so embedding fields work out of the\n * box. Throws a {@link ConfigurationError} if the package isn't installed.\n * - **`false`** — skip the extension entirely; the backend advertises no\n * vector capability (mirroring a SQLite connection without sqlite-vec).\n * Use when a graph carries no embeddings, or to avoid the extension dep.\n * - **a PGlite `Extension`** — bring your own pgvector build or custom\n * extension packaging. Decouples this helper from a specific pgvector\n * package version.\n */\n vector?: false | Extension;\n\n /**\n * Override the fulltext strategy. Defaults to `tsvectorStrategy`. Pass\n * `false` to disable fulltext support entirely — the backend then\n * advertises no `capabilities.fulltext` and omits the fulltext CRUD/search\n * methods, and the installation DDL never creates the fulltext table,\n * mirroring `vector: false`.\n */\n fulltext?: FulltextStrategy | false;\n /** Opt in to provisioning within caller-owned schema transactions. */\n schemaProvisioning?: SchemaProvisioning;\n}>;\n\n/**\n * Result of creating a local PGlite backend.\n */\nexport type LocalPgliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore. Its `close()`\n * disposes the underlying PGlite engine.\n */\n backend: AdapterBackend<AnyPgTransaction>;\n\n /**\n * The underlying Drizzle database instance. Useful for direct SQL access.\n */\n db: PgliteDatabase;\n\n /**\n * The raw PGlite instance, for engine-specific operations such as\n * `dumpDataDir()` / `clone()` not surfaced through Drizzle.\n */\n client: PGlite;\n}>;\n\n// ============================================================\n// Vector extension loading\n// ============================================================\n\n/**\n * Dynamically loads the default pgvector extension from\n * `@electric-sql/pglite-pgvector`. Kept as a runtime import so the package\n * stays an optional peer dependency — callers using `vector: false` or\n * supplying their own extension never need it installed.\n */\nasync function loadDefaultPgvectorExtension(): Promise<Extension> {\n try {\n const module_ = await import(\"@electric-sql/pglite-pgvector\");\n return module_.vector;\n } catch (error) {\n throw new ConfigurationError(\n \"createLocalPgliteBackend needs the pgvector extension but \" +\n \"`@electric-sql/pglite-pgvector` could not be loaded. Install it \" +\n \"(`pnpm add @electric-sql/pglite-pgvector`), pass your own `vector` \" +\n \"extension, or set `vector: false` to disable vector support.\",\n { backend: \"pglite\", dependency: \"@electric-sql/pglite-pgvector\" },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a TypeGraph backend backed by an in-process PGlite database.\n *\n * Constructs the PGlite engine (loading pgvector unless disabled), executes\n * the schema DDL, and wires the standard Postgres backend. The returned\n * backend owns the engine: call `backend.close()` to dispose it.\n *\n * For production Postgres, or a PGlite instance you construct yourself,\n * use `createPostgresBackend` directly with your own Drizzle database — the\n * execution fast path detects PGlite and routes it correctly.\n *\n * @param options - Configuration options\n * @returns Backend, Drizzle database, and raw PGlite client\n */\nexport async function createLocalPgliteBackend(\n options: LocalPgliteBackendOptions = {},\n): Promise<LocalPgliteBackendResult> {\n const tables = options.tables ?? defaultTables;\n\n // pgvector lives in the WASM instance, so the extension must be passed at\n // construction — `CREATE EXTENSION vector` alone can't pull it in. An\n // explicitly supplied extension wins; `false` disables; otherwise load the\n // default package.\n const vectorExtension =\n options.vector === false ?\n undefined\n : (options.vector ?? (await loadDefaultPgvectorExtension()));\n const vectorEnabled = vectorExtension !== undefined;\n\n // Construct via the single options-object form (passing `dataDir` as a\n // field), not the positional `create(dataDir, options)` overload: with a\n // leading `undefined` dataDir, that overload silently drops `extensions`\n // (\"extension vector is not available\"). The options form loads them for\n // both the in-memory and on-disk cases.\n const client = await PGlite.create({\n ...(options.dataDir === undefined ? {} : { dataDir: options.dataDir }),\n ...(vectorExtension === undefined ?\n {}\n : { extensions: { vector: vectorExtension } }),\n });\n\n try {\n // `exec` runs a multi-statement batch (DDL + the pgvector `CREATE\n // EXTENSION` when enabled) in one round trip.\n const migrationSql =\n vectorEnabled ?\n generatePostgresMigrationSQL(tables, options.fulltext)\n : generateVectorlessPostgresMigrationSQL(tables, options.fulltext);\n await client.exec(migrationSql);\n\n const db = drizzle(client);\n const backend = createPostgresBackend(db, {\n ...(options.schemaProvisioning === undefined ?\n {}\n : { schemaProvisioning: options.schemaProvisioning }),\n tables,\n ...(vectorEnabled ? {} : { vector: false }),\n ...(options.fulltext === undefined ? {} : { fulltext: options.fulltext }),\n });\n const managedBackend = wrapWithManagedClose(backend, async () => {\n await client.close();\n });\n\n return {\n backend: markBundledRootAutocommitEligible(managedBackend),\n db,\n client,\n };\n } catch (error) {\n return closeAfterFailure(client, error);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/backend/postgres/pglite.ts"],"names":["ConfigurationError","tables","PGlite","generatePostgresMigrationSQL","generateVectorlessPostgresMigrationSQL","drizzle","createPostgresBackend","wrapWithManagedClose","markBundledRootAutocommitEligible","closeAfterFailure"],"mappings":";;;;;;;;;AAsJA,eAAe,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A,MACxC,GAAI,QAAQ,kBAAA,KAAuB,KAAA,CAAA,GACjC,EAAC,GACD,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAmB;AAAA,MACnD,MAAA,EAAAL,OAAAA;AAAA,MACA,GAAI,aAAA,GAAgB,EAAC,GAAI,EAAE,QAAQ,KAAA,EAAM;AAAA,MACzC,GAAI,QAAQ,QAAA,KAAa,KAAA,CAAA,GAAY,EAAC,GAAI,EAAE,QAAA,EAAU,OAAA,CAAQ,QAAA;AAAS,KACxE,CAAA;AACD,IAAA,MAAM,cAAA,GAAiBM,sCAAA,CAAqB,OAAA,EAAS,YAAY;AAC/D,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB,CAAC,CAAA;AAED,IAAA,OAAO;AAAA,MACL,OAAA,EAASC,oDAAkC,cAAc,CAAA;AAAA,MACzD,EAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,OAAOC,mCAAA,CAAkB,QAAQ,KAAK,CAAA;AAAA,EACxC;AACF","file":"chunk-E6XL3KMZ.cjs","sourcesContent":["/**\n * Local PGlite backend — Postgres-in-WASM, running in-process.\n *\n * [PGlite](https://pglite.dev/) is a full Postgres compiled to WebAssembly\n * that runs inside the Node/Bun/Deno/browser process with no server and no\n * native addon. This is the batteries-included Postgres analog of\n * `createLocalSqliteBackend`: it constructs a PGlite instance, loads the\n * pgvector extension, runs the schema DDL, and returns a ready\n * `{ backend, db }` pair whose `close()` disposes the engine.\n *\n * `@electric-sql/pglite` is an optional peer dependency. Vector support\n * additionally needs `@electric-sql/pglite-pgvector` (PGlite ≥ 0.5 ships\n * pgvector as a separate package). Install what you need:\n *\n * ```bash\n * pnpm add @electric-sql/pglite @electric-sql/pglite-pgvector\n * ```\n *\n * @example In-memory database (default, vector enabled)\n * ```typescript\n * import { createLocalPgliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/postgres/pglite\";\n *\n * const { backend } = await createLocalPgliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example Persistent on-disk database\n * ```typescript\n * const { backend, db } = await createLocalPgliteBackend({ dataDir: \"./pgdata\" });\n * ```\n *\n * @example No vector support (skip the pgvector extension)\n * ```typescript\n * const { backend } = await createLocalPgliteBackend({ vector: false });\n * ```\n *\n * PGlite is single-connection and serial: there is no pooling, so concurrent\n * `store.transaction()` calls queue rather than run in parallel.\n */\nimport { type Extension, PGlite } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { type FulltextStrategy } from \"../../query/dialect/fulltext-strategy\";\nimport { markBundledRootAutocommitEligible } from \"../capabilities/autocommit-single-statement\";\nimport { wrapWithManagedClose } from \"../derive-backend\";\nexport type { GraphIdentityConfig } from \"../../core/define-graph\";\nimport {\n generatePostgresMigrationSQL,\n generateVectorlessPostgresMigrationSQL,\n} from \"../drizzle/ddl\";\nimport { type AnyPgTransaction } from \"../drizzle/execution\";\nexport type { AnyPgDatabase, AnyPgTransaction } from \"../drizzle/execution\";\nimport {\n createPostgresBackend,\n type PostgresTables,\n tables as defaultTables,\n} from \"../drizzle/postgres\";\nimport {\n type AdapterBackend,\n closeAfterFailure,\n type SchemaProvisioning,\n} from \"../types\";\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a local PGlite backend.\n */\nexport type LocalPgliteBackendOptions = Readonly<{\n /**\n * PGlite data directory. Omit for an in-memory database (the default).\n * Accepts any PGlite data-dir spec: a filesystem path (`\"./pgdata\"`),\n * `\"memory://\"`, or a browser/runtime-specific scheme such as\n * `\"idb://my-db\"`.\n */\n dataDir?: string;\n\n /**\n * Custom table definitions. Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n\n /**\n * Controls the pgvector stack:\n *\n * - **omitted (default)** — load pgvector from `@electric-sql/pglite-pgvector`\n * and run `CREATE EXTENSION vector`, so embedding fields work out of the\n * box. Throws a {@link ConfigurationError} if the package isn't installed.\n * - **`false`** — skip the extension entirely; the backend advertises no\n * vector capability (mirroring a SQLite connection without sqlite-vec).\n * Use when a graph carries no embeddings, or to avoid the extension dep.\n * - **a PGlite `Extension`** — bring your own pgvector build or custom\n * extension packaging. Decouples this helper from a specific pgvector\n * package version.\n */\n vector?: false | Extension;\n\n /**\n * Override the fulltext strategy. Defaults to `tsvectorStrategy`. Pass\n * `false` to disable fulltext support entirely — the backend then\n * advertises no `capabilities.fulltext` and omits the fulltext CRUD/search\n * methods, and the installation DDL never creates the fulltext table,\n * mirroring `vector: false`.\n */\n fulltext?: FulltextStrategy | false;\n /** Opt in to provisioning within caller-owned schema transactions. */\n schemaProvisioning?: SchemaProvisioning;\n}>;\n\n/**\n * Result of creating a local PGlite backend.\n */\nexport type LocalPgliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore. Its `close()`\n * disposes the underlying PGlite engine.\n */\n backend: AdapterBackend<AnyPgTransaction>;\n\n /**\n * The underlying Drizzle database instance. Useful for direct SQL access.\n */\n db: PgliteDatabase;\n\n /**\n * The raw PGlite instance, for engine-specific operations such as\n * `dumpDataDir()` / `clone()` not surfaced through Drizzle.\n */\n client: PGlite;\n}>;\n\n// ============================================================\n// Vector extension loading\n// ============================================================\n\n/**\n * Dynamically loads the default pgvector extension from\n * `@electric-sql/pglite-pgvector`. Kept as a runtime import so the package\n * stays an optional peer dependency — callers using `vector: false` or\n * supplying their own extension never need it installed.\n */\nasync function loadDefaultPgvectorExtension(): Promise<Extension> {\n try {\n const module_ = await import(\"@electric-sql/pglite-pgvector\");\n return module_.vector;\n } catch (error) {\n throw new ConfigurationError(\n \"createLocalPgliteBackend needs the pgvector extension but \" +\n \"`@electric-sql/pglite-pgvector` could not be loaded. Install it \" +\n \"(`pnpm add @electric-sql/pglite-pgvector`), pass your own `vector` \" +\n \"extension, or set `vector: false` to disable vector support.\",\n { backend: \"pglite\", dependency: \"@electric-sql/pglite-pgvector\" },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a TypeGraph backend backed by an in-process PGlite database.\n *\n * Constructs the PGlite engine (loading pgvector unless disabled), executes\n * the schema DDL, and wires the standard Postgres backend. The returned\n * backend owns the engine: call `backend.close()` to dispose it.\n *\n * For production Postgres, or a PGlite instance you construct yourself,\n * use `createPostgresBackend` directly with your own Drizzle database — the\n * execution fast path detects PGlite and routes it correctly.\n *\n * @param options - Configuration options\n * @returns Backend, Drizzle database, and raw PGlite client\n */\nexport async function createLocalPgliteBackend(\n options: LocalPgliteBackendOptions = {},\n): Promise<LocalPgliteBackendResult> {\n const tables = options.tables ?? defaultTables;\n\n // pgvector lives in the WASM instance, so the extension must be passed at\n // construction — `CREATE EXTENSION vector` alone can't pull it in. An\n // explicitly supplied extension wins; `false` disables; otherwise load the\n // default package.\n const vectorExtension =\n options.vector === false ?\n undefined\n : (options.vector ?? (await loadDefaultPgvectorExtension()));\n const vectorEnabled = vectorExtension !== undefined;\n\n // Construct via the single options-object form (passing `dataDir` as a\n // field), not the positional `create(dataDir, options)` overload: with a\n // leading `undefined` dataDir, that overload silently drops `extensions`\n // (\"extension vector is not available\"). The options form loads them for\n // both the in-memory and on-disk cases.\n const client = await PGlite.create({\n ...(options.dataDir === undefined ? {} : { dataDir: options.dataDir }),\n ...(vectorExtension === undefined ?\n {}\n : { extensions: { vector: vectorExtension } }),\n });\n\n try {\n // `exec` runs a multi-statement batch (DDL + the pgvector `CREATE\n // EXTENSION` when enabled) in one round trip.\n const migrationSql =\n vectorEnabled ?\n generatePostgresMigrationSQL(tables, options.fulltext)\n : generateVectorlessPostgresMigrationSQL(tables, options.fulltext);\n await client.exec(migrationSql);\n\n const db = drizzle(client);\n const backend = createPostgresBackend(db, {\n ...(options.schemaProvisioning === undefined ?\n {}\n : { schemaProvisioning: options.schemaProvisioning }),\n tables,\n ...(vectorEnabled ? {} : { vector: false }),\n ...(options.fulltext === undefined ? {} : { fulltext: options.fulltext }),\n });\n const managedBackend = wrapWithManagedClose(backend, async () => {\n await client.close();\n });\n\n return {\n backend: markBundledRootAutocommitEligible(managedBackend),\n db,\n client,\n };\n } catch (error) {\n return closeAfterFailure(client, error);\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { buildValidatedKindRegistry, serializeSchema, computeSchemaHash } from './chunk-
|
|
1
|
+
import { buildValidatedKindRegistry, serializeSchema, computeSchemaHash } from './chunk-6CKSTY2D.js';
|
|
2
2
|
import { resolveGraphVectorSlots } from './chunk-PC2UBAUB.js';
|
|
3
3
|
import { hasOwnKey } from './chunk-QD2JFTSL.js';
|
|
4
4
|
import { ConfigurationError } from './chunk-GMKPIYHY.js';
|
|
@@ -187,5 +187,5 @@ function graphTemplatesUnsupportedError(backend) {
|
|
|
187
187
|
}
|
|
188
188
|
|
|
189
189
|
export { deserializeSchema, instantiateGraph, instantiateGraphTemplate, registerGraphTemplate };
|
|
190
|
-
//# sourceMappingURL=chunk-
|
|
191
|
-
//# sourceMappingURL=chunk-
|
|
190
|
+
//# sourceMappingURL=chunk-EFSXK3DW.js.map
|
|
191
|
+
//# sourceMappingURL=chunk-EFSXK3DW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema/deserializer.ts","../src/schema/graph-templates.ts"],"names":[],"mappings":";;;;;;AAqFO,SAAS,kBACd,MAAA,EACoB;AACpB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,aAAA,GAAgB,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,SAAS,SAAS,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,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,gCAAA,EAAkC,UAAA;AAAW,GACvD;AACF;AAGO,SAAS,gBAAA,CACd,SACA,MAAA,EAC4C;AAC5C,EAAA,OAAO,wBAAA,CAAyB,SAAS,MAAM,CAAA;AACjD;AAEA,SAAS,+BACP,OAAA,EACoB;AACpB,EAAA,OAAO,IAAI,kBAAA;AAAA,IACT,CAAA,IAAA,EAAO,QAAQ,OAAO,CAAA,kDAAA,CAAA;AAAA,IACtB,EAAE,IAAA,EAAM,6BAAA,EAA+B,OAAA,EAAS,QAAQ,OAAA;AAAQ,GAClE;AACF","file":"chunk-SSDHR2C2.js","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { type NamedOntologyRelation } from \"../ontology/validation\";\nimport { buildValidatedKindRegistry } from \"../registry/build-validated\";\nimport type { KindRegistry } from \"../registry/kind-registry\";\nimport { type EdgeEndpointKinds } from \"../registry/validate-implies\";\nimport { hasOwnKey } from \"../utils/object\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the durable TypeGraph Identity Profile configuration. */\n getIdentity: () => SerializedSchema[\"identity\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a validated KindRegistry by recomputing closures from relations */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n // Own-key reads, for the same reason {@link buildEdgeEndpointKinds} below\n // uses a `Map`: `schema` is parsed out of a stored JSON document and the\n // caller supplies the name, so a raw read hands back an `Object.prototype`\n // member typed as a definition for any name no kind is registered under.\n getNode: (name) =>\n hasOwnKey(schema.nodes, name) ? schema.nodes[name] : undefined,\n getNodeNames: () => nodeNames,\n\n getEdge: (name) =>\n hasOwnKey(schema.edges, name) ? schema.edges[name] : undefined,\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) =>\n hasOwnKey(schema.ontology.metaEdges, name) ?\n schema.ontology.metaEdges[name]\n : undefined,\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getIdentity: () => schema.identity,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromRelations(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized relations.\n *\n * Persisted closures are a legacy inspection artifact. Relations are validated\n * and closures are recomputed so old schemas gain current hardening rules.\n */\nfunction buildRegistryFromRelations(schema: SerializedSchema): KindRegistry {\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map<string, NodeType>();\n const edgeKinds = new Map<string, AnyEdgeType>();\n return buildValidatedKindRegistry({\n nodeKinds,\n edgeKinds,\n ontology: schema.ontology.relations.map(\n (relation): NamedOntologyRelation => ({\n metaEdge: relation.metaEdge,\n from: relation.from,\n to: relation.to,\n }),\n ),\n edgeEndpoints: buildEdgeEndpointKinds(schema.edges),\n ...(schema.identity === undefined ? {} : { identity: schema.identity }),\n });\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n const pairs: { from: string; to: string }[] = [];\n if (def.targetKindsBySource === undefined) {\n for (const fromKind of def.fromKinds) {\n for (const toKind of def.toKinds) {\n pairs.push({ from: fromKind, to: toKind });\n }\n }\n } else {\n for (const [sourceKind, targetKinds] of Object.entries(\n def.targetKindsBySource,\n )) {\n for (const targetKind of targetKinds) {\n pairs.push({ from: sourceKind, to: targetKind });\n }\n }\n }\n result.set(kind, {\n from: def.fromKinds,\n to: def.toKinds,\n pairs,\n });\n }\n return result;\n}\n","import type { GraphBackend, SchemaVersionRow } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { ConfigurationError } from \"../errors\";\nimport { type ReconciledSchema } from \"../store/store\";\nimport { computeSchemaHash, serializeSchema } from \"./serializer\";\n\n/** A locally held handle for a durable server-side graph template. */\nexport type GraphTemplate<G extends GraphDef> = Readonly<{\n id: string;\n reconciled: ReconciledSchema<G>;\n schemaHash: string;\n}>;\n\nexport type InstantiateGraphTemplateResult<G extends GraphDef> = Readonly<{\n status: \"ready\";\n reconciled: ReconciledSchema<G>;\n schema: SchemaVersionRow;\n}>;\n\n/**\n * Registers the fully materialized shape of a verified store as a durable\n * template. The original schema version is retained only as snapshot\n * provenance: every instantiated graph starts at v1 with that final shape.\n */\nexport async function registerGraphTemplate<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ templateId: string; reconciled: ReconciledSchema<G> }>,\n): Promise<GraphTemplate<G>> {\n const register = backend.registerGraphTemplate;\n if (register === undefined) throw graphTemplatesUnsupportedError(backend);\n await backend.assertBaseSchemaCurrent?.();\n const { reconciled } = params;\n if (reconciled.version === undefined || reconciled.hash === undefined) {\n throw new ConfigurationError(\n \"A graph template requires a reconciled schema from a managed or verified Store.\",\n { code: \"GRAPH_TEMPLATE_REQUIRES_RECONCILED_SCHEMA\" },\n );\n }\n if (\n resolveGraphVectorSlots(reconciled.graph).length > 0 &&\n backend.capabilities.vector?.supported === true\n ) {\n throw new ConfigurationError(\n \"Graph templates do not support embedding fields because vector storage is graph-scoped and cannot be instantiated schema-only.\",\n {\n code: \"GRAPH_TEMPLATE_VECTOR_UNSUPPORTED\",\n graphId: reconciled.graph.id,\n },\n {\n suggestion:\n \"Provision the graph through createStoreWithSchema until template instantiation can atomically materialize vector contributions.\",\n },\n );\n }\n const schemaDocument = serializeSchema(reconciled.graph, reconciled.version);\n const schemaHash = await computeSchemaHash(schemaDocument);\n if (schemaHash !== reconciled.hash) {\n throw new ConfigurationError(\n \"Reconciled schema hash does not match its graph snapshot.\",\n { code: \"GRAPH_TEMPLATE_RECONCILED_HASH_MISMATCH\" },\n );\n }\n await register({\n templateId: params.templateId,\n schemaHash,\n schemaDoc: schemaDocument,\n });\n return Object.freeze({\n id: params.templateId,\n reconciled,\n schemaHash,\n });\n}\n\n/**\n * Instantiates the template's final graph shape as target schema v1. Only the\n * target hash crosses the wire; the durable source document stays in the\n * backend template registry and is rebound to `graphId` by one SQL statement.\n */\nexport async function instantiateGraphTemplate<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ template: GraphTemplate<G>; graphId: string }>,\n): Promise<InstantiateGraphTemplateResult<G>> {\n const instantiate = backend.instantiateGraphTemplate;\n if (instantiate === undefined) throw graphTemplatesUnsupportedError(backend);\n await backend.assertBaseSchemaCurrent?.();\n const sourceVersion = params.template.reconciled.version;\n const reconciledHash = params.template.reconciled.hash;\n if (sourceVersion === undefined || reconciledHash === undefined) {\n throw graphTemplateHandleMismatchError(params.template.id);\n }\n const sourceHash = await computeSchemaHash(\n serializeSchema(params.template.reconciled.graph, sourceVersion),\n );\n if (\n sourceHash !== params.template.schemaHash ||\n reconciledHash !== params.template.schemaHash\n ) {\n throw graphTemplateHandleMismatchError(params.template.id);\n }\n const targetGraph: G = Object.freeze({\n ...params.template.reconciled.graph,\n id: params.graphId,\n });\n const targetHash = await computeSchemaHash(serializeSchema(targetGraph, 1));\n const result = await instantiate({\n templateId: params.template.id,\n templateSchemaHash: params.template.schemaHash,\n graphId: params.graphId,\n schemaHash: targetHash,\n });\n if (result.status === \"refused\") {\n throw new ConfigurationError(\n `Graph template instantiation was refused for graph \"${params.graphId}\". The template may be absent, or the graph already has a different schema.`,\n {\n code: \"GRAPH_TEMPLATE_INSTANTIATION_REFUSED\",\n graphId: params.graphId,\n templateId: params.template.id,\n },\n );\n }\n if (\n result.row.graph_id !== params.graphId ||\n result.row.version !== 1 ||\n result.row.schema_hash !== targetHash\n ) {\n throw new ConfigurationError(\n \"Graph template backend returned a schema row that does not match the requested target.\",\n { code: \"GRAPH_TEMPLATE_INVALID_RESULT\", graphId: params.graphId },\n );\n }\n return Object.freeze({\n status: \"ready\",\n reconciled: Object.freeze({\n graph: targetGraph,\n version: result.row.version,\n hash: result.row.schema_hash,\n }),\n schema: result.row,\n });\n}\n\nfunction graphTemplateHandleMismatchError(\n templateId: string,\n): ConfigurationError {\n return new ConfigurationError(\n `Graph template handle \"${templateId}\" does not match its reconciled schema snapshot.`,\n { code: \"GRAPH_TEMPLATE_HANDLE_MISMATCH\", templateId },\n );\n}\n\n/** Short public name for {@link instantiateGraphTemplate}. */\nexport function instantiateGraph<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ template: GraphTemplate<G>; graphId: string }>,\n): Promise<InstantiateGraphTemplateResult<G>> {\n return instantiateGraphTemplate(backend, params);\n}\n\nfunction graphTemplatesUnsupportedError(\n backend: GraphBackend,\n): ConfigurationError {\n return new ConfigurationError(\n `The ${backend.dialect} backend does not support durable graph templates.`,\n { code: \"GRAPH_TEMPLATES_UNSUPPORTED\", dialect: backend.dialect },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema/deserializer.ts","../src/schema/graph-templates.ts"],"names":[],"mappings":";;;;;;AAqFO,SAAS,kBACd,MAAA,EACoB;AACpB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,aAAA,GAAgB,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,SAAS,SAAS,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,aAAa,MAAA,CAAO,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMpB,OAAA,EAAS,CAAC,IAAA,KACR,SAAA,CAAU,MAAA,CAAO,KAAA,EAAO,IAAI,CAAA,GAAI,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,GAAI,MAAA;AAAA,I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,CAAA;AAAA,IACtB,EAAE,IAAA,EAAM,6BAAA,EAA+B,OAAA,EAAS,QAAQ,OAAA;AAAQ,GAClE;AACF","file":"chunk-EFSXK3DW.js","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { type NamedOntologyRelation } from \"../ontology/validation\";\nimport { buildValidatedKindRegistry } from \"../registry/build-validated\";\nimport type { KindRegistry } from \"../registry/kind-registry\";\nimport { type EdgeEndpointKinds } from \"../registry/validate-implies\";\nimport { hasOwnKey } from \"../utils/object\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the durable TypeGraph Identity Profile configuration. */\n getIdentity: () => SerializedSchema[\"identity\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a validated KindRegistry by recomputing closures from relations */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n // Own-key reads, for the same reason {@link buildEdgeEndpointKinds} below\n // uses a `Map`: `schema` is parsed out of a stored JSON document and the\n // caller supplies the name, so a raw read hands back an `Object.prototype`\n // member typed as a definition for any name no kind is registered under.\n getNode: (name) =>\n hasOwnKey(schema.nodes, name) ? schema.nodes[name] : undefined,\n getNodeNames: () => nodeNames,\n\n getEdge: (name) =>\n hasOwnKey(schema.edges, name) ? schema.edges[name] : undefined,\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) =>\n hasOwnKey(schema.ontology.metaEdges, name) ?\n schema.ontology.metaEdges[name]\n : undefined,\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getIdentity: () => schema.identity,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromRelations(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized relations.\n *\n * Persisted closures are a legacy inspection artifact. Relations are validated\n * and closures are recomputed so old schemas gain current hardening rules.\n */\nfunction buildRegistryFromRelations(schema: SerializedSchema): KindRegistry {\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map<string, NodeType>();\n const edgeKinds = new Map<string, AnyEdgeType>();\n return buildValidatedKindRegistry({\n nodeKinds,\n edgeKinds,\n ontology: schema.ontology.relations.map(\n (relation): NamedOntologyRelation => ({\n metaEdge: relation.metaEdge,\n from: relation.from,\n to: relation.to,\n }),\n ),\n edgeEndpoints: buildEdgeEndpointKinds(schema.edges),\n ...(schema.identity === undefined ? {} : { identity: schema.identity }),\n });\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n const pairs: { from: string; to: string }[] = [];\n if (def.targetKindsBySource === undefined) {\n for (const fromKind of def.fromKinds) {\n for (const toKind of def.toKinds) {\n pairs.push({ from: fromKind, to: toKind });\n }\n }\n } else {\n for (const [sourceKind, targetKinds] of Object.entries(\n def.targetKindsBySource,\n )) {\n for (const targetKind of targetKinds) {\n pairs.push({ from: sourceKind, to: targetKind });\n }\n }\n }\n result.set(kind, {\n from: def.fromKinds,\n to: def.toKinds,\n pairs,\n });\n }\n return result;\n}\n","import type { GraphBackend, SchemaVersionRow } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { ConfigurationError } from \"../errors\";\nimport { type ReconciledSchema } from \"../store/store\";\nimport { computeSchemaHash, serializeSchema } from \"./serializer\";\n\n/** A locally held handle for a durable server-side graph template. */\nexport type GraphTemplate<G extends GraphDef> = Readonly<{\n id: string;\n reconciled: ReconciledSchema<G>;\n schemaHash: string;\n}>;\n\nexport type InstantiateGraphTemplateResult<G extends GraphDef> = Readonly<{\n status: \"ready\";\n reconciled: ReconciledSchema<G>;\n schema: SchemaVersionRow;\n}>;\n\n/**\n * Registers the fully materialized shape of a verified store as a durable\n * template. The original schema version is retained only as snapshot\n * provenance: every instantiated graph starts at v1 with that final shape.\n */\nexport async function registerGraphTemplate<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ templateId: string; reconciled: ReconciledSchema<G> }>,\n): Promise<GraphTemplate<G>> {\n const register = backend.registerGraphTemplate;\n if (register === undefined) throw graphTemplatesUnsupportedError(backend);\n await backend.assertBaseSchemaCurrent?.();\n const { reconciled } = params;\n if (reconciled.version === undefined || reconciled.hash === undefined) {\n throw new ConfigurationError(\n \"A graph template requires a reconciled schema from a managed or verified Store.\",\n { code: \"GRAPH_TEMPLATE_REQUIRES_RECONCILED_SCHEMA\" },\n );\n }\n if (\n resolveGraphVectorSlots(reconciled.graph).length > 0 &&\n backend.capabilities.vector?.supported === true\n ) {\n throw new ConfigurationError(\n \"Graph templates do not support embedding fields because vector storage is graph-scoped and cannot be instantiated schema-only.\",\n {\n code: \"GRAPH_TEMPLATE_VECTOR_UNSUPPORTED\",\n graphId: reconciled.graph.id,\n },\n {\n suggestion:\n \"Provision the graph through createStoreWithSchema until template instantiation can atomically materialize vector contributions.\",\n },\n );\n }\n const schemaDocument = serializeSchema(reconciled.graph, reconciled.version);\n const schemaHash = await computeSchemaHash(schemaDocument);\n if (schemaHash !== reconciled.hash) {\n throw new ConfigurationError(\n \"Reconciled schema hash does not match its graph snapshot.\",\n { code: \"GRAPH_TEMPLATE_RECONCILED_HASH_MISMATCH\" },\n );\n }\n await register({\n templateId: params.templateId,\n schemaHash,\n schemaDoc: schemaDocument,\n });\n return Object.freeze({\n id: params.templateId,\n reconciled,\n schemaHash,\n });\n}\n\n/**\n * Instantiates the template's final graph shape as target schema v1. Only the\n * target hash crosses the wire; the durable source document stays in the\n * backend template registry and is rebound to `graphId` by one SQL statement.\n */\nexport async function instantiateGraphTemplate<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ template: GraphTemplate<G>; graphId: string }>,\n): Promise<InstantiateGraphTemplateResult<G>> {\n const instantiate = backend.instantiateGraphTemplate;\n if (instantiate === undefined) throw graphTemplatesUnsupportedError(backend);\n await backend.assertBaseSchemaCurrent?.();\n const sourceVersion = params.template.reconciled.version;\n const reconciledHash = params.template.reconciled.hash;\n if (sourceVersion === undefined || reconciledHash === undefined) {\n throw graphTemplateHandleMismatchError(params.template.id);\n }\n const sourceHash = await computeSchemaHash(\n serializeSchema(params.template.reconciled.graph, sourceVersion),\n );\n if (\n sourceHash !== params.template.schemaHash ||\n reconciledHash !== params.template.schemaHash\n ) {\n throw graphTemplateHandleMismatchError(params.template.id);\n }\n const targetGraph: G = Object.freeze({\n ...params.template.reconciled.graph,\n id: params.graphId,\n });\n const targetHash = await computeSchemaHash(serializeSchema(targetGraph, 1));\n const result = await instantiate({\n templateId: params.template.id,\n templateSchemaHash: params.template.schemaHash,\n graphId: params.graphId,\n schemaHash: targetHash,\n });\n if (result.status === \"refused\") {\n throw new ConfigurationError(\n `Graph template instantiation was refused for graph \"${params.graphId}\". The template may be absent, or the graph already has a different schema.`,\n {\n code: \"GRAPH_TEMPLATE_INSTANTIATION_REFUSED\",\n graphId: params.graphId,\n templateId: params.template.id,\n },\n );\n }\n if (\n result.row.graph_id !== params.graphId ||\n result.row.version !== 1 ||\n result.row.schema_hash !== targetHash\n ) {\n throw new ConfigurationError(\n \"Graph template backend returned a schema row that does not match the requested target.\",\n { code: \"GRAPH_TEMPLATE_INVALID_RESULT\", graphId: params.graphId },\n );\n }\n return Object.freeze({\n status: \"ready\",\n reconciled: Object.freeze({\n graph: targetGraph,\n version: result.row.version,\n hash: result.row.schema_hash,\n }),\n schema: result.row,\n });\n}\n\nfunction graphTemplateHandleMismatchError(\n templateId: string,\n): ConfigurationError {\n return new ConfigurationError(\n `Graph template handle \"${templateId}\" does not match its reconciled schema snapshot.`,\n { code: \"GRAPH_TEMPLATE_HANDLE_MISMATCH\", templateId },\n );\n}\n\n/** Short public name for {@link instantiateGraphTemplate}. */\nexport function instantiateGraph<G extends GraphDef>(\n backend: GraphBackend,\n params: Readonly<{ template: GraphTemplate<G>; graphId: string }>,\n): Promise<InstantiateGraphTemplateResult<G>> {\n return instantiateGraphTemplate(backend, params);\n}\n\nfunction graphTemplatesUnsupportedError(\n backend: GraphBackend,\n): ConfigurationError {\n return new ConfigurationError(\n `The ${backend.dialect} backend does not support durable graph templates.`,\n { code: \"GRAPH_TEMPLATES_UNSUPPORTED\", dialect: backend.dialect },\n );\n}\n"]}
|
|
@@ -3729,6 +3729,15 @@ function buildClearGraph(tables3, graphId, fulltextStrategy) {
|
|
|
3729
3729
|
{
|
|
3730
3730
|
query: sql`DELETE FROM ${tables3.reconciliationMarkers} WHERE ${tables3.reconciliationMarkers.graphId} = ${graphId}`
|
|
3731
3731
|
},
|
|
3732
|
+
// Tolerates absence for the same reason the recorded relations do: the
|
|
3733
|
+
// marker table is provisioned lazily by the materializer's ensure, so a
|
|
3734
|
+
// database that never materialized a contribution has no such table, and
|
|
3735
|
+
// clearing a graph must not become the operation that fails on it.
|
|
3736
|
+
{
|
|
3737
|
+
query: sql`DELETE FROM ${tables3.contributionMaterializations} WHERE ${tables3.contributionMaterializations.graphId} = ${graphId}`,
|
|
3738
|
+
ignoreMissingTable: true,
|
|
3739
|
+
requiredTableName: getTableName(tables3.contributionMaterializations)
|
|
3740
|
+
},
|
|
3732
3741
|
{
|
|
3733
3742
|
query: sql`DELETE FROM ${tables3.schemaVersions} WHERE ${tables3.schemaVersions.graphId} = ${graphId}`
|
|
3734
3743
|
}
|
|
@@ -17460,5 +17469,5 @@ function createTransactionBackend2(options) {
|
|
|
17460
17469
|
}
|
|
17461
17470
|
|
|
17462
17471
|
export { CURRENT_BASE_SCHEMA_VERSION, DERIVABLE_ENGINE_PROFILE_KEYS, ORDERED_AGGREGATE_PROBE_SQL, assertNoLegacyTransactionCapability, buildPostgresEngineProfile, buildSqliteEngineProfile, createPostgresBackend, createPostgresTables, createSqlBackend, createSqliteBackend, createSqliteTables, deriveEngineProfile, edgeClaims, edgeClaims2, edges, edges2, fulltext, generatePostgresDDL, generatePostgresMigrationSQL, generateSqliteDDL, generateSqliteMigrationSQL, generateVectorlessPostgresMigrationSQL, isLocalLibsqlClient, nodes, nodes2, planSqliteEdgeMatchIdentityAdoption, quoteDdlIdentifier, recordedClock, recordedClock2, recordedEdges, recordedEdges2, recordedNodes, recordedNodes2, schemaVersions, schemaVersions2, tables, tables2, uniques, uniques2 };
|
|
17463
|
-
//# sourceMappingURL=chunk-
|
|
17464
|
-
//# sourceMappingURL=chunk-
|
|
17472
|
+
//# sourceMappingURL=chunk-EORFWD6O.js.map
|
|
17473
|
+
//# sourceMappingURL=chunk-EORFWD6O.js.map
|