@g9tm/lynxcontrols-sqlite 1.4.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.
Files changed (111) hide show
  1. package/README.md +12 -0
  2. package/contract/cases.json +463 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/codecs/codecs.d.ts +68 -0
  5. package/dist/codecs/codecs.d.ts.map +1 -0
  6. package/dist/codecs/codecs.js +201 -0
  7. package/dist/codecs/codecs.js.map +1 -0
  8. package/dist/contract/run-contract.d.ts +94 -0
  9. package/dist/contract/run-contract.d.ts.map +1 -0
  10. package/dist/contract/run-contract.js +159 -0
  11. package/dist/contract/run-contract.js.map +1 -0
  12. package/dist/driver/types.d.ts +87 -0
  13. package/dist/driver/types.d.ts.map +1 -0
  14. package/dist/driver/types.js +14 -0
  15. package/dist/driver/types.js.map +1 -0
  16. package/dist/errors.d.ts +39 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +57 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/index.d.ts +25 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +22 -0
  23. package/dist/query/builders.d.ts +216 -0
  24. package/dist/query/builders.d.ts.map +1 -0
  25. package/dist/query/builders.js +490 -0
  26. package/dist/query/builders.js.map +1 -0
  27. package/dist/query/compile.d.ts +42 -0
  28. package/dist/query/compile.d.ts.map +1 -0
  29. package/dist/query/compile.js +307 -0
  30. package/dist/query/compile.js.map +1 -0
  31. package/dist/query/expr.d.ts +201 -0
  32. package/dist/query/expr.d.ts.map +1 -0
  33. package/dist/query/expr.js +247 -0
  34. package/dist/query/expr.js.map +1 -0
  35. package/dist/repo/audit.d.ts +19 -0
  36. package/dist/repo/audit.d.ts.map +1 -0
  37. package/dist/repo/audit.js +36 -0
  38. package/dist/repo/audit.js.map +1 -0
  39. package/dist/repo/repository.d.ts +233 -0
  40. package/dist/repo/repository.d.ts.map +1 -0
  41. package/dist/repo/repository.js +715 -0
  42. package/dist/repo/repository.js.map +1 -0
  43. package/dist/schema/columns.d.ts +115 -0
  44. package/dist/schema/columns.d.ts.map +1 -0
  45. package/dist/schema/columns.js +112 -0
  46. package/dist/schema/columns.js.map +1 -0
  47. package/dist/schema/entity.d.ts +135 -0
  48. package/dist/schema/entity.d.ts.map +1 -0
  49. package/dist/schema/entity.js +227 -0
  50. package/dist/schema/entity.js.map +1 -0
  51. package/dist/schema/policies.d.ts +89 -0
  52. package/dist/schema/policies.d.ts.map +1 -0
  53. package/dist/schema/policies.js +54 -0
  54. package/dist/schema/policies.js.map +1 -0
  55. package/dist/session/ambient.d.ts +32 -0
  56. package/dist/session/ambient.d.ts.map +1 -0
  57. package/dist/session/ambient.js +28 -0
  58. package/dist/session/ambient.js.map +1 -0
  59. package/dist/session/cache.d.ts +62 -0
  60. package/dist/session/cache.d.ts.map +1 -0
  61. package/dist/session/cache.js +239 -0
  62. package/dist/session/cache.js.map +1 -0
  63. package/dist/session/database.d.ts +221 -0
  64. package/dist/session/database.d.ts.map +1 -0
  65. package/dist/session/database.js +430 -0
  66. package/dist/session/database.js.map +1 -0
  67. package/dist/session/locator.d.ts +33 -0
  68. package/dist/session/locator.d.ts.map +1 -0
  69. package/dist/session/locator.js +39 -0
  70. package/dist/session/locator.js.map +1 -0
  71. package/dist/session/migrations.d.ts +75 -0
  72. package/dist/session/migrations.d.ts.map +1 -0
  73. package/dist/session/migrations.js +88 -0
  74. package/dist/session/migrations.js.map +1 -0
  75. package/dist/session/mutex.d.ts +7 -0
  76. package/dist/session/mutex.d.ts.map +1 -0
  77. package/dist/session/mutex.js +27 -0
  78. package/dist/session/mutex.js.map +1 -0
  79. package/dist/session/rows.d.ts +17 -0
  80. package/dist/session/rows.d.ts.map +1 -0
  81. package/dist/session/rows.js +52 -0
  82. package/dist/session/rows.js.map +1 -0
  83. package/dist/session/schema-setup.d.ts +21 -0
  84. package/dist/session/schema-setup.d.ts.map +1 -0
  85. package/dist/session/schema-setup.js +227 -0
  86. package/dist/session/schema-setup.js.map +1 -0
  87. package/dist/session/scope.d.ts +117 -0
  88. package/dist/session/scope.d.ts.map +1 -0
  89. package/dist/session/scope.js +233 -0
  90. package/dist/session/scope.js.map +1 -0
  91. package/dist/session/write-hooks.d.ts +84 -0
  92. package/dist/session/write-hooks.d.ts.map +1 -0
  93. package/dist/session/write-hooks.js +55 -0
  94. package/dist/session/write-hooks.js.map +1 -0
  95. package/dist/values/ids.d.ts +46 -0
  96. package/dist/values/ids.d.ts.map +1 -0
  97. package/dist/values/ids.js +84 -0
  98. package/dist/values/ids.js.map +1 -0
  99. package/dist/values/int64.d.ts +33 -0
  100. package/dist/values/int64.d.ts.map +1 -0
  101. package/dist/values/int64.js +105 -0
  102. package/dist/values/int64.js.map +1 -0
  103. package/dist/values/local-date-time.d.ts +61 -0
  104. package/dist/values/local-date-time.d.ts.map +1 -0
  105. package/dist/values/local-date-time.js +122 -0
  106. package/dist/values/local-date-time.js.map +1 -0
  107. package/dist/values/sql-value.d.ts +36 -0
  108. package/dist/values/sql-value.d.ts.map +1 -0
  109. package/dist/values/sql-value.js +70 -0
  110. package/dist/values/sql-value.js.map +1 -0
  111. package/package.json +27 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/schema-setup.js","sources":["../../src/session/schema-setup.ts"],"sourcesContent":["import { type G9CodecContext, g9DefaultCodecContext } from '../codecs/codecs';\nimport type { G9DriverStatement, G9RunOptions, G9SessionToken, G9SqlResult, G9TxToken } from '../driver/types';\nimport { G9SqliteError, isG9SqliteError } from '../errors';\nimport { compileExpr, inlineSql, quoteIdentifier } from '../query/compile';\nimport { and, type G9ColumnRef, type G9Predicate, not } from '../query/expr';\nimport type { G9EntityColumn, G9EntityDescriptor } from '../schema/entity';\nimport { formatLegacyDateTime } from '../values/local-date-time';\nimport type { G9SqliteDatabase } from './database';\nimport {\n G9_SCHEMA_HISTORY_COLUMNS,\n G9_SCHEMA_HISTORY_DDL,\n G9_SCHEMA_HISTORY_TABLE,\n type G9Migration,\n type G9MigrationContext,\n} from './migrations';\nimport { decodeGenericRows } from './rows';\n\n/** Deterministic `CREATE TABLE IF NOT EXISTS` for an entity. */\nexport function createTableSql(entity: G9EntityDescriptor): string {\n const singleKey = entity.primaryKey.length === 1 ? entity.primaryKey[0] : undefined;\n const columns = entity.columns.map((c) => {\n let sql = `${quoteIdentifier(c.column)} ${c.codec.sqlType}`;\n if (!c.nullable) sql += ' NOT NULL';\n if (c.collation) sql += ` COLLATE ${c.collation}`;\n if (singleKey === c) sql += c.autoIncrement ? ' PRIMARY KEY AUTOINCREMENT' : ' PRIMARY KEY';\n return sql;\n });\n if (entity.primaryKey.length > 1) {\n columns.push(`PRIMARY KEY (${entity.primaryKey.map((c) => quoteIdentifier(c.column)).join(', ')})`);\n }\n return `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(entity.table)} (${columns.join(', ')})`;\n}\n\n/** Name of a declared index (`IX_Table_A_B`, `UX_…` for unique) unless the declaration names it. */\nexport function indexName(entity: G9EntityDescriptor, index: G9EntityDescriptor['indexes'][number]): string {\n if (index.name) return index.name;\n // Index parts were validated against the columns when the entity was defined.\n const columns = index.parts.map((p) => (entity.byProperty.get(p.property) as G9EntityColumn).column);\n return `${index.unique ? 'UX' : 'IX'}_${entity.table}_${columns.join('_')}`;\n}\n\n/**\n * Deterministic DDL for an entity's declared indexes (N07): order, collation, partial predicate; a unique index on\n * a soft-delete entity covers live rows only unless `includeDeleted`. Partial predicates are inlined (SQLite does not\n * allow parameters in index definitions).\n */\nexport function createIndexSql(\n entity: G9EntityDescriptor,\n codecContext: G9CodecContext = g9DefaultCodecContext,\n): string[] {\n return entity.indexes.map((index) => {\n const parts = index.parts.map((p) => {\n const column = entity.byProperty.get(p.property);\n if (!column) throw new G9SqliteError('misuse', `Index on '${entity.name}' names no column '${p.property}'.`);\n let sql = quoteIdentifier(column.column);\n if (p.collate) sql += ` COLLATE ${p.collate}`;\n if (p.descending) sql += ' DESC';\n return sql;\n });\n const predicates: G9Predicate[] = [];\n if (index.where) predicates.push(index.where(entity.refs));\n if (index.unique && entity.softDelete && !index.includeDeleted) {\n predicates.push(\n not((entity.refs as Record<string, G9ColumnRef<boolean>>)[entity.softDelete.flag] as G9ColumnRef<boolean>),\n );\n }\n let sql = `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quoteIdentifier(indexName(entity, index))} ON ${quoteIdentifier(entity.table)} (${parts.join(', ')})`;\n if (predicates.length) {\n const f = compileExpr(predicates.length === 1 ? (predicates[0] as G9Predicate) : and(...predicates), {\n codec: codecContext,\n culture: null,\n localized: new Set(),\n qualify: false,\n maxInListParameters: Number.MAX_SAFE_INTEGER,\n });\n sql += ` WHERE ${inlineSql(f.sql, f.params)}`;\n }\n return sql;\n });\n}\n\ninterface SetupRunner {\n run(statements: readonly G9DriverStatement[], tx: G9TxToken | null): Promise<ReturnType<typeof decodeGenericRows>[]>;\n changes(sql: string, params: readonly unknown[], tx: G9TxToken | null): Promise<number>;\n}\n\nfunction makeContext(db: G9SqliteDatabase, runner: SetupRunner, tx: G9TxToken | null): G9MigrationContext {\n const codec = db.options.codec;\n const ctx: G9MigrationContext = {\n signal: undefined,\n execute: (sql, ...params) => runner.changes(sql, params, tx),\n async query(sql, ...params) {\n const [rows] = await runner.run([{ sql, params: db.encodeRaw(params) }], tx);\n return rows as Record<string, unknown>[];\n },\n async tableExists(table) {\n const rows = await ctx.query(\"SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?\", table);\n return Number(rows[0]?.n) > 0;\n },\n async columnExists(table, column) {\n const rows = await ctx.query(\n 'SELECT COUNT(*) AS n FROM pragma_table_info(?) WHERE lower(name) = lower(?)',\n table,\n column,\n );\n return Number(rows[0]?.n) > 0;\n },\n async createTable(entity) {\n await ctx.execute(createTableSql(entity));\n },\n async createIndexes(entity) {\n for (const sql of createIndexSql(entity, codec)) {\n try {\n await ctx.execute(sql);\n } catch (error) {\n if (!isG9SqliteError(error, 'constraint')) throw error;\n throw new G9SqliteError(\n 'constraint',\n `Cannot create a unique index on '${entity.table}': existing rows violate it. No data was changed; ` +\n `resolve the duplicates in a migration before declaring the index. (${sql})`,\n { sql, cause: error },\n );\n }\n }\n },\n };\n return ctx;\n}\n\n/**\n * Runs once per database path on its first connection, inside the connection lock: history-table collision check,\n * migrations (N01), declared indexes of registered entities (N07), then initializers (N02). Any failure closes the\n * connection; the next call retries from the first unapplied step.\n */\nexport async function runSchemaSetup(db: G9SqliteDatabase, session: G9SessionToken): Promise<void> {\n const { driver, migrations, initializers, entities, readOnly } = db.options;\n const runner: SetupRunner = {\n async run(statements, tx) {\n const options: G9RunOptions = tx ? { tx } : {};\n const results = await driver.run(session, statements, options);\n return results.map((r) => decodeGenericRows(r));\n },\n async changes(sql, params, tx) {\n const options: G9RunOptions = tx ? { tx } : {};\n const [result] = await driver.run(session, [{ sql, params: db.encodeRaw(params) }], options);\n return (result as G9SqlResult).changes;\n },\n };\n const needsHistory = migrations.length > 0 || initializers.some((i) => i.mode === 'once');\n const indexed = entities.filter((e) => e.indexes.length > 0);\n if (!needsHistory && indexed.length === 0 && initializers.length === 0) return;\n if (readOnly) {\n if (needsHistory || initializers.length) {\n throw new G9SqliteError('readonly', 'Migrations and initializers cannot run on a read-only database.');\n }\n return;\n }\n\n async function inTx<T>(work: (tx: G9TxToken) => Promise<T>): Promise<T> {\n const tx = await driver.begin(session, 'immediate');\n try {\n const value = await work(tx);\n await driver.commit(tx);\n return value;\n } catch (error) {\n await driver.rollback(tx).catch(() => undefined);\n throw error;\n }\n }\n\n if (needsHistory) {\n const [info] = await runner.run(\n [{ sql: `SELECT name FROM pragma_table_info('${G9_SCHEMA_HISTORY_TABLE}')`, params: [] }],\n null,\n );\n const existing = (info as Record<string, unknown>[]).map((r) => String(r.name));\n if (existing.length > 0 && G9_SCHEMA_HISTORY_COLUMNS.some((c) => existing.indexOf(c) < 0)) {\n throw new G9SqliteError(\n 'other',\n `A table named '${G9_SCHEMA_HISTORY_TABLE}' exists with other columns (${existing.join(', ')}); it is not ` +\n 'G9 migration history. Rename it before using migrations.',\n );\n }\n if (existing.length === 0) await runner.changes(G9_SCHEMA_HISTORY_DDL, [], null);\n }\n\n const now = () => formatLegacyDateTime(db.options.clock.now(), 'provider');\n const history = async (tx: G9TxToken | null) => {\n const [rows] = await runner.run(\n [{ sql: `SELECT \"Kind\", \"Key\", \"Version\", \"Checksum\" FROM \"${G9_SCHEMA_HISTORY_TABLE}\"`, params: [] }],\n tx,\n );\n return rows as Record<string, unknown>[];\n };\n\n if (migrations.length > 0) {\n const applied = await history(null);\n const appliedMigrations = applied.filter((r) => r.Kind === 'migration');\n for (const m of migrations) {\n const row = appliedMigrations.find((r) => Number(r.Version) === m.version);\n if (row && row.Checksum !== m.checksum) {\n throw new G9SqliteError(\n 'other',\n `Migration ${m.version} ('${m.name}') was applied with checksum ${String(row.Checksum)} but is now ` +\n `${m.checksum}. An applied migration must never change; add a new one instead.`,\n );\n }\n }\n for (const m of migrations) {\n if (appliedMigrations.some((r) => Number(r.Version) === m.version)) continue;\n await applyMigration(db, runner, inTx, m, now);\n }\n }\n\n for (const entity of indexed) {\n const ctx = makeContext(db, runner, null);\n if (!(await ctx.tableExists(entity.table))) continue;\n await inTx(async (tx) => makeContext(db, runner, tx).createIndexes(entity));\n }\n\n for (const initializer of initializers) {\n if (initializer.mode === 'everyOpen') {\n await inTx(async (tx) => initializer.run(makeContext(db, runner, tx)));\n continue;\n }\n await inTx(async (tx) => {\n const rows = await history(tx);\n if (rows.some((r) => r.Kind === 'initializer' && r.Key === initializer.name)) return;\n await initializer.run(makeContext(db, runner, tx));\n await runner.changes(\n `INSERT INTO \"${G9_SCHEMA_HISTORY_TABLE}\" (\"Kind\", \"Key\", \"Version\", \"Name\", \"Checksum\", \"AppliedAt\") VALUES ('initializer', ?, NULL, ?, '', ?)`,\n [initializer.name, initializer.name, now()],\n tx,\n );\n });\n }\n}\n\nasync function applyMigration(\n db: G9SqliteDatabase,\n runner: SetupRunner,\n inTx: <T>(work: (tx: G9TxToken) => Promise<T>) => Promise<T>,\n m: G9Migration,\n now: () => string,\n): Promise<void> {\n const record = (tx: G9TxToken | null) =>\n runner.changes(\n `INSERT INTO \"${G9_SCHEMA_HISTORY_TABLE}\" (\"Kind\", \"Key\", \"Version\", \"Name\", \"Checksum\", \"AppliedAt\") VALUES ('migration', ?, ?, ?, ?, ?)`,\n [String(m.version), m.version, m.name, m.checksum, now()],\n tx,\n );\n const check = async (tx: G9TxToken | null): Promise<'applied' | 'pending'> => {\n const [rows] = await runner.run(\n [\n {\n sql: `SELECT \"Version\", \"Checksum\" FROM \"${G9_SCHEMA_HISTORY_TABLE}\" WHERE \"Kind\" = 'migration'`,\n params: [],\n },\n ],\n tx,\n );\n const list = rows as Record<string, unknown>[];\n if (list.some((r) => Number(r.Version) === m.version)) return 'applied';\n const newer = list.map((r) => Number(r.Version)).filter((v) => v > m.version);\n if (newer.length > 0) {\n throw new G9SqliteError(\n 'other',\n `Migration ${m.version} ('${m.name}') is registered below already-applied version ${Math.max(...newer)}: ` +\n 'it would never run in order. Give it a version above the newest applied one.',\n );\n }\n return 'pending';\n };\n try {\n if (!m.transactional) {\n if ((await check(null)) === 'applied') return;\n await m.up(makeContext(db, runner, null));\n await record(null);\n return;\n }\n await inTx(async (tx) => {\n // Re-checked under the write lock: a second opener may have applied it meanwhile.\n if ((await check(tx)) === 'applied') return;\n await m.up(makeContext(db, runner, tx));\n await record(tx);\n });\n } catch (error) {\n if (isG9SqliteError(error) && error.message.startsWith('Migration ')) throw error;\n throw new G9SqliteError(\n isG9SqliteError(error) ? error.code : 'other',\n `Migration ${m.version} ('${m.name}') failed and was rolled back; it runs again on the next open. ` +\n `${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n"],"names":["createTableSql","entity","singleKey","undefined","columns","c","sql","quoteIdentifier","indexName","index","p","createIndexSql","codecContext","g9DefaultCodecContext","parts","column","G9SqliteError","predicates","not","f","compileExpr","and","Set","Number","inlineSql","makeContext","db","runner","tx","codec","ctx","params","rows","table","_rows_","error","isG9SqliteError","runSchemaSetup","session","driver","migrations","initializers","entities","readOnly","statements","options","results","r","decodeGenericRows","result","needsHistory","i","indexed","e","inTx","work","value","info","G9_SCHEMA_HISTORY_TABLE","existing","String","G9_SCHEMA_HISTORY_COLUMNS","G9_SCHEMA_HISTORY_DDL","now","formatLegacyDateTime","history","applied","appliedMigrations","m","row","applyMigration","initializer","record","check","list","newer","v","Math","Error"],"mappings":";;;;;;;AAkBO,SAASA,eAAeC,MAA0B;IACvD,MAAMC,YAAYD,AAA6B,MAA7BA,OAAO,UAAU,CAAC,MAAM,GAASA,OAAO,UAAU,CAAC,EAAE,GAAGE;IAC1E,MAAMC,UAAUH,OAAO,OAAO,CAAC,GAAG,CAAC,CAACI;QAClC,IAAIC,MAAM,GAAGC,gBAAgBF,EAAE,MAAM,EAAE,CAAC,EAAEA,EAAE,KAAK,CAAC,OAAO,EAAE;QAC3D,IAAI,CAACA,EAAE,QAAQ,EAAEC,OAAO;QACxB,IAAID,EAAE,SAAS,EAAEC,OAAO,CAAC,SAAS,EAAED,EAAE,SAAS,EAAE;QACjD,IAAIH,cAAcG,GAAGC,OAAOD,EAAE,aAAa,GAAG,+BAA+B;QAC7E,OAAOC;IACT;IACA,IAAIL,OAAO,UAAU,CAAC,MAAM,GAAG,GAC7BG,QAAQ,IAAI,CAAC,CAAC,aAAa,EAAEH,OAAO,UAAU,CAAC,GAAG,CAAC,CAACI,IAAME,gBAAgBF,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAEpG,OAAO,CAAC,2BAA2B,EAAEE,gBAAgBN,OAAO,KAAK,EAAE,EAAE,EAAEG,QAAQ,IAAI,CAAC,MAAM,CAAC,CAAC;AAC9F;AAGO,SAASI,UAAUP,MAA0B,EAAEQ,KAA4C;IAChG,IAAIA,MAAM,IAAI,EAAE,OAAOA,MAAM,IAAI;IAEjC,MAAML,UAAUK,MAAM,KAAK,CA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KAAK,GAAG,IAAIF,OAAO,8EAAE,CAAC;QAI9G,OAAO;IACT;IACA,IAAI;QACF,IAAI,CAACP,EAAE,aAAa,EAAE;YACpB,IAAK,MAAMK,MAAM,UAAW,WAAW;YACvC,MAAML,EAAE,EAAE,CAAC3C,YAAYC,IAAIC,QAAQ;YACnC,MAAM6C,OAAO;YACb;QACF;QACA,MAAMlB,KAAK,OAAO1B;YAEhB,IAAK,MAAM6C,MAAM7C,QAAS,WAAW;YACrC,MAAMwC,EAAE,EAAE,CAAC3C,YAAYC,IAAIC,QAAQC;YACnC,MAAM4C,OAAO5C;QACf;IACF,EAAE,OAAOO,OAAO;QACd,IAAIC,gBAAgBD,UAAUA,MAAM,OAAO,CAAC,UAAU,CAAC,eAAe,MAAMA;QAC5E,MAAM,IAAInB,cACRoB,gBAAgBD,SAASA,MAAM,IAAI,GAAG,SACtC,CAAC,UAAU,EAAEiC,EAAE,OAAO,CAAC,GAAG,EAAEA,EAAE,IAAI,CAC/B,iEAAEjC,iBAAiB2C,QAAQ3C,MAAM,OAAO,GAAGyB,OAAOzB,QAD8C,EAEnG;YAAE,OAAOA;QAAM;IAEnB;AACF"}
@@ -0,0 +1,117 @@
1
+ import type { G9DriverCapabilities } from '../driver/types.js';
2
+ import type { G9SqlStatement } from '../query/builders.js';
3
+ import { G9Repository } from '../repo/repository.js';
4
+ import type { G9EntityDescriptor } from '../schema/entity.js';
5
+ import type { G9CachePolicy } from '../schema/policies.js';
6
+ import type { G9CacheHandle } from './cache.js';
7
+ import { G9SqliteDatabase, type G9SqliteOptions, type G9TransactionOptions, type G9TxState } from './database.js';
8
+ import type { G9ChangeEvent } from './write-hooks.js';
9
+ /**
10
+ * Where work runs: the database (each call its own atomic unit) or inside a transaction (every call joins it). Both
11
+ * {@link G9Sqlite} and transaction scopes have this surface.
12
+ */
13
+ export declare class G9SqliteScope {
14
+ /** @internal */ readonly db: G9SqliteDatabase;
15
+ /** @internal */ readonly tx: G9TxState | null;
16
+ /** @internal */ readonly bypassFilters: boolean;
17
+ private readonly repos;
18
+ /** @internal */
19
+ constructor(db: G9SqliteDatabase, tx: G9TxState | null, bypassFilters: boolean);
20
+ /** The repository of an entity in this scope (MAUI `SqliteRepository<T>`; one instance per entity). */
21
+ repo<E extends G9EntityDescriptor>(entity: E): G9Repository<E>;
22
+ /** Raw statement (DDL/DML). Outside filters, soft delete and audit. A mutation invalidates every cache. */
23
+ execute(sql: string | G9SqlStatement, ...params: unknown[]): Promise<number>;
24
+ /** Raw query: records keyed by result column (int64 beyond 2^53 as decimal strings). */
25
+ query<R = Record<string, unknown>>(sql: string | G9SqlStatement, ...params: unknown[]): Promise<R[]>;
26
+ /** Raw scalar: first column of the first row, or `null`. */
27
+ scalar<R = unknown>(sql: string | G9SqlStatement, ...params: unknown[]): Promise<R | null>;
28
+ private run;
29
+ /**
30
+ * Runs `work` in a transaction (MAUI `RunInTransactionAsync`). At the top level: an immediate transaction holding
31
+ * the connection for its duration, committed when `work` resolves, rolled back when it throws, and retried whole on
32
+ * `busy` (N10). Inside a transaction: a savepoint (nested transactions); its commit effects fire only when the
33
+ * outermost transaction commits, and are dropped when the savepoint rolls back.
34
+ */
35
+ transaction<T>(work: (tx: G9SqliteScope) => Promise<T>, options?: G9TransactionOptions): Promise<T>;
36
+ /** MAUI-style explicit transaction (`IG9SqliteTransaction`): commit or roll back yourself; `dispose()` rolls back. */
37
+ beginTransaction(options?: G9TransactionOptions): Promise<G9SqliteTransaction>;
38
+ /**
39
+ * N06 scoped bypass: runs `work` with a scope whose repositories ignore every always-filter (soft delete is still
40
+ * governed per query with `includeDeleted()`).
41
+ */
42
+ unfiltered<T>(work: (scope: G9SqliteScope) => Promise<T>): Promise<T>;
43
+ }
44
+ /** An explicit transaction (MAUI `IG9SqliteTransaction`). Holds the connection until finished. */
45
+ export declare class G9SqliteTransaction extends G9SqliteScope {
46
+ private readonly release;
47
+ private state;
48
+ /** @internal */
49
+ constructor(db: G9SqliteDatabase, tx: G9TxState, release: () => void, bypassFilters: boolean);
50
+ /** `true` once committed or rolled back. */
51
+ get isFinished(): boolean;
52
+ /** MAUI `CommitAsync`: commits. Calling twice is an error. Commit effects (caches, hooks) run afterwards. */
53
+ commit(): Promise<void>;
54
+ /** MAUI `RollbackAsync`: rolls back (no-op when already finished). */
55
+ rollback(): Promise<void>;
56
+ /** MAUI `DisposeAsync`: rolls back when not committed, so an early return never half-applies. */
57
+ dispose(): Promise<void>;
58
+ }
59
+ /**
60
+ * The database facade returned by {@link createG9Sqlite} (MAUI `AddG9Sqlite` + `G9SqliteConnectionProvider` +
61
+ * `SqliteRepositoryCacheRegistry`).
62
+ */
63
+ export declare class G9Sqlite extends G9SqliteScope {
64
+ /** @internal */
65
+ constructor(db: G9SqliteDatabase);
66
+ /** MAUI `DatabasePath`. */
67
+ get databasePath(): string;
68
+ /** MAUI `ActiveDatabasePath`. */
69
+ get activeDatabasePath(): string | null;
70
+ /** MAUI `HasActiveDatabase`. */
71
+ get hasActiveDatabase(): boolean;
72
+ /** The user/path generation (bumped by every switch). */
73
+ get generation(): number;
74
+ /** Driver capabilities. */
75
+ capabilities(): Promise<G9DriverCapabilities>;
76
+ /** MAUI `SqliteMigrationRunner.RunAsync`: open now (migrations, index DDL, initializers). */
77
+ migrate(): Promise<void>;
78
+ /** MAUI `SwitchDatabaseAsync`. */
79
+ switchDatabase(): Promise<void>;
80
+ /** MAUI `CloseCurrentConnectionAsync`. */
81
+ closeConnection(): Promise<void>;
82
+ /** MAUI `CheckpointWalAsync`. */
83
+ checkpointWal(): Promise<void>;
84
+ /** Disposes the database (MAUI `DisposeAsync`). */
85
+ close(): Promise<void>;
86
+ /** Committed-change notifications. */
87
+ onChange(listener: (event: G9ChangeEvent) => void): () => void;
88
+ /** An external writer changed these tables: caches over them refresh, listeners hear it. */
89
+ notifyExternalChange(change: {
90
+ readonly tables: readonly string[];
91
+ }): void;
92
+ /** MAUI `SqliteDtoCache.DefineCache`: a cache of a projection over source entities, refreshed after their commits. */
93
+ defineDtoCache<T>(name: string, sources: readonly G9EntityDescriptor[], load: (db: G9Sqlite) => Promise<T[]>, policy: G9CachePolicy): G9CacheHandle<T>;
94
+ /** The DTO cache of that name (MAUI `GetDtoCacheData…`). */
95
+ dtoCache<T>(name: string): G9CacheHandle<T> | undefined;
96
+ /** MAUI cache registry: `HardRefreshAllCache`, `RefreshCacheAsync(Type)`, `RefreshEntityAndDtoCachesAsync`, reset. */
97
+ get caches(): {
98
+ refreshAll(): Promise<void>;
99
+ refresh(entity: G9EntityDescriptor): Promise<boolean>;
100
+ refreshEntityAndDtoCaches(entity: G9EntityDescriptor): Promise<void>;
101
+ resetAll(): void;
102
+ readonly totalRows: number;
103
+ };
104
+ }
105
+ /**
106
+ * Creates the persistence layer (MAUI `services.AddG9Sqlite(...)`). Configuration errors (duplicate migration
107
+ * versions, invalid options) throw here; the connection opens on first use, running migrations, index DDL and
108
+ * initializers once per database path.
109
+ *
110
+ * ```ts
111
+ * const db = createG9Sqlite({ driver, locator: perUserDatabaseLocator({ root, userId }), create: true,
112
+ * entities: { sample: Sample }, migrations: [m1], interceptors: [stampSyncDirty] });
113
+ * const rows = await db.repo(Sample).select.where((x) => ne(x.title, 'blocked'));
114
+ * ```
115
+ */
116
+ export declare function createG9Sqlite(options: G9SqliteOptions): G9Sqlite;
117
+ //# sourceMappingURL=scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../../src/session/scope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAe,MAAM,iBAAiB,CAAC;AAEzE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAiB,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,aAAa,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,CAEjE"}
@@ -0,0 +1,233 @@
1
+ import { G9SqliteError } from "../errors.js";
2
+ import { G9Repository, isMutationSql } from "../repo/repository.js";
3
+ import { isInt64Tag } from "../values/sql-value.js";
4
+ import { G9SqliteDatabase } from "./database.js";
5
+ import { decodeGenericRows } from "./rows.js";
6
+ function _define_property(obj, key, value) {
7
+ if (key in obj) Object.defineProperty(obj, key, {
8
+ value: value,
9
+ enumerable: true,
10
+ configurable: true,
11
+ writable: true
12
+ });
13
+ else obj[key] = value;
14
+ return obj;
15
+ }
16
+ let savepointSeed = 0;
17
+ class G9SqliteScope {
18
+ repo(entity) {
19
+ let repo = this.repos.get(entity);
20
+ if (!repo) {
21
+ if (!entity || !Array.isArray(entity.columns)) throw new G9SqliteError('misuse', "repo() needs an entity descriptor from defineEntity().");
22
+ repo = new G9Repository(this, entity);
23
+ this.repos.set(entity, repo);
24
+ }
25
+ return repo;
26
+ }
27
+ async execute(sql, ...params) {
28
+ const statement = 'string' == typeof sql ? {
29
+ sql,
30
+ params: this.db.encodeRaw(params)
31
+ } : sql;
32
+ return this.db.unit(this.tx, false, async (uow)=>{
33
+ const [r] = await uow.run([
34
+ statement
35
+ ]);
36
+ const changes = r.changes;
37
+ if (isMutationSql(statement.sql)) uow.onCommit(()=>{
38
+ this.db.caches.invalidateAll();
39
+ this.db.emitChange({
40
+ table: '*',
41
+ entity: null,
42
+ kind: 'raw',
43
+ rowCount: changes
44
+ });
45
+ });
46
+ return changes;
47
+ });
48
+ }
49
+ async query(sql, ...params) {
50
+ const [r] = await this.run(sql, params);
51
+ return decodeGenericRows(r);
52
+ }
53
+ async scalar(sql, ...params) {
54
+ var _r_rows_;
55
+ const [r] = await this.run(sql, params);
56
+ const v = null == r ? void 0 : null == (_r_rows_ = r.rows[0]) ? void 0 : _r_rows_[0];
57
+ return void 0 === v ? null : isInt64Tag(v) ? v.int64 : v;
58
+ }
59
+ run(sql, params) {
60
+ const statement = 'string' == typeof sql ? {
61
+ sql,
62
+ params: this.db.encodeRaw(params)
63
+ } : sql;
64
+ if (this.tx) return this.db.runInTx(this.tx, [
65
+ statement
66
+ ], void 0, void 0);
67
+ return this.db.runRead([
68
+ statement
69
+ ]);
70
+ }
71
+ async transaction(work, options = {}) {
72
+ if (this.tx) {
73
+ const parent = this.tx;
74
+ const name = `g9_sp_${++savepointSeed}`;
75
+ const mark = parent.commitCallbacks.length;
76
+ await this.db.runInTx(parent, [
77
+ {
78
+ sql: `SAVEPOINT ${name}`,
79
+ params: []
80
+ }
81
+ ], void 0, options.signal);
82
+ try {
83
+ const value = await work(new G9SqliteScope(this.db, parent, this.bypassFilters));
84
+ await this.db.runInTx(parent, [
85
+ {
86
+ sql: `RELEASE ${name}`,
87
+ params: []
88
+ }
89
+ ], void 0, void 0);
90
+ return value;
91
+ } catch (error) {
92
+ parent.commitCallbacks.length = mark;
93
+ await this.db.runInTx(parent, [
94
+ {
95
+ sql: `ROLLBACK TO ${name}`,
96
+ params: []
97
+ },
98
+ {
99
+ sql: `RELEASE ${name}`,
100
+ params: []
101
+ }
102
+ ], void 0, void 0).catch((e)=>this.db.report('savepoint rollback failed', e));
103
+ throw error;
104
+ }
105
+ }
106
+ return this.db.unit(null, true, (uow)=>work(new G9SqliteScope(this.db, uow.txState, this.bypassFilters)), options);
107
+ }
108
+ async beginTransaction(options = {}) {
109
+ if (this.tx) throw new G9SqliteError('misuse', 'beginTransaction inside a transaction: use transaction() (savepoint).');
110
+ const { tx, release } = await this.db.openTransaction(options);
111
+ return new G9SqliteTransaction(this.db, tx, release, this.bypassFilters);
112
+ }
113
+ unfiltered(work) {
114
+ return work(new G9SqliteScope(this.db, this.tx, true));
115
+ }
116
+ constructor(db, tx, bypassFilters){
117
+ _define_property(this, "db", void 0);
118
+ _define_property(this, "tx", void 0);
119
+ _define_property(this, "bypassFilters", void 0);
120
+ _define_property(this, "repos", new Map());
121
+ this.db = db;
122
+ this.tx = tx;
123
+ this.bypassFilters = bypassFilters;
124
+ }
125
+ }
126
+ class G9SqliteTransaction extends G9SqliteScope {
127
+ get isFinished() {
128
+ return 'open' !== this.state;
129
+ }
130
+ async commit() {
131
+ if ('open' !== this.state) throw new G9SqliteError('misuse', 'The transaction is already finished.');
132
+ const tx = this.tx;
133
+ try {
134
+ await this.db.commitTx(tx);
135
+ } catch (error) {
136
+ if (tx.finished) this.state = 'committed';
137
+ else {
138
+ await this.db.rollbackTx(tx);
139
+ this.state = 'rolledBack';
140
+ }
141
+ this.release();
142
+ throw error;
143
+ }
144
+ this.state = 'committed';
145
+ this.release();
146
+ await this.db.runCommitCallbacks(tx.commitCallbacks);
147
+ }
148
+ async rollback() {
149
+ if ('open' !== this.state) return;
150
+ this.state = 'rolledBack';
151
+ try {
152
+ await this.db.rollbackTx(this.tx);
153
+ } finally{
154
+ this.release();
155
+ }
156
+ }
157
+ dispose() {
158
+ return this.rollback();
159
+ }
160
+ constructor(db, tx, release, bypassFilters){
161
+ super(db, tx, bypassFilters), _define_property(this, "release", void 0), _define_property(this, "state", 'open');
162
+ this.release = release;
163
+ }
164
+ }
165
+ class G9Sqlite extends G9SqliteScope {
166
+ get databasePath() {
167
+ return this.db.databasePath;
168
+ }
169
+ get activeDatabasePath() {
170
+ return this.db.activeDatabasePath;
171
+ }
172
+ get hasActiveDatabase() {
173
+ return this.db.hasActiveDatabase;
174
+ }
175
+ get generation() {
176
+ return this.db.generation;
177
+ }
178
+ capabilities() {
179
+ return this.db.capabilities();
180
+ }
181
+ migrate() {
182
+ return this.db.migrate();
183
+ }
184
+ switchDatabase() {
185
+ return this.db.switchDatabase();
186
+ }
187
+ closeConnection() {
188
+ return this.db.closeConnection();
189
+ }
190
+ checkpointWal() {
191
+ return this.db.checkpointWal();
192
+ }
193
+ close() {
194
+ return this.db.close();
195
+ }
196
+ onChange(listener) {
197
+ return this.db.onChange(listener);
198
+ }
199
+ notifyExternalChange(change) {
200
+ this.db.notifyExternalChange(change);
201
+ }
202
+ defineDtoCache(name, sources, load, policy) {
203
+ return this.db.caches.defineDtoCache(name, sources, policy, async (maxRows)=>{
204
+ const rows = await load(this);
205
+ if (rows.length > maxRows) throw new G9SqliteError('too-many-rows', `DTO cache '${name}' produced ${rows.length} rows (max ${maxRows}).`);
206
+ return rows;
207
+ });
208
+ }
209
+ dtoCache(name) {
210
+ return this.db.caches.dtoCache(name);
211
+ }
212
+ get caches() {
213
+ const registry = this.db.caches;
214
+ return {
215
+ refreshAll: ()=>registry.refreshAll(),
216
+ refresh: (entity)=>registry.refreshEntity(entity),
217
+ refreshEntityAndDtoCaches: (entity)=>registry.refreshEntityAndDtoCaches(entity),
218
+ resetAll: ()=>registry.resetAll(),
219
+ get totalRows () {
220
+ return registry.totalRows;
221
+ }
222
+ };
223
+ }
224
+ constructor(db){
225
+ super(db, null, false);
226
+ }
227
+ }
228
+ function createG9Sqlite(options) {
229
+ return new G9Sqlite(new G9SqliteDatabase(options));
230
+ }
231
+ export { G9Sqlite, G9SqliteScope, G9SqliteTransaction, createG9Sqlite };
232
+
233
+ //# sourceMappingURL=scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/scope.js","sources":["../../src/session/scope.ts"],"sourcesContent":["import type { G9DriverCapabilities, G9SqlResult } from '../driver/types';\nimport { G9SqliteError } from '../errors';\nimport type { G9SqlStatement } from '../query/builders';\nimport { G9Repository, isMutationSql } from '../repo/repository';\nimport type { G9EntityDescriptor } from '../schema/entity';\nimport type { G9CachePolicy } from '../schema/policies';\nimport { isInt64Tag } from '../values/sql-value';\nimport type { G9CacheHandle } from './cache';\nimport { G9SqliteDatabase, type G9SqliteOptions, type G9TransactionOptions, type G9TxState } from './database';\nimport { decodeGenericRows } from './rows';\nimport type { G9ChangeEvent } from './write-hooks';\n\nlet savepointSeed = 0;\n\n/**\n * Where work runs: the database (each call its own atomic unit) or inside a transaction (every call joins it). Both\n * {@link G9Sqlite} and transaction scopes have this surface.\n */\nexport class G9SqliteScope {\n /** @internal */ readonly db: G9SqliteDatabase;\n /** @internal */ readonly tx: G9TxState | null;\n /** @internal */ readonly bypassFilters: boolean;\n private readonly repos = new Map<G9EntityDescriptor, G9Repository<G9EntityDescriptor>>();\n\n /** @internal */\n constructor(db: G9SqliteDatabase, tx: G9TxState | null, bypassFilters: boolean) {\n this.db = db;\n this.tx = tx;\n this.bypassFilters = bypassFilters;\n }\n\n /** The repository of an entity in this scope (MAUI `SqliteRepository<T>`; one instance per entity). */\n repo<E extends G9EntityDescriptor>(entity: E): G9Repository<E> {\n let repo = this.repos.get(entity);\n if (!repo) {\n if (!entity || !Array.isArray(entity.columns)) {\n throw new G9SqliteError('misuse', 'repo() needs an entity descriptor from defineEntity().');\n }\n repo = new G9Repository(this, entity) as unknown as G9Repository<G9EntityDescriptor>;\n this.repos.set(entity, repo);\n }\n return repo as unknown as G9Repository<E>;\n }\n\n /** Raw statement (DDL/DML). Outside filters, soft delete and audit. A mutation invalidates every cache. */\n async execute(sql: string | G9SqlStatement, ...params: unknown[]): Promise<number> {\n const statement = typeof sql === 'string' ? { sql, params: this.db.encodeRaw(params) } : sql;\n return this.db.unit(this.tx, false, async (uow) => {\n const [r] = await uow.run([statement]);\n const changes = (r as G9SqlResult).changes;\n if (isMutationSql(statement.sql)) {\n uow.onCommit(() => {\n this.db.caches.invalidateAll();\n this.db.emitChange({ table: '*', entity: null, kind: 'raw', rowCount: changes });\n });\n }\n return changes;\n });\n }\n\n /** Raw query: records keyed by result column (int64 beyond 2^53 as decimal strings). */\n async query<R = Record<string, unknown>>(sql: string | G9SqlStatement, ...params: unknown[]): Promise<R[]> {\n const [r] = await this.run(sql, params);\n return decodeGenericRows(r as G9SqlResult) as R[];\n }\n\n /** Raw scalar: first column of the first row, or `null`. */\n async scalar<R = unknown>(sql: string | G9SqlStatement, ...params: unknown[]): Promise<R | null> {\n const [r] = await this.run(sql, params);\n const v = r?.rows[0]?.[0];\n return (v === undefined ? null : isInt64Tag(v) ? v.int64 : v) as R | null;\n }\n\n private run(sql: string | G9SqlStatement, params: unknown[]): Promise<G9SqlResult[]> {\n const statement = typeof sql === 'string' ? { sql, params: this.db.encodeRaw(params) } : sql;\n if (this.tx) return this.db.runInTx(this.tx, [statement], undefined, undefined);\n return this.db.runRead([statement]);\n }\n\n /**\n * Runs `work` in a transaction (MAUI `RunInTransactionAsync`). At the top level: an immediate transaction holding\n * the connection for its duration, committed when `work` resolves, rolled back when it throws, and retried whole on\n * `busy` (N10). Inside a transaction: a savepoint (nested transactions); its commit effects fire only when the\n * outermost transaction commits, and are dropped when the savepoint rolls back.\n */\n async transaction<T>(work: (tx: G9SqliteScope) => Promise<T>, options: G9TransactionOptions = {}): Promise<T> {\n if (this.tx) {\n const parent = this.tx;\n const name = `g9_sp_${++savepointSeed}`;\n const mark = parent.commitCallbacks.length;\n await this.db.runInTx(parent, [{ sql: `SAVEPOINT ${name}`, params: [] }], undefined, options.signal);\n try {\n const value = await work(new G9SqliteScope(this.db, parent, this.bypassFilters));\n await this.db.runInTx(parent, [{ sql: `RELEASE ${name}`, params: [] }], undefined, undefined);\n return value;\n } catch (error) {\n parent.commitCallbacks.length = mark;\n await this.db\n .runInTx(\n parent,\n [\n { sql: `ROLLBACK TO ${name}`, params: [] },\n { sql: `RELEASE ${name}`, params: [] },\n ],\n undefined,\n undefined,\n )\n .catch((e) => this.db.report('savepoint rollback failed', e));\n throw error;\n }\n }\n return this.db.unit(\n null,\n true,\n (uow) => work(new G9SqliteScope(this.db, uow.txState, this.bypassFilters)),\n options,\n );\n }\n\n /** MAUI-style explicit transaction (`IG9SqliteTransaction`): commit or roll back yourself; `dispose()` rolls back. */\n async beginTransaction(options: G9TransactionOptions = {}): Promise<G9SqliteTransaction> {\n if (this.tx)\n throw new G9SqliteError('misuse', 'beginTransaction inside a transaction: use transaction() (savepoint).');\n const { tx, release } = await this.db.openTransaction(options);\n return new G9SqliteTransaction(this.db, tx, release, this.bypassFilters);\n }\n\n /**\n * N06 scoped bypass: runs `work` with a scope whose repositories ignore every always-filter (soft delete is still\n * governed per query with `includeDeleted()`).\n */\n unfiltered<T>(work: (scope: G9SqliteScope) => Promise<T>): Promise<T> {\n return work(new G9SqliteScope(this.db, this.tx, true));\n }\n}\n\n/** An explicit transaction (MAUI `IG9SqliteTransaction`). Holds the connection until finished. */\nexport class G9SqliteTransaction extends G9SqliteScope {\n private readonly release: () => void;\n private state: 'open' | 'committed' | 'rolledBack' = 'open';\n\n /** @internal */\n constructor(db: G9SqliteDatabase, tx: G9TxState, release: () => void, bypassFilters: boolean) {\n super(db, tx, bypassFilters);\n this.release = release;\n }\n\n /** `true` once committed or rolled back. */\n get isFinished(): boolean {\n return this.state !== 'open';\n }\n\n /** MAUI `CommitAsync`: commits. Calling twice is an error. Commit effects (caches, hooks) run afterwards. */\n async commit(): Promise<void> {\n if (this.state !== 'open') throw new G9SqliteError('misuse', 'The transaction is already finished.');\n const tx = this.tx as G9TxState;\n try {\n await this.db.commitTx(tx);\n } catch (error) {\n if (!tx.finished) {\n await this.db.rollbackTx(tx);\n this.state = 'rolledBack';\n } else this.state = 'committed';\n this.release();\n throw error;\n }\n this.state = 'committed';\n this.release();\n await this.db.runCommitCallbacks(tx.commitCallbacks);\n }\n\n /** MAUI `RollbackAsync`: rolls back (no-op when already finished). */\n async rollback(): Promise<void> {\n if (this.state !== 'open') return;\n this.state = 'rolledBack';\n try {\n await this.db.rollbackTx(this.tx as G9TxState);\n } finally {\n this.release();\n }\n }\n\n /** MAUI `DisposeAsync`: rolls back when not committed, so an early return never half-applies. */\n dispose(): Promise<void> {\n return this.rollback();\n }\n}\n\n/**\n * The database facade returned by {@link createG9Sqlite} (MAUI `AddG9Sqlite` + `G9SqliteConnectionProvider` +\n * `SqliteRepositoryCacheRegistry`).\n */\nexport class G9Sqlite extends G9SqliteScope {\n /** @internal */\n constructor(db: G9SqliteDatabase) {\n super(db, null, false);\n }\n\n /** MAUI `DatabasePath`. */\n get databasePath(): string {\n return this.db.databasePath;\n }\n\n /** MAUI `ActiveDatabasePath`. */\n get activeDatabasePath(): string | null {\n return this.db.activeDatabasePath;\n }\n\n /** MAUI `HasActiveDatabase`. */\n get hasActiveDatabase(): boolean {\n return this.db.hasActiveDatabase;\n }\n\n /** The user/path generation (bumped by every switch). */\n get generation(): number {\n return this.db.generation;\n }\n\n /** Driver capabilities. */\n capabilities(): Promise<G9DriverCapabilities> {\n return this.db.capabilities();\n }\n\n /** MAUI `SqliteMigrationRunner.RunAsync`: open now (migrations, index DDL, initializers). */\n migrate(): Promise<void> {\n return this.db.migrate();\n }\n\n /** MAUI `SwitchDatabaseAsync`. */\n switchDatabase(): Promise<void> {\n return this.db.switchDatabase();\n }\n\n /** MAUI `CloseCurrentConnectionAsync`. */\n closeConnection(): Promise<void> {\n return this.db.closeConnection();\n }\n\n /** MAUI `CheckpointWalAsync`. */\n checkpointWal(): Promise<void> {\n return this.db.checkpointWal();\n }\n\n /** Disposes the database (MAUI `DisposeAsync`). */\n close(): Promise<void> {\n return this.db.close();\n }\n\n /** Committed-change notifications. */\n onChange(listener: (event: G9ChangeEvent) => void): () => void {\n return this.db.onChange(listener);\n }\n\n /** An external writer changed these tables: caches over them refresh, listeners hear it. */\n notifyExternalChange(change: { readonly tables: readonly string[] }): void {\n this.db.notifyExternalChange(change);\n }\n\n /** MAUI `SqliteDtoCache.DefineCache`: a cache of a projection over source entities, refreshed after their commits. */\n defineDtoCache<T>(\n name: string,\n sources: readonly G9EntityDescriptor[],\n load: (db: G9Sqlite) => Promise<T[]>,\n policy: G9CachePolicy,\n ): G9CacheHandle<T> {\n return this.db.caches.defineDtoCache<T>(name, sources, policy, async (maxRows) => {\n const rows = await load(this);\n if (rows.length > maxRows) {\n throw new G9SqliteError('too-many-rows', `DTO cache '${name}' produced ${rows.length} rows (max ${maxRows}).`);\n }\n return rows;\n });\n }\n\n /** The DTO cache of that name (MAUI `GetDtoCacheData…`). */\n dtoCache<T>(name: string): G9CacheHandle<T> | undefined {\n return this.db.caches.dtoCache<T>(name);\n }\n\n /** MAUI cache registry: `HardRefreshAllCache`, `RefreshCacheAsync(Type)`, `RefreshEntityAndDtoCachesAsync`, reset. */\n get caches(): {\n refreshAll(): Promise<void>;\n refresh(entity: G9EntityDescriptor): Promise<boolean>;\n refreshEntityAndDtoCaches(entity: G9EntityDescriptor): Promise<void>;\n resetAll(): void;\n readonly totalRows: number;\n } {\n const registry = this.db.caches;\n return {\n refreshAll: () => registry.refreshAll(),\n refresh: (entity) => registry.refreshEntity(entity),\n refreshEntityAndDtoCaches: (entity) => registry.refreshEntityAndDtoCaches(entity),\n resetAll: () => registry.resetAll(),\n get totalRows() {\n return registry.totalRows;\n },\n };\n }\n}\n\n/**\n * Creates the persistence layer (MAUI `services.AddG9Sqlite(...)`). Configuration errors (duplicate migration\n * versions, invalid options) throw here; the connection opens on first use, running migrations, index DDL and\n * initializers once per database path.\n *\n * ```ts\n * const db = createG9Sqlite({ driver, locator: perUserDatabaseLocator({ root, userId }), create: true,\n * entities: { sample: Sample }, migrations: [m1], interceptors: [stampSyncDirty] });\n * const rows = await db.repo(Sample).select.where((x) => ne(x.title, 'blocked'));\n * ```\n */\nexport function createG9Sqlite(options: G9SqliteOptions): G9Sqlite {\n return new G9Sqlite(new G9SqliteDatabase(options));\n}\n"],"names":["savepointSeed","G9SqliteScope","entity","repo","Array","G9SqliteError","G9Repository","sql","params","statement","uow","r","changes","isMutationSql","decodeGenericRows","_r_rows_","v","undefined","isInt64Tag","work","options","parent","name","mark","value","error","e","tx","release","G9SqliteTransaction","db","bypassFilters","Map","G9Sqlite","listener","change","sources","load","policy","maxRows","rows","registry","createG9Sqlite","G9SqliteDatabase"],"mappings":";;;;;;;;;;;;;;;AAYA,IAAIA,gBAAgB;AAMb,MAAMC;IAcX,KAAmCC,MAAS,EAAmB;QAC7D,IAAIC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAACD;QAC1B,IAAI,CAACC,MAAM;YACT,IAAI,CAACD,UAAU,CAACE,MAAM,OAAO,CAACF,OAAO,OAAO,GAC1C,MAAM,IAAIG,cAAc,UAAU;YAEpCF,OAAO,IAAIG,aAAa,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AAE;QAChC,KAAK,CAACA,IAAI,MAAM;IAClB;AAsGF;AAaO,SAASY,eAAetB,OAAwB;IACrD,OAAO,IAAIa,SAAS,IAAIU,iBAAiBvB;AAC3C"}
@@ -0,0 +1,84 @@
1
+ import type { G9AbortSignal } from '@g9tm/lynxcontrols-foundation';
2
+ import { G9SqliteError } from '../errors.js';
3
+ import type { G9Predicate } from '../query/expr.js';
4
+ import type { G9EntityDescriptor } from '../schema/entity.js';
5
+ /** Which write is happening (MAUI `G9WriteKind`). Interceptors branch on it. */
6
+ export declare const G9WriteKind: {
7
+ readonly Insert: "insert";
8
+ readonly Update: "update";
9
+ readonly PartialUpdate: "partialUpdate";
10
+ readonly Delete: "delete";
11
+ readonly SoftDelete: "softDelete";
12
+ readonly Upsert: "upsert";
13
+ };
14
+ export type G9WriteKind = (typeof G9WriteKind)[keyof typeof G9WriteKind];
15
+ /** Whether a write proceeds, and why not (MAUI `G9WriteDecision`). A veto is an expected outcome, not a failure. */
16
+ export interface G9WriteDecision {
17
+ readonly proceed: boolean;
18
+ /** Why it was vetoed; never null on a veto. */
19
+ readonly reason: string | null;
20
+ }
21
+ /** MAUI `G9WriteDecision.Allow()` / `.Veto(reason)`. */
22
+ export declare const G9WriteDecision: {
23
+ readonly allow: () => G9WriteDecision;
24
+ readonly veto: (reason: string) => G9WriteDecision;
25
+ };
26
+ /** Thrown to the caller when an interceptor vetoed (the whole atomic write rolled back). */
27
+ export declare class G9WriteVetoedError extends G9SqliteError {
28
+ readonly reason: string;
29
+ readonly entityName: string;
30
+ readonly kind: G9WriteKind;
31
+ constructor(entityName: string, kind: G9WriteKind, reason: string);
32
+ }
33
+ /** What an interceptor is told about a write (MAUI `G9WriteContext`). */
34
+ export interface G9WriteContext<Row extends object = Record<string, unknown>> {
35
+ readonly kind: G9WriteKind;
36
+ /** MAUI `EntityType`: always available, also for set-based writes. */
37
+ readonly entity: G9EntityDescriptor;
38
+ /** MAUI `Entity`: the row (mutable in `onWriting` to stamp fields), or `null` for a set-based write. */
39
+ readonly row: Row | null;
40
+ /** MAUI `RowCount`: 1 for a single write, N for a batch, −1 for a set-based write of unknown size. */
41
+ readonly rowCount: number;
42
+ /** MAUI `Items`: state shared between `onWriting` and `onWritten` of the same row. */
43
+ readonly items: Map<string, unknown>;
44
+ /** The transaction the write runs in: writes made through it are part of the same commit (outbox rows). */
45
+ readonly transaction: G9WriteTransaction;
46
+ }
47
+ /** MAUI `G9WriteContext.EntityAs<T>()`: the row when the write is for `entity`, otherwise `null`. */
48
+ export declare function writeRowAs<E extends G9EntityDescriptor>(context: G9WriteContext, entity: E): (E extends G9EntityDescriptor<infer C> ? {
49
+ [K in keyof C]: unknown;
50
+ } : never) | null;
51
+ /** The slice of a transaction an interceptor may use while a write is in flight. */
52
+ export interface G9WriteTransaction {
53
+ execute(sql: string, ...params: unknown[]): Promise<number>;
54
+ query(sql: string, ...params: unknown[]): Promise<Record<string, unknown>[]>;
55
+ }
56
+ /**
57
+ * Hooks into writes (MAUI `IG9SqliteInterceptor`, base class `G9SqliteInterceptor`): every member is optional, so an
58
+ * interceptor implements only what it needs.
59
+ *
60
+ * - `appliesTo(entity)`: pure function of the entity; cached per entity. Default: every entity.
61
+ * - `onWriting`: inside the transaction, before SQL. Mutate `context.row` or veto. A throw rolls the write back.
62
+ * - `onWritten`: after the commit. A throw cannot undo the write; it is reported to diagnostics, never turned into
63
+ * a rollback claim. Use it for effects outside the database; inside a retried transaction keep it side-effect free.
64
+ * - `writeCondition(kind, refs)`: MAUI `IG9WriteConditionProvider`: a predicate ANDed into every update and delete
65
+ * of the entity (it can only narrow what is affected).
66
+ */
67
+ export interface G9SqliteInterceptor {
68
+ readonly name?: string;
69
+ appliesTo?(entity: G9EntityDescriptor): boolean;
70
+ onWriting?(context: G9WriteContext, signal: G9AbortSignal | undefined): G9WriteDecision | undefined | void | Promise<G9WriteDecision | undefined | void>;
71
+ onWritten?(context: G9WriteContext, signal: G9AbortSignal | undefined): void | Promise<void>;
72
+ writeCondition?(kind: G9WriteKind, refs: any, entity: G9EntityDescriptor): G9Predicate | null | undefined;
73
+ }
74
+ /** MAUI `G9SqliteInterceptor` base class equivalent: an identity helper that keeps the object literal typed. */
75
+ export declare function defineInterceptor(interceptor: G9SqliteInterceptor): G9SqliteInterceptor;
76
+ /** One committed change, published to `db.onChange` listeners once per committed write. */
77
+ export interface G9ChangeEvent {
78
+ readonly table: string;
79
+ readonly entity: G9EntityDescriptor | null;
80
+ readonly kind: G9WriteKind | 'external' | 'raw';
81
+ /** Rows affected (−1 when unknown). */
82
+ readonly rowCount: number;
83
+ }
84
+ //# sourceMappingURL=write-hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-hooks.d.ts","sourceRoot":"","sources":["../../src/session/write-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,gFAAgF;AAChF,eAAO,MAAM,WAAW;;;;;;;CAOd,CAAC;AACX,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAID,wDAAwD;AACxD,eAAO,MAAM,eAAe;0BACjB,eAAe;4BAGX,MAAM,KAAG,eAAe;CAM7B,CAAC;AAEX,4FAA4F;AAC5F,qBAAa,kBAAmB,SAAQ,aAAa;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE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AmB;IAClC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC;IAChD,SAAS,CAAC,CACR,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,aAAa,GAAG,SAAS,GAEhC,eAAe,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,GAAG,IAAI,CAAC,CAAC;IACpF,SAAS,CAAC,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,aAAa,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7F,cAAc,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,kBAAkB,GAAG,WAAW,GAAG,IAAI,GAAG,SAAS,CAAC;CAC3G;AAED,gHAAgH;AAChH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,mBAAmB,GAAG,mBAAmB,CAEvF;AAED,2FAA2F;AAC3F,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAC3C,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,UAAU,GAAG,KAAK,CAAC;IAChD,uCAAuC;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B"}
@@ -0,0 +1,55 @@
1
+ import { G9SqliteError } from "../errors.js";
2
+ function _define_property(obj, key, value) {
3
+ if (key in obj) Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ else obj[key] = value;
10
+ return obj;
11
+ }
12
+ const G9WriteKind = {
13
+ Insert: 'insert',
14
+ Update: 'update',
15
+ PartialUpdate: 'partialUpdate',
16
+ Delete: 'delete',
17
+ SoftDelete: 'softDelete',
18
+ Upsert: 'upsert'
19
+ };
20
+ const ALLOW = Object.freeze({
21
+ proceed: true,
22
+ reason: null
23
+ });
24
+ const G9WriteDecision = {
25
+ allow () {
26
+ return ALLOW;
27
+ },
28
+ veto (reason) {
29
+ if ('string' != typeof reason || '' === reason.trim()) throw new G9SqliteError('misuse', 'A veto needs a reason the caller can show.');
30
+ return Object.freeze({
31
+ proceed: false,
32
+ reason
33
+ });
34
+ }
35
+ };
36
+ class G9WriteVetoedError extends G9SqliteError {
37
+ constructor(entityName, kind, reason){
38
+ super('vetoed', `${kind} of '${entityName}' was vetoed: ${reason}`), _define_property(this, "reason", void 0), _define_property(this, "entityName", void 0), _define_property(this, "kind", void 0);
39
+ this.name = 'G9WriteVetoedError';
40
+ this.reason = reason;
41
+ this.entityName = entityName;
42
+ this.kind = kind;
43
+ }
44
+ }
45
+ function writeRowAs(context, entity) {
46
+ return context.entity === entity && context.row ? context.row : null;
47
+ }
48
+ function defineInterceptor(interceptor) {
49
+ return Object.freeze({
50
+ ...interceptor
51
+ });
52
+ }
53
+ export { G9WriteDecision, G9WriteKind, G9WriteVetoedError, defineInterceptor, writeRowAs };
54
+
55
+ //# sourceMappingURL=write-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/write-hooks.js","sources":["../../src/session/write-hooks.ts"],"sourcesContent":["import type { G9AbortSignal } from '@g9tm/lynxcontrols-foundation';\nimport { G9SqliteError } from '../errors';\nimport type { G9Predicate } from '../query/expr';\nimport type { G9EntityDescriptor } from '../schema/entity';\n\n/** Which write is happening (MAUI `G9WriteKind`). Interceptors branch on it. */\nexport const G9WriteKind = {\n Insert: 'insert',\n Update: 'update',\n PartialUpdate: 'partialUpdate',\n Delete: 'delete',\n SoftDelete: 'softDelete',\n Upsert: 'upsert',\n} as const;\nexport type G9WriteKind = (typeof G9WriteKind)[keyof typeof G9WriteKind];\n\n/** Whether a write proceeds, and why not (MAUI `G9WriteDecision`). A veto is an expected outcome, not a failure. */\nexport interface G9WriteDecision {\n readonly proceed: boolean;\n /** Why it was vetoed; never null on a veto. */\n readonly reason: string | null;\n}\n\nconst ALLOW: G9WriteDecision = Object.freeze({ proceed: true, reason: null });\n\n/** MAUI `G9WriteDecision.Allow()` / `.Veto(reason)`. */\nexport const G9WriteDecision = {\n allow(): G9WriteDecision {\n return ALLOW;\n },\n veto(reason: string): G9WriteDecision {\n if (typeof reason !== 'string' || reason.trim() === '') {\n throw new G9SqliteError('misuse', 'A veto needs a reason the caller can show.');\n }\n return Object.freeze({ proceed: false, reason });\n },\n} as const;\n\n/** Thrown to the caller when an interceptor vetoed (the whole atomic write rolled back). */\nexport class G9WriteVetoedError extends G9SqliteError {\n readonly reason: string;\n readonly entityName: string;\n readonly kind: G9WriteKind;\n\n constructor(entityName: string, kind: G9WriteKind, reason: string) {\n super('vetoed', `${kind} of '${entityName}' was vetoed: ${reason}`);\n this.name = 'G9WriteVetoedError';\n this.reason = reason;\n this.entityName = entityName;\n this.kind = kind;\n }\n}\n\n/** What an interceptor is told about a write (MAUI `G9WriteContext`). */\nexport interface G9WriteContext<Row extends object = Record<string, unknown>> {\n readonly kind: G9WriteKind;\n /** MAUI `EntityType`: always available, also for set-based writes. */\n readonly entity: G9EntityDescriptor;\n /** MAUI `Entity`: the row (mutable in `onWriting` to stamp fields), or `null` for a set-based write. */\n readonly row: Row | null;\n /** MAUI `RowCount`: 1 for a single write, N for a batch, −1 for a set-based write of unknown size. */\n readonly rowCount: number;\n /** MAUI `Items`: state shared between `onWriting` and `onWritten` of the same row. */\n readonly items: Map<string, unknown>;\n /** The transaction the write runs in: writes made through it are part of the same commit (outbox rows). */\n readonly transaction: G9WriteTransaction;\n}\n\n/** MAUI `G9WriteContext.EntityAs<T>()`: the row when the write is for `entity`, otherwise `null`. */\nexport function writeRowAs<E extends G9EntityDescriptor>(\n context: G9WriteContext,\n entity: E,\n): (E extends G9EntityDescriptor<infer C> ? { [K in keyof C]: unknown } : never) | null {\n return context.entity === entity && context.row ? (context.row as never) : null;\n}\n\n/** The slice of a transaction an interceptor may use while a write is in flight. */\nexport interface G9WriteTransaction {\n execute(sql: string, ...params: unknown[]): Promise<number>;\n query(sql: string, ...params: unknown[]): Promise<Record<string, unknown>[]>;\n}\n\n/**\n * Hooks into writes (MAUI `IG9SqliteInterceptor`, base class `G9SqliteInterceptor`): every member is optional, so an\n * interceptor implements only what it needs.\n *\n * - `appliesTo(entity)`: pure function of the entity; cached per entity. Default: every entity.\n * - `onWriting`: inside the transaction, before SQL. Mutate `context.row` or veto. A throw rolls the write back.\n * - `onWritten`: after the commit. A throw cannot undo the write; it is reported to diagnostics, never turned into\n * a rollback claim. Use it for effects outside the database; inside a retried transaction keep it side-effect free.\n * - `writeCondition(kind, refs)`: MAUI `IG9WriteConditionProvider`: a predicate ANDed into every update and delete\n * of the entity (it can only narrow what is affected).\n */\nexport interface G9SqliteInterceptor {\n readonly name?: string;\n appliesTo?(entity: G9EntityDescriptor): boolean;\n onWriting?(\n context: G9WriteContext,\n signal: G9AbortSignal | undefined,\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that only mutates returns nothing (= allow).\n ): G9WriteDecision | undefined | void | Promise<G9WriteDecision | undefined | void>;\n onWritten?(context: G9WriteContext, signal: G9AbortSignal | undefined): void | Promise<void>;\n // biome-ignore lint/suspicious/noExplicitAny: refs are typed by the entity at the call site.\n writeCondition?(kind: G9WriteKind, refs: any, entity: G9EntityDescriptor): G9Predicate | null | undefined;\n}\n\n/** MAUI `G9SqliteInterceptor` base class equivalent: an identity helper that keeps the object literal typed. */\nexport function defineInterceptor(interceptor: G9SqliteInterceptor): G9SqliteInterceptor {\n return Object.freeze({ ...interceptor });\n}\n\n/** One committed change, published to `db.onChange` listeners once per committed write. */\nexport interface G9ChangeEvent {\n readonly table: string;\n readonly entity: G9EntityDescriptor | null;\n readonly kind: G9WriteKind | 'external' | 'raw';\n /** Rows affected (−1 when unknown). */\n readonly rowCount: number;\n}\n"],"names":["G9WriteKind","ALLOW","Object","G9WriteDecision","reason","G9SqliteError","G9WriteVetoedError","entityName","kind","writeRowAs","context","entity","defineInterceptor","interceptor"],"mappings":";;;;;;;;;;;AAMO,MAAMA,cAAc;IACzB,QAAQ;IACR,QAAQ;IACR,eAAe;IACf,QAAQ;IACR,YAAY;IACZ,QAAQ;AACV;AAUA,MAAMC,QAAyBC,OAAO,MAAM,CAAC;IAAE,SAAS;IAAM,QAAQ;AAAK;AAGpE,MAAMC,kBAAkB;IAC7B;QACE,OAAOF;IACT;IACA,MAAKG,MAAc;QACjB,IAAI,AAAkB,YAAlB,OAAOA,UAAuBA,AAAkB,OAAlBA,OAAO,IAAI,IAC3C,MAAM,IAAIC,cAAc,UAAU;QAEpC,OAAOH,OAAO,MAAM,CAAC;YAAE,SAAS;YAAOE;QAAO;IAChD;AACF;AAGO,MAAME,2BAA2BD;IAKtC,YAAYE,UAAkB,EAAEC,IAAiB,EAAEJ,MAAc,CAAE;QACjE,KAAK,CAAC,UAAU,GAAGI,KAAK,KAAK,EAAED,WAAW,cAAc,EAAEH,QAAQ,GALpE,uBAAS,UAAT,SACA,uBAAS,cAAT,SACA,uBAAS,QAAT;QAIE,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,MAAM,GAAGA;QACd,IAAI,CAAC,UAAU,GAAGG;QAClB,IAAI,CAAC,IAAI,GAAGC;IACd;AACF;AAkBO,SAASC,WACdC,OAAuB,EACvBC,MAAS;IAET,OAAOD,QAAQ,MAAM,KAAKC,UAAUD,QAAQ,GAAG,GAAIA,QAAQ,GAAG,GAAa;AAC7E;AAiCO,SAASE,kBAAkBC,WAAgC;IAChE,OAAOX,OAAO,MAAM,CAAC;QAAE,GAAGW,WAAW;IAAC;AACxC"}