@nicia-ai/typegraph 0.7.0 → 0.9.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/backend/postgres/index.cjs +26 -26
- package/dist/backend/postgres/index.js +2 -2
- package/dist/backend/sqlite/index.cjs +12 -12
- package/dist/backend/sqlite/index.d.cts +15 -3
- package/dist/backend/sqlite/index.d.ts +15 -3
- package/dist/backend/sqlite/index.js +2 -2
- package/dist/backend/sqlite/local.cjs +5 -6
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.js +2 -3
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/{chunk-PDQBCQ34.cjs → chunk-7VITUTRA.cjs} +6 -6
- package/dist/{chunk-PDQBCQ34.cjs.map → chunk-7VITUTRA.cjs.map} +1 -1
- package/dist/{chunk-K5O7TOJO.cjs → chunk-FXZOTO6F.cjs} +56 -48
- package/dist/chunk-FXZOTO6F.cjs.map +1 -0
- package/dist/{chunk-JUZWF5NX.js → chunk-IRFD3MEU.js} +12 -12
- package/dist/chunk-IRFD3MEU.js.map +1 -0
- package/dist/{chunk-2DKSQNPW.js → chunk-KP2HKVXU.js} +45 -37
- package/dist/chunk-KP2HKVXU.js.map +1 -0
- package/dist/{chunk-23NGZHUN.cjs → chunk-MGEVSTDX.cjs} +2 -13
- package/dist/chunk-MGEVSTDX.cjs.map +1 -0
- package/dist/{chunk-BELXZTVK.cjs → chunk-NI2GV74U.cjs} +12 -12
- package/dist/chunk-NI2GV74U.cjs.map +1 -0
- package/dist/{chunk-SH237DWD.js → chunk-PYV4ADC6.js} +3 -3
- package/dist/{chunk-SH237DWD.js.map → chunk-PYV4ADC6.js.map} +1 -1
- package/dist/{chunk-JPO7W262.js → chunk-X3OXNIMH.js} +3 -13
- package/dist/chunk-X3OXNIMH.js.map +1 -0
- package/dist/index.cjs +61 -61
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- package/dist/interchange/index.cjs +6 -6
- package/dist/interchange/index.d.cts +2 -2
- package/dist/interchange/index.d.ts +2 -2
- package/dist/interchange/index.js +1 -1
- package/dist/{manager-Ba2CXGMG.d.ts → manager-BCLhWysp.d.ts} +8 -6
- package/dist/{manager-Cu3JQN0H.d.cts → manager-DGSnJa1v.d.cts} +8 -6
- package/dist/profiler/index.d.cts +2 -2
- package/dist/profiler/index.d.ts +2 -2
- package/dist/schema/index.cjs +21 -21
- package/dist/schema/index.d.cts +2 -2
- package/dist/schema/index.d.ts +2 -2
- package/dist/schema/index.js +3 -3
- package/dist/{store-CL-QMus7.d.cts → store-DgzIgrmn.d.cts} +1 -1
- package/dist/{store-DJpuUOSL.d.ts → store-wqOO3GSy.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-23NGZHUN.cjs.map +0 -1
- package/dist/chunk-2DKSQNPW.js.map +0 -1
- package/dist/chunk-BELXZTVK.cjs.map +0 -1
- package/dist/chunk-JPO7W262.js.map +0 -1
- package/dist/chunk-JUZWF5NX.js.map +0 -1
- package/dist/chunk-K5O7TOJO.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["executeCompiled","tables","sql"],"mappings":";;;;AAUA,IAAM,oCAAA,GAAuC,GAAA;AAoD7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,EAAgC;AACjE,EAAA,OAAO,cAAA,CAAe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,EAAO;AACd,YAAA,EAAA,CAAG,IAAIA,GAAAA,CAAAA,QAAAA,CAAa,CAAA;AACpB,YAAA,MAAM,KAAA;AAAA,UACR;AAAA,QACF,CAAC,CAAA;AAAA,MACH;AAEA,MAAA,OAAO,EAAA,CAAG,WAAA,CAAY,OAAO,EAAA,KAAO;AAClC,QAAA,MAAM,YAAY,wBAAA,CAAyB;AAAA,UACzC,YAAA;AAAA,UACA,EAAA,EAAI,EAAA;AAAA,UACJ,iBAAA;AAAA,UACA,YAAA,EAAc,EAAE,IAAA,EAAM,KAAA,EAAO,QAAQ,KAAA,EAAM;AAAA,UAC3C;AAAA,SACD,CAAA;AACD,QAAA,OAAO,GAAG,SAAS,CAAA;AAAA,MACrB,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IAEA,MAAM,KAAA,GAAuB;AAAA,IAG7B;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,yBACP,OAAA,EACoB;AACpB,EAAA,MAAM,kBAAA,GACJ,OAAA,CAAQ,gBAAA,IACR,4BAAA,CAA6B,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAEH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ;AAAA,GACrB,CAAA;AACH","file":"chunk-2DKSQNPW.js","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{\n $client?: SqliteClientWithPrepare;\n}>;\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isD1?: boolean;\n isSync?: boolean;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n isD1: boolean;\n isSync: boolean;\n supportsCompiledExecution: boolean;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n): boolean {\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\") {\n return true;\n }\n if (sessionName === \"SQLiteD1Session\") {\n return false;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectD1Profile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n): boolean {\n if (profileHints.isD1 !== undefined) {\n return profileHints.isD1;\n }\n\n return isD1DatabaseBySessionName(db);\n}\n\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const databaseWithClient = db as SqliteClientCarrier;\n const sqliteClient = databaseWithClient.$client;\n if (sqliteClient?.prepare === undefined) {\n return undefined;\n }\n return sqliteClient;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n const cachedStatement = cache.get(sqlText);\n if (cachedStatement !== undefined) {\n // Promote to most-recently-used position for LRU eviction\n cache.delete(sqlText);\n cache.set(sqlText, cachedStatement);\n return cachedStatement;\n }\n\n const preparedStatement = sqliteClient.prepare(sqlText);\n cache.set(sqlText, preparedStatement);\n\n if (cache.size > cacheMax) {\n const oldestSqlText = cache.keys().next().value;\n if (typeof oldestSqlText === \"string\") {\n cache.delete(oldestSqlText);\n }\n }\n\n return preparedStatement;\n}\n\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n const rows = db.all(query);\n return (rows instanceof Promise ? await rows : rows) as readonly TRow[];\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\"\n ? { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const profileBase: Readonly<{\n isD1: boolean;\n isSync: boolean;\n sqliteClient: SqliteClientWithPrepare | undefined;\n }> = {\n isD1: detectD1Profile(db, profileHints),\n isSync: detectSyncProfile(db, profileHints),\n sqliteClient: resolveSqliteClient(db),\n };\n\n const supportsCompiledExecution =\n profileBase.isSync &&\n !profileBase.isD1 &&\n profileBase.sqliteClient !== undefined;\n\n const profile: SqliteExecutionProfile = {\n isD1: profileBase.isD1,\n isSync: profileBase.isSync,\n supportsCompiledExecution,\n };\n\n const compile = (query: SQL): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (supportsCompiledExecution) {\n const sqliteClient = profileBase.sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n sqliteClient,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n sqliteClient,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport { getTableName, type SQL, sql } from \"drizzle-orm\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport type { SqlTableNames } from \"../../query/compiler/schema\";\nimport {\n type CreateVectorIndexParams,\n D1_CAPABILITIES,\n type DropVectorIndexParams,\n type GraphBackend,\n SQLITE_CAPABILITIES,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport { createCommonOperationBackend } from \"./operation-backend-core\";\nimport { createSqliteOperationStrategy } from \"./operations/strategy\";\nimport {\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport { type SqliteTables, tables as defaultTables } from \"./schema/sqlite\";\nimport {\n createSqliteVectorIndex,\n dropSqliteVectorIndex,\n type VectorIndexOptions,\n} from \"./vector-index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `isD1: true` when using Cloudflare D1.\n */\n executionProfile?: SqliteExecutionProfileHints;\n}>;\n\nconst SQLITE_MAX_BIND_PARAMETERS = 999;\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst SQLITE_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 2,\n);\nconst SQLITE_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 1,\n);\n\ntype SerializedExecutionQueue = Readonly<{\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(SQLITE_ROW_MAPPER_CONFIG);\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n async runExclusive<T>(task: () => Promise<T>): Promise<T> {\n const runTask = async (): Promise<T> => task();\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nasync function runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: SqlTableNames;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: SqlTableNames;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): TransactionBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n } = options;\n\n async function execGet<T>(query: SQL): Promise<T | undefined> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.get(query);\n return (result instanceof Promise ? await result : result) as T | undefined;\n });\n }\n\n async function execAll<T>(query: SQL): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.all(query);\n return (result instanceof Promise ? await result : result) as T[];\n });\n }\n\n async function execRun(query: SQL): Promise<void> {\n await runWithSerializedQueue(serializedQueue, async () => {\n const result = db.run(query);\n if (result instanceof Promise) await result;\n });\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: SQLITE_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: SQLITE_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: SQLITE_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n const operationBackend: TransactionBackend = {\n ...commonBackend,\n ...executeRawMethod,\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n\n createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n const indexOptions: VectorIndexOptions = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.fieldPath,\n dimensions: params.dimensions,\n indexType: params.indexType,\n metric: params.metric,\n ...(params.indexParams?.m === undefined\n ? {}\n : { hnswM: params.indexParams.m }),\n ...(params.indexParams?.efConstruction === undefined\n ? {}\n : { hnswEfConstruction: params.indexParams.efConstruction }),\n ...(params.indexParams?.lists === undefined\n ? {}\n : { ivfflatLists: params.indexParams.lists }),\n };\n\n const result = createSqliteVectorIndex(indexOptions);\n\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to create SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n const result = dropSqliteVectorIndex(\n params.graphId,\n params.nodeKind,\n params.fieldPath,\n );\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to drop SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(query: SQL): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isD1, isSync } = executionAdapter.profile;\n const capabilities = isD1 ? D1_CAPABILITIES : SQLITE_CAPABILITIES;\n\n const tableNames: SqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n embeddings: getTableName(tables.embeddings),\n };\n const operationStrategy = createSqliteOperationStrategy(tables);\n const serializedQueue = isSync ? createSerializedExecutionQueue() : undefined;\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n const backend: GraphBackend = {\n ...operations,\n\n async setActiveSchema(graphId: string, version: number): Promise<void> {\n await backend.transaction(async (txBackend) => {\n await txBackend.setActiveSchema(graphId, version);\n });\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n _options?: TransactionOptions,\n ): Promise<T> {\n if (isD1) {\n throw new ConfigurationError(\n \"Cloudflare D1 does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n {\n backend: \"D1\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n\n if (isSync) {\n return runWithSerializedQueue(serializedQueue, async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isD1: false, isSync: true },\n tableNames,\n });\n db.run(sql`BEGIN`);\n\n try {\n const result = await fn(txBackend);\n db.run(sql`COMMIT`);\n return result;\n } catch (error) {\n db.run(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n return db.transaction(async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx as AnySqliteDatabase,\n operationStrategy,\n profileHints: { isD1: false, isSync: false },\n tableNames,\n });\n return fn(txBackend);\n }) as Promise<T>;\n },\n\n async close(): Promise<void> {\n // Drizzle doesn't expose a close method\n // Users manage connection lifecycle themselves\n },\n };\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): TransactionBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames,SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":["ConfigurationError","ValidationError"],"mappings":";;;;;AAOO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AA0PxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAKO,SAAS,WAAW,KAAA,EAAsC;AAC/D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAMO,SAAS,wBACd,KAAA,EACgC;AAChC,EAAA,OACE,WAAW,KAAK,CAAA,IAChB,MAAM,OAAA,CAAQ,KAAA,CAAM,IAA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AAA,CAAA;AAAA,MAEvD;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,eAAA,CAAgB,OAAO,SAAS,CAAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-BELXZTVK.cjs","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (if it has from/to defined)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | EdgeTypeWithEndpoints;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n */\ntype NormalizedEdges<TEdges extends Record<string, EdgeEntry>> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends EdgeTypeWithEndpoints ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"][number],\n TEdges[K][\"to\"][number]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(name: string, entry: EdgeEntry): EdgeRegistration {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to - convert to EdgeRegistration\n return {\n type: entry,\n from: entry.from,\n to: entry.to,\n };\n }\n\n // Already EdgeRegistration - validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const normalizedEdges = normalizeEdges(config.edges);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes) as (keyof G[\"nodes\"] & string)[];\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges) as (keyof G[\"edges\"] & string)[];\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
|