@anvia/neo4j 1.0.2 → 1.0.4

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.
@@ -0,0 +1,1486 @@
1
+ // src/schema.ts
2
+ import { z } from "zod";
3
+ var reservedPrefix = "__anvia_";
4
+ function defineNeo4jGraphSchema(options) {
5
+ if (Object.keys(options.nodes).length === 0) {
6
+ throw new TypeError("A Neo4j graph schema requires at least one node type.");
7
+ }
8
+ for (const [type, definition] of Object.entries(options.nodes)) {
9
+ assertName(type, "node type");
10
+ assertDescription(definition.description, `node ${type}`);
11
+ if (!(definition.properties instanceof z.ZodObject)) {
12
+ throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);
13
+ }
14
+ assertExactPropertySchema(definition.properties, `node ${type}`);
15
+ if (definition.identity.length === 0 || new Set(definition.identity).size !== definition.identity.length) {
16
+ throw new TypeError(`Node ${type} must declare unique identity properties.`);
17
+ }
18
+ const shape = definition.properties.shape;
19
+ for (const property of definition.identity) {
20
+ assertPropertyName(property);
21
+ if (!(property in shape)) {
22
+ throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);
23
+ }
24
+ }
25
+ for (const property of Object.keys(shape)) assertPropertyName(property);
26
+ }
27
+ for (const [type, definition] of Object.entries(options.relationships)) {
28
+ assertName(type, "relationship type");
29
+ assertDescription(definition.description, `relationship ${type}`);
30
+ if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {
31
+ throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);
32
+ }
33
+ if (!(definition.properties instanceof z.ZodObject)) {
34
+ throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);
35
+ }
36
+ assertExactPropertySchema(definition.properties, `relationship ${type}`);
37
+ const identity = definition.identity ?? [];
38
+ if (new Set(identity).size !== identity.length) {
39
+ throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);
40
+ }
41
+ for (const property of Object.keys(definition.properties.shape)) assertPropertyName(property);
42
+ for (const property of identity) {
43
+ if (!(property in definition.properties.shape)) {
44
+ throw new TypeError(
45
+ `Identity property ${property} is not declared by relationship ${type}.`
46
+ );
47
+ }
48
+ }
49
+ }
50
+ const nodes = Object.fromEntries(
51
+ Object.entries(options.nodes).map(([type, definition]) => [
52
+ type,
53
+ Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) })
54
+ ])
55
+ );
56
+ const relationships = Object.fromEntries(
57
+ Object.entries(options.relationships).map(([type, definition]) => {
58
+ const copy = { ...definition };
59
+ if (definition.identity !== void 0) {
60
+ Object.assign(copy, { identity: Object.freeze([...definition.identity]) });
61
+ }
62
+ return [type, Object.freeze(copy)];
63
+ })
64
+ );
65
+ return Object.freeze({
66
+ nodes: Object.freeze(nodes),
67
+ relationships: Object.freeze(relationships),
68
+ kind: "neo4j-graph-schema"
69
+ });
70
+ }
71
+ function parseNeo4jProperties(value, label) {
72
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
73
+ throw new TypeError(`${label} must be an object of Neo4j property values.`);
74
+ }
75
+ const output = {};
76
+ for (const [key, item] of Object.entries(value)) {
77
+ assertPropertyName(key);
78
+ output[key] = parseNeo4jPropertyValue(item, `${label}.${key}`);
79
+ }
80
+ return output;
81
+ }
82
+ function parseNeo4jPropertyValue(value, label) {
83
+ if (typeof value === "string" || typeof value === "boolean") return value;
84
+ if (typeof value === "number") {
85
+ if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);
86
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
87
+ throw new TypeError(`${label} must be a safe integer.`);
88
+ }
89
+ return value;
90
+ }
91
+ if (Array.isArray(value)) {
92
+ if (value.length === 0) return [];
93
+ const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));
94
+ const type = typeof parsed[0];
95
+ if (!parsed.every((item) => typeof item === type)) {
96
+ throw new TypeError(`${label} must be a homogeneous array.`);
97
+ }
98
+ return parsed;
99
+ }
100
+ throw new TypeError(`${label} is not a supported Neo4j property value.`);
101
+ }
102
+ function parsePrimitive(value, label) {
103
+ const parsed = parseNeo4jPropertyValue(value, label);
104
+ if (typeof parsed === "string" || typeof parsed === "number" || typeof parsed === "boolean") {
105
+ return parsed;
106
+ }
107
+ throw new TypeError(`${label} must be a primitive property value.`);
108
+ }
109
+ function assertName(value, label) {
110
+ if (typeof value !== "string" || value.length === 0) {
111
+ throw new TypeError(`${label} must be a non-empty string.`);
112
+ }
113
+ }
114
+ function assertPropertyName(value) {
115
+ assertName(value, "Neo4j property name");
116
+ if (value.startsWith(reservedPrefix)) {
117
+ throw new TypeError(`Neo4j property names beginning with ${reservedPrefix} are reserved.`);
118
+ }
119
+ }
120
+ function assertDescription(value, label) {
121
+ if (typeof value !== "string" || value.trim().length === 0) {
122
+ throw new TypeError(`${label} requires a non-empty description.`);
123
+ }
124
+ }
125
+ function assertExactPropertySchema(schema, label) {
126
+ const definition = schema._zod.def;
127
+ if (!(definition.catchall instanceof z.ZodNever)) {
128
+ throw new TypeError(`${label} properties must use a strict Zod object schema.`);
129
+ }
130
+ for (const [property, propertySchema] of Object.entries(schema.shape)) {
131
+ assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, /* @__PURE__ */ new Set());
132
+ }
133
+ }
134
+ function assertNonEffectfulSchema(value, label, visited) {
135
+ if (!(value instanceof z.ZodType)) {
136
+ throw new TypeError(`${label} must be a Zod schema.`);
137
+ }
138
+ const schema = value;
139
+ if (visited.has(schema)) return;
140
+ visited.add(schema);
141
+ const definition = schema._zod.def;
142
+ const type = definition.type;
143
+ if (definition.coerce === true || type === "default" || type === "prefault" || type === "catch" || type === "transform" || type === "pipe") {
144
+ throw new TypeError(
145
+ `${label} must not coerce, default, transform, preprocess, or catch values.`
146
+ );
147
+ }
148
+ const checks = definition.checks;
149
+ if (Array.isArray(checks) && checks.some((check) => {
150
+ if (typeof check !== "object" || check === null) return false;
151
+ const internals = check._zod;
152
+ return internals?.def?.check === "overwrite";
153
+ })) {
154
+ throw new TypeError(`${label} must not normalize or overwrite values.`);
155
+ }
156
+ for (const child of schemaChildren(definition)) {
157
+ assertNonEffectfulSchema(child, label, visited);
158
+ }
159
+ }
160
+ function schemaChildren(definition) {
161
+ const children = [];
162
+ for (const key of ["innerType", "element", "left", "right", "rest", "keyType", "valueType"]) {
163
+ const value = definition[key];
164
+ if (value instanceof z.ZodType) children.push(value);
165
+ }
166
+ for (const key of ["options", "items"]) {
167
+ const value = definition[key];
168
+ if (Array.isArray(value)) {
169
+ for (const item of value) if (item instanceof z.ZodType) children.push(item);
170
+ }
171
+ }
172
+ return children;
173
+ }
174
+
175
+ // src/helpers.ts
176
+ import { isInt } from "neo4j-driver";
177
+ function quoteIdentifier(value) {
178
+ if (typeof value !== "string" || value.length === 0) {
179
+ throw new TypeError("Neo4j identifiers must be non-empty strings.");
180
+ }
181
+ if (value.includes("\0")) throw new TypeError("Neo4j identifiers must not contain NUL.");
182
+ return `\`${value.replaceAll("`", "``")}\``;
183
+ }
184
+ function throwIfAborted(signal) {
185
+ if (signal?.aborted) {
186
+ throw abortError();
187
+ }
188
+ }
189
+ function abortError() {
190
+ const error = new Error("The operation was aborted.");
191
+ error.name = "AbortError";
192
+ return error;
193
+ }
194
+ function positiveInteger(value, label, maximum) {
195
+ if (!Number.isSafeInteger(value) || value < 1 || maximum !== void 0 && value > maximum) {
196
+ throw new RangeError(
197
+ `${label} must be a positive safe integer${maximum === void 0 ? "" : ` no greater than ${maximum}`}.`
198
+ );
199
+ }
200
+ return value;
201
+ }
202
+ function finiteScore(value, label) {
203
+ if (value !== void 0 && !Number.isFinite(value))
204
+ throw new RangeError(`${label} must be finite.`);
205
+ }
206
+ function strictProperties(value, label) {
207
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
208
+ throw new TypeError(`${label} must be an object.`);
209
+ }
210
+ const normalized = {};
211
+ for (const [key, item] of Object.entries(value))
212
+ normalized[key] = normalizeDriverValue(item, `${label}.${key}`);
213
+ return parseNeo4jProperties(normalized, label);
214
+ }
215
+ function normalizeDriverValue(value, label) {
216
+ if (isInt(value)) {
217
+ if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);
218
+ return value.toNumber();
219
+ }
220
+ if (Array.isArray(value))
221
+ return value.map((item, index) => normalizeDriverValue(item, `${label}[${index}]`));
222
+ return value;
223
+ }
224
+ function stableObject(value) {
225
+ return JSON.stringify(
226
+ Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)))
227
+ );
228
+ }
229
+
230
+ // src/graph.ts
231
+ import {
232
+ isInt as isInt2
233
+ } from "neo4j-driver";
234
+ var Neo4jKnowledgeGraphBase = class {
235
+ constructor(owner, schema) {
236
+ this.owner = owner;
237
+ this.schema = schema;
238
+ if (schema.kind !== "neo4j-graph-schema" && schema.kind !== "graph-schema") {
239
+ throw new TypeError(
240
+ "Neo4j knowledge graphs require defineGraphSchema() or defineNeo4jGraphSchema()."
241
+ );
242
+ }
243
+ }
244
+ owner;
245
+ schema;
246
+ async validate(options = {}) {
247
+ throwIfAborted(options.abortSignal);
248
+ await this.assertSupportedVersion(options.abortSignal);
249
+ const expected = expectedIndexes(this.seeds);
250
+ const names = [...expected.keys()];
251
+ const result = await this.query(
252
+ "SHOW INDEXES YIELD name, state, type, entityType, labelsOrTypes, properties, options WHERE name IN $names RETURN name, state, type, entityType, labelsOrTypes, properties, options",
253
+ { names },
254
+ options.abortSignal
255
+ );
256
+ const actual = new Map(
257
+ result.records.map((record) => [
258
+ requiredString(record.get("name"), "Neo4j index name"),
259
+ record
260
+ ])
261
+ );
262
+ for (const [name, definition] of expected) {
263
+ const record = actual.get(name);
264
+ if (record === void 0) throw new Error(`Neo4j index ${name} does not exist.`);
265
+ validateIndexRecord(record, definition);
266
+ }
267
+ }
268
+ async query(text, parameters, abortSignal, access = "read") {
269
+ return this.runTransaction(
270
+ access,
271
+ abortSignal,
272
+ async (transaction) => await transaction.run(text, parameters)
273
+ );
274
+ }
275
+ async retrieve(options) {
276
+ const { retrieveGraphContext } = await import("./retrieve-QRQHIVRO.js");
277
+ return retrieveGraphContext({
278
+ ...options,
279
+ graph: this
280
+ });
281
+ }
282
+ async explore(options) {
283
+ const { exploreGraph } = await import("./explore-RA53GFX2.js");
284
+ return exploreGraph(this, options);
285
+ }
286
+ seed(name) {
287
+ const seed = this.seeds[name];
288
+ if (seed === void 0) throw new TypeError(`Unknown Neo4j graph seed: ${name}`);
289
+ return seed;
290
+ }
291
+ async transaction(abortSignal, run) {
292
+ return this.runTransaction("write", abortSignal, run);
293
+ }
294
+ async runTransaction(access, abortSignal, run) {
295
+ throwIfAborted(abortSignal);
296
+ const sessionOptions = {
297
+ defaultAccessMode: access === "read" ? "READ" : "WRITE"
298
+ };
299
+ if (this.owner.database !== void 0) {
300
+ Object.assign(sessionOptions, { database: this.owner.database });
301
+ }
302
+ const session = this.owner.nativeDriver().session(sessionOptions);
303
+ const transaction = session.beginTransaction();
304
+ let rejectAbort;
305
+ const aborted = new Promise((_resolve, reject) => {
306
+ rejectAbort = reject;
307
+ });
308
+ const onAbort = () => {
309
+ rejectAbort?.(abortError());
310
+ };
311
+ abortSignal?.addEventListener("abort", onAbort, { once: true });
312
+ let committing = false;
313
+ try {
314
+ const value = await Promise.race([run(transaction), aborted]);
315
+ throwIfAborted(abortSignal);
316
+ committing = true;
317
+ await transaction.commit();
318
+ return value;
319
+ } catch (error) {
320
+ if (transaction.isOpen()) await transaction.rollback();
321
+ if (!committing && abortSignal?.aborted) throw abortError();
322
+ throw error;
323
+ } finally {
324
+ abortSignal?.removeEventListener("abort", onAbort);
325
+ if (transaction.isOpen()) await transaction.rollback();
326
+ await session.close();
327
+ }
328
+ }
329
+ async assertSupportedVersion(abortSignal) {
330
+ const result = await this.query(
331
+ "CALL dbms.components() YIELD versions RETURN versions[0] AS version LIMIT 1",
332
+ {},
333
+ abortSignal
334
+ );
335
+ const version = result.records[0]?.get("version");
336
+ if (typeof version !== "string") {
337
+ throw new TypeError("Neo4j returned a non-string server version.");
338
+ }
339
+ if (!supportedVersion(version)) {
340
+ throw new Error(`@anvia/neo4j requires Neo4j 2026.01 or newer; received ${version}.`);
341
+ }
342
+ }
343
+ };
344
+ var Neo4jKnowledgeGraph = class extends Neo4jKnowledgeGraphBase {
345
+ evidenceCapability = "none";
346
+ seeds;
347
+ constructor(owner, options) {
348
+ super(owner, options.schema);
349
+ if (Object.keys(options.seeds).length === 0) {
350
+ throw new TypeError("An existing Neo4j knowledge graph requires at least one seed.");
351
+ }
352
+ const seeds = {};
353
+ for (const [name, seed] of Object.entries(options.seeds)) {
354
+ assertName(name, "Neo4j seed name");
355
+ seeds[name] = validateExistingSeed(options.schema, seed);
356
+ }
357
+ this.seeds = Object.freeze(seeds);
358
+ }
359
+ };
360
+ var ManagedNeo4jKnowledgeGraph = class extends Neo4jKnowledgeGraphBase {
361
+ evidenceCapability = "chunks";
362
+ seeds;
363
+ resources;
364
+ name;
365
+ constructor(owner, options) {
366
+ super(owner, options.schema);
367
+ assertName(options.name, "Managed Neo4j graph name");
368
+ this.name = options.name;
369
+ this.resources = validateManagedResources(options.resources);
370
+ let chunks = {
371
+ labels: Object.freeze([this.resources.labels.chunk]),
372
+ vectorIndex: Object.freeze({
373
+ ...this.resources.indexes.chunks.vector,
374
+ property: "__anvia_embedding"
375
+ }),
376
+ entryRelationshipType: "ANVIA_MENTIONS"
377
+ };
378
+ if (this.resources.indexes.chunks.fulltext !== void 0) {
379
+ chunks = {
380
+ ...chunks,
381
+ fulltextIndex: Object.freeze({
382
+ ...this.resources.indexes.chunks.fulltext,
383
+ properties: Object.freeze(["__anvia_text"])
384
+ })
385
+ };
386
+ }
387
+ let entities = {
388
+ labels: Object.freeze([this.resources.labels.entity]),
389
+ vectorIndex: Object.freeze({
390
+ ...this.resources.indexes.entities.vector,
391
+ property: "__anvia_embedding"
392
+ })
393
+ };
394
+ if (this.resources.indexes.entities.fulltext !== void 0) {
395
+ entities = {
396
+ ...entities,
397
+ fulltextIndex: Object.freeze({
398
+ ...this.resources.indexes.entities.fulltext,
399
+ properties: Object.freeze(
400
+ Array.from(this.resources.indexes.entities.fulltext.properties ?? [])
401
+ )
402
+ })
403
+ };
404
+ }
405
+ this.seeds = Object.freeze({
406
+ chunks: Object.freeze(chunks),
407
+ entities: Object.freeze(entities)
408
+ });
409
+ }
410
+ async ensure(options) {
411
+ positiveInteger(options.indexTimeoutMs, "Neo4j index timeout");
412
+ throwIfAborted(options.abortSignal);
413
+ const { labels, indexes } = this.resources;
414
+ const statements = [
415
+ uniquenessConstraint(constraintName(this.name, "document"), labels.document, ["__anvia_id"]),
416
+ uniquenessConstraint(constraintName(this.name, "chunk"), labels.chunk, ["__anvia_id"]),
417
+ uniquenessConstraint(constraintName(this.name, "entity"), labels.entity, ["__anvia_key"]),
418
+ ...Object.entries(this.schema.nodes).map(
419
+ ([type, definition]) => uniquenessConstraint(
420
+ constraintName(this.name, `entity_${type}`),
421
+ type,
422
+ definition.identity
423
+ )
424
+ ),
425
+ vectorIndex(indexes.chunks.vector, labels.chunk),
426
+ vectorIndex(indexes.entities.vector, labels.entity)
427
+ ];
428
+ if (indexes.chunks.fulltext !== void 0) {
429
+ statements.push(fulltextIndex(indexes.chunks.fulltext.name, labels.chunk, ["__anvia_text"]));
430
+ }
431
+ if (indexes.entities.fulltext !== void 0) {
432
+ statements.push(
433
+ fulltextIndex(
434
+ indexes.entities.fulltext.name,
435
+ labels.entity,
436
+ indexes.entities.fulltext.properties ?? []
437
+ )
438
+ );
439
+ }
440
+ for (const statement of statements)
441
+ await this.query(statement, {}, options.abortSignal, "write");
442
+ await this.query(
443
+ "CALL db.awaitIndexes($timeoutSeconds)",
444
+ { timeoutSeconds: Math.ceil(options.indexTimeoutMs / 1e3) },
445
+ options.abortSignal
446
+ );
447
+ await this.validate({ abortSignal: options.abortSignal });
448
+ }
449
+ async validate(options = {}) {
450
+ await super.validate(options);
451
+ const expected = this.expectedConstraints();
452
+ const names = expected.map((constraint) => constraint.name);
453
+ const result = await this.query(
454
+ "SHOW CONSTRAINTS YIELD name, type, entityType, labelsOrTypes, properties WHERE name IN $names RETURN name, type, entityType, labelsOrTypes, properties",
455
+ { names },
456
+ options.abortSignal
457
+ );
458
+ const actual = new Map(
459
+ result.records.map((record) => [
460
+ requiredString(record.get("name"), "Neo4j constraint name"),
461
+ record
462
+ ])
463
+ );
464
+ for (const constraint of expected) {
465
+ const record = actual.get(constraint.name);
466
+ if (record === void 0) {
467
+ throw new Error(`Neo4j constraint ${constraint.name} does not exist.`);
468
+ }
469
+ validateConstraintRecord(record, constraint);
470
+ }
471
+ }
472
+ async replaceDocuments(options) {
473
+ validateReplacement(options, this.resources.indexes, this.schema);
474
+ if (options.documents.length === 0) return emptyWriteResult();
475
+ const documentIds = options.documents.map((document) => document.id);
476
+ const chunksById = new Map(options.chunks.map((chunk) => [chunk.id, chunk.document]));
477
+ const sourceDocuments = (sourceChunkIds) => [
478
+ ...new Set(
479
+ sourceChunkIds.map((chunkId) => {
480
+ const chunk = chunksById.get(chunkId);
481
+ if (chunk === void 0)
482
+ throw new TypeError(`Graph fact references unknown chunk ${chunkId}.`);
483
+ return chunk.documentId;
484
+ })
485
+ )
486
+ ];
487
+ return await this.transaction(options.abortSignal, async (transaction) => {
488
+ const targets = replacementSnapshotTargets(options);
489
+ const before = await snapshotGraphState(
490
+ transaction,
491
+ this.name,
492
+ this.resources.labels,
493
+ targets
494
+ );
495
+ await removeDocuments(
496
+ transaction,
497
+ this.name,
498
+ this.resources.labels,
499
+ documentIds,
500
+ options.orphanEntities
501
+ );
502
+ await writeDocuments(transaction, this.resources.labels, options.documents);
503
+ await writeChunks(transaction, this.resources.labels, options.chunks);
504
+ await writeEntities(
505
+ transaction,
506
+ this.name,
507
+ this.resources.labels.entity,
508
+ options.entities,
509
+ options.conflict,
510
+ sourceDocuments
511
+ );
512
+ await writeMentions(transaction, this.resources.labels, options.mentions);
513
+ await writeRelationships(
514
+ transaction,
515
+ this.name,
516
+ this.resources.labels.entity,
517
+ options.relationships,
518
+ options.conflict,
519
+ sourceDocuments
520
+ );
521
+ const after = await snapshotGraphState(
522
+ transaction,
523
+ this.name,
524
+ this.resources.labels,
525
+ expandSnapshotTargets(targets, before)
526
+ );
527
+ return diffGraphSnapshots(before, after);
528
+ });
529
+ }
530
+ async deleteDocuments(options) {
531
+ validateOrphanPolicy(options.orphanEntities);
532
+ const ids = uniqueIds(options.documentIds, "document");
533
+ if (ids.length === 0) return emptyWriteResult();
534
+ return await this.transaction(options.abortSignal, async (transaction) => {
535
+ const targets = emptySnapshotTargets(ids);
536
+ const before = await snapshotGraphState(
537
+ transaction,
538
+ this.name,
539
+ this.resources.labels,
540
+ targets
541
+ );
542
+ await removeDocuments(
543
+ transaction,
544
+ this.name,
545
+ this.resources.labels,
546
+ ids,
547
+ options.orphanEntities
548
+ );
549
+ const after = await snapshotGraphState(
550
+ transaction,
551
+ this.name,
552
+ this.resources.labels,
553
+ expandSnapshotTargets(targets, before)
554
+ );
555
+ return diffGraphSnapshots(before, after);
556
+ });
557
+ }
558
+ expectedConstraints() {
559
+ return [
560
+ {
561
+ name: constraintName(this.name, "document"),
562
+ label: this.resources.labels.document,
563
+ properties: ["__anvia_id"]
564
+ },
565
+ {
566
+ name: constraintName(this.name, "chunk"),
567
+ label: this.resources.labels.chunk,
568
+ properties: ["__anvia_id"]
569
+ },
570
+ {
571
+ name: constraintName(this.name, "entity"),
572
+ label: this.resources.labels.entity,
573
+ properties: ["__anvia_key"]
574
+ },
575
+ ...Object.entries(this.schema.nodes).map(([type, definition]) => ({
576
+ name: constraintName(this.name, `entity_${type}`),
577
+ label: type,
578
+ properties: definition.identity
579
+ }))
580
+ ];
581
+ }
582
+ };
583
+ function validateExistingSeed(schema, seed) {
584
+ if (seed.nodeTypes.length !== 1) {
585
+ throw new TypeError(
586
+ "Each existing Neo4j seed requires exactly one indexed node type; register additional indexes as separate seeds."
587
+ );
588
+ }
589
+ for (const type of seed.nodeTypes) {
590
+ if (!(type in schema.nodes))
591
+ throw new TypeError(`Neo4j seed references unknown node type ${type}.`);
592
+ }
593
+ validateVectorIndex(seed.vectorIndex);
594
+ assertPropertyName(seed.vectorIndex.property);
595
+ if (seed.fulltextIndex !== void 0) {
596
+ validateFulltextIndex(seed.fulltextIndex, "Existing Neo4j full-text index");
597
+ }
598
+ let registration = {
599
+ labels: Object.freeze([...seed.nodeTypes]),
600
+ vectorIndex: Object.freeze({ ...seed.vectorIndex })
601
+ };
602
+ if (seed.fulltextIndex !== void 0) {
603
+ registration = {
604
+ ...registration,
605
+ fulltextIndex: Object.freeze({
606
+ ...seed.fulltextIndex,
607
+ properties: Object.freeze([...seed.fulltextIndex.properties])
608
+ })
609
+ };
610
+ }
611
+ return Object.freeze(registration);
612
+ }
613
+ function validateManagedResources(resources) {
614
+ const labels = Object.values(resources.labels);
615
+ for (const label of labels) assertName(label, "Neo4j managed label");
616
+ if (new Set(labels).size !== labels.length)
617
+ throw new TypeError("Managed Neo4j graph labels must be distinct.");
618
+ const indexes = [resources.indexes.chunks.vector, resources.indexes.entities.vector];
619
+ for (const index of indexes) validateVectorIndex(index);
620
+ const names = [
621
+ ...indexes.map((index) => index.name),
622
+ resources.indexes.chunks.fulltext?.name,
623
+ resources.indexes.entities.fulltext?.name
624
+ ].filter((name) => name !== void 0);
625
+ if (new Set(names).size !== names.length)
626
+ throw new TypeError("Managed Neo4j index names must be unique.");
627
+ if (resources.indexes.entities.fulltext !== void 0) {
628
+ const properties = resources.indexes.entities.fulltext.properties ?? [];
629
+ if (properties.length === 0)
630
+ throw new TypeError("Entity full-text indexes require explicit properties.");
631
+ }
632
+ if (resources.indexes.chunks.fulltext !== void 0) {
633
+ validateFulltextIndex(
634
+ { ...resources.indexes.chunks.fulltext, properties: ["__anvia_text"] },
635
+ "Chunk full-text index",
636
+ true
637
+ );
638
+ }
639
+ if (resources.indexes.entities.fulltext !== void 0) {
640
+ validateFulltextIndex(
641
+ {
642
+ ...resources.indexes.entities.fulltext,
643
+ properties: resources.indexes.entities.fulltext.properties ?? []
644
+ },
645
+ "Entity full-text index"
646
+ );
647
+ }
648
+ const copyFulltext = (fulltext) => {
649
+ let copy = { ...fulltext };
650
+ if (fulltext.properties !== void 0) {
651
+ copy = { ...copy, properties: Object.freeze([...fulltext.properties]) };
652
+ }
653
+ return Object.freeze(copy);
654
+ };
655
+ let chunks = Object.freeze({
656
+ vector: Object.freeze({ ...resources.indexes.chunks.vector })
657
+ });
658
+ if (resources.indexes.chunks.fulltext !== void 0) {
659
+ chunks = Object.freeze({
660
+ ...chunks,
661
+ fulltext: copyFulltext(resources.indexes.chunks.fulltext)
662
+ });
663
+ }
664
+ let entities = Object.freeze({
665
+ vector: Object.freeze({ ...resources.indexes.entities.vector })
666
+ });
667
+ if (resources.indexes.entities.fulltext !== void 0) {
668
+ entities = Object.freeze({
669
+ ...entities,
670
+ fulltext: copyFulltext(resources.indexes.entities.fulltext)
671
+ });
672
+ }
673
+ return Object.freeze({
674
+ labels: Object.freeze({ ...resources.labels }),
675
+ indexes: Object.freeze({
676
+ chunks,
677
+ entities
678
+ })
679
+ });
680
+ }
681
+ function validateVectorIndex(index) {
682
+ assertName(index.name, "Neo4j vector index name");
683
+ positiveInteger(index.dimensions, "Neo4j vector dimensions", 4096);
684
+ if (index.similarity !== "cosine" && index.similarity !== "euclidean") {
685
+ throw new TypeError("Neo4j vector similarity must be cosine or euclidean.");
686
+ }
687
+ }
688
+ function validateFulltextIndex(index, label, allowReservedProperties = false) {
689
+ assertName(index.name, `${label} name`);
690
+ if (index.properties.length === 0 || new Set(index.properties).size !== index.properties.length) {
691
+ throw new TypeError(`${label} requires unique properties.`);
692
+ }
693
+ for (const property of index.properties) {
694
+ if (allowReservedProperties) assertName(property, `${label} property`);
695
+ else assertPropertyName(property);
696
+ }
697
+ }
698
+ function expectedIndexes(seeds) {
699
+ const expected = /* @__PURE__ */ new Map();
700
+ const register = (index) => {
701
+ const previous = expected.get(index.name);
702
+ if (previous !== void 0 && stableObject(previous) !== stableObject(index)) {
703
+ throw new TypeError(`Neo4j index ${index.name} has conflicting registrations.`);
704
+ }
705
+ expected.set(index.name, index);
706
+ };
707
+ for (const seed of Object.values(seeds)) {
708
+ register({
709
+ kind: "vector",
710
+ name: seed.vectorIndex.name,
711
+ labels: seed.labels,
712
+ properties: [seed.vectorIndex.property],
713
+ dimensions: seed.vectorIndex.dimensions,
714
+ similarity: seed.vectorIndex.similarity
715
+ });
716
+ if (seed.fulltextIndex !== void 0) {
717
+ register({
718
+ kind: "fulltext",
719
+ name: seed.fulltextIndex.name,
720
+ labels: seed.labels,
721
+ properties: seed.fulltextIndex.properties
722
+ });
723
+ }
724
+ }
725
+ return expected;
726
+ }
727
+ function validateIndexRecord(record, expected) {
728
+ const state = requiredString(record.get("state"), `Neo4j index ${expected.name} state`);
729
+ if (state !== "ONLINE") throw new Error(`Neo4j index ${expected.name} is ${state}, not ONLINE.`);
730
+ const type = requiredString(record.get("type"), `Neo4j index ${expected.name} type`);
731
+ const entityType = requiredString(
732
+ record.get("entityType"),
733
+ `Neo4j index ${expected.name} entity type`
734
+ );
735
+ const labels = requiredStringArray(
736
+ record.get("labelsOrTypes"),
737
+ `Neo4j index ${expected.name} labels`
738
+ );
739
+ const properties = requiredStringArray(
740
+ record.get("properties"),
741
+ `Neo4j index ${expected.name} properties`
742
+ );
743
+ if (entityType !== "NODE" || type !== expected.kind.toUpperCase() || !sameStrings(labels, expected.labels) || !sameStrings(properties, expected.properties)) {
744
+ throw new Error(`Neo4j index ${expected.name} does not match its registration.`);
745
+ }
746
+ if (expected.kind === "vector") {
747
+ const options = requiredObject(record.get("options"), `Neo4j index ${expected.name} options`);
748
+ const config = requiredObject(
749
+ options.indexConfig,
750
+ `Neo4j index ${expected.name} vector configuration`
751
+ );
752
+ const dimensions = requiredSafeInteger(
753
+ config["vector.dimensions"],
754
+ `Neo4j index ${expected.name} dimensions`
755
+ );
756
+ const similarity = requiredString(
757
+ config["vector.similarity_function"],
758
+ `Neo4j index ${expected.name} similarity`
759
+ ).toLowerCase();
760
+ if (dimensions !== expected.dimensions || similarity !== expected.similarity) {
761
+ throw new Error(`Neo4j index ${expected.name} has incompatible vector configuration.`);
762
+ }
763
+ }
764
+ }
765
+ function validateConstraintRecord(record, expected) {
766
+ const type = requiredString(record.get("type"), `Neo4j constraint ${expected.name} type`);
767
+ const entityType = requiredString(
768
+ record.get("entityType"),
769
+ `Neo4j constraint ${expected.name} entity type`
770
+ );
771
+ const labels = requiredStringArray(
772
+ record.get("labelsOrTypes"),
773
+ `Neo4j constraint ${expected.name} labels`
774
+ );
775
+ const properties = requiredStringArray(
776
+ record.get("properties"),
777
+ `Neo4j constraint ${expected.name} properties`
778
+ );
779
+ if (entityType !== "NODE" || type !== "UNIQUENESS" || !sameStrings(labels, [expected.label]) || !sameStrings(properties, expected.properties)) {
780
+ throw new Error(`Neo4j constraint ${expected.name} does not match its registration.`);
781
+ }
782
+ }
783
+ function requiredObject(value, label) {
784
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
785
+ throw new TypeError(`${label} must be an object.`);
786
+ }
787
+ return value;
788
+ }
789
+ function requiredStringArray(value, label) {
790
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
791
+ throw new TypeError(`${label} must be a string array.`);
792
+ }
793
+ return [...value];
794
+ }
795
+ function requiredSafeInteger(value, label) {
796
+ if (isInt2(value)) {
797
+ if (!value.inSafeRange()) throw new TypeError(`${label} must be a safe integer.`);
798
+ return value.toNumber();
799
+ }
800
+ if (!Number.isSafeInteger(value)) throw new TypeError(`${label} must be a safe integer.`);
801
+ return value;
802
+ }
803
+ function sameStrings(left, right) {
804
+ if (left.length !== right.length) return false;
805
+ const sortedLeft = [...left].sort();
806
+ const sortedRight = [...right].sort();
807
+ return sortedLeft.every((value, index) => value === sortedRight[index]);
808
+ }
809
+ function supportedVersion(value) {
810
+ const match = /^(\d{4})\.(\d+)/.exec(value);
811
+ if (match === null) return false;
812
+ const year = Number(match[1]);
813
+ const month = Number(match[2]);
814
+ return year > 2026 || year === 2026 && month >= 1;
815
+ }
816
+ function constraintName(graph, resource) {
817
+ return `anvia_${graph}_${resource}_identity`;
818
+ }
819
+ function uniquenessConstraint(name, label, properties) {
820
+ const expression = properties.length === 1 ? `n.${quoteIdentifier(properties[0])}` : `(${properties.map((property) => `n.${quoteIdentifier(property)}`).join(", ")})`;
821
+ return `CREATE CONSTRAINT ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) REQUIRE ${expression} IS UNIQUE`;
822
+ }
823
+ function vectorIndex(index, label) {
824
+ return `CREATE VECTOR INDEX ${quoteIdentifier(index.name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON (n.${quoteIdentifier("__anvia_embedding")}) OPTIONS {indexConfig: {\`vector.dimensions\`: ${index.dimensions}, \`vector.similarity_function\`: '${index.similarity}'}}`;
825
+ }
826
+ function fulltextIndex(name, label, properties) {
827
+ if (properties.length === 0) throw new TypeError(`Full-text index ${name} requires properties.`);
828
+ return `CREATE FULLTEXT INDEX ${quoteIdentifier(name)} IF NOT EXISTS FOR (n:${quoteIdentifier(label)}) ON EACH [${properties.map((property) => `n.${quoteIdentifier(property)}`).join(", ")}]`;
829
+ }
830
+ function validateReplacement(options, indexes, schema) {
831
+ if (!Array.isArray(options.documents) || !Array.isArray(options.chunks) || !Array.isArray(options.entities) || !Array.isArray(options.relationships) || !Array.isArray(options.mentions)) {
832
+ throw new TypeError("Neo4j replacement collections must be arrays.");
833
+ }
834
+ if (options.conflict !== "error" && options.conflict !== "overwrite" && options.conflict !== "keep-existing") {
835
+ throw new TypeError("Neo4j conflict policy must be error, overwrite, or keep-existing.");
836
+ }
837
+ validateOrphanPolicy(options.orphanEntities);
838
+ const documentIds = uniqueIds(
839
+ options.documents.map((document, index) => {
840
+ requiredObject(document, `Neo4j document at index ${index}`);
841
+ return document.id;
842
+ }),
843
+ "document"
844
+ );
845
+ const documentSet = new Set(documentIds);
846
+ const chunkIds = uniqueIds(
847
+ options.chunks.map((chunk, index) => {
848
+ requiredObject(chunk, `Neo4j chunk at index ${index}`);
849
+ requiredObject(chunk.document, `Neo4j chunk document at index ${index}`);
850
+ return chunk.id;
851
+ }),
852
+ "chunk"
853
+ );
854
+ const chunkSet = new Set(chunkIds);
855
+ const entityIds = uniqueIds(
856
+ options.entities.map((entity, index) => {
857
+ requiredObject(entity, `Neo4j entity at index ${index}`);
858
+ requiredObject(entity.document, `Neo4j entity document at index ${index}`);
859
+ return entity.id;
860
+ }),
861
+ "entity"
862
+ );
863
+ const entitySet = new Set(entityIds);
864
+ for (const document of options.documents)
865
+ parseNeo4jProperties(document.properties ?? {}, `document ${document.id}`);
866
+ const chunkPositions = /* @__PURE__ */ new Set();
867
+ for (const chunk of options.chunks) {
868
+ if (!documentSet.has(chunk.document.documentId))
869
+ throw new TypeError(`Chunk ${chunk.id} references an unknown document.`);
870
+ if (chunk.document.id !== chunk.id)
871
+ throw new TypeError(`Embedded chunk ${chunk.id} has a mismatched document id.`);
872
+ if (!Number.isSafeInteger(chunk.document.index) || chunk.document.index < 0) {
873
+ throw new TypeError(`Chunk ${chunk.id} index must be a non-negative safe integer.`);
874
+ }
875
+ if (typeof chunk.document.text !== "string") {
876
+ throw new TypeError(`Chunk ${chunk.id} text must be a string.`);
877
+ }
878
+ const position = `${chunk.document.documentId}\0${chunk.document.index}`;
879
+ if (chunkPositions.has(position)) {
880
+ throw new TypeError(
881
+ `Document ${chunk.document.documentId} contains duplicate chunk index ${chunk.document.index}.`
882
+ );
883
+ }
884
+ chunkPositions.add(position);
885
+ singleEmbedding(chunk.embeddings, indexes.chunks.vector.dimensions, `chunk ${chunk.id}`);
886
+ parseNeo4jProperties(chunk.document.metadata ?? {}, `chunk ${chunk.id} metadata`);
887
+ }
888
+ const entityTypes = /* @__PURE__ */ new Map();
889
+ const entitySourceChunks = /* @__PURE__ */ new Map();
890
+ for (const entity of options.entities) {
891
+ if (entity.document.key !== entity.id)
892
+ throw new TypeError(`Embedded entity ${entity.id} has a mismatched key.`);
893
+ singleEmbedding(entity.embeddings, indexes.entities.vector.dimensions, `entity ${entity.id}`);
894
+ const type = entity.document.type;
895
+ if (typeof type !== "string") throw new TypeError(`Entity ${entity.id} type must be a string.`);
896
+ const definition = schema.nodes[type];
897
+ if (definition === void 0)
898
+ throw new TypeError(`Entity ${entity.id} has unknown type ${type}.`);
899
+ const properties = parseExactSchemaProperties(
900
+ definition.properties,
901
+ entity.document.properties,
902
+ `entity ${entity.id} properties`
903
+ );
904
+ const identity = parseIdentity(entity.document.identity, definition.identity, properties, type);
905
+ const expectedKey = `${type}:${stableObject(identity)}`;
906
+ if (entity.id !== expectedKey) {
907
+ throw new TypeError(`Entity ${entity.id} does not match its canonical identity key.`);
908
+ }
909
+ const sourceChunkIds = validateSourceChunkIds(
910
+ entity.document.sourceChunkIds,
911
+ chunkSet,
912
+ `entity ${entity.id}`
913
+ );
914
+ entityTypes.set(entity.id, type);
915
+ entitySourceChunks.set(entity.id, new Set(sourceChunkIds));
916
+ }
917
+ uniqueIds(
918
+ options.relationships.map((relationship, index) => {
919
+ requiredObject(relationship, `Neo4j relationship at index ${index}`);
920
+ return relationship.key;
921
+ }),
922
+ "relationship"
923
+ );
924
+ for (const relationship of options.relationships) {
925
+ const definition = schema.relationships[relationship.type];
926
+ if (definition === void 0) {
927
+ throw new TypeError(
928
+ `Relationship ${relationship.key} has unknown type ${relationship.type}.`
929
+ );
930
+ }
931
+ if (!entitySet.has(relationship.from) || !entitySet.has(relationship.to)) {
932
+ throw new TypeError(`Relationship ${relationship.key} references an unknown entity.`);
933
+ }
934
+ if (entityTypes.get(relationship.from) !== definition.from || entityTypes.get(relationship.to) !== definition.to) {
935
+ throw new TypeError(`Relationship ${relationship.key} has incompatible endpoint types.`);
936
+ }
937
+ const properties = parseExactSchemaProperties(
938
+ definition.properties,
939
+ relationship.properties,
940
+ `relationship ${relationship.key} properties`
941
+ );
942
+ const identity = identityFromProperties(
943
+ definition.identity ?? [],
944
+ properties,
945
+ relationship.type
946
+ );
947
+ const expectedKey = `${relationship.type}:${relationship.from}->${relationship.to}:${stableObject(identity)}`;
948
+ if (relationship.key !== expectedKey) {
949
+ throw new TypeError(`Relationship ${relationship.key} does not match its canonical key.`);
950
+ }
951
+ const sourceChunkIds = validateSourceChunkIds(
952
+ relationship.sourceChunkIds,
953
+ chunkSet,
954
+ `relationship ${relationship.key}`
955
+ );
956
+ const fromSources = entitySourceChunks.get(relationship.from);
957
+ const toSources = entitySourceChunks.get(relationship.to);
958
+ if (fromSources === void 0 || toSources === void 0 || sourceChunkIds.some((chunkId) => !fromSources.has(chunkId) || !toSources.has(chunkId))) {
959
+ throw new TypeError(
960
+ `Relationship ${relationship.key} source chunks must support both endpoint entities.`
961
+ );
962
+ }
963
+ }
964
+ const mentionKeys = /* @__PURE__ */ new Set();
965
+ const mentionChunksByEntity = /* @__PURE__ */ new Map();
966
+ for (const [index, mention] of options.mentions.entries()) {
967
+ requiredObject(mention, `Neo4j mention at index ${index}`);
968
+ if (!chunkSet.has(mention.chunkId) || !entitySet.has(mention.entityKey)) {
969
+ throw new TypeError(`Mention at index ${index} references an unknown chunk or entity.`);
970
+ }
971
+ const key = `${mention.chunkId}\0${mention.entityKey}`;
972
+ if (mentionKeys.has(key)) throw new TypeError(`Duplicate Neo4j mention at index ${index}.`);
973
+ mentionKeys.add(key);
974
+ const chunks = mentionChunksByEntity.get(mention.entityKey);
975
+ if (chunks === void 0)
976
+ mentionChunksByEntity.set(mention.entityKey, /* @__PURE__ */ new Set([mention.chunkId]));
977
+ else chunks.add(mention.chunkId);
978
+ }
979
+ for (const entityId of entityIds) {
980
+ const sources = Array.from(entitySourceChunks.get(entityId) ?? []);
981
+ const mentions = Array.from(mentionChunksByEntity.get(entityId) ?? []);
982
+ if (!sameStrings(sources, mentions)) {
983
+ throw new TypeError(`Entity ${entityId} source chunks must exactly match its mentions.`);
984
+ }
985
+ }
986
+ }
987
+ function parseExactSchemaProperties(schema, value, label) {
988
+ const input = parseNeo4jProperties(value, label);
989
+ const result = schema.safeParse(value);
990
+ if (!result.success) throw new TypeError(`${label} does not match the graph schema.`);
991
+ const output = parseNeo4jProperties(result.data, `${label} output`);
992
+ if (stableObject(input) !== stableObject(output)) {
993
+ throw new TypeError(`${label} must not be coerced, defaulted, transformed, or stripped.`);
994
+ }
995
+ return input;
996
+ }
997
+ function parseIdentity(value, keys, properties, type) {
998
+ const identity = identityFromProperties(
999
+ keys,
1000
+ parseNeo4jProperties(value, `${type} identity`),
1001
+ type
1002
+ );
1003
+ if (!sameStrings(Object.keys(identity), keys)) {
1004
+ throw new TypeError(`Entity ${type} identity must contain exactly its declared properties.`);
1005
+ }
1006
+ for (const key of keys) {
1007
+ if (identity[key] !== properties[key]) {
1008
+ throw new TypeError(`Entity ${type} identity property ${key} does not match its properties.`);
1009
+ }
1010
+ }
1011
+ return identity;
1012
+ }
1013
+ function identityFromProperties(keys, properties, type) {
1014
+ const identity = {};
1015
+ for (const key of keys) {
1016
+ const value = properties[key];
1017
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
1018
+ throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);
1019
+ }
1020
+ identity[key] = value;
1021
+ }
1022
+ return identity;
1023
+ }
1024
+ function validateSourceChunkIds(value, chunkIds, label) {
1025
+ const ids = uniqueIds(value, `${label} source chunk`);
1026
+ if (ids.length === 0) throw new TypeError(`${label} requires source chunk provenance.`);
1027
+ for (const id of ids) {
1028
+ if (!chunkIds.has(id)) throw new TypeError(`${label} references unknown source chunk ${id}.`);
1029
+ }
1030
+ return ids;
1031
+ }
1032
+ function validateOrphanPolicy(value) {
1033
+ if (value !== "delete" && value !== "keep") {
1034
+ throw new TypeError("Neo4j orphan entity policy must be delete or keep.");
1035
+ }
1036
+ }
1037
+ function singleEmbedding(embeddings, dimensions, label) {
1038
+ if (!Array.isArray(embeddings)) throw new TypeError(`${label} embeddings must be an array.`);
1039
+ if (embeddings.length !== 1) throw new TypeError(`${label} requires exactly one embedding.`);
1040
+ const vector = embeddings[0]?.vector;
1041
+ if (vector === void 0 || vector.length !== dimensions || !vector.every(Number.isFinite)) {
1042
+ throw new TypeError(`${label} has an invalid ${dimensions}-dimension embedding.`);
1043
+ }
1044
+ return vector;
1045
+ }
1046
+ function uniqueIds(ids, label) {
1047
+ if (!Array.isArray(ids)) throw new TypeError(`Neo4j ${label} ids must be an array.`);
1048
+ const seen = /* @__PURE__ */ new Set();
1049
+ for (const id of ids) {
1050
+ if (typeof id !== "string" || id.length === 0)
1051
+ throw new TypeError(`Neo4j ${label} ids must be non-empty strings.`);
1052
+ if (seen.has(id)) throw new TypeError(`Duplicate Neo4j ${label} id: ${id}`);
1053
+ seen.add(id);
1054
+ }
1055
+ return [...seen];
1056
+ }
1057
+ function replacementSnapshotTargets(options) {
1058
+ return {
1059
+ documentIds: options.documents.map((document) => document.id),
1060
+ chunkIds: options.chunks.map((chunk) => chunk.id),
1061
+ entityKeys: options.entities.map((entity) => entity.id),
1062
+ relationshipKeys: options.relationships.map((relationship) => relationship.key),
1063
+ mentions: options.mentions
1064
+ };
1065
+ }
1066
+ function emptySnapshotTargets(documentIds) {
1067
+ return {
1068
+ documentIds,
1069
+ chunkIds: [],
1070
+ entityKeys: [],
1071
+ relationshipKeys: [],
1072
+ mentions: []
1073
+ };
1074
+ }
1075
+ function expandSnapshotTargets(targets, snapshot) {
1076
+ const mentions = new Map(
1077
+ targets.mentions.map((mention) => [mentionKey(mention.chunkId, mention.entityKey), mention])
1078
+ );
1079
+ for (const key of snapshot.mentions.keys()) {
1080
+ const separator = key.indexOf("\0");
1081
+ if (separator < 0) throw new TypeError("Stored Neo4j mention has an invalid identity.");
1082
+ mentions.set(key, { chunkId: key.slice(0, separator), entityKey: key.slice(separator + 1) });
1083
+ }
1084
+ return {
1085
+ documentIds: targets.documentIds,
1086
+ chunkIds: [.../* @__PURE__ */ new Set([...targets.chunkIds, ...snapshot.chunks.keys()])],
1087
+ entityKeys: [.../* @__PURE__ */ new Set([...targets.entityKeys, ...snapshot.entities.keys()])],
1088
+ relationshipKeys: [.../* @__PURE__ */ new Set([...targets.relationshipKeys, ...snapshot.relationships.keys()])],
1089
+ mentions: [...mentions.values()]
1090
+ };
1091
+ }
1092
+ async function snapshotGraphState(transaction, graphName, labels, targets) {
1093
+ const documentsResult = await transaction.run(
1094
+ `MATCH (d:${quoteIdentifier(labels.document)})
1095
+ WHERE d.${quoteIdentifier("__anvia_id")} IN $documentIds
1096
+ RETURN d.${quoteIdentifier("__anvia_id")} AS key, properties(d) AS properties`,
1097
+ { documentIds: targets.documentIds }
1098
+ );
1099
+ const chunksResult = await transaction.run(
1100
+ `MATCH (c:${quoteIdentifier(labels.chunk)})
1101
+ OPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier("ANVIA_HAS_CHUNK")}]->(c)
1102
+ WITH c, d WHERE c.${quoteIdentifier("__anvia_id")} IN $chunkIds OR d.${quoteIdentifier("__anvia_id")} IN $documentIds
1103
+ RETURN c.${quoteIdentifier("__anvia_id")} AS key, properties(c) AS properties`,
1104
+ { chunkIds: targets.chunkIds, documentIds: targets.documentIds }
1105
+ );
1106
+ const entitiesResult = await transaction.run(
1107
+ `MATCH (e:${quoteIdentifier(labels.entity)})
1108
+ WHERE e.${quoteIdentifier("__anvia_graph")} = $graph AND (
1109
+ e.${quoteIdentifier("__anvia_key")} IN $entityKeys OR
1110
+ any(id IN coalesce(e.${quoteIdentifier("__anvia_source_document_ids")}, []) WHERE id IN $documentIds)
1111
+ )
1112
+ RETURN e.${quoteIdentifier("__anvia_key")} AS key, labels(e) AS labels, properties(e) AS properties`,
1113
+ { graph: graphName, entityKeys: targets.entityKeys, documentIds: targets.documentIds }
1114
+ );
1115
+ const relationshipsResult = await transaction.run(
1116
+ `MATCH ()-[r]->()
1117
+ WHERE r.${quoteIdentifier("__anvia_graph")} = $graph AND (
1118
+ r.${quoteIdentifier("__anvia_key")} IN $relationshipKeys OR
1119
+ any(id IN coalesce(r.${quoteIdentifier("__anvia_source_document_ids")}, []) WHERE id IN $documentIds)
1120
+ )
1121
+ RETURN r.${quoteIdentifier("__anvia_key")} AS key,
1122
+ type(r) AS type,
1123
+ startNode(r).${quoteIdentifier("__anvia_key")} AS source,
1124
+ endNode(r).${quoteIdentifier("__anvia_key")} AS target,
1125
+ properties(r) AS properties`,
1126
+ {
1127
+ graph: graphName,
1128
+ relationshipKeys: targets.relationshipKeys,
1129
+ documentIds: targets.documentIds
1130
+ }
1131
+ );
1132
+ const mentionsResult = await transaction.run(
1133
+ `MATCH (c:${quoteIdentifier(labels.chunk)})-[:${quoteIdentifier("ANVIA_MENTIONS")}]->(e:${quoteIdentifier(labels.entity)})
1134
+ OPTIONAL MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier("ANVIA_HAS_CHUNK")}]->(c)
1135
+ WITH c, e, d WHERE d.${quoteIdentifier("__anvia_id")} IN $documentIds OR
1136
+ any(item IN $mentions WHERE item.chunkId = c.${quoteIdentifier("__anvia_id")} AND item.entityKey = e.${quoteIdentifier("__anvia_key")})
1137
+ RETURN c.${quoteIdentifier("__anvia_id")} AS chunkId, e.${quoteIdentifier("__anvia_key")} AS entityKey`,
1138
+ { documentIds: targets.documentIds, mentions: targets.mentions }
1139
+ );
1140
+ return {
1141
+ documents: snapshotProperties(documentsResult.records, "document"),
1142
+ chunks: snapshotProperties(chunksResult.records, "chunk"),
1143
+ entities: snapshotProperties(entitiesResult.records, "entity", true),
1144
+ relationships: snapshotRelationships(relationshipsResult.records),
1145
+ mentions: snapshotMentions(mentionsResult.records)
1146
+ };
1147
+ }
1148
+ function snapshotProperties(records, resource, includeLabels = false) {
1149
+ const output = /* @__PURE__ */ new Map();
1150
+ for (const record of records) {
1151
+ const key = requiredString(record.get("key"), `Neo4j ${resource} snapshot key`);
1152
+ if (output.has(key))
1153
+ throw new TypeError(`Neo4j ${resource} snapshot contains duplicate ${key}.`);
1154
+ const properties = normalizedSnapshotProperties(
1155
+ record.get("properties"),
1156
+ `Neo4j ${resource} snapshot`
1157
+ );
1158
+ const labels = includeLabels ? requiredStringArray(record.get("labels"), `Neo4j ${resource} snapshot labels`).sort() : [];
1159
+ output.set(key, stableObject({ labels: labels.join("\0"), properties }));
1160
+ }
1161
+ return output;
1162
+ }
1163
+ function snapshotRelationships(records) {
1164
+ const output = /* @__PURE__ */ new Map();
1165
+ for (const record of records) {
1166
+ const key = requiredString(record.get("key"), "Neo4j relationship snapshot key");
1167
+ if (output.has(key))
1168
+ throw new TypeError(`Neo4j relationship snapshot contains duplicate ${key}.`);
1169
+ output.set(
1170
+ key,
1171
+ stableObject({
1172
+ source: requiredString(record.get("source"), "Neo4j relationship snapshot source"),
1173
+ target: requiredString(record.get("target"), "Neo4j relationship snapshot target"),
1174
+ type: requiredString(record.get("type"), "Neo4j relationship snapshot type"),
1175
+ properties: normalizedSnapshotProperties(
1176
+ record.get("properties"),
1177
+ "Neo4j relationship snapshot"
1178
+ )
1179
+ })
1180
+ );
1181
+ }
1182
+ return output;
1183
+ }
1184
+ function snapshotMentions(records) {
1185
+ const output = /* @__PURE__ */ new Map();
1186
+ for (const record of records) {
1187
+ const key = mentionKey(
1188
+ requiredString(record.get("chunkId"), "Neo4j mention chunk id"),
1189
+ requiredString(record.get("entityKey"), "Neo4j mention entity key")
1190
+ );
1191
+ if (output.has(key)) throw new TypeError(`Neo4j mention snapshot contains duplicate ${key}.`);
1192
+ output.set(key, key);
1193
+ }
1194
+ return output;
1195
+ }
1196
+ function normalizedSnapshotProperties(value, label) {
1197
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1198
+ throw new TypeError(`${label} properties must be an object.`);
1199
+ }
1200
+ const normalized = {};
1201
+ for (const [key, item] of Object.entries(value)) {
1202
+ normalized[key] = parseNeo4jPropertyValue(
1203
+ normalizeSnapshotDriverValue(item, `${label}.${key}`),
1204
+ `${label}.${key}`
1205
+ );
1206
+ }
1207
+ for (const property of ["__anvia_source_document_ids", "__anvia_source_chunk_ids"]) {
1208
+ const items = normalized[property];
1209
+ if (items !== void 0) {
1210
+ if (!Array.isArray(items) || !items.every((item) => typeof item === "string")) {
1211
+ throw new TypeError(`${label}.${property} must be a string array.`);
1212
+ }
1213
+ normalized[property] = [...new Set(items)].sort();
1214
+ }
1215
+ }
1216
+ return stableObject(normalized);
1217
+ }
1218
+ function normalizeSnapshotDriverValue(value, label) {
1219
+ if (isInt2(value)) {
1220
+ if (!value.inSafeRange()) throw new TypeError(`${label} contains an unsafe Neo4j integer.`);
1221
+ return value.toNumber();
1222
+ }
1223
+ if (Array.isArray(value)) {
1224
+ return value.map((item, index) => normalizeSnapshotDriverValue(item, `${label}[${index}]`));
1225
+ }
1226
+ return value;
1227
+ }
1228
+ function mentionKey(chunkId, entityKey) {
1229
+ return `${chunkId}\0${entityKey}`;
1230
+ }
1231
+ function diffGraphSnapshots(before, after) {
1232
+ return {
1233
+ documents: diffSnapshotMaps(before.documents, after.documents),
1234
+ chunks: diffSnapshotMaps(before.chunks, after.chunks),
1235
+ entities: diffSnapshotMaps(before.entities, after.entities),
1236
+ relationships: diffSnapshotMaps(before.relationships, after.relationships),
1237
+ mentions: diffSnapshotMaps(before.mentions, after.mentions)
1238
+ };
1239
+ }
1240
+ function diffSnapshotMaps(before, after) {
1241
+ let created = 0;
1242
+ let updated = 0;
1243
+ let deleted = 0;
1244
+ let unchanged = 0;
1245
+ for (const key of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
1246
+ const previous = before.get(key);
1247
+ const next = after.get(key);
1248
+ if (previous === void 0) created += 1;
1249
+ else if (next === void 0) deleted += 1;
1250
+ else if (previous === next) unchanged += 1;
1251
+ else updated += 1;
1252
+ }
1253
+ return { created, updated, deleted, unchanged };
1254
+ }
1255
+ function emptyWriteResult() {
1256
+ const empty = () => ({ created: 0, updated: 0, deleted: 0, unchanged: 0 });
1257
+ return {
1258
+ documents: empty(),
1259
+ chunks: empty(),
1260
+ entities: empty(),
1261
+ relationships: empty(),
1262
+ mentions: empty()
1263
+ };
1264
+ }
1265
+ async function removeDocuments(transaction, graphName, labels, documentIds, orphanEntities) {
1266
+ const chunks = await transaction.run(
1267
+ `MATCH (d:${quoteIdentifier(labels.document)})-[:${quoteIdentifier("ANVIA_HAS_CHUNK")}]->(c:${quoteIdentifier(labels.chunk)}) WHERE d.${quoteIdentifier("__anvia_id")} IN $documentIds RETURN collect(c.${quoteIdentifier("__anvia_id")}) AS chunkIds`,
1268
+ { documentIds }
1269
+ );
1270
+ const chunkIdsValue = chunks.records[0]?.get("chunkIds");
1271
+ const chunkIds = requiredStringArray(chunkIdsValue, "Neo4j replacement chunk ids");
1272
+ await transaction.run(
1273
+ `MATCH ()-[r]->() WHERE r.${quoteIdentifier("__anvia_graph")} = $graph AND any(id IN r.${quoteIdentifier("__anvia_source_document_ids")} WHERE id IN $documentIds)
1274
+ SET r.${quoteIdentifier("__anvia_source_document_ids")} = [id IN r.${quoteIdentifier("__anvia_source_document_ids")} WHERE NOT id IN $documentIds]
1275
+ SET r.${quoteIdentifier("__anvia_source_chunk_ids")} = [id IN coalesce(r.${quoteIdentifier("__anvia_source_chunk_ids")}, []) WHERE NOT id IN $chunkIds]
1276
+ WITH r WHERE size(r.${quoteIdentifier("__anvia_source_document_ids")}) = 0 DELETE r`,
1277
+ { graph: graphName, documentIds, chunkIds }
1278
+ );
1279
+ await transaction.run(
1280
+ `MATCH (d:${quoteIdentifier(labels.document)}) WHERE d.${quoteIdentifier("__anvia_id")} IN $documentIds
1281
+ OPTIONAL MATCH (d)-[:${quoteIdentifier("ANVIA_HAS_CHUNK")}]->(c:${quoteIdentifier(labels.chunk)})
1282
+ DETACH DELETE c, d`,
1283
+ { documentIds }
1284
+ );
1285
+ await transaction.run(
1286
+ `MATCH (e:${quoteIdentifier(labels.entity)})
1287
+ WHERE e.${quoteIdentifier("__anvia_graph")} = $graph AND
1288
+ any(id IN coalesce(e.${quoteIdentifier("__anvia_source_document_ids")}, []) WHERE id IN $documentIds)
1289
+ SET e.${quoteIdentifier("__anvia_source_document_ids")} = [id IN e.${quoteIdentifier("__anvia_source_document_ids")} WHERE NOT id IN $documentIds],
1290
+ e.${quoteIdentifier("__anvia_source_chunk_ids")} = [id IN coalesce(e.${quoteIdentifier("__anvia_source_chunk_ids")}, []) WHERE NOT id IN $chunkIds]
1291
+ WITH e WHERE $deleteOrphans AND size(e.${quoteIdentifier("__anvia_source_document_ids")}) = 0
1292
+ DETACH DELETE e`,
1293
+ {
1294
+ graph: graphName,
1295
+ documentIds,
1296
+ chunkIds,
1297
+ deleteOrphans: orphanEntities === "delete"
1298
+ }
1299
+ );
1300
+ }
1301
+ async function writeDocuments(transaction, labels, documents) {
1302
+ await transaction.run(
1303
+ `UNWIND $rows AS row MERGE (d:${quoteIdentifier(labels.document)} {${quoteIdentifier("__anvia_id")}: row.id}) SET d += row.properties`,
1304
+ {
1305
+ rows: documents.map((document) => ({
1306
+ id: document.id,
1307
+ properties: document.properties ?? {}
1308
+ }))
1309
+ }
1310
+ );
1311
+ }
1312
+ async function writeChunks(transaction, labels, chunks) {
1313
+ const rows = chunks.map((chunk) => ({
1314
+ id: chunk.id,
1315
+ documentId: chunk.document.documentId,
1316
+ index: chunk.document.index,
1317
+ text: chunk.document.text,
1318
+ metadata: chunk.document.metadata ?? {},
1319
+ embedding: chunk.embeddings[0]?.vector
1320
+ }));
1321
+ await transaction.run(
1322
+ `UNWIND $rows AS row
1323
+ MATCH (d:${quoteIdentifier(labels.document)} {${quoteIdentifier("__anvia_id")}: row.documentId})
1324
+ CREATE (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier("__anvia_id")}: row.id, ${quoteIdentifier("__anvia_document_id")}: row.documentId, ${quoteIdentifier("__anvia_index")}: row.index, ${quoteIdentifier("__anvia_text")}: row.text, ${quoteIdentifier("__anvia_embedding")}: row.embedding})
1325
+ SET c += row.metadata
1326
+ CREATE (d)-[:${quoteIdentifier("ANVIA_HAS_CHUNK")}]->(c)`,
1327
+ { rows }
1328
+ );
1329
+ const pairs = [...rows].sort(
1330
+ (left, right) => left.documentId.localeCompare(right.documentId) || left.index - right.index
1331
+ ).flatMap((row, index, all) => {
1332
+ const next = all[index + 1];
1333
+ return next !== void 0 && next.documentId === row.documentId ? [{ from: row.id, to: next.id }] : [];
1334
+ });
1335
+ if (pairs.length > 0) {
1336
+ await transaction.run(
1337
+ `UNWIND $rows AS row MATCH (a:${quoteIdentifier(labels.chunk)} {${quoteIdentifier("__anvia_id")}: row.from}), (b:${quoteIdentifier(labels.chunk)} {${quoteIdentifier("__anvia_id")}: row.to}) CREATE (a)-[:${quoteIdentifier("ANVIA_NEXT_CHUNK")}]->(b)`,
1338
+ { rows: pairs }
1339
+ );
1340
+ }
1341
+ }
1342
+ async function writeEntities(transaction, graphName, entityLabel, entities, conflict, sourceDocuments) {
1343
+ const grouped = groupBy(entities, (entity) => entity.document.type);
1344
+ for (const [type, values] of grouped) {
1345
+ const rows = values.map((entity) => ({
1346
+ key: entity.id,
1347
+ properties: entity.document.properties,
1348
+ embedding: entity.embeddings[0]?.vector,
1349
+ sourceDocumentIds: sourceDocuments(entity.document.sourceChunkIds),
1350
+ sourceChunkIds: entity.document.sourceChunkIds
1351
+ }));
1352
+ if (conflict === "error") await assertEntityConflicts(transaction, entityLabel, rows);
1353
+ const propertySet = conflictPropertySet("e", conflict);
1354
+ const embedding = entityEmbeddingExpression(conflict);
1355
+ await transaction.run(
1356
+ `UNWIND $rows AS row
1357
+ MERGE (e:${quoteIdentifier(entityLabel)}:${quoteIdentifier(type)} {${quoteIdentifier("__anvia_key")}: row.key})
1358
+ ${propertySet}
1359
+ SET e.${quoteIdentifier("__anvia_key")} = row.key,
1360
+ e.${quoteIdentifier("__anvia_graph")} = $graph,
1361
+ e.${quoteIdentifier("__anvia_embedding")} = ${embedding},
1362
+ e.${quoteIdentifier("__anvia_source_document_ids")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),
1363
+ e.${quoteIdentifier("__anvia_source_chunk_ids")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,
1364
+ { rows, graph: graphName }
1365
+ );
1366
+ }
1367
+ }
1368
+ async function assertEntityConflicts(transaction, entityLabel, rows) {
1369
+ const result = await transaction.run(
1370
+ `UNWIND $keys AS key MATCH (e:${quoteIdentifier(entityLabel)} {${quoteIdentifier("__anvia_key")}: key}) RETURN key, properties(e) AS properties`,
1371
+ { keys: rows.map((row) => row.key) }
1372
+ );
1373
+ const incoming = new Map(rows.map((row) => [row.key, row.properties]));
1374
+ for (const record of result.records) {
1375
+ const key = requiredString(record.get("key"), "Neo4j entity key");
1376
+ const existing = applicationProperties(record.get("properties"));
1377
+ if (stableObject(existing) !== stableObject(incoming.get(key) ?? {})) {
1378
+ throw new Error(`Neo4j entity ${key} conflicts with existing properties.`);
1379
+ }
1380
+ }
1381
+ }
1382
+ async function writeMentions(transaction, labels, mentions) {
1383
+ if (mentions.length === 0) return;
1384
+ await transaction.run(
1385
+ `UNWIND $rows AS row
1386
+ MATCH (c:${quoteIdentifier(labels.chunk)} {${quoteIdentifier("__anvia_id")}: row.chunkId}), (e:${quoteIdentifier(labels.entity)} {${quoteIdentifier("__anvia_key")}: row.entityKey})
1387
+ MERGE (c)-[:${quoteIdentifier("ANVIA_MENTIONS")}]->(e)`,
1388
+ { rows: mentions }
1389
+ );
1390
+ }
1391
+ async function writeRelationships(transaction, graphName, entityLabel, relationships, conflict, sourceDocuments) {
1392
+ const grouped = groupBy(relationships, (relationship) => relationship.type);
1393
+ for (const [type, values] of grouped) {
1394
+ const rows = values.map((relationship) => ({
1395
+ key: relationship.key,
1396
+ from: relationship.from,
1397
+ to: relationship.to,
1398
+ properties: relationship.properties,
1399
+ sourceDocumentIds: sourceDocuments(relationship.sourceChunkIds),
1400
+ sourceChunkIds: relationship.sourceChunkIds
1401
+ }));
1402
+ if (conflict === "error") {
1403
+ const existing = await transaction.run(
1404
+ `UNWIND $keys AS key MATCH ()-[r:${quoteIdentifier(type)} {${quoteIdentifier("__anvia_key")}: key}]->() RETURN key, properties(r) AS properties`,
1405
+ { keys: rows.map((row) => row.key) }
1406
+ );
1407
+ const incoming = new Map(rows.map((row) => [row.key, row.properties]));
1408
+ for (const record of existing.records) {
1409
+ const key = requiredString(record.get("key"), "Neo4j relationship key");
1410
+ if (stableObject(applicationProperties(record.get("properties"))) !== stableObject(incoming.get(key) ?? {})) {
1411
+ throw new Error(`Neo4j relationship ${key} conflicts with existing properties.`);
1412
+ }
1413
+ }
1414
+ }
1415
+ const propertySet = conflictPropertySet("r", conflict);
1416
+ await transaction.run(
1417
+ `UNWIND $rows AS row
1418
+ MATCH (a:${quoteIdentifier(entityLabel)} {${quoteIdentifier("__anvia_key")}: row.from}), (b:${quoteIdentifier(entityLabel)} {${quoteIdentifier("__anvia_key")}: row.to})
1419
+ MERGE (a)-[r:${quoteIdentifier(type)} {${quoteIdentifier("__anvia_key")}: row.key}]->(b)
1420
+ ${propertySet}
1421
+ SET r.${quoteIdentifier("__anvia_key")} = row.key,
1422
+ r.${quoteIdentifier("__anvia_graph")} = $graph,
1423
+ r.${quoteIdentifier("__anvia_source_document_ids")} = reduce(all = existingDocumentIds, id IN row.sourceDocumentIds | CASE WHEN id IN all THEN all ELSE all + id END),
1424
+ r.${quoteIdentifier("__anvia_source_chunk_ids")} = reduce(all = existingChunkIds, id IN row.sourceChunkIds | CASE WHEN id IN all THEN all ELSE all + id END)`,
1425
+ { rows, graph: graphName }
1426
+ );
1427
+ }
1428
+ }
1429
+ function conflictPropertySet(variable, conflict) {
1430
+ const sourceDocuments = quoteIdentifier("__anvia_source_document_ids");
1431
+ const sourceChunks = quoteIdentifier("__anvia_source_chunk_ids");
1432
+ const existingSources = `WITH ${variable}, row,
1433
+ coalesce(${variable}.${sourceDocuments}, []) AS existingDocumentIds,
1434
+ coalesce(${variable}.${sourceChunks}, []) AS existingChunkIds`;
1435
+ if (conflict === "keep-existing") {
1436
+ return `ON CREATE SET ${variable} += row.properties
1437
+ ${existingSources}`;
1438
+ }
1439
+ if (conflict === "overwrite") {
1440
+ return `${existingSources}
1441
+ SET ${variable} = row.properties`;
1442
+ }
1443
+ return `${existingSources}
1444
+ SET ${variable} += row.properties`;
1445
+ }
1446
+ function entityEmbeddingExpression(conflict) {
1447
+ if (conflict === "keep-existing") {
1448
+ return `coalesce(e.${quoteIdentifier("__anvia_embedding")}, row.embedding)`;
1449
+ }
1450
+ return "row.embedding";
1451
+ }
1452
+ function requiredString(value, label) {
1453
+ if (typeof value !== "string") throw new TypeError(`${label} must be a string.`);
1454
+ return value;
1455
+ }
1456
+ function applicationProperties(value) {
1457
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
1458
+ return parseNeo4jProperties(
1459
+ Object.fromEntries(Object.entries(value).filter(([key]) => !key.startsWith("__anvia_"))),
1460
+ "stored Neo4j properties"
1461
+ );
1462
+ }
1463
+ function groupBy(values, keyFor) {
1464
+ const groups = /* @__PURE__ */ new Map();
1465
+ for (const value of values) {
1466
+ const key = keyFor(value);
1467
+ const group = groups.get(key);
1468
+ if (group === void 0) groups.set(key, [value]);
1469
+ else group.push(value);
1470
+ }
1471
+ return groups;
1472
+ }
1473
+
1474
+ export {
1475
+ defineNeo4jGraphSchema,
1476
+ parseNeo4jProperties,
1477
+ quoteIdentifier,
1478
+ throwIfAborted,
1479
+ positiveInteger,
1480
+ finiteScore,
1481
+ strictProperties,
1482
+ Neo4jKnowledgeGraphBase,
1483
+ Neo4jKnowledgeGraph,
1484
+ ManagedNeo4jKnowledgeGraph
1485
+ };
1486
+ //# sourceMappingURL=chunk-QNHOT7P2.js.map