@danielsimonjr/memoryjs 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -21032,6 +21032,431 @@ var ObservationStore = class _ObservationStore {
21032
21032
 
21033
21033
  // src/core/StorageFactory.ts
21034
21034
  init_cjs_shims();
21035
+
21036
+ // src/core/PostgreSQLStorage.ts
21037
+ init_cjs_shims();
21038
+ init_logger();
21039
+ var ENTITY_COLUMNS = [
21040
+ "name",
21041
+ "entity_type",
21042
+ "observations",
21043
+ "parent_id",
21044
+ "tags",
21045
+ "importance",
21046
+ "created_at",
21047
+ "last_modified",
21048
+ "ttl",
21049
+ "confidence",
21050
+ "project_id",
21051
+ "version",
21052
+ "parent_entity_name",
21053
+ "root_entity_name",
21054
+ "is_latest",
21055
+ "superseded_by",
21056
+ "content_hash",
21057
+ "valid_from",
21058
+ "valid_until",
21059
+ "observation_meta",
21060
+ "lifecycle_status",
21061
+ "extra"
21062
+ ];
21063
+ var FIRST_CLASS_ENTITY_KEYS = /* @__PURE__ */ new Set([
21064
+ "name",
21065
+ "entityType",
21066
+ "observations",
21067
+ "parentId",
21068
+ "tags",
21069
+ "importance",
21070
+ "createdAt",
21071
+ "lastModified",
21072
+ "ttl",
21073
+ "confidence",
21074
+ "projectId",
21075
+ "version",
21076
+ "parentEntityName",
21077
+ "rootEntityName",
21078
+ "isLatest",
21079
+ "supersededBy",
21080
+ "contentHash",
21081
+ "validFrom",
21082
+ "validUntil",
21083
+ "observationMeta",
21084
+ "lifecycleStatus"
21085
+ ]);
21086
+ var SCHEMA_DDL = `
21087
+ CREATE TABLE IF NOT EXISTS entities (
21088
+ name TEXT PRIMARY KEY,
21089
+ entity_type TEXT NOT NULL,
21090
+ observations TEXT[] NOT NULL DEFAULT '{}',
21091
+ parent_id TEXT,
21092
+ tags TEXT[],
21093
+ importance NUMERIC(4, 2),
21094
+ created_at TIMESTAMPTZ DEFAULT NOW(),
21095
+ last_modified TIMESTAMPTZ DEFAULT NOW(),
21096
+ ttl INTEGER,
21097
+ confidence NUMERIC(4, 3),
21098
+ project_id TEXT,
21099
+ version INTEGER,
21100
+ parent_entity_name TEXT,
21101
+ root_entity_name TEXT,
21102
+ is_latest BOOLEAN,
21103
+ superseded_by TEXT,
21104
+ content_hash TEXT,
21105
+ valid_from TIMESTAMPTZ,
21106
+ valid_until TIMESTAMPTZ,
21107
+ observation_meta JSONB,
21108
+ lifecycle_status TEXT,
21109
+ extra JSONB
21110
+ );
21111
+
21112
+ CREATE INDEX IF NOT EXISTS idx_entities_entity_type ON entities(entity_type);
21113
+ CREATE INDEX IF NOT EXISTS idx_entities_project_id ON entities(project_id);
21114
+ CREATE INDEX IF NOT EXISTS idx_entities_content_hash ON entities(content_hash);
21115
+ CREATE INDEX IF NOT EXISTS idx_entities_tags_gin ON entities USING GIN(tags);
21116
+
21117
+ CREATE TABLE IF NOT EXISTS relations (
21118
+ from_name TEXT NOT NULL,
21119
+ to_name TEXT NOT NULL,
21120
+ relation_type TEXT NOT NULL,
21121
+ metadata JSONB,
21122
+ created_at TIMESTAMPTZ DEFAULT NOW(),
21123
+ valid_from TIMESTAMPTZ,
21124
+ valid_until TIMESTAMPTZ,
21125
+ PRIMARY KEY (from_name, to_name, relation_type)
21126
+ );
21127
+
21128
+ CREATE INDEX IF NOT EXISTS idx_relations_to ON relations(to_name);
21129
+ CREATE INDEX IF NOT EXISTS idx_relations_type ON relations(relation_type);
21130
+ `;
21131
+ var PostgreSQLStorage = class {
21132
+ connectionString;
21133
+ pool = null;
21134
+ cache = null;
21135
+ nameIndex = /* @__PURE__ */ new Map();
21136
+ outgoingRelations = /* @__PURE__ */ new Map();
21137
+ incomingRelations = /* @__PURE__ */ new Map();
21138
+ pendingAppends = 0;
21139
+ schemaInitPromise = null;
21140
+ constructor(connectionString) {
21141
+ this.connectionString = connectionString;
21142
+ }
21143
+ // ==================== Connection management ====================
21144
+ /**
21145
+ * Get or lazily-construct the `pg.Pool`. Throws a friendly error if
21146
+ * the `pg` package isn't installed.
21147
+ */
21148
+ async getPool() {
21149
+ if (this.pool) return this.pool;
21150
+ let pgModule;
21151
+ try {
21152
+ pgModule = await import("pg");
21153
+ } catch {
21154
+ throw new Error(
21155
+ "The 'pg' package is required for the PostgreSQL backend but is not installed. Run: npm install pg @types/pg"
21156
+ );
21157
+ }
21158
+ this.pool = new pgModule.Pool({ connectionString: this.connectionString });
21159
+ return this.pool;
21160
+ }
21161
+ /**
21162
+ * Run schema DDL idempotently. Called from `ensureLoaded`.
21163
+ */
21164
+ async initSchema() {
21165
+ if (this.schemaInitPromise) return this.schemaInitPromise;
21166
+ this.schemaInitPromise = (async () => {
21167
+ const pool = await this.getPool();
21168
+ await pool.query(SCHEMA_DDL);
21169
+ })();
21170
+ return this.schemaInitPromise;
21171
+ }
21172
+ // ==================== Row ⇄ Entity / Relation mapping ====================
21173
+ entityToRow(entity) {
21174
+ const extra = {};
21175
+ for (const key of Object.keys(entity)) {
21176
+ if (!FIRST_CLASS_ENTITY_KEYS.has(key)) {
21177
+ extra[key] = entity[key];
21178
+ }
21179
+ }
21180
+ return {
21181
+ name: entity.name,
21182
+ entity_type: entity.entityType,
21183
+ observations: entity.observations,
21184
+ parent_id: entity.parentId ?? null,
21185
+ tags: entity.tags ?? null,
21186
+ importance: entity.importance ?? null,
21187
+ created_at: entity.createdAt ?? null,
21188
+ last_modified: entity.lastModified ?? null,
21189
+ ttl: entity.ttl ?? null,
21190
+ confidence: entity.confidence ?? null,
21191
+ project_id: entity.projectId ?? null,
21192
+ version: entity.version ?? null,
21193
+ parent_entity_name: entity.parentEntityName ?? null,
21194
+ root_entity_name: entity.rootEntityName ?? null,
21195
+ is_latest: entity.isLatest ?? null,
21196
+ superseded_by: entity.supersededBy ?? null,
21197
+ content_hash: entity.contentHash ?? null,
21198
+ valid_from: entity.validFrom ?? null,
21199
+ valid_until: entity.validUntil ?? null,
21200
+ observation_meta: entity.observationMeta ?? null,
21201
+ lifecycle_status: entity.lifecycleStatus ?? null,
21202
+ extra: Object.keys(extra).length > 0 ? extra : null
21203
+ };
21204
+ }
21205
+ rowToEntity(row) {
21206
+ const entity = {
21207
+ name: String(row.name),
21208
+ entityType: String(row.entity_type),
21209
+ observations: Array.isArray(row.observations) ? row.observations : []
21210
+ };
21211
+ if (row.parent_id != null) entity.parentId = String(row.parent_id);
21212
+ if (Array.isArray(row.tags)) entity.tags = row.tags;
21213
+ if (row.importance != null) entity.importance = Number(row.importance);
21214
+ if (row.created_at != null) entity.createdAt = new Date(String(row.created_at)).toISOString();
21215
+ if (row.last_modified != null) entity.lastModified = new Date(String(row.last_modified)).toISOString();
21216
+ if (row.ttl != null) entity.ttl = Number(row.ttl);
21217
+ if (row.confidence != null) entity.confidence = Number(row.confidence);
21218
+ if (row.project_id != null) entity.projectId = String(row.project_id);
21219
+ if (row.version != null) entity.version = Number(row.version);
21220
+ if (row.parent_entity_name != null) entity.parentEntityName = String(row.parent_entity_name);
21221
+ if (row.root_entity_name != null) entity.rootEntityName = String(row.root_entity_name);
21222
+ if (row.is_latest != null) entity.isLatest = Boolean(row.is_latest);
21223
+ if (row.superseded_by != null) entity.supersededBy = String(row.superseded_by);
21224
+ if (row.content_hash != null) entity.contentHash = String(row.content_hash);
21225
+ if (row.valid_from != null) entity.validFrom = new Date(String(row.valid_from)).toISOString();
21226
+ if (row.valid_until != null) entity.validUntil = new Date(String(row.valid_until)).toISOString();
21227
+ if (row.observation_meta != null) {
21228
+ entity.observationMeta = row.observation_meta;
21229
+ }
21230
+ if (row.lifecycle_status != null) {
21231
+ entity.lifecycleStatus = String(row.lifecycle_status);
21232
+ }
21233
+ if (row.extra != null && typeof row.extra === "object") {
21234
+ Object.assign(entity, row.extra);
21235
+ }
21236
+ return entity;
21237
+ }
21238
+ rowToRelation(row) {
21239
+ const relation = {
21240
+ from: String(row.from_name),
21241
+ to: String(row.to_name),
21242
+ relationType: String(row.relation_type)
21243
+ };
21244
+ return relation;
21245
+ }
21246
+ // ==================== Cache management ====================
21247
+ rebuildIndexes(graph) {
21248
+ this.nameIndex.clear();
21249
+ this.outgoingRelations.clear();
21250
+ this.incomingRelations.clear();
21251
+ for (const e of graph.entities) this.nameIndex.set(e.name, e);
21252
+ for (const r of graph.relations) {
21253
+ const outArr = this.outgoingRelations.get(r.from) ?? [];
21254
+ outArr.push(r);
21255
+ this.outgoingRelations.set(r.from, outArr);
21256
+ const inArr = this.incomingRelations.get(r.to) ?? [];
21257
+ inArr.push(r);
21258
+ this.incomingRelations.set(r.to, inArr);
21259
+ }
21260
+ }
21261
+ // ==================== IGraphStorage — read ====================
21262
+ async loadGraph() {
21263
+ await this.ensureLoaded();
21264
+ return this.cache;
21265
+ }
21266
+ async getGraphForMutation() {
21267
+ await this.ensureLoaded();
21268
+ const cache = this.cache;
21269
+ return {
21270
+ entities: cache.entities.map((e) => ({
21271
+ ...e,
21272
+ observations: [...e.observations],
21273
+ tags: e.tags ? [...e.tags] : void 0
21274
+ })),
21275
+ relations: cache.relations.map((r) => ({ ...r }))
21276
+ };
21277
+ }
21278
+ async ensureLoaded() {
21279
+ if (this.cache) return;
21280
+ await this.initSchema();
21281
+ const pool = await this.getPool();
21282
+ const [eRes, rRes] = await Promise.all([
21283
+ pool.query("SELECT * FROM entities"),
21284
+ pool.query("SELECT * FROM relations")
21285
+ ]);
21286
+ const graph = {
21287
+ entities: eRes.rows.map((r) => this.rowToEntity(r)),
21288
+ relations: rRes.rows.map((r) => this.rowToRelation(r))
21289
+ };
21290
+ this.cache = graph;
21291
+ this.rebuildIndexes(graph);
21292
+ }
21293
+ get cachedGraph() {
21294
+ return this.cache;
21295
+ }
21296
+ // ==================== IGraphStorage — write ====================
21297
+ async saveGraph(graph) {
21298
+ await this.initSchema();
21299
+ const pool = await this.getPool();
21300
+ await pool.query("TRUNCATE entities, relations");
21301
+ for (const entity of graph.entities) {
21302
+ await this.insertEntityRow(pool, entity);
21303
+ }
21304
+ for (const relation of graph.relations) {
21305
+ await this.insertRelationRow(pool, relation);
21306
+ }
21307
+ this.cache = {
21308
+ entities: graph.entities.map((e) => ({ ...e })),
21309
+ relations: graph.relations.map((r) => ({ ...r }))
21310
+ };
21311
+ this.rebuildIndexes(this.cache);
21312
+ this.pendingAppends = 0;
21313
+ }
21314
+ async insertEntityRow(pool, entity) {
21315
+ const row = this.entityToRow(entity);
21316
+ const cols = ENTITY_COLUMNS.join(", ");
21317
+ const placeholders = ENTITY_COLUMNS.map((_, i) => `$${i + 1}`).join(", ");
21318
+ const values = ENTITY_COLUMNS.map((c) => row[c]);
21319
+ await pool.query(
21320
+ `INSERT INTO entities (${cols}) VALUES (${placeholders})
21321
+ ON CONFLICT (name) DO UPDATE SET ${ENTITY_COLUMNS.filter((c) => c !== "name").map((c) => `${c} = EXCLUDED.${c}`).join(", ")}`,
21322
+ values
21323
+ );
21324
+ }
21325
+ async insertRelationRow(pool, relation) {
21326
+ await pool.query(
21327
+ `INSERT INTO relations (from_name, to_name, relation_type)
21328
+ VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
21329
+ [relation.from, relation.to, relation.relationType]
21330
+ );
21331
+ }
21332
+ async appendEntity(entity) {
21333
+ await this.ensureLoaded();
21334
+ const pool = await this.getPool();
21335
+ await this.insertEntityRow(pool, entity);
21336
+ if (!this.cache) return;
21337
+ const existingIdx = this.cache.entities.findIndex((e) => e.name === entity.name);
21338
+ if (existingIdx >= 0) this.cache.entities[existingIdx] = entity;
21339
+ else this.cache.entities.push(entity);
21340
+ this.nameIndex.set(entity.name, entity);
21341
+ this.pendingAppends += 1;
21342
+ }
21343
+ async appendRelation(relation) {
21344
+ await this.ensureLoaded();
21345
+ const pool = await this.getPool();
21346
+ await this.insertRelationRow(pool, relation);
21347
+ if (!this.cache) return;
21348
+ const duplicate = this.cache.relations.some(
21349
+ (r) => r.from === relation.from && r.to === relation.to && r.relationType === relation.relationType
21350
+ );
21351
+ if (!duplicate) {
21352
+ this.cache.relations.push(relation);
21353
+ const outArr = this.outgoingRelations.get(relation.from) ?? [];
21354
+ outArr.push(relation);
21355
+ this.outgoingRelations.set(relation.from, outArr);
21356
+ const inArr = this.incomingRelations.get(relation.to) ?? [];
21357
+ inArr.push(relation);
21358
+ this.incomingRelations.set(relation.to, inArr);
21359
+ }
21360
+ this.pendingAppends += 1;
21361
+ }
21362
+ async updateEntity(entityName, updates) {
21363
+ await this.ensureLoaded();
21364
+ const existing = this.nameIndex.get(entityName);
21365
+ if (!existing) return false;
21366
+ const merged = {
21367
+ ...existing,
21368
+ ...updates,
21369
+ name: entityName,
21370
+ lastModified: updates.lastModified ?? (/* @__PURE__ */ new Date()).toISOString()
21371
+ };
21372
+ const pool = await this.getPool();
21373
+ await this.insertEntityRow(pool, merged);
21374
+ if (this.cache) {
21375
+ const idx = this.cache.entities.findIndex((e) => e.name === entityName);
21376
+ if (idx >= 0) this.cache.entities[idx] = merged;
21377
+ }
21378
+ this.nameIndex.set(entityName, merged);
21379
+ this.pendingAppends += 1;
21380
+ return true;
21381
+ }
21382
+ async compact() {
21383
+ if (this.cache) await this.saveGraph(this.cache);
21384
+ }
21385
+ clearCache() {
21386
+ this.cache = null;
21387
+ this.nameIndex.clear();
21388
+ this.outgoingRelations.clear();
21389
+ this.incomingRelations.clear();
21390
+ this.pendingAppends = 0;
21391
+ }
21392
+ // ==================== IGraphStorage — sync getters ====================
21393
+ getEntityByName(name) {
21394
+ return this.nameIndex.get(name);
21395
+ }
21396
+ hasEntity(name) {
21397
+ return this.nameIndex.has(name);
21398
+ }
21399
+ getEntitiesByType(entityType) {
21400
+ const result = [];
21401
+ for (const entity of this.nameIndex.values()) {
21402
+ if (entity.entityType === entityType) result.push(entity);
21403
+ }
21404
+ return result;
21405
+ }
21406
+ getEntityTypes() {
21407
+ const types = /* @__PURE__ */ new Set();
21408
+ for (const entity of this.nameIndex.values()) types.add(entity.entityType);
21409
+ return Array.from(types);
21410
+ }
21411
+ getLowercased(entityName) {
21412
+ const e = this.nameIndex.get(entityName);
21413
+ if (!e) return void 0;
21414
+ return {
21415
+ name: e.name.toLowerCase(),
21416
+ entityType: e.entityType.toLowerCase(),
21417
+ observations: e.observations.map((o) => o.toLowerCase()),
21418
+ tags: e.tags?.map((t) => t.toLowerCase()) ?? []
21419
+ };
21420
+ }
21421
+ getRelationsFrom(entityName) {
21422
+ return this.outgoingRelations.get(entityName) ?? [];
21423
+ }
21424
+ getRelationsTo(entityName) {
21425
+ return this.incomingRelations.get(entityName) ?? [];
21426
+ }
21427
+ getRelationsFor(entityName) {
21428
+ return [
21429
+ ...this.outgoingRelations.get(entityName) ?? [],
21430
+ ...this.incomingRelations.get(entityName) ?? []
21431
+ ];
21432
+ }
21433
+ hasRelations(entityName) {
21434
+ return (this.outgoingRelations.get(entityName)?.length ?? 0) + (this.incomingRelations.get(entityName)?.length ?? 0) > 0;
21435
+ }
21436
+ // ==================== Utility ====================
21437
+ getFilePath() {
21438
+ return this.connectionString;
21439
+ }
21440
+ getPendingAppends() {
21441
+ return this.pendingAppends;
21442
+ }
21443
+ /**
21444
+ * Close the underlying `pg.Pool`. Call from process-shutdown handlers to
21445
+ * avoid keeping the event loop alive on idle connections.
21446
+ */
21447
+ async close() {
21448
+ if (this.pool) {
21449
+ try {
21450
+ await this.pool.end();
21451
+ } catch (e) {
21452
+ logger.warn("PostgreSQLStorage.close: pool.end failed:", e);
21453
+ }
21454
+ this.pool = null;
21455
+ }
21456
+ }
21457
+ };
21458
+
21459
+ // src/core/StorageFactory.ts
21035
21460
  var DEFAULT_STORAGE_TYPE = "jsonl";
21036
21461
  function createStorage(config) {
21037
21462
  const storageType = process.env.MEMORY_STORAGE_TYPE || config.type || DEFAULT_STORAGE_TYPE;
@@ -21040,9 +21465,12 @@ function createStorage(config) {
21040
21465
  return new GraphStorage(config.path);
21041
21466
  case "sqlite":
21042
21467
  return new SQLiteStorage(config.path);
21468
+ case "postgres":
21469
+ case "postgresql":
21470
+ return new PostgreSQLStorage(config.path);
21043
21471
  default:
21044
21472
  throw new Error(
21045
- `Unknown storage type: ${storageType}. Supported types: jsonl, sqlite`
21473
+ `Unknown storage type: ${storageType}. Supported types: jsonl, sqlite, postgres`
21046
21474
  );
21047
21475
  }
21048
21476
  }