@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,227 @@
1
+ import { guidCodec } from "../codecs/codecs.js";
2
+ import { G9SqliteError } from "../errors.js";
3
+ function _define_property(obj, key, value) {
4
+ if (key in obj) Object.defineProperty(obj, key, {
5
+ value: value,
6
+ enumerable: true,
7
+ configurable: true,
8
+ writable: true
9
+ });
10
+ else obj[key] = value;
11
+ return obj;
12
+ }
13
+ function pascal(name) {
14
+ return name.charAt(0).toUpperCase() + name.slice(1);
15
+ }
16
+ function createColumnRefs(columns, scope) {
17
+ const refs = {};
18
+ for (const c of columns)refs[c.property] = Object.freeze({
19
+ kind: 'col',
20
+ scope,
21
+ property: c.property,
22
+ column: c.column,
23
+ spec: c
24
+ });
25
+ return Object.freeze(refs);
26
+ }
27
+ class G9EntityBuilder {
28
+ table(name) {
29
+ this.state.table = name;
30
+ return this;
31
+ }
32
+ columnCase(mode) {
33
+ this.state.columnCase = mode;
34
+ return this;
35
+ }
36
+ hasGuidId(property) {
37
+ this.state.guidIds.add(property);
38
+ return this;
39
+ }
40
+ audited(enabled = true) {
41
+ this.state.audited = enabled;
42
+ return this;
43
+ }
44
+ softDelete(flag, options = {}) {
45
+ this.state.softDelete = Object.freeze({
46
+ flag,
47
+ deletedTime: options.deletedTime,
48
+ deletedByUserId: options.deletedByUserId
49
+ });
50
+ return this;
51
+ }
52
+ alwaysFilter(filter) {
53
+ this.state.alwaysFilter = filter;
54
+ return this;
55
+ }
56
+ index(properties, options = {}) {
57
+ return this.addIndex(properties, false, options);
58
+ }
59
+ unique(properties, options = {}) {
60
+ return this.addIndex(properties, true, options);
61
+ }
62
+ addIndex(properties, unique, options) {
63
+ const list = 'string' == typeof properties ? [
64
+ properties
65
+ ] : properties;
66
+ this.state.indexes.push(Object.freeze({
67
+ name: options.name,
68
+ unique,
69
+ parts: Object.freeze(list.map((p)=>Object.freeze('string' == typeof p ? {
70
+ property: p,
71
+ descending: false,
72
+ collate: void 0
73
+ } : {
74
+ property: p.property,
75
+ descending: true === p.descending,
76
+ collate: p.collate
77
+ }))),
78
+ where: options.where,
79
+ includeDeleted: true === options.includeDeleted
80
+ }));
81
+ return this;
82
+ }
83
+ onConflict(policy) {
84
+ this.state.conflictPolicy = policy;
85
+ return this;
86
+ }
87
+ cache(policy) {
88
+ this.state.cachePolicy = policy;
89
+ return this;
90
+ }
91
+ constructor(table){
92
+ _define_property(this, "state", void 0);
93
+ this.state = {
94
+ table,
95
+ columnCase: 'pascal',
96
+ guidIds: new Set(),
97
+ audited: void 0,
98
+ softDelete: null,
99
+ alwaysFilter: null,
100
+ conflictPolicy: 'abort',
101
+ cachePolicy: null,
102
+ indexes: []
103
+ };
104
+ }
105
+ }
106
+ function fail(entity, problem) {
107
+ throw new G9SqliteError('misuse', `Entity '${entity}': ${problem}`);
108
+ }
109
+ const AUDIT_PROPS = [
110
+ 'id',
111
+ 'createdTime',
112
+ 'updatedTime',
113
+ 'createdByUserId',
114
+ 'updatedByUserId'
115
+ ];
116
+ function defineEntity(name, columns, configure) {
117
+ var _s_audited;
118
+ if ('string' != typeof name || '' === name.trim()) fail(String(name), 'needs a non-empty name.');
119
+ const builder = new G9EntityBuilder(name);
120
+ null == configure || configure(builder);
121
+ const s = builder.state;
122
+ if ('' === s.table.trim()) fail(name, 'table name is empty.');
123
+ const list = [];
124
+ const byProperty = new Map();
125
+ const byColumn = new Map();
126
+ for (const property of Object.keys(columns)){
127
+ var _spec_columnName;
128
+ const def = columns[property];
129
+ if (!def || 'object' != typeof def || !('spec' in def)) fail(name, `'${property}' is not a column.`);
130
+ let spec = def.spec;
131
+ if (s.guidIds.has(property) || 'id' === property && 'text' === spec.codec.kind) {
132
+ var _spec_collation;
133
+ if ('TEXT' !== spec.codec.sqlType) fail(name, `hasGuidId('${property}') needs a text column.`);
134
+ spec = {
135
+ ...spec,
136
+ guid: true,
137
+ collation: null != (_spec_collation = spec.collation) ? _spec_collation : 'NOCASE'
138
+ };
139
+ if ('text' === spec.codec.kind) spec = {
140
+ ...spec,
141
+ codec: guidCodec
142
+ };
143
+ }
144
+ const column = null != (_spec_columnName = spec.columnName) ? _spec_columnName : 'pascal' === s.columnCase ? pascal(property) : property;
145
+ const key = column.toLowerCase();
146
+ if (byColumn.has(key)) fail(name, `two properties map to column '${column}'.`);
147
+ if (spec.autoIncrement && 'INTEGER' !== spec.codec.sqlType) fail(name, `'${property}' autoIncrement needs an integer.`);
148
+ const entry = Object.freeze({
149
+ ...spec,
150
+ property,
151
+ column
152
+ });
153
+ list.push(entry);
154
+ byProperty.set(property, entry);
155
+ byColumn.set(key, entry);
156
+ }
157
+ if (0 === list.length) fail(name, 'has no columns.');
158
+ for (const g of s.guidIds)if (!byProperty.has(g)) fail(name, `hasGuidId('${g}') names no column.`);
159
+ const primaryKey = list.filter((c)=>c.primaryKey);
160
+ if (primaryKey.filter((c)=>c.autoIncrement).length > 0 && primaryKey.length > 1) fail(name, 'an autoIncrement key cannot be part of a composite key.');
161
+ const hasAuditColumns = AUDIT_PROPS.every((p)=>byProperty.has(p));
162
+ if (true === s.audited && !hasAuditColumns) fail(name, `audited() needs the columns ${AUDIT_PROPS.join(', ')} (see auditColumns()).`);
163
+ const audited = null != (_s_audited = s.audited) ? _s_audited : hasAuditColumns;
164
+ if (audited) {
165
+ const times = [
166
+ byProperty.get('createdTime'),
167
+ byProperty.get('updatedTime')
168
+ ];
169
+ if (times.some((t)=>(null == t ? void 0 : t.codec.kind) !== 'legacyDateTime')) fail(name, 'audit time columns must be legacyDateTime().');
170
+ }
171
+ if (s.softDelete) {
172
+ const flag = byProperty.get(s.softDelete.flag);
173
+ if (!flag) fail(name, `softDelete('${s.softDelete.flag}') names no column.`);
174
+ if ('bool' !== flag.codec.kind) fail(name, `softDelete flag '${s.softDelete.flag}' must be a bool() column.`);
175
+ for (const extra of [
176
+ s.softDelete.deletedTime,
177
+ s.softDelete.deletedByUserId
178
+ ])if (void 0 !== extra) {
179
+ const c = byProperty.get(extra);
180
+ if (!c) fail(name, `softDelete names no column '${extra}'.`);
181
+ if (!c.nullable) fail(name, `softDelete column '${extra}' must be nullable (it is cleared on restore).`);
182
+ }
183
+ }
184
+ for (const index of s.indexes){
185
+ if (0 === index.parts.length) fail(name, 'an index needs at least one column.');
186
+ for (const part of index.parts)if (!byProperty.has(part.property)) fail(name, `index names no column '${part.property}'.`);
187
+ }
188
+ if ('object' == typeof s.conflictPolicy) {
189
+ var _s_conflictPolicy_target, _s_conflictPolicy_update;
190
+ for (const p of null != (_s_conflictPolicy_target = s.conflictPolicy.target) ? _s_conflictPolicy_target : [])if (!byProperty.has(p)) fail(name, `conflict target names no column '${p}'.`);
191
+ for (const p of null != (_s_conflictPolicy_update = s.conflictPolicy.update) ? _s_conflictPolicy_update : [])if (!byProperty.has(p)) fail(name, `conflict update names no column '${p}'.`);
192
+ }
193
+ const scope = Object.freeze({
194
+ table: s.table,
195
+ entityName: name,
196
+ alias: void 0
197
+ });
198
+ const descriptor = {
199
+ name,
200
+ table: s.table,
201
+ columns: Object.freeze(list),
202
+ byProperty,
203
+ byColumn,
204
+ primaryKey: Object.freeze(primaryKey),
205
+ guidIdProperties: new Set(list.filter((c)=>c.guid).map((c)=>c.property)),
206
+ audit: audited ? Object.freeze({
207
+ id: 'id',
208
+ createdTime: 'createdTime',
209
+ updatedTime: 'updatedTime',
210
+ createdByUserId: 'createdByUserId',
211
+ updatedByUserId: 'updatedByUserId'
212
+ }) : null,
213
+ softDelete: s.softDelete,
214
+ alwaysFilter: s.alwaysFilter,
215
+ conflictPolicy: s.conflictPolicy,
216
+ cachePolicy: s.cachePolicy,
217
+ indexes: Object.freeze([
218
+ ...s.indexes
219
+ ]),
220
+ refs: createColumnRefs(list, scope),
221
+ scope
222
+ };
223
+ return Object.freeze(descriptor);
224
+ }
225
+ export { G9EntityBuilder, createColumnRefs, defineEntity };
226
+
227
+ //# sourceMappingURL=entity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema/entity.js","sources":["../../src/schema/entity.ts"],"sourcesContent":["import { guidCodec } from '../codecs/codecs';\nimport { G9SqliteError } from '../errors';\nimport type { G9ColumnRef, G9Predicate, G9QueryScope } from '../query/expr';\nimport type { G9Column, G9ColumnSpec, G9Columns, G9InputValue, G9InsertRowOf, G9RowOf } from './columns';\nimport type { G9CachePolicy, G9ConflictPolicy, G9IndexDescriptor, G9SoftDeleteDescriptor } from './policies';\n\n/** One column as an entity knows it: the property, its stored name and its spec. */\nexport interface G9EntityColumn extends G9ColumnSpec {\n readonly property: string;\n readonly column: string;\n}\n\n/** Column references of an entity, keyed by property: what predicates receive. */\nexport type G9ColumnRefs<C extends G9Columns> = {\n readonly [K in keyof C]: G9ColumnRef<\n C[K] extends G9Column<infer T, infer N, boolean>\n ? N extends true\n ? G9InputValue<T> | null\n : G9InputValue<T>\n : never\n >;\n};\n\n/** How column names are derived from property names. */\nexport type G9ColumnCase = 'pascal' | 'as-is';\n\n/** The MAUI `IG9AuditedEntity` mapping: which properties hold the audit facts. */\nexport interface G9AuditMapping {\n readonly id: string;\n readonly createdTime: string;\n readonly updatedTime: string;\n readonly createdByUserId: string;\n readonly updatedByUserId: string;\n}\n\n/**\n * Everything the library knows about one entity, frozen at definition (MAUI `G9EntityDescriptor`). Every later\n * decision reads it: id normalisation, codecs, audit, soft delete, filters, conflicts, cache, indexes.\n */\n// The `any` default makes every concrete descriptor assignable to the unparameterised type (its alwaysFilter is\n// contravariant in C, so `G9Columns` as the default would reject every real entity).\n// biome-ignore lint/suspicious/noExplicitAny: see above.\nexport interface G9EntityDescriptor<C extends G9Columns = any> {\n readonly name: string;\n readonly table: string;\n readonly columns: readonly G9EntityColumn[];\n readonly byProperty: ReadonlyMap<string, G9EntityColumn>;\n /** Stored column name (any case) → column. */\n readonly byColumn: ReadonlyMap<string, G9EntityColumn>;\n readonly primaryKey: readonly G9EntityColumn[];\n /** MAUI `GuidIdProperties`: properties holding GUID strings. */\n readonly guidIdProperties: ReadonlySet<string>;\n /** MAUI `IsAudited` (with the mapping), or `null`. */\n readonly audit: G9AuditMapping | null;\n readonly softDelete: G9SoftDeleteDescriptor | null;\n /** MAUI `AlwaysFilter`: a predicate ANDed into every managed read, update and delete. */\n readonly alwaysFilter: ((refs: G9ColumnRefs<C>) => G9Predicate) | null;\n /** MAUI `ConflictPolicy` (default `abort`). */\n readonly conflictPolicy: G9ConflictPolicy;\n /** MAUI `CachePolicy`, or `null` for no cache. */\n readonly cachePolicy: G9CachePolicy | null;\n readonly indexes: readonly G9IndexDescriptor[];\n /** Column references for the root occurrence of this entity. */\n readonly refs: G9ColumnRefs<C>;\n readonly scope: G9QueryScope;\n /** @internal type witnesses. */\n readonly __row?: G9RowOf<C>;\n readonly __insert?: G9InsertRowOf<C>;\n}\n\n/** Row type of an entity descriptor. */\nexport type G9Row<E> = E extends G9EntityDescriptor<infer C> ? G9RowOf<C> : never;\n/** Insert-input type of an entity descriptor. */\nexport type G9InsertRow<E> = E extends G9EntityDescriptor<infer C> ? G9InsertRowOf<C> : never;\n/** Column refs of an entity descriptor. */\nexport type G9RefsOf<E> = E extends G9EntityDescriptor<infer C> ? G9ColumnRefs<C> : never;\n\nfunction pascal(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/** Builds refs for one occurrence of an entity in a query. */\nexport function createColumnRefs<C extends G9Columns>(\n columns: readonly G9EntityColumn[],\n scope: G9QueryScope,\n): G9ColumnRefs<C> {\n const refs: Record<string, G9ColumnRef> = {};\n for (const c of columns) {\n refs[c.property] = Object.freeze({ kind: 'col', scope, property: c.property, column: c.column, spec: c });\n }\n return Object.freeze(refs) as G9ColumnRefs<C>;\n}\n\n/**\n * MAUI `G9EntityBuilder<T>`: configures one entity's descriptor. Conventions (a GUID `id`, the five audit columns)\n * apply first; builder calls override them.\n */\nexport class G9EntityBuilder<C extends G9Columns> {\n /** @internal */ state: {\n table: string;\n columnCase: G9ColumnCase;\n guidIds: Set<string>;\n audited: boolean | undefined;\n softDelete: G9SoftDeleteDescriptor | null;\n alwaysFilter: ((refs: G9ColumnRefs<C>) => G9Predicate) | null;\n conflictPolicy: G9ConflictPolicy;\n cachePolicy: G9CachePolicy | null;\n indexes: G9IndexDescriptor[];\n };\n\n constructor(table: string) {\n this.state = {\n table,\n columnCase: 'pascal',\n guidIds: new Set(),\n audited: undefined,\n softDelete: null,\n alwaysFilter: null,\n conflictPolicy: 'abort',\n cachePolicy: null,\n indexes: [],\n };\n }\n\n /** Stored table name when it differs from the entity name (MAUI `[Table]`). */\n table(name: string): this {\n this.state.table = name;\n return this;\n }\n\n /**\n * Column naming: `'pascal'` (default) stores `parentId` as `ParentId`, the MAUI property names that existing\n * databases use; `'as-is'` stores property names unchanged. `.named()` on a column always wins.\n */\n columnCase(mode: G9ColumnCase): this {\n this.state.columnCase = mode;\n return this;\n }\n\n /** MAUI `HasGuidId`: marks a text property as a GUID (normalised, `COLLATE NOCASE`). */\n hasGuidId(property: keyof C & string): this {\n this.state.guidIds.add(property);\n return this;\n }\n\n /** Forces audit maintenance on or off (the convention turns it on when the five audit columns exist). */\n audited(enabled = true): this {\n this.state.audited = enabled;\n return this;\n }\n\n /**\n * MAUI `SoftDelete`: delete becomes an update of the flag (`true`), and reads exclude flagged rows unless asked.\n * Optional `deletedTime` / `deletedByUserId` properties are stamped on delete and cleared on restore.\n */\n softDelete(\n flag: keyof C & string,\n options: { deletedTime?: keyof C & string; deletedByUserId?: keyof C & string } = {},\n ): this {\n this.state.softDelete = Object.freeze({\n flag,\n deletedTime: options.deletedTime,\n deletedByUserId: options.deletedByUserId,\n });\n return this;\n }\n\n /** MAUI `AlwaysFilter`: ANDed into every managed read, update and delete of this entity. */\n alwaysFilter(filter: (refs: G9ColumnRefs<C>) => G9Predicate): this {\n this.state.alwaysFilter = filter;\n return this;\n }\n\n /** MAUI `Index`: a (composite) index, created by migrations/initialisation. */\n index(\n properties:\n | (keyof C & string)\n | readonly ((keyof C & string) | { property: keyof C & string; descending?: boolean; collate?: string })[],\n options: { name?: string; where?: (refs: G9ColumnRefs<C>) => G9Predicate } = {},\n ): this {\n return this.addIndex(properties, false, options);\n }\n\n /** MAUI `Unique`: a unique (composite) index. With soft delete, uniqueness applies to live rows only. */\n unique(\n properties:\n | (keyof C & string)\n | readonly ((keyof C & string) | { property: keyof C & string; descending?: boolean; collate?: string })[],\n options: { name?: string; where?: (refs: G9ColumnRefs<C>) => G9Predicate; includeDeleted?: boolean } = {},\n ): this {\n return this.addIndex(properties, true, options);\n }\n\n private addIndex(\n properties: string | readonly (string | { property: string; descending?: boolean; collate?: string })[],\n unique: boolean,\n options: { name?: string; where?: (refs: G9ColumnRefs<C>) => G9Predicate; includeDeleted?: boolean },\n ): this {\n const list = typeof properties === 'string' ? [properties] : properties;\n this.state.indexes.push(\n Object.freeze({\n name: options.name,\n unique,\n parts: Object.freeze(\n list.map((p) =>\n Object.freeze(\n typeof p === 'string'\n ? { property: p, descending: false, collate: undefined }\n : { property: p.property, descending: p.descending === true, collate: p.collate },\n ),\n ),\n ),\n where: options.where as G9IndexDescriptor['where'],\n includeDeleted: options.includeDeleted === true,\n }),\n );\n return this;\n }\n\n /** MAUI `OnConflict`: default insert conflict policy (overridable per call). */\n onConflict(policy: G9ConflictPolicy): this {\n this.state.conflictPolicy = policy;\n return this;\n }\n\n /** MAUI `Cache`: keep this (small, hot) entity's rows in memory with the given policy. */\n cache(policy: G9CachePolicy): this {\n this.state.cachePolicy = policy;\n return this;\n }\n}\n\nfunction fail(entity: string, problem: string): never {\n throw new G9SqliteError('misuse', `Entity '${entity}': ${problem}`);\n}\n\nconst AUDIT_PROPS = ['id', 'createdTime', 'updatedTime', 'createdByUserId', 'updatedByUserId'] as const;\n\n/**\n * Defines an entity (MAUI: an entity class + `G9SqliteBuilder.Entity<T>(…)`). Validation happens here, so an invalid\n * descriptor fails at definition, never at the first query.\n *\n * ```ts\n * const Sample = defineEntity('Sample', { ...auditColumns(), samplingId: guid(), title: text().nullable() },\n * (e) => e.softDelete('isDeleted').alwaysFilter((x) => eq(x.isDeleted, false)).index('samplingId'));\n * ```\n */\nexport function defineEntity<C extends G9Columns>(\n name: string,\n columns: C,\n configure?: (entity: G9EntityBuilder<C>) => unknown,\n): G9EntityDescriptor<C> {\n if (typeof name !== 'string' || name.trim() === '') fail(String(name), 'needs a non-empty name.');\n const builder = new G9EntityBuilder<C>(name);\n configure?.(builder);\n const s = builder.state;\n if (s.table.trim() === '') fail(name, 'table name is empty.');\n\n const list: G9EntityColumn[] = [];\n const byProperty = new Map<string, G9EntityColumn>();\n const byColumn = new Map<string, G9EntityColumn>();\n for (const property of Object.keys(columns)) {\n const def = columns[property];\n if (!def || typeof def !== 'object' || !('spec' in def)) fail(name, `'${property}' is not a column.`);\n let spec: G9ColumnSpec = def.spec;\n if (s.guidIds.has(property) || (property === 'id' && spec.codec.kind === 'text')) {\n if (spec.codec.sqlType !== 'TEXT') fail(name, `hasGuidId('${property}') needs a text column.`);\n spec = { ...spec, guid: true, collation: spec.collation ?? 'NOCASE' };\n if (spec.codec.kind === 'text') {\n // Re-use the guid codec so writes and predicates normalise.\n spec = { ...spec, codec: guidCodec as G9ColumnSpec['codec'] };\n }\n }\n const column = spec.columnName ?? (s.columnCase === 'pascal' ? pascal(property) : property);\n const key = column.toLowerCase();\n if (byColumn.has(key)) fail(name, `two properties map to column '${column}'.`);\n if (spec.autoIncrement && spec.codec.sqlType !== 'INTEGER')\n fail(name, `'${property}' autoIncrement needs an integer.`);\n const entry: G9EntityColumn = Object.freeze({ ...spec, property, column });\n list.push(entry);\n byProperty.set(property, entry);\n byColumn.set(key, entry);\n }\n if (list.length === 0) fail(name, 'has no columns.');\n for (const g of s.guidIds) if (!byProperty.has(g)) fail(name, `hasGuidId('${g}') names no column.`);\n const primaryKey = list.filter((c) => c.primaryKey);\n if (primaryKey.filter((c) => c.autoIncrement).length > 0 && primaryKey.length > 1) {\n fail(name, 'an autoIncrement key cannot be part of a composite key.');\n }\n\n const hasAuditColumns = AUDIT_PROPS.every((p) => byProperty.has(p));\n if (s.audited === true && !hasAuditColumns) {\n fail(name, `audited() needs the columns ${AUDIT_PROPS.join(', ')} (see auditColumns()).`);\n }\n const audited = s.audited ?? hasAuditColumns;\n if (audited) {\n const times = [byProperty.get('createdTime'), byProperty.get('updatedTime')];\n if (times.some((t) => t?.codec.kind !== 'legacyDateTime'))\n fail(name, 'audit time columns must be legacyDateTime().');\n }\n\n if (s.softDelete) {\n const flag = byProperty.get(s.softDelete.flag);\n if (!flag) fail(name, `softDelete('${s.softDelete.flag}') names no column.`);\n if (flag.codec.kind !== 'bool') fail(name, `softDelete flag '${s.softDelete.flag}' must be a bool() column.`);\n for (const extra of [s.softDelete.deletedTime, s.softDelete.deletedByUserId]) {\n if (extra !== undefined) {\n const c = byProperty.get(extra);\n if (!c) fail(name, `softDelete names no column '${extra}'.`);\n if (!c.nullable) fail(name, `softDelete column '${extra}' must be nullable (it is cleared on restore).`);\n }\n }\n }\n for (const index of s.indexes) {\n if (index.parts.length === 0) fail(name, 'an index needs at least one column.');\n for (const part of index.parts)\n if (!byProperty.has(part.property)) fail(name, `index names no column '${part.property}'.`);\n }\n if (typeof s.conflictPolicy === 'object') {\n for (const p of s.conflictPolicy.target ?? [])\n if (!byProperty.has(p)) fail(name, `conflict target names no column '${p}'.`);\n for (const p of s.conflictPolicy.update ?? [])\n if (!byProperty.has(p)) fail(name, `conflict update names no column '${p}'.`);\n }\n\n const scope: G9QueryScope = Object.freeze({ table: s.table, entityName: name, alias: undefined });\n const descriptor: G9EntityDescriptor<C> = {\n name,\n table: s.table,\n columns: Object.freeze(list),\n byProperty,\n byColumn,\n primaryKey: Object.freeze(primaryKey),\n guidIdProperties: new Set(list.filter((c) => c.guid).map((c) => c.property)),\n audit: audited\n ? Object.freeze({\n id: 'id',\n createdTime: 'createdTime',\n updatedTime: 'updatedTime',\n createdByUserId: 'createdByUserId',\n updatedByUserId: 'updatedByUserId',\n })\n : null,\n softDelete: s.softDelete,\n alwaysFilter: s.alwaysFilter,\n conflictPolicy: s.conflictPolicy,\n cachePolicy: s.cachePolicy,\n indexes: Object.freeze([...s.indexes]),\n refs: createColumnRefs<C>(list, scope),\n scope,\n };\n return Object.freeze(descriptor);\n}\n"],"names":["pascal","name","createColumnRefs","columns","scope","refs","c","Object","G9EntityBuilder","mode","property","enabled","flag","options","filter","properties","unique","list","p","undefined","policy","table","Set","fail","entity","problem","G9SqliteError","AUDIT_PROPS","defineEntity","configure","_s_audited","String","builder","s","byProperty","Map","byColumn","_spec_columnName","def","spec","_spec_collation","guidCodec","column","key","entry","g","primaryKey","hasAuditColumns","audited","times","t","extra","index","part","_s_conflictPolicy_target","_s_conflictPolicy_update","descriptor"],"mappings":";;;;;;;;;;;;AA6EA,SAASA,OAAOC,IAAY;IAC1B,OAAOA,KAAK,MAAM,CAAC,GAAG,WAAW,KAAKA,KAAK,KAAK,CAAC;AACnD;AAGO,SAASC,iBACdC,OAAkC,EAClCC,KAAmB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,cAAc,CAAC,MAAM,AAAD,IAAtBA,2BAA2B,EAAE,CAC3C,IAAI,CAACpB,WAAW,GAAG,CAAChB,IAAIK,KAAKtB,MAAM,CAAC,iCAAiC,EAAEiB,EAAE,EAAE,CAAC;QAC9E,KAAK,MAAMA,KAAK,QAAAqC,CAAAA,2BAAAA,EAAE,cAAc,CAAC,MAAM,AAAD,IAAtBA,2BAA2B,EAAE,CAC3C,IAAI,CAACrB,WAAW,GAAG,CAAChB,IAAIK,KAAKtB,MAAM,CAAC,iCAAiC,EAAEiB,EAAE,EAAE,CAAC;IAChF;IAEA,MAAMd,QAAsBG,OAAO,MAAM,CAAC;QAAE,OAAO0B,EAAE,KAAK;QAAE,YAAYhC;QAAM,OAAOkB;IAAU;IAC/F,MAAMqC,aAAoC;QACxCvD;QACA,OAAOgC,EAAE,KAAK;QACd,SAAS1B,OAAO,MAAM,CAACU;QACvBiB;QACAE;QACA,YAAY7B,OAAO,MAAM,CAACuC;QAC1B,kBAAkB,IAAIxB,IAAIL,KAAK,MAAM,CAAC,CAACX,IAAMA,EAAE,IAAI,EAAE,GAAG,CAAC,CAACA,IAAMA,EAAE,QAAQ;QAC1E,OAAO0C,UACHzC,OAAO,MAAM,CAAC;YACZ,IAAI;YACJ,aAAa;YACb,aAAa;YACb,iBAAiB;YACjB,iBAAiB;QACnB,KACA;QACJ,YAAY0B,EAAE,UAAU;QACxB,cAAcA,EAAE,YAAY;QAC5B,gBAAgBA,EAAE,cAAc;QAChC,aAAaA,EAAE,WAAW;QAC1B,SAAS1B,OAAO,MAAM,CAAC;eAAI0B,EAAE,OAAO;SAAC;QACrC,MAAM/B,iBAAoBe,MAAMb;QAChCA;IACF;IACA,OAAOG,OAAO,MAAM,CAACiD;AACvB"}
@@ -0,0 +1,89 @@
1
+ import type { G9Predicate } from '../query/expr.js';
2
+ /**
3
+ * What an INSERT does when a key collides (MAUI `G9ConflictPolicy`).
4
+ * - `abort` (default): fail with a `constraint` error. A surprise collision is usually a bug worth hearing about.
5
+ * - `ignore`: skip the row (`INSERT OR IGNORE`); the returned count excludes it.
6
+ * - `replace`: `INSERT OR REPLACE`, which SQLite executes as DELETE + INSERT: columns the row does not supply reset
7
+ * to their defaults, and the implicit delete fires DELETE triggers only under `PRAGMA recursive_triggers=ON`
8
+ * (default OFF), so sync capture triggers do not see it. Only when asked for explicitly.
9
+ * - an upsert ({@link upsert}): `ON CONFLICT (target) DO UPDATE SET` the given (or every supplied non-key) columns,
10
+ * leaving the rest and the audit creation fields intact. MAUI `Upsert`.
11
+ */
12
+ export type G9ConflictPolicy = 'abort' | 'ignore' | 'replace' | G9UpsertPolicy;
13
+ /** An upsert conflict policy. */
14
+ export interface G9UpsertPolicy {
15
+ readonly kind: 'upsert';
16
+ /** Conflict target properties (default: the primary key). */
17
+ readonly target: readonly string[] | undefined;
18
+ /** Properties to update on conflict (default: every supplied non-target column except creation audit fields). */
19
+ readonly update: readonly string[] | undefined;
20
+ }
21
+ /** MAUI `G9ConflictPolicy` members by their C# names. */
22
+ export declare const G9ConflictPolicy: {
23
+ readonly Abort: "abort";
24
+ readonly Ignore: "ignore";
25
+ readonly Replace: "replace";
26
+ readonly Upsert: G9UpsertPolicy;
27
+ };
28
+ /** An upsert on the given conflict target, optionally limited to some update columns. */
29
+ export declare function upsert(options?: {
30
+ target?: readonly string[];
31
+ update?: readonly string[];
32
+ }): G9UpsertPolicy;
33
+ /**
34
+ * Whether and how an entity's rows are cached in memory (MAUI `G9CachePolicy`). For small, hot, rarely-written
35
+ * reference tables: the cache holds every (filtered) row and a committed write invalidates it.
36
+ */
37
+ export interface G9CachePolicy {
38
+ /** Coalescing window for invalidations; 0 refreshes right after each commit. */
39
+ readonly debounceMs: number;
40
+ /** Upper bound on cached rows; a larger table fails the refresh with a typed error instead of growing. */
41
+ readonly maxRows: number;
42
+ /** Rows older than this are reloaded on the next read; `undefined` = until invalidated. */
43
+ readonly ttlMs: number | undefined;
44
+ }
45
+ /** Cache policy factories (MAUI `G9CachePolicy.Immediate()` / `.Debounced(250)` plus TTL and size bounds). */
46
+ export declare const G9CachePolicy: {
47
+ /** Refresh right after each committed write. For a table written rarely and read constantly. */
48
+ readonly immediate: (options?: {
49
+ maxRows?: number;
50
+ ttlMs?: number;
51
+ }) => G9CachePolicy;
52
+ /** Coalesce invalidations over a window (default 250 ms, MAUI's default): one refresh after a batch import. */
53
+ readonly debounced: (debounceMs?: number, options?: {
54
+ maxRows?: number;
55
+ ttlMs?: number;
56
+ }) => G9CachePolicy;
57
+ /** Every row, bounded: refreshed after commits and capped at `maxRows`. */
58
+ readonly all: (maxRows: number, options?: {
59
+ debounceMs?: number;
60
+ ttlMs?: number;
61
+ }) => G9CachePolicy;
62
+ /** Reloaded on read once older than `ttlMs` (and after commits). */
63
+ readonly ttl: (ttlMs: number, options?: {
64
+ debounceMs?: number;
65
+ maxRows?: number;
66
+ }) => G9CachePolicy;
67
+ };
68
+ /** One part of an index: a property, its direction and optional collation. */
69
+ export interface G9IndexPart {
70
+ readonly property: string;
71
+ readonly descending: boolean;
72
+ readonly collate: string | undefined;
73
+ }
74
+ /** MAUI `G9IndexDescriptor` (`Properties`, `IsUnique`) plus name, order, collation and a partial predicate. */
75
+ export interface G9IndexDescriptor {
76
+ readonly name: string | undefined;
77
+ readonly unique: boolean;
78
+ readonly parts: readonly G9IndexPart[];
79
+ readonly where: ((refs: any) => G9Predicate) | undefined;
80
+ /** For a soft-delete entity: `true` makes a unique index cover deleted rows too (default: live rows only). */
81
+ readonly includeDeleted: boolean;
82
+ }
83
+ /** MAUI `SoftDeleteProperty`, plus optional deletion audit properties. */
84
+ export interface G9SoftDeleteDescriptor {
85
+ readonly flag: string;
86
+ readonly deletedTime: string | undefined;
87
+ readonly deletedByUserId: string | undefined;
88
+ }
89
+ //# sourceMappingURL=policies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policies.d.ts","sourceRoot":"","sources":["../../src/schema/policies.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,E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AAA;KAAE,KAAQ,aAAa;IAG1F,oEAAoE;0BACzD,MAAM,YAAW;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,KAAQ,aAAa;CAGlF,CAAC;AAEX,8EAA8E;AAC9E,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AAED,+GAA+G;AAC/G,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IAEvC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,WAAW,CAAC,GAAG,SAAS,CAAC;IACzD,8GAA8G;IAC9G,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;CAClC;AAED,0EAA0E;AAC1E,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;CAC9C"}
@@ -0,0 +1,54 @@
1
+ import { G9SqliteError } from "../errors.js";
2
+ const G9ConflictPolicy = {
3
+ Abort: 'abort',
4
+ Ignore: 'ignore',
5
+ Replace: 'replace',
6
+ Upsert: Object.freeze({
7
+ kind: 'upsert',
8
+ target: void 0,
9
+ update: void 0
10
+ })
11
+ };
12
+ function upsert(options = {}) {
13
+ return Object.freeze({
14
+ kind: 'upsert',
15
+ target: options.target ? Object.freeze([
16
+ ...options.target
17
+ ]) : void 0,
18
+ update: options.update ? Object.freeze([
19
+ ...options.update
20
+ ]) : void 0
21
+ });
22
+ }
23
+ const DEFAULT_MAX_ROWS = 10000;
24
+ function policy(debounceMs, maxRows, ttlMs) {
25
+ if (!Number.isFinite(debounceMs) || debounceMs < 0) throw new G9SqliteError('misuse', 'debounceMs must be ≥ 0.');
26
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1) throw new G9SqliteError('misuse', 'maxRows must be ≥ 1.');
27
+ if (void 0 !== ttlMs && (!Number.isFinite(ttlMs) || ttlMs <= 0)) throw new G9SqliteError('misuse', 'ttlMs must be > 0.');
28
+ return Object.freeze({
29
+ debounceMs,
30
+ maxRows,
31
+ ttlMs
32
+ });
33
+ }
34
+ const G9CachePolicy = {
35
+ immediate (options = {}) {
36
+ var _options_maxRows;
37
+ return policy(0, null != (_options_maxRows = options.maxRows) ? _options_maxRows : DEFAULT_MAX_ROWS, options.ttlMs);
38
+ },
39
+ debounced (debounceMs = 250, options = {}) {
40
+ var _options_maxRows;
41
+ return policy(debounceMs, null != (_options_maxRows = options.maxRows) ? _options_maxRows : DEFAULT_MAX_ROWS, options.ttlMs);
42
+ },
43
+ all (maxRows, options = {}) {
44
+ var _options_debounceMs;
45
+ return policy(null != (_options_debounceMs = options.debounceMs) ? _options_debounceMs : 0, maxRows, options.ttlMs);
46
+ },
47
+ ttl (ttlMs, options = {}) {
48
+ var _options_debounceMs, _options_maxRows;
49
+ return policy(null != (_options_debounceMs = options.debounceMs) ? _options_debounceMs : 0, null != (_options_maxRows = options.maxRows) ? _options_maxRows : DEFAULT_MAX_ROWS, ttlMs);
50
+ }
51
+ };
52
+ export { G9CachePolicy, G9ConflictPolicy, upsert };
53
+
54
+ //# sourceMappingURL=policies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema/policies.js","sources":["../../src/schema/policies.ts"],"sourcesContent":["import { G9SqliteError } from '../errors';\nimport type { G9Predicate } from '../query/expr';\n\n/**\n * What an INSERT does when a key collides (MAUI `G9ConflictPolicy`).\n * - `abort` (default): fail with a `constraint` error. A surprise collision is usually a bug worth hearing about.\n * - `ignore`: skip the row (`INSERT OR IGNORE`); the returned count excludes it.\n * - `replace`: `INSERT OR REPLACE`, which SQLite executes as DELETE + INSERT: columns the row does not supply reset\n * to their defaults, and the implicit delete fires DELETE triggers only under `PRAGMA recursive_triggers=ON`\n * (default OFF), so sync capture triggers do not see it. Only when asked for explicitly.\n * - an upsert ({@link upsert}): `ON CONFLICT (target) DO UPDATE SET` the given (or every supplied non-key) columns,\n * leaving the rest and the audit creation fields intact. MAUI `Upsert`.\n */\nexport type G9ConflictPolicy = 'abort' | 'ignore' | 'replace' | G9UpsertPolicy;\n\n/** An upsert conflict policy. */\nexport interface G9UpsertPolicy {\n readonly kind: 'upsert';\n /** Conflict target properties (default: the primary key). */\n readonly target: readonly string[] | undefined;\n /** Properties to update on conflict (default: every supplied non-target column except creation audit fields). */\n readonly update: readonly string[] | undefined;\n}\n\n/** MAUI `G9ConflictPolicy` members by their C# names. */\nexport const G9ConflictPolicy = {\n Abort: 'abort',\n Ignore: 'ignore',\n Replace: 'replace',\n Upsert: Object.freeze({ kind: 'upsert', target: undefined, update: undefined }) as G9UpsertPolicy,\n} as const;\n\n/** An upsert on the given conflict target, optionally limited to some update columns. */\nexport function upsert(options: { target?: readonly string[]; update?: readonly string[] } = {}): G9UpsertPolicy {\n return Object.freeze({\n kind: 'upsert',\n target: options.target ? Object.freeze([...options.target]) : undefined,\n update: options.update ? Object.freeze([...options.update]) : undefined,\n });\n}\n\n/**\n * Whether and how an entity's rows are cached in memory (MAUI `G9CachePolicy`). For small, hot, rarely-written\n * reference tables: the cache holds every (filtered) row and a committed write invalidates it.\n */\nexport interface G9CachePolicy {\n /** Coalescing window for invalidations; 0 refreshes right after each commit. */\n readonly debounceMs: number;\n /** Upper bound on cached rows; a larger table fails the refresh with a typed error instead of growing. */\n readonly maxRows: number;\n /** Rows older than this are reloaded on the next read; `undefined` = until invalidated. */\n readonly ttlMs: number | undefined;\n}\n\nconst DEFAULT_MAX_ROWS = 10_000;\n\nfunction policy(debounceMs: number, maxRows: number, ttlMs: number | undefined): G9CachePolicy {\n if (!Number.isFinite(debounceMs) || debounceMs < 0) throw new G9SqliteError('misuse', 'debounceMs must be ≥ 0.');\n if (!Number.isSafeInteger(maxRows) || maxRows < 1) throw new G9SqliteError('misuse', 'maxRows must be ≥ 1.');\n if (ttlMs !== undefined && (!Number.isFinite(ttlMs) || ttlMs <= 0)) {\n throw new G9SqliteError('misuse', 'ttlMs must be > 0.');\n }\n return Object.freeze({ debounceMs, maxRows, ttlMs });\n}\n\n/** Cache policy factories (MAUI `G9CachePolicy.Immediate()` / `.Debounced(250)` plus TTL and size bounds). */\nexport const G9CachePolicy = {\n /** Refresh right after each committed write. For a table written rarely and read constantly. */\n immediate(options: { maxRows?: number; ttlMs?: number } = {}): G9CachePolicy {\n return policy(0, options.maxRows ?? DEFAULT_MAX_ROWS, options.ttlMs);\n },\n /** Coalesce invalidations over a window (default 250 ms, MAUI's default): one refresh after a batch import. */\n debounced(debounceMs = 250, options: { maxRows?: number; ttlMs?: number } = {}): G9CachePolicy {\n return policy(debounceMs, options.maxRows ?? DEFAULT_MAX_ROWS, options.ttlMs);\n },\n /** Every row, bounded: refreshed after commits and capped at `maxRows`. */\n all(maxRows: number, options: { debounceMs?: number; ttlMs?: number } = {}): G9CachePolicy {\n return policy(options.debounceMs ?? 0, maxRows, options.ttlMs);\n },\n /** Reloaded on read once older than `ttlMs` (and after commits). */\n ttl(ttlMs: number, options: { debounceMs?: number; maxRows?: number } = {}): G9CachePolicy {\n return policy(options.debounceMs ?? 0, options.maxRows ?? DEFAULT_MAX_ROWS, ttlMs);\n },\n} as const;\n\n/** One part of an index: a property, its direction and optional collation. */\nexport interface G9IndexPart {\n readonly property: string;\n readonly descending: boolean;\n readonly collate: string | undefined;\n}\n\n/** MAUI `G9IndexDescriptor` (`Properties`, `IsUnique`) plus name, order, collation and a partial predicate. */\nexport interface G9IndexDescriptor {\n readonly name: string | undefined;\n readonly unique: boolean;\n readonly parts: readonly G9IndexPart[];\n // biome-ignore lint/suspicious/noExplicitAny: the refs type depends on the entity; checked at definition.\n readonly where: ((refs: any) => G9Predicate) | undefined;\n /** For a soft-delete entity: `true` makes a unique index cover deleted rows too (default: live rows only). */\n readonly includeDeleted: boolean;\n}\n\n/** MAUI `SoftDeleteProperty`, plus optional deletion audit properties. */\nexport interface G9SoftDeleteDescriptor {\n readonly flag: string;\n readonly deletedTime: string | undefined;\n readonly deletedByUserId: string | undefined;\n}\n"],"names":["G9ConflictPolicy","Object","undefined","upsert","options","DEFAULT_MAX_ROWS","policy","debounceMs","maxRows","ttlMs","Number","G9SqliteError","G9CachePolicy","_options_maxRows","_options_debounceMs"],"mappings":";AAyBO,MAAMA,mBAAmB;IAC9B,OAAO;IACP,QAAQ;IACR,SAAS;IACT,QAAQC,OAAO,MAAM,CAAC;QAAE,MAAM;QAAU,QAAQC;QAAW,QAAQA;IAAU;AAC/E;AAGO,SAASC,OAAOC,UAAsE,CAAC,CAAC;IAC7F,OAAOH,OAAO,MAAM,CAAC;QACnB,MAAM;QACN,QAAQG,QAAQ,MAAM,GAAGH,OAAO,MAAM,CAAC;eAAIG,QAAQ,MAAM;SAAC,IAAIF;QAC9D,QAAQE,QAAQ,MAAM,GAAGH,OAAO,MAAM,CAAC;eAAIG,QAAQ,MAAM;SAAC,IAAIF;IAChE;AACF;AAeA,MAAMG,mBAAmB;AAEzB,SAASC,OAAOC,UAAkB,EAAEC,OAAe,EAAEC,KAAyB;IAC5E,IAAI,CAACC,OAAO,QAAQ,CAACH,eAAeA,aAAa,GAAG,MAAM,IAAII,cAAc,UAAU;IACtF,IAAI,CAACD,OAAO,aAAa,CAACF,YAAYA,UAAU,GAAG,MAAM,IAAIG,cAAc,UAAU;IACrF,IAAIF,AAAUP,WAAVO,SAAwB,EAACC,OAAO,QAAQ,CAACD,UAAUA,SAAS,IAC9D,MAAM,IAAIE,cAAc,UAAU;IAEpC,OAAOV,OAAO,MAAM,CAAC;QAAEM;QAAYC;QAASC;IAAM;AACpD;AAGO,MAAMG,gBAAgB;IAE3B,WAAUR,UAAgD,CAAC,CAAC;YACzCS;QAAjB,OAAOP,OAAO,GAAG,QAAAO,CAAAA,mBAAAA,QAAQ,OAAO,AAAD,IAAdA,mBAAmBR,kBAAkBD,QAAQ,KAAK;IACrE;IAEA,WAAUG,aAAa,GAAG,EAAEH,UAAgD,CAAC,CAAC;YAClDS;QAA1B,OAAOP,OAAOC,YAAY,QAAAM,CAAAA,mBAAAA,QAAQ,OAAO,AAAD,IAAdA,mBAAmBR,kBAAkBD,QAAQ,KAAK;IAC9E;IAEA,KAAII,OAAe,EAAEJ,UAAmD,CAAC,CAAC;YAC1DU;QAAd,OAAOR,OAAO,QAAAQ,CAAAA,sBAAAA,QAAQ,UAAU,AAAD,IAAjBA,sBAAsB,GAAGN,SAASJ,QAAQ,KAAK;IAC/D;IAEA,KAAIK,KAAa,EAAEL,UAAqD,CAAC,CAAC;YAC1DU,qBAAyBD;QAAvC,OAAOP,OAAO,QAAAQ,CAAAA,sBAAAA,QAAQ,UAAU,AAAD,IAAjBA,sBAAsB,GAAG,QAAAD,CAAAA,mBAAAA,QAAQ,OAAO,AAAD,IAAdA,mBAAmBR,kBAAkBI;IAC9E;AACF"}
@@ -0,0 +1,32 @@
1
+ import { type G9Clock } from '@g9tm/lynxcontrols-foundation';
2
+ import { type G9IdCase } from '../values/ids.js';
3
+ import { type G9LocalDateTime } from '../values/local-date-time.js';
4
+ /**
5
+ * Supplies "now" for audit columns (MAUI `IG9Clock`). Read at write time, never captured: a captured value would
6
+ * freeze at startup.
7
+ */
8
+ export interface G9AuditClock {
9
+ now(): G9LocalDateTime;
10
+ }
11
+ /** MAUI `G9SystemClock`: UTC wall time. The default. */
12
+ export declare function createSystemAuditClock(clock?: G9Clock): G9AuditClock;
13
+ /**
14
+ * A clock at a fixed UTC offset (e.g. a business time zone without DST, `+210` for Tehran since 2022). For zones with
15
+ * DST, implement {@link G9AuditClock} with the app's own zone rules: G9 never guesses a zone.
16
+ */
17
+ export declare function createOffsetAuditClock(offsetMinutes: number, clock?: G9Clock): G9AuditClock;
18
+ /**
19
+ * Supplies the current user id for audit columns (MAUI `IG9CurrentUserProvider`), read at write time. `null` is a
20
+ * legitimate answer: existing user columns are kept rather than overwritten with nothing.
21
+ */
22
+ export interface G9CurrentUserProvider {
23
+ getCurrentUserId(): string | null;
24
+ }
25
+ /** MAUI `G9NoCurrentUser`: nobody. Audit user columns keep what the row carried. */
26
+ export declare const g9NoCurrentUser: G9CurrentUserProvider;
27
+ /**
28
+ * MAUI `SqliteEntityAuditDefaults.ResolveCurrentUserId`: the provider's id, normalised; `null` when the provider
29
+ * throws (a provider must never fail a write: an unattributed row is recoverable, a lost one is not).
30
+ */
31
+ export declare function resolveCurrentUserId(provider: G9CurrentUserProvider, idCase: G9IdCase): string | null;
32
+ //# sourceMappingURL=ambient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ambient.d.ts","sourceRoot":"","sources":["../../src/session/ambient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,KAAK,QAAQ,EAAe,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,KAAK,eAAe,EAA4B,MAAM,2BAA2B,CAAC;AAE3F;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,GAAG,IAAI,eAAe,CAAC;CACxB;AAED,wDAAwD;AACxD,wBAAgB,sBAAsB,CAAC,KAAK,GAAE,OAA6B,GAAG,YAAY,CAEzF;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,aAAa,EAAE,MAAM,EAAE,KAAK,GAAE,OAA6B,GAAG,YAAY,CAKhH;AAED;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,oFAAoF;AACpF,eAAO,MAAM,eAAe,EAAE,qBAAuE,CAAC;AAEtG;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,qBAAqB,EAAE,MAAM,EAAE,QAAQ,GAAG,MAAM,GAAG,IAAI,CAMrG"}
@@ -0,0 +1,28 @@
1
+ import { createSystemClock } from "@g9tm/lynxcontrols-foundation";
2
+ import { G9SqliteError } from "../errors.js";
3
+ import { normalizeId } from "../values/ids.js";
4
+ import { localDateTimeFromEpochMs } from "../values/local-date-time.js";
5
+ function createSystemAuditClock(clock = createSystemClock()) {
6
+ return {
7
+ now: ()=>localDateTimeFromEpochMs(clock.now(), 0)
8
+ };
9
+ }
10
+ function createOffsetAuditClock(offsetMinutes, clock = createSystemClock()) {
11
+ if (!Number.isInteger(offsetMinutes) || Math.abs(offsetMinutes) > 1080) throw new G9SqliteError('misuse', 'offsetMinutes must be an integer within ±18 hours.');
12
+ return {
13
+ now: ()=>localDateTimeFromEpochMs(clock.now(), offsetMinutes)
14
+ };
15
+ }
16
+ const g9NoCurrentUser = Object.freeze({
17
+ getCurrentUserId: ()=>null
18
+ });
19
+ function resolveCurrentUserId(provider, idCase) {
20
+ try {
21
+ return normalizeId(provider.getCurrentUserId(), idCase);
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ export { createOffsetAuditClock, createSystemAuditClock, g9NoCurrentUser, resolveCurrentUserId };
27
+
28
+ //# sourceMappingURL=ambient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/ambient.js","sources":["../../src/session/ambient.ts"],"sourcesContent":["import { createSystemClock, type G9Clock } from '@g9tm/lynxcontrols-foundation';\nimport { G9SqliteError } from '../errors';\nimport { type G9IdCase, normalizeId } from '../values/ids';\nimport { type G9LocalDateTime, localDateTimeFromEpochMs } from '../values/local-date-time';\n\n/**\n * Supplies \"now\" for audit columns (MAUI `IG9Clock`). Read at write time, never captured: a captured value would\n * freeze at startup.\n */\nexport interface G9AuditClock {\n now(): G9LocalDateTime;\n}\n\n/** MAUI `G9SystemClock`: UTC wall time. The default. */\nexport function createSystemAuditClock(clock: G9Clock = createSystemClock()): G9AuditClock {\n return { now: () => localDateTimeFromEpochMs(clock.now(), 0) };\n}\n\n/**\n * A clock at a fixed UTC offset (e.g. a business time zone without DST, `+210` for Tehran since 2022). For zones with\n * DST, implement {@link G9AuditClock} with the app's own zone rules: G9 never guesses a zone.\n */\nexport function createOffsetAuditClock(offsetMinutes: number, clock: G9Clock = createSystemClock()): G9AuditClock {\n if (!Number.isInteger(offsetMinutes) || Math.abs(offsetMinutes) > 18 * 60) {\n throw new G9SqliteError('misuse', 'offsetMinutes must be an integer within ±18 hours.');\n }\n return { now: () => localDateTimeFromEpochMs(clock.now(), offsetMinutes) };\n}\n\n/**\n * Supplies the current user id for audit columns (MAUI `IG9CurrentUserProvider`), read at write time. `null` is a\n * legitimate answer: existing user columns are kept rather than overwritten with nothing.\n */\nexport interface G9CurrentUserProvider {\n getCurrentUserId(): string | null;\n}\n\n/** MAUI `G9NoCurrentUser`: nobody. Audit user columns keep what the row carried. */\nexport const g9NoCurrentUser: G9CurrentUserProvider = Object.freeze({ getCurrentUserId: () => null });\n\n/**\n * MAUI `SqliteEntityAuditDefaults.ResolveCurrentUserId`: the provider's id, normalised; `null` when the provider\n * throws (a provider must never fail a write: an unattributed row is recoverable, a lost one is not).\n */\nexport function resolveCurrentUserId(provider: G9CurrentUserProvider, idCase: G9IdCase): string | null {\n try {\n return normalizeId(provider.getCurrentUserId(), idCase);\n } catch {\n return null;\n }\n}\n"],"names":["createSystemAuditClock","clock","createSystemClock","localDateTimeFromEpochMs","createOffsetAuditClock","offsetMinutes","Number","Math","G9SqliteError","g9NoCurrentUser","Object","resolveCurrentUserId","provider","idCase","normalizeId"],"mappings":";;;;AAcO,SAASA,uBAAuBC,QAAiBC,mBAAmB;IACzE,OAAO;QAAE,KAAK,IAAMC,yBAAyBF,MAAM,GAAG,IAAI;IAAG;AAC/D;AAMO,SAASG,uBAAuBC,aAAqB,EAAEJ,QAAiBC,mBAAmB;IAChG,IAAI,CAACI,OAAO,SAAS,CAACD,kBAAkBE,KAAK,GAAG,CAACF,iBAAiB,MAChE,MAAM,IAAIG,cAAc,UAAU;IAEpC,OAAO;QAAE,KAAK,IAAML,yBAAyBF,MAAM,GAAG,IAAII;IAAe;AAC3E;AAWO,MAAMI,kBAAyCC,OAAO,MAAM,CAAC;IAAE,kBAAkB,IAAM;AAAK;AAM5F,SAASC,qBAAqBC,QAA+B,EAAEC,MAAgB;IACpF,IAAI;QACF,OAAOC,YAAYF,SAAS,gBAAgB,IAAIC;IAClD,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -0,0 +1,62 @@
1
+ import type { G9EntityDescriptor } from '../schema/entity.js';
2
+ import type { G9CachePolicy } from '../schema/policies.js';
3
+ import type { G9SqliteDatabase } from './database.js';
4
+ /**
5
+ * An in-memory copy of a small, hot table or a DTO projection over tables (MAUI repository cache and
6
+ * `SqliteDtoCache`). Invalidated only by committed writes (never by a rollback), coalesced by the policy's debounce,
7
+ * bounded by `maxRows`, optionally expiring, and reset on a user switch so no row of one user reaches the next.
8
+ */
9
+ export interface G9CacheHandle<T> {
10
+ readonly name: string;
11
+ readonly policy: G9CachePolicy;
12
+ /** MAUI `GetCacheDataAsync`: loads on first use (and after expiry or reset), then serves copies. */
13
+ get(): Promise<T[]>;
14
+ /** MAUI `GetCacheData` (synchronous): a copy when loaded, otherwise `undefined` (JS cannot block on a load). */
15
+ peek(): T[] | undefined;
16
+ /** MAUI `RefreshCache`: reload now, cancelling a pending debounced refresh. */
17
+ refresh(): Promise<void>;
18
+ /** MAUI `ListenToCacheData`: called with a copy after each refresh and with `[]` on reset; immediately if loaded. */
19
+ listen(listener: (rows: T[]) => void): () => void;
20
+ /** MAUI `StopListeningToCacheData`. */
21
+ stopListening(listener: (rows: T[]) => void): boolean;
22
+ /** MAUI `ScheduleDebouncedRefresh`. */
23
+ scheduleRefresh(): void;
24
+ /** Rows currently held (for bounds checks). */
25
+ readonly size: number;
26
+ }
27
+ /**
28
+ * Every cache of one database (MAUI `SqliteRepositoryCacheRegistry`): entity caches keyed by descriptor, DTO caches
29
+ * by name, all invalidated by table on commit.
30
+ */
31
+ export declare class G9CacheRegistry {
32
+ private readonly db;
33
+ private readonly entityCaches;
34
+ private readonly dtoCaches;
35
+ private readonly dtoByEntity;
36
+ constructor(db: G9SqliteDatabase);
37
+ private all;
38
+ /** MAUI `DefineCache` (+ descriptor `Cache(policy)`): idempotent per entity. */
39
+ defineEntityCache<T>(entity: G9EntityDescriptor, policy: G9CachePolicy, load?: (maxRows: number) => Promise<T[]>): G9CacheHandle<T>;
40
+ /** The entity's cache, or `undefined` when none is defined (MAUI `HasDefinedCache`). */
41
+ entityCache<T>(entity: G9EntityDescriptor): G9CacheHandle<T> | undefined;
42
+ /** MAUI `SqliteDtoCache<TEntity,TDto>.DefineCache` / `RegisterDtoCacheForEntity`. */
43
+ defineDtoCache<T>(name: string, sources: readonly G9EntityDescriptor[], policy: G9CachePolicy, load: (maxRows: number) => Promise<T[]>): G9CacheHandle<T>;
44
+ /** The DTO cache of that name, if defined. */
45
+ dtoCache<T>(name: string): G9CacheHandle<T> | undefined;
46
+ /** Commit-driven invalidation: every cache reading this table schedules its refresh. */
47
+ invalidateTable(table: string): void;
48
+ /** A raw mutation of unknown tables: every cache schedules its refresh. */
49
+ invalidateAll(): void;
50
+ /** MAUI `ResetAllCachesForSession`: each cache resets even if another fails. */
51
+ resetAll(): void;
52
+ /** MAUI `HardRefreshAllCacheAsync`. */
53
+ refreshAll(): Promise<void>;
54
+ /** MAUI `RefreshCacheAsync(Type)`: `false` when the entity has no cache. */
55
+ refreshEntity(entity: G9EntityDescriptor): Promise<boolean>;
56
+ /** MAUI `RefreshEntityAndDtoCachesAsync`. */
57
+ refreshEntityAndDtoCaches(entity: G9EntityDescriptor): Promise<void>;
58
+ /** Total cached rows (memory-bound checks). */
59
+ get totalRows(): number;
60
+ dispose(): void;
61
+ }
62
+ //# sourceMappingURL=cache.d.ts.map
@@ -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