@haverstack/record-adapter-do-sqlite 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +118 -53
- package/dist/index.js +84 -79
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,113 @@
|
|
|
1
1
|
import { StackRecord, RecordChanges, RecordVersion, ActorOptions, TypeId, StackQuery, QueryResult, FileId, StackType, Association } from '@haverstack/core';
|
|
2
2
|
import { StackRecordAdapter, AdapterCapabilities } from '@haverstack/core/adapter';
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Normalizes a SQLite binding's call convention (array-bind-then-step,
|
|
6
|
+
* spread-args run/get/all, cursor-returning exec) behind one interface,
|
|
7
|
+
* so the actual CRUD/query/version/type/association/token logic can live
|
|
8
|
+
* once in this package instead of being re-typed per engine. Each adapter
|
|
9
|
+
* package provides a thin SqlExecutor implementation over its own
|
|
10
|
+
* database handle.
|
|
11
|
+
*
|
|
12
|
+
* Deliberately synchronous: every binding this targets executes queries
|
|
13
|
+
* in-process without yielding, and an async interface would force the
|
|
14
|
+
* shared logic's transaction sequences to interleave.
|
|
15
|
+
*/
|
|
16
|
+
interface SqlExecutor {
|
|
17
|
+
/** Run DDL, pragmas, or any statement(s) with no bound params and no results needed. */
|
|
18
|
+
exec(sql: string): void;
|
|
19
|
+
/** Run a single parameterized statement. Returns the number of rows affected (INSERT/UPDATE/DELETE). */
|
|
20
|
+
run(sql: string, params?: readonly unknown[]): number;
|
|
21
|
+
/** Run a parameterized statement and return the first result row, or undefined. */
|
|
22
|
+
get<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T | undefined;
|
|
23
|
+
/** Run a parameterized statement and return all result rows. */
|
|
24
|
+
all<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T[];
|
|
25
|
+
/**
|
|
26
|
+
* Run `fn` atomically: every statement it issues commits together, or
|
|
27
|
+
* none do if it throws. `fn` must be synchronous and call back into
|
|
28
|
+
* this executor only — not every engine's transaction primitive can
|
|
29
|
+
* straddle a suspended call. A binding with a real multi-statement
|
|
30
|
+
* transaction (BEGIN/COMMIT/ROLLBACK) implements this with one; a
|
|
31
|
+
* binding whose transaction primitive is itself a callback wrapper
|
|
32
|
+
* (e.g. a Durable Object's storage.transactionSync) can pass `fn`
|
|
33
|
+
* straight through to it.
|
|
34
|
+
*/
|
|
35
|
+
transaction<T>(fn: () => T): T;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** timezone is optional passthrough app metadata — no default. */
|
|
39
|
+
type StackConfig = {
|
|
40
|
+
entityId: string;
|
|
41
|
+
timezone: string | undefined;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The engine-independent half of a SQLite-backed StackRecordAdapter: the
|
|
46
|
+
* capability declaration and the delegation of all seventeen
|
|
47
|
+
* StackRecordAdapter methods onto SharedSqlRecordLogic. Every method here
|
|
48
|
+
* is a forward with no engine-specific content, so an adapter that owns a
|
|
49
|
+
* SqlExecutor already knows how to answer all of them.
|
|
50
|
+
*
|
|
51
|
+
* What a concrete adapter is left to supply is exactly what differs
|
|
52
|
+
* between bindings: constructing the database handle, applying the
|
|
53
|
+
* schema, and its own lifecycle (flush/close) — hence those two being the
|
|
54
|
+
* only abstract members.
|
|
55
|
+
*
|
|
56
|
+
* Lives in record.js's barrel rather than index.js's, so an adapter that
|
|
57
|
+
* imports it never pulls in token-logic.ts's `node:crypto` — see the note
|
|
58
|
+
* at the top of record.ts.
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
declare abstract class SharedSqlRecordAdapter implements StackRecordAdapter {
|
|
62
|
+
readonly capabilities: AdapterCapabilities;
|
|
63
|
+
readonly ownerEntityId: string;
|
|
64
|
+
readonly timezone: string | undefined;
|
|
65
|
+
private readonly record;
|
|
66
|
+
protected constructor(exec: SqlExecutor, config: StackConfig);
|
|
67
|
+
createRecord(record: StackRecord): Promise<StackRecord>;
|
|
68
|
+
getRecord(id: string): Promise<StackRecord | null>;
|
|
69
|
+
mutateRecord(id: string, changes: RecordChanges, opts?: {
|
|
70
|
+
expectedVersion?: number;
|
|
71
|
+
snapshot?: RecordVersion;
|
|
72
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
73
|
+
deleteRecord(id: string, opts?: {
|
|
74
|
+
hard?: boolean;
|
|
75
|
+
expectedVersion?: number;
|
|
76
|
+
snapshot?: RecordVersion;
|
|
77
|
+
} & ActorOptions): Promise<StackRecord | null>;
|
|
78
|
+
undeleteRecord(id: string, opts?: {
|
|
79
|
+
expectedVersion?: number;
|
|
80
|
+
snapshot?: RecordVersion;
|
|
81
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
82
|
+
restoreVersion(id: string, version: number, opts?: {
|
|
83
|
+
expectedVersion?: number;
|
|
84
|
+
snapshot?: RecordVersion;
|
|
85
|
+
} & {
|
|
86
|
+
restoreAssociations?: boolean;
|
|
87
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
88
|
+
commitMigration(id: string, toTypeId: TypeId, content: Record<string, unknown>, opts?: {
|
|
89
|
+
expectedVersion?: number;
|
|
90
|
+
snapshot?: RecordVersion;
|
|
91
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
92
|
+
queryRecords(query: StackQuery): Promise<QueryResult>;
|
|
93
|
+
deleteUnreferencedAttachmentRecords(fileId: FileId, metadataTypeIds: TypeId[]): Promise<StackRecord[]>;
|
|
94
|
+
getVersions(id: string): Promise<RecordVersion[]>;
|
|
95
|
+
getVersion(id: string, version: number): Promise<RecordVersion | null>;
|
|
96
|
+
saveVersion(id: string, version: RecordVersion): Promise<void>;
|
|
97
|
+
saveType(type: StackType): Promise<void>;
|
|
98
|
+
getType(id: TypeId): Promise<StackType | null>;
|
|
99
|
+
listTypes(): Promise<StackType[]>;
|
|
100
|
+
associate(recordId: string, association: Association, opts?: {
|
|
101
|
+
expectedVersion?: number;
|
|
102
|
+
snapshot?: RecordVersion;
|
|
103
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
104
|
+
dissociate(recordId: string, association: Association, opts?: {
|
|
105
|
+
expectedVersion?: number;
|
|
106
|
+
snapshot?: RecordVersion;
|
|
107
|
+
} & ActorOptions): Promise<StackRecord>;
|
|
108
|
+
abstract flush(): Promise<void>;
|
|
109
|
+
abstract close(): Promise<void>;
|
|
110
|
+
}
|
|
4
111
|
|
|
5
112
|
/**
|
|
6
113
|
* Normalizes a Durable Object's ctx.storage.sql to SqlExecutor.
|
|
@@ -47,12 +154,12 @@ declare class DurableObjectSqliteExecutor implements SqlExecutor {
|
|
|
47
154
|
* call returns, so flush()/close() are no-ops kept only to satisfy the
|
|
48
155
|
* optional StackRecordAdapter methods.
|
|
49
156
|
*
|
|
50
|
-
* This class itself is a thin binding:
|
|
51
|
-
*
|
|
157
|
+
* This class itself is a thin binding: the one piece of genuinely
|
|
158
|
+
* engine-specific wiring — SqlExecutor.transaction() reaching
|
|
52
159
|
* ctx.storage.transactionSync() instead of raw SQL BEGIN/COMMIT/ROLLBACK,
|
|
53
|
-
* which DO SQLite rejects outright —
|
|
54
|
-
*
|
|
55
|
-
*
|
|
160
|
+
* which DO SQLite rejects outright — lives in executor.ts. Everything
|
|
161
|
+
* above storage comes from @haverstack/sqlite-shared's
|
|
162
|
+
* SharedSqlRecordAdapter, exactly as it does for record-adapter-sqlite.
|
|
56
163
|
*/
|
|
57
164
|
|
|
58
165
|
type DoRecordCreateOptions = {
|
|
@@ -61,12 +168,7 @@ type DoRecordCreateOptions = {
|
|
|
61
168
|
/** IANA timezone string e.g. "America/New_York". Optional passthrough app metadata — no default. */
|
|
62
169
|
timezone?: string;
|
|
63
170
|
};
|
|
64
|
-
declare class DoSQLiteRecordAdapter
|
|
65
|
-
private readonly exec;
|
|
66
|
-
readonly capabilities: AdapterCapabilities;
|
|
67
|
-
ownerEntityId: string;
|
|
68
|
-
timezone: string | undefined;
|
|
69
|
-
private readonly record;
|
|
171
|
+
declare class DoSQLiteRecordAdapter extends SharedSqlRecordAdapter {
|
|
70
172
|
private constructor();
|
|
71
173
|
/**
|
|
72
174
|
* Create (or reattach to) the adapter for a DO instance. There is no
|
|
@@ -76,49 +178,12 @@ declare class DoSQLiteRecordAdapter implements StackRecordAdapter {
|
|
|
76
178
|
* or it doesn't (first call — opts.entityId/timezone become the config).
|
|
77
179
|
* Schema DDL is `CREATE TABLE IF NOT EXISTS`, so running it every call
|
|
78
180
|
* is idempotent and cheap.
|
|
181
|
+
*
|
|
182
|
+
* DO SQLite manages its own durability and rejects PRAGMA journal_mode
|
|
183
|
+
* outright ("not authorized") — verified against the real runtime, not
|
|
184
|
+
* assumed — hence `wal: false`, unlike record-adapter-sqlite.
|
|
79
185
|
*/
|
|
80
186
|
static create(storage: DurableObjectStorage, opts: DoRecordCreateOptions): Promise<DoSQLiteRecordAdapter>;
|
|
81
|
-
createRecord(record: StackRecord): Promise<StackRecord>;
|
|
82
|
-
getRecord(id: string): Promise<StackRecord | null>;
|
|
83
|
-
mutateRecord(id: string, changes: RecordChanges, opts?: {
|
|
84
|
-
expectedVersion?: number;
|
|
85
|
-
snapshot?: RecordVersion;
|
|
86
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
87
|
-
deleteRecord(id: string, opts?: {
|
|
88
|
-
hard?: boolean;
|
|
89
|
-
expectedVersion?: number;
|
|
90
|
-
snapshot?: RecordVersion;
|
|
91
|
-
} & ActorOptions): Promise<StackRecord | null>;
|
|
92
|
-
undeleteRecord(id: string, opts?: {
|
|
93
|
-
expectedVersion?: number;
|
|
94
|
-
snapshot?: RecordVersion;
|
|
95
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
96
|
-
restoreVersion(id: string, version: number, opts?: {
|
|
97
|
-
expectedVersion?: number;
|
|
98
|
-
snapshot?: RecordVersion;
|
|
99
|
-
} & {
|
|
100
|
-
restoreAssociations?: boolean;
|
|
101
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
102
|
-
commitMigration(id: string, toTypeId: TypeId, content: Record<string, unknown>, opts?: {
|
|
103
|
-
expectedVersion?: number;
|
|
104
|
-
snapshot?: RecordVersion;
|
|
105
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
106
|
-
queryRecords(query: StackQuery): Promise<QueryResult>;
|
|
107
|
-
deleteUnreferencedAttachmentRecords(fileId: FileId, metadataTypeIds: TypeId[]): Promise<StackRecord[]>;
|
|
108
|
-
getVersions(id: string): Promise<RecordVersion[]>;
|
|
109
|
-
getVersion(id: string, version: number): Promise<RecordVersion | null>;
|
|
110
|
-
saveVersion(id: string, version: RecordVersion): Promise<void>;
|
|
111
|
-
saveType(type: StackType): Promise<void>;
|
|
112
|
-
getType(id: TypeId): Promise<StackType | null>;
|
|
113
|
-
listTypes(): Promise<StackType[]>;
|
|
114
|
-
associate(recordId: string, association: Association, opts?: {
|
|
115
|
-
expectedVersion?: number;
|
|
116
|
-
snapshot?: RecordVersion;
|
|
117
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
118
|
-
dissociate(recordId: string, association: Association, opts?: {
|
|
119
|
-
expectedVersion?: number;
|
|
120
|
-
snapshot?: RecordVersion;
|
|
121
|
-
} & ActorOptions): Promise<StackRecord>;
|
|
122
187
|
/** No-op: every write through ctx.storage.sql is already durable. */
|
|
123
188
|
flush(): Promise<void>;
|
|
124
189
|
/** No-op: no lock file, no connection to release — the DO's own lifecycle governs storage. */
|
package/dist/index.js
CHANGED
|
@@ -132,6 +132,11 @@ var FTS5_SCHEMA_SQL = `
|
|
|
132
132
|
);
|
|
133
133
|
`;
|
|
134
134
|
var PRAGMA_FOREIGN_KEYS_ON = `PRAGMA foreign_keys = ON;`;
|
|
135
|
+
var applyRecordSchema = (exec, opts) => {
|
|
136
|
+
exec.exec(PRAGMA_FOREIGN_KEYS_ON);
|
|
137
|
+
exec.exec(RECORD_SCHEMA_SQL);
|
|
138
|
+
exec.exec(FTS5_SCHEMA_SQL);
|
|
139
|
+
};
|
|
135
140
|
var SORT_FIELDS = NATIVE_SORT_FIELDS;
|
|
136
141
|
var toBase64 = (text) => {
|
|
137
142
|
const bytes = new TextEncoder().encode(text);
|
|
@@ -631,15 +636,17 @@ var isForeignKeyViolation = (err) => err instanceof Error && err.message.include
|
|
|
631
636
|
var isUniqueConstraintViolation = (err) => err instanceof Error && err.message.includes("UNIQUE constraint failed");
|
|
632
637
|
|
|
633
638
|
// ../sqlite-shared/dist/config.js
|
|
639
|
+
var CONFIG_ROW_SQL = `SELECT content FROM records WHERE id = '_config'`;
|
|
634
640
|
var insertConfigRecord = (exec, entityId, timezone) => {
|
|
635
641
|
const now = Date.now();
|
|
636
642
|
exec.run(`INSERT INTO records (id, type_id, created_at, updated_at, content, version)
|
|
637
643
|
VALUES ('_config', '_config@1', ?, ?, ?, 1)`, [now, now, JSON.stringify({ entityId, timezone })]);
|
|
644
|
+
return { entityId, timezone };
|
|
638
645
|
};
|
|
639
|
-
var
|
|
640
|
-
const row = exec.get(
|
|
646
|
+
var tryReadStackConfig = (exec) => {
|
|
647
|
+
const row = exec.get(CONFIG_ROW_SQL);
|
|
641
648
|
if (!row)
|
|
642
|
-
|
|
649
|
+
return null;
|
|
643
650
|
const content = JSON.parse(row.content);
|
|
644
651
|
return { entityId: content.entityId, timezone: content.timezone };
|
|
645
652
|
};
|
|
@@ -1240,87 +1247,31 @@ var SharedSqlRecordLogic = class {
|
|
|
1240
1247
|
}
|
|
1241
1248
|
};
|
|
1242
1249
|
|
|
1243
|
-
//
|
|
1244
|
-
var
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
return cursor.rowsWritten;
|
|
1258
|
-
}
|
|
1259
|
-
get(sql, params = []) {
|
|
1260
|
-
const rows = this.sql.exec(sql, ...params).toArray();
|
|
1261
|
-
return rows[0];
|
|
1262
|
-
}
|
|
1263
|
-
all(sql, params = []) {
|
|
1264
|
-
return this.sql.exec(sql, ...params).toArray();
|
|
1265
|
-
}
|
|
1266
|
-
transaction(fn) {
|
|
1267
|
-
return this.storage.transactionSync(fn);
|
|
1250
|
+
// ../sqlite-shared/dist/record-adapter.js
|
|
1251
|
+
var SQLITE_RECORD_CAPABILITIES = {
|
|
1252
|
+
filter: {
|
|
1253
|
+
content: "path",
|
|
1254
|
+
contentPresent: true,
|
|
1255
|
+
search: true
|
|
1256
|
+
},
|
|
1257
|
+
sort: {
|
|
1258
|
+
fields: ["createdAt", "updatedAt", "version"],
|
|
1259
|
+
contentField: true
|
|
1260
|
+
},
|
|
1261
|
+
limits: {
|
|
1262
|
+
attachmentBytes: null,
|
|
1263
|
+
contentBytes: null
|
|
1268
1264
|
}
|
|
1269
1265
|
};
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
var DoSQLiteRecordAdapter = class _DoSQLiteRecordAdapter {
|
|
1273
|
-
constructor(exec) {
|
|
1274
|
-
this.exec = exec;
|
|
1275
|
-
this.record = new SharedSqlRecordLogic({ exec });
|
|
1276
|
-
}
|
|
1277
|
-
exec;
|
|
1278
|
-
capabilities = {
|
|
1279
|
-
filter: {
|
|
1280
|
-
content: "path",
|
|
1281
|
-
contentPresent: true,
|
|
1282
|
-
search: true
|
|
1283
|
-
},
|
|
1284
|
-
sort: {
|
|
1285
|
-
fields: ["createdAt", "updatedAt", "version"],
|
|
1286
|
-
contentField: true
|
|
1287
|
-
},
|
|
1288
|
-
limits: {
|
|
1289
|
-
attachmentBytes: null,
|
|
1290
|
-
contentBytes: null
|
|
1291
|
-
}
|
|
1292
|
-
};
|
|
1266
|
+
var SharedSqlRecordAdapter = class {
|
|
1267
|
+
capabilities = SQLITE_RECORD_CAPABILITIES;
|
|
1293
1268
|
ownerEntityId;
|
|
1294
1269
|
timezone;
|
|
1295
1270
|
record;
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
* reattach, opts.entityId/timezone ignored in favor of what's stored)
|
|
1301
|
-
* or it doesn't (first call — opts.entityId/timezone become the config).
|
|
1302
|
-
* Schema DDL is `CREATE TABLE IF NOT EXISTS`, so running it every call
|
|
1303
|
-
* is idempotent and cheap.
|
|
1304
|
-
*/
|
|
1305
|
-
static async create(storage, opts) {
|
|
1306
|
-
const exec = new DurableObjectSqliteExecutor(storage);
|
|
1307
|
-
exec.exec(RECORD_SCHEMA_SQL);
|
|
1308
|
-
exec.exec(FTS5_SCHEMA_SQL);
|
|
1309
|
-
exec.exec(PRAGMA_FOREIGN_KEYS_ON);
|
|
1310
|
-
const adapter = new _DoSQLiteRecordAdapter(exec);
|
|
1311
|
-
const existing = exec.get(
|
|
1312
|
-
`SELECT content FROM records WHERE id = '_config'`
|
|
1313
|
-
);
|
|
1314
|
-
if (existing) {
|
|
1315
|
-
const config = readStackConfig(exec);
|
|
1316
|
-
adapter.ownerEntityId = config.entityId;
|
|
1317
|
-
adapter.timezone = config.timezone;
|
|
1318
|
-
} else {
|
|
1319
|
-
insertConfigRecord(exec, opts.entityId, opts.timezone);
|
|
1320
|
-
adapter.ownerEntityId = opts.entityId;
|
|
1321
|
-
adapter.timezone = opts.timezone;
|
|
1322
|
-
}
|
|
1323
|
-
return adapter;
|
|
1271
|
+
constructor(exec, config) {
|
|
1272
|
+
this.record = new SharedSqlRecordLogic({ exec });
|
|
1273
|
+
this.ownerEntityId = config.entityId;
|
|
1274
|
+
this.timezone = config.timezone;
|
|
1324
1275
|
}
|
|
1325
1276
|
// -------------------------------------------------------
|
|
1326
1277
|
// Records
|
|
@@ -1385,6 +1336,60 @@ var DoSQLiteRecordAdapter = class _DoSQLiteRecordAdapter {
|
|
|
1385
1336
|
dissociate(recordId, association, opts) {
|
|
1386
1337
|
return this.record.dissociate(recordId, association, opts);
|
|
1387
1338
|
}
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
// src/executor.ts
|
|
1342
|
+
var DurableObjectSqliteExecutor = class {
|
|
1343
|
+
constructor(storage) {
|
|
1344
|
+
this.storage = storage;
|
|
1345
|
+
}
|
|
1346
|
+
storage;
|
|
1347
|
+
get sql() {
|
|
1348
|
+
return this.storage.sql;
|
|
1349
|
+
}
|
|
1350
|
+
exec(sql) {
|
|
1351
|
+
this.sql.exec(sql);
|
|
1352
|
+
}
|
|
1353
|
+
run(sql, params = []) {
|
|
1354
|
+
const cursor = this.sql.exec(sql, ...params);
|
|
1355
|
+
return cursor.rowsWritten;
|
|
1356
|
+
}
|
|
1357
|
+
get(sql, params = []) {
|
|
1358
|
+
const rows = this.sql.exec(sql, ...params).toArray();
|
|
1359
|
+
return rows[0];
|
|
1360
|
+
}
|
|
1361
|
+
all(sql, params = []) {
|
|
1362
|
+
return this.sql.exec(sql, ...params).toArray();
|
|
1363
|
+
}
|
|
1364
|
+
transaction(fn) {
|
|
1365
|
+
return this.storage.transactionSync(fn);
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1368
|
+
|
|
1369
|
+
// src/index.ts
|
|
1370
|
+
var DoSQLiteRecordAdapter = class _DoSQLiteRecordAdapter extends SharedSqlRecordAdapter {
|
|
1371
|
+
constructor(exec, config) {
|
|
1372
|
+
super(exec, config);
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Create (or reattach to) the adapter for a DO instance. There is no
|
|
1376
|
+
* initialize()/open() split the way file-based adapters need one: a DO
|
|
1377
|
+
* id either already has a config record (a previous call created it —
|
|
1378
|
+
* reattach, opts.entityId/timezone ignored in favor of what's stored)
|
|
1379
|
+
* or it doesn't (first call — opts.entityId/timezone become the config).
|
|
1380
|
+
* Schema DDL is `CREATE TABLE IF NOT EXISTS`, so running it every call
|
|
1381
|
+
* is idempotent and cheap.
|
|
1382
|
+
*
|
|
1383
|
+
* DO SQLite manages its own durability and rejects PRAGMA journal_mode
|
|
1384
|
+
* outright ("not authorized") — verified against the real runtime, not
|
|
1385
|
+
* assumed — hence `wal: false`, unlike record-adapter-sqlite.
|
|
1386
|
+
*/
|
|
1387
|
+
static async create(storage, opts) {
|
|
1388
|
+
const exec = new DurableObjectSqliteExecutor(storage);
|
|
1389
|
+
applyRecordSchema(exec);
|
|
1390
|
+
const config = tryReadStackConfig(exec) ?? insertConfigRecord(exec, opts.entityId, opts.timezone);
|
|
1391
|
+
return new _DoSQLiteRecordAdapter(exec, config);
|
|
1392
|
+
}
|
|
1388
1393
|
// -------------------------------------------------------
|
|
1389
1394
|
// Lifecycle
|
|
1390
1395
|
// -------------------------------------------------------
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../sqlite-shared/src/schema.ts","../../sqlite-shared/src/cursor.ts","../../sqlite-shared/src/fts5.ts","../../sqlite-shared/src/query.ts","../../sqlite-shared/src/mappers.ts","../../sqlite-shared/src/executor.ts","../../sqlite-shared/src/config.ts","../../sqlite-shared/src/record-logic.ts","../src/executor.ts","../src/index.ts"],"names":["StackQueryError","cursor","page","statement","contentSortEntry"],"mappings":";;;;AAQO,IAAM,iBAAA,GAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJ1B,IAAM,eAAA,GAAkB;;;;;;;;AAexB,IAAM,sBAAA,GAAyB,CAAA,yBAAA,CAAA;ACpJ/B,IAAM,WAAA,GAAoC,kBAAA;AAiBjD,IAAM,QAAA,GAAW,CAAC,IAAA,KAAwB;AACxC,EAAA,MAAM,KAAA,GAAQ,IAAI,WAAA,EAAW,CAAG,OAAO,IAAI,CAAA;AAC3C,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA;AAAO,IAAA,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,KA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sC;AAChD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,EAAE,CAAA;AAAA,EACnC;AAAA,EAEA,UAAA,CAAW,IAAY,OAAA,EAAgD;AACrE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,CAAW,EAAA,EAAI,OAAO,CAAA;AAAA,EAC3C;AAAA,EAEA,WAAA,CAAY,IAAY,OAAA,EAAuC;AAC7D,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,EAAA,EAAI,OAAO,CAAA;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,IAAA,EAAgC;AACvC,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,QAAA,CAAS,IAAI,CAAA;AAAA,EAClC;AAAA,EAEA,QAAQ,EAAA,EAAuC;AAC7C,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,EAAE,CAAA;AAAA,EAC/B;AAAA,EAEA,SAAA,GAAkC;AAChC,IAAA,OAAO,IAAA,CAAK,OAAO,SAAA,EAAU;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA,EAMA,SAAA,CACE,QAAA,EACA,WAAA,EACA,IAAA,EACsB;AACtB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,SAAA,CAAU,QAAA,EAAU,aAAa,IAAI,CAAA;AAAA,EAC1D;AAAA,EAEA,UAAA,CACE,QAAA,EACA,WAAA,EACA,IAAA,EACsB;AACtB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,CAAW,QAAA,EAAU,aAAa,IAAI,CAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAA,GAAuB;AAAA,EAAC;AAAA;AAAA,EAG9B,MAAM,KAAA,GAAuB;AAAA,EAAC;AAChC","file":"index.js","sourcesContent":["/**\n * Schema DDL shared by SQLite-backed record adapters. TOKENS_SCHEMA_SQL\n * is split out from RECORD_SCHEMA_SQL because token storage lives in its\n * own file, never bundled with records — see NativeTokenStore in\n * record-adapter-sqlite and the StackTokenStore portability rationale\n * (docs/spec/wire-format.md § Authentication).\n */\n\nexport const RECORD_SCHEMA_SQL = `\n CREATE TABLE IF NOT EXISTS records (\n id TEXT PRIMARY KEY,\n type_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n content TEXT NOT NULL CHECK (json_valid(content)),\n version INTEGER NOT NULL DEFAULT 1,\n parent_id TEXT,\n entity_id TEXT,\n app_id TEXT,\n principal_id TEXT,\n updated_by TEXT,\n updated_via TEXT,\n deleted_at INTEGER,\n unlisted_at INTEGER,\n permissions TEXT CHECK (permissions IS NULL OR json_valid(permissions))\n ) STRICT;\n\n -- A relationship's target is (related_scope, related_id) plus one\n -- qualifier: related_stack for a record in another stack, related_ns for\n -- a foreign namespace. All four are in the primary key, so two targets\n -- differing only by namespace are two associations.\n --\n -- The primary key leads with record_id, so its implicit index already\n -- serves every by-record read and delete; the indexes below exist only\n -- for the filter directions it cannot answer.\n CREATE TABLE IF NOT EXISTS associations (\n record_id TEXT NOT NULL REFERENCES records(id),\n kind TEXT NOT NULL CHECK (kind IN ('tag', 'attachment', 'relationship')),\n label TEXT NOT NULL,\n file_id TEXT NOT NULL DEFAULT '',\n related_scope TEXT NOT NULL DEFAULT '' CHECK (related_scope IN ('', 'record', 'entity', 'external')),\n related_id TEXT NOT NULL DEFAULT '',\n related_ns TEXT NOT NULL DEFAULT '',\n related_stack TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (record_id, kind, label, file_id, related_scope, related_id, related_ns, related_stack)\n ) STRICT;\n\n -- parent_id holds the container the record sat in, NULL for the root --\n -- the same encoding records.parent_id uses, since a snapshot states\n -- where the record was rather than an instruction to apply.\n CREATE TABLE IF NOT EXISTS versions (\n record_id TEXT NOT NULL REFERENCES records(id),\n version INTEGER NOT NULL,\n type_id TEXT NOT NULL,\n content TEXT NOT NULL CHECK (json_valid(content)),\n updated_at INTEGER NOT NULL,\n entity_id TEXT,\n updated_by TEXT,\n updated_via TEXT,\n parent_id TEXT,\n associations TEXT CHECK (associations IS NULL OR json_valid(associations)),\n permissions TEXT CHECK (permissions IS NULL OR json_valid(permissions)),\n PRIMARY KEY (record_id, version)\n ) STRICT;\n\n CREATE TABLE IF NOT EXISTS types (\n id TEXT PRIMARY KEY,\n base_id TEXT NOT NULL,\n version INTEGER NOT NULL,\n name TEXT NOT NULL,\n schema TEXT NOT NULL CHECK (json_valid(schema)),\n schema_hash TEXT NOT NULL,\n migrates_from TEXT,\n created_at INTEGER NOT NULL\n ) STRICT;\n\n -- One row per top-level scalar content field a record holds a value at:\n -- what it orders as, and the file it references. See\n -- docs/spec/adapters.md § Adapter backends and\n -- docs/spec/data-model.md § Sorting by a content field.\n --\n -- value_rank is 0 for a numeric value and 1 for a text one — the same\n -- split as \"num_value IS NULL\", but non-null, so one index can carry\n -- the whole ordering. file_id is set only for a 'file-ref' field.\n CREATE TABLE IF NOT EXISTS content_index (\n record_id TEXT NOT NULL REFERENCES records(id),\n field TEXT NOT NULL,\n value_rank INTEGER NOT NULL CHECK (value_rank IN (0, 1)),\n num_value REAL,\n text_key TEXT,\n text_value TEXT,\n file_id TEXT,\n PRIMARY KEY (record_id, field)\n ) STRICT;\n\n -- Indexes. Each filter column continues into (created_at, id) — the\n -- default ordering and its tiebreak — because these columns are\n -- low-cardinality by design, and a narrow index on one leaves the\n -- planner sorting the whole matching set before it can honor LIMIT.\n --\n -- deleted_at and unlisted_at deliberately have none: nothing searches\n -- for the rows they mark, and an index on a column every query tests\n -- for IS NULL only lures the planner off the one answering ORDER BY.\n CREATE INDEX IF NOT EXISTS idx_records_type_id ON records(type_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_parent_id ON records(parent_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_entity_id ON records(entity_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_app_id ON records(app_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_principal_id ON records(principal_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_created_at ON records(created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_updated_at ON records(updated_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_version ON records(version, id);\n\n -- Each association index ends with record_id so the semi-joins in\n -- query.ts read the matching record ids out of the index alone.\n -- idx_assoc_related carries related_ns ahead of related_id because a\n -- record- or entity-scoped target always stores '' there, which\n -- buildQueryPlan states explicitly to keep the prefix contiguous.\n CREATE INDEX IF NOT EXISTS idx_assoc_kind_label ON associations(kind, label, record_id);\n CREATE INDEX IF NOT EXISTS idx_assoc_kind_file_id ON associations(kind, file_id, record_id);\n CREATE INDEX IF NOT EXISTS idx_assoc_related ON associations(kind, related_scope, related_ns, related_id, record_id);\n CREATE INDEX IF NOT EXISTS idx_types_base_id ON types(base_id, version);\n\n -- The whole content ordering, in index order, for one field at a time:\n -- a content-sorted page is an ordered walk of a slice of this index.\n CREATE INDEX IF NOT EXISTS idx_content_index_sort\n ON content_index(field, value_rank, num_value, text_key, text_value, record_id);\n CREATE INDEX IF NOT EXISTS idx_content_index_file\n ON content_index(file_id, record_id) WHERE file_id IS NOT NULL;\n`;\n\n/**\n * Bearer-token storage backing StackTokenStore. Kept separate from\n * RECORD_SCHEMA_SQL so an adapter can put it in its own file — the\n * portable stack file shouldn't also carry a server's auth material.\n */\nexport const TOKENS_SCHEMA_SQL = `\n CREATE TABLE IF NOT EXISTS tokens (\n id TEXT PRIMARY KEY,\n token_hash TEXT NOT NULL UNIQUE,\n principal_id TEXT NOT NULL,\n subject_id TEXT NOT NULL,\n label TEXT,\n created_at INTEGER NOT NULL,\n expires_at INTEGER\n ) STRICT;\n`;\n\n/**\n * The full-text index behind `StackQuery.filter.search` (see fts5.ts).\n * What `columnsize=0` costs a reader is in docs/spec/adapters.md\n * § Adapter backends. `detail` stays at its default: sanitizeFts5Query\n * passes phrase queries through, and a phrase needs the token positions\n * only that setting records.\n */\nexport const FTS5_SCHEMA_SQL = `\n CREATE VIRTUAL TABLE IF NOT EXISTS records_fts USING fts5(\n content,\n content='records',\n content_rowid='rowid',\n columnsize=0\n );\n`;\n\n/**\n * Enforces the REFERENCES constraints declared above (off by default per\n * SQLite connection), so touching a nonexistent record fails loudly\n * instead of creating an orphan row. Adapters map the constraint\n * violation to StackNotFoundError at the call sites that can trigger it.\n */\nexport const PRAGMA_FOREIGN_KEYS_ON = `PRAGMA foreign_keys = ON;`;\n\n/**\n * WAL journaling: page-level writes, crash-safe without our own\n * temp-file-and-rename dance, and real SQLite file locking. Only\n * meaningful for a real file (a :memory: database silently ignores it).\n */\nexport const PRAGMA_JOURNAL_MODE_WAL = `PRAGMA journal_mode = WAL;`;\n","/**\n * Cursor encode/decode for keyset pagination. The payload is JSON in\n * base64 rather than delimited fields: a content sort carries the field's\n * stored text, and neither a field name nor a text value is constrained\n * to avoid whatever character a delimiter would claim. Uses btoa/atob\n * with an explicit UTF-8 step rather than Node's Buffer, so the codec\n * stays runtime-agnostic and a non-Latin-1 value survives the round trip.\n */\n\nimport { NATIVE_SORT_FIELDS, StackQueryError } from '@haverstack/core';\nimport { contentSortEntry } from '@haverstack/core/adapter';\nimport type { StackRecord, NativeSortField, QuerySort, ScalarFieldKind } from '@haverstack/core';\n\nexport type SortField = NativeSortField;\n\n/**\n * Re-exported under this package's own name rather than re-spelled: the\n * set a cursor's `native` field is narrowed against is the same set core\n * narrows a wire request's sort field to, and a fourth column added there\n * must not need finding here too.\n */\nexport const SORT_FIELDS: readonly SortField[] = NATIVE_SORT_FIELDS;\n\n/**\n * Which partition of the ordering a cursor sits in: a native column or a\n * content field's number, text, or absent value. The three content cases\n * are the boundary keyset pagination has to hold — a page that ended on\n * the last numeric value resumes at the first text one, not back at the\n * top of either.\n */\nexport type CursorKind = 'native' | 'num' | 'text' | 'absent';\n\nexport type DecodedCursor =\n | { kind: 'native'; field: SortField; value: number; id: string }\n | { kind: 'num'; field: string; value: number; id: string }\n | { kind: 'text'; field: string; value: string; id: string }\n | { kind: 'absent'; field: string; id: string };\n\nconst toBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text);\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n};\n\nconst fromBase64 = (cursor: string): string => {\n const binary = atob(cursor);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n};\n\nexport const encodeCursor = (decoded: DecodedCursor): string =>\n toBase64(\n JSON.stringify(\n decoded.kind === 'absent'\n ? { k: decoded.kind, f: decoded.field, i: decoded.id }\n : { k: decoded.kind, f: decoded.field, i: decoded.id, v: decoded.value },\n ),\n );\n\n/** Throws StackQueryError for any malformed, corrupt, or unrecognized cursor. */\nexport const decodeCursor = (cursor: string): DecodedCursor => {\n const malformed = () => new StackQueryError(`Invalid cursor: malformed \"${cursor}\"`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64(cursor));\n } catch {\n throw malformed();\n }\n if (!parsed || typeof parsed !== 'object') throw malformed();\n const { k, f, i, v } = parsed as Record<string, unknown>;\n if (typeof f !== 'string' || !f || typeof i !== 'string') throw malformed();\n\n if (k === 'absent') return { kind: 'absent', field: f, id: i };\n if (k === 'text') {\n if (typeof v !== 'string') throw malformed();\n return { kind: 'text', field: f, value: v, id: i };\n }\n if (k === 'num' || k === 'native') {\n if (typeof v !== 'number' || !isFinite(v)) {\n throw new StackQueryError(`Invalid cursor: non-numeric sort value`);\n }\n if (k === 'native') {\n if (!SORT_FIELDS.includes(f as SortField)) {\n throw new StackQueryError(`Invalid cursor: unknown sort field \"${f}\"`);\n }\n return { kind: 'native', field: f as SortField, value: v, id: i };\n }\n return { kind: 'num', field: f, value: v, id: i };\n }\n throw malformed();\n};\n\nexport const getSortField = (query: { sort?: QuerySort }): SortField =>\n query.sort?.field ?? 'createdAt';\n\nexport const getSortColumn = (field: SortField): string =>\n field === 'createdAt' ? 'created_at' : field === 'updatedAt' ? 'updated_at' : 'version';\n\n/**\n * The cursor naming the last record of a page: where the next page\n * resumes. A content sort re-derives the record's ordered value from its\n * stored content rather than reading it back out of the index, so the\n * cursor and the index can only ever disagree if the write path is\n * broken — in which case pagination is not the thing to paper over.\n */\nexport const makeCursor = (\n record: StackRecord,\n sort: QuerySort | undefined,\n kindOf?: (record: StackRecord, field: string) => ScalarFieldKind | undefined,\n): string => {\n const contentField = sort?.contentField;\n if (contentField === undefined) {\n const field = getSortField({ sort });\n const value =\n field === 'updatedAt'\n ? record.updatedAt.getTime()\n : field === 'version'\n ? record.version\n : record.createdAt.getTime();\n return encodeCursor({ kind: 'native', field, value, id: record.id });\n }\n\n const kind = kindOf?.(record, contentField);\n const entry = kind ? contentSortEntry(kind, record.content[contentField]) : null;\n if (!entry) return encodeCursor({ kind: 'absent', field: contentField, id: record.id });\n return entry.kind === 'num'\n ? encodeCursor({ kind: 'num', field: contentField, value: entry.num, id: record.id })\n : encodeCursor({ kind: 'text', field: contentField, value: entry.text, id: record.id });\n};\n","/**\n * FTS5 query sanitization and indexing — the full-text search half of the\n * shared record logic.\n *\n * FTS5's query language supports operators (AND/OR/NOT, phrases, NEAR,\n * wildcards) that can be expensive or cause parse errors with untrusted\n * input, so a search string is rewritten before it reaches the engine:\n *\n * kept: AND/OR/NOT (with a left operand), phrase queries (\"…\"), implicit AND\n * removed: wildcards (*), NEAR(...) (terms kept, wrapper dropped), every\n * character outside the allow-list, bare NOT (no left operand),\n * operators with no right operand\n * capped: parenthesis nesting depth (default: 2)\n * closed: an odd trailing quote\n *\n * Two FTS5 grammar details drive the less obvious rules:\n *\n * - FTS5's NEAR is a function-call form — `NEAR(a b, 10)`. Deleting the\n * whole span would also delete the terms inside it, which can leave a\n * dangling operator when NEAR(...) sits next to AND/OR (e.g. \"x AND\n * NEAR(a b, 5)\" -> \"x AND\" — a syntax error). So this keeps the terms\n * and drops only the NEAR(...) wrapper and distance.\n * - FTS5 has real column-filter syntax and errors hard on any name but\n * the table's actual columns. It is wider than `colname:term`: `-name`\n * and `{a b}` filter columns with no colon at all, so an ordinary\n * hyphenated word is read as one. Since records_fts has exactly one\n * column and callers have no business targeting columns explicitly,\n * everything outside a phrase is reduced to an allow-list rather than\n * validated — see OUTSIDE_PHRASE_DISALLOWED.\n *\n * The rewrite is best-effort and makes no completeness claim against\n * FTS5's grammar — which is why the caller wraps execution as well, so a\n * case this misses surfaces as a StackQueryError rather than a raw engine\n * error. Search text is what a person typed into a box: an unbalanced\n * quote or a trailing \"AND\" is ordinary input, not a malformed request.\n *\n * What this bounds is the grammar, not the cost: a syntactically modest\n * search over a large index can still be expensive, and node:sqlite blocks\n * the calling thread, so there is no timeout to set from inside the call.\n * Bounding execution time belongs to whoever drives the engine under load\n * — see docs/spec/wire-format.md § Bounding query cost for the server-side\n * expectation and the `timeout` wire error that goes with it.\n */\n\nimport type { SqlExecutor } from './executor.js';\n\n/**\n * Outside a phrase, everything but a letter, digit, mark, underscore,\n * whitespace, paren or quote becomes a separator.\n *\n * An allow-list rather than a list of metacharacters to strip, because\n * FTS5's column-filter syntax is wider than it looks and an enumeration\n * kept missing parts of it: `-name` and `{a b}` filter columns with no\n * colon in sight, so `-cats` and even the hyphen inside `cats-dogs` were\n * read as column names and answered \"no such column\". `+` is a bare\n * syntax error. Listing what may pass means the next piece of syntax\n * nobody here anticipated arrives as a separator instead of as an error.\n *\n * Nothing is lost by it: FTS5's default tokenizer already splits terms on\n * these characters, so `cats-dogs` searches for the same two tokens it was\n * indexed as.\n */\nconst OUTSIDE_PHRASE_DISALLOWED = /[^\\p{L}\\p{N}\\p{M}_\\s()\"]/gu;\n\n/**\n * Collapse every whitespace run to a single space.\n *\n * Every rule below that reasons about what sits beside an operator or a\n * paren spells \"beside\" as `\\s*`, and a `\\s*` with a long run to chew on\n * re-tries the whole run once per starting position — quadratic in the\n * run, on text a caller types into a box. Keeping runs collapsed bounds\n * what any of them can backtrack over to a single character. What it does\n * not buy is linearity overall: the rewrite still costs a little more\n * than proportionally as the text grows, which is why bounding a search's\n * length belongs to whoever accepts it.\n *\n * Nothing is lost by it: FTS5's tokenizer splits on whitespace, so a\n * collapsed run tokenizes exactly as the original did — inside a phrase\n * as well as outside, since a phrase matches a sequence of tokens rather\n * than the spacing between them.\n */\nconst collapseWhitespace = (query: string): string => query.replace(/\\s+/g, ' ');\n\nexport const sanitizeFts5Query = (query: string, maxDepth = 2): string => {\n if (!query) return '';\n\n // Drop control characters, inside a phrase as well as outside. A NUL in\n // particular ends the string early for SQLite's C API, so the engine sees\n // an opening quote whose closing one is past the truncation and reports an\n // unterminated string; none of them can match an indexed token anyway.\n let clean = query.replace(/[\\p{Cc}\\p{Cf}]/gu, ' ');\n\n // Remove wildcards\n clean = clean.replace(/\\*/g, '');\n\n // Replace NEAR(terms, distance) with just its terms — see note above.\n //\n // Two things here are about what the engine does when the closing paren\n // never arrives, on text a caller types into a box.\n //\n // No `\\s*` after the paren, though the terms it captures may open with\n // whitespace: `[^,()]*` already matches a space, so a second quantifier\n // that also does gives the engine an ambiguous split to backtrack\n // through. The captured space is collapsed with all the rest on the way\n // out.\n //\n // And neither run crosses a `(`, which bounds where the failure is\n // found: `NEAR(NEAR(NEAR(` used to re-scan to the end of the string once\n // per occurrence. A NEAR's terms are words and phrases and its distance\n // is a number, so neither holds a paren in any input FTS5 would accept.\n clean = clean.replace(/\\bNEAR\\s*\\(([^,()]*)(?:,[^()]*)?\\)/gi, '$1');\n\n // A NEAR( with no closing paren isn't the function-call form the rule\n // above rewrites, and the paren auto-close below would hand FTS5 a NEAR\n // call it never meant to write. Keep the grouping, drop the keyword.\n clean = clean.replace(/\\bNEAR\\s*\\(/gi, '(');\n\n // Reduce to the characters that carry meaning outside a phrase — see note\n // above. Everything else becomes a separator, which is what FTS5's own\n // tokenizer would do with it anyway.\n clean = clean.replace(/\"[^\"]*\"|[^\"]+/g, (span) =>\n span.startsWith('\"') ? span : span.replace(OUTSIDE_PHRASE_DISALLOWED, ' '),\n );\n\n // The reduction above turns every disallowed character into a space, so\n // this is where the long runs come from.\n clean = collapseWhitespace(clean);\n\n // Strip bare NOT with no left operand — FTS5 requires \"term NOT term\", not \"NOT term\"\n clean = clean.replace(/(?:^|\\(\\s*)NOT\\s+/gi, (m) => m.replace(/NOT\\s+/i, ''));\n\n // Enforce max nesting depth; replace excess ( with a space and discard\n // unmatched ). Parens inside a phrase are literal text to FTS5, so the\n // depth count steps over quoted spans rather than reading them as syntax.\n let currentDepth = 0;\n let inPhrase = false;\n let result = '';\n for (const char of clean) {\n if (char === '\"') {\n inPhrase = !inPhrase;\n result += char;\n } else if (inPhrase) {\n result += char;\n } else if (char === '(') {\n if (currentDepth < maxDepth) {\n currentDepth++;\n result += char;\n } else result += ' ';\n } else if (char === ')') {\n if (currentDepth > 0) {\n currentDepth--;\n result += char;\n } else result += ' ';\n } else {\n result += char;\n }\n }\n\n // Close an odd trailing quote before the parens, so the added ) lands\n // outside the phrase rather than becoming a literal character in it.\n if (inPhrase) result += '\"';\n\n // Auto-close any unclosed parens\n if (currentDepth > 0) result += ')'.repeat(currentDepth);\n\n // Remove empty paren pairs left behind by NEAR/NOT stripping, and drop\n // operators left without an operand. Looped together because each can\n // create work for the other: removing an operator can empty a paren pair\n // (\"(a AND)\" -> \"(a)\" -> ...), and removing a pair can strand the\n // operator that pointed at it (\"x AND ()\" -> \"x AND\").\n let prev: string;\n do {\n prev = result;\n // Empty phrases and empty paren pairs, each of which matches nothing,\n // in one rule so that a run of them collapses to a single space\n // rather than to one space apiece — a run of spaces is what the rules\n // below would have to backtrack over. An empty phrase is also the one\n // construct whose quotes can re-pair differently once a rule inserts\n // text beside it, which is why this repeats to a fixpoint.\n result = result.replace(/(?:\"\"|\\(\\s*\\))+/g, ' ');\n result = dropDanglingOperators(result);\n result = restoreImplicitAnd(result);\n } while (result !== prev);\n\n return collapseWhitespace(result).replace(/\\(\\s+/g, '(').replace(/\\s+\\)/g, ')').trim();\n};\n\n/** An operator FTS5 requires a term on both sides of. */\nconst OPERATOR = String.raw`(?:AND|OR|NOT)`;\n\n/**\n * Stands in for a phrase while operators are rewritten. A private-use\n * character is not a word character, so `\\b` still sees the operator\n * beside it, while `^`, `$` and the paren anchors see an operand — which\n * is what a phrase is. Nothing reaches here holding one: `clean` is\n * rewritten from the caller's string, and a literal U+E000 in it would be\n * a term character FTS5 tokenizes away regardless.\n */\nconst PHRASE_HOLE = '\\u{E000}';\n\n/**\n * Drop operators left without an operand — the shape a person types on\n * their way to a longer query (\"cats AND\") or lands on once the rules\n * above have removed a term. FTS5 rejects each of them outright, so what\n * would otherwise be a syntax error becomes the search for the terms that\n * are actually there.\n *\n * Phrases are masked out first: `\"cats AND dogs\"` is literal text to FTS5,\n * and rewriting inside it would change what the user asked for.\n */\nconst dropDanglingOperators = (query: string): string =>\n withPhrasesMasked(query, (masked) => {\n let out = masked;\n let prev: string;\n do {\n prev = out;\n // A run of operators keeps only the first — the rest have no left operand.\n out = out.replace(\n new RegExp(String.raw`\\b(${OPERATOR})\\b(?:\\s+\\b${OPERATOR}\\b)+`, 'gi'),\n '$1',\n );\n // No left operand: at the start of the query or straight after \"(\".\n out = out.replace(new RegExp(String.raw`(^|\\()\\s*\\b${OPERATOR}\\b\\s*`, 'gi'), '$1');\n // No right operand: at the end of the query or straight before \")\".\n // No leading `\\s*` — whitespace before the operator is left for the\n // collapse on the way out, and a `\\s*` here would re-scan a run of\n // spaces once per position in it before failing to find an operator.\n out = out.replace(new RegExp(String.raw`\\b${OPERATOR}\\b\\s*($|\\))`, 'gi'), '$1');\n } while (out !== prev);\n return out;\n });\n\n/**\n * Run `rewrite` over the query with each phrase swapped for PHRASE_HOLE,\n * then put the phrases back in order. Every rule that reasons about what\n * sits beside an operator or a paren needs this: inside a phrase the text\n * is literal, and from outside one the phrase is a single operand.\n */\nconst withPhrasesMasked = (query: string, rewrite: (masked: string) => string): string => {\n const phrases: string[] = [];\n const masked = query.replace(/\"[^\"]*\"/g, (phrase) => {\n phrases.push(phrase);\n return PHRASE_HOLE;\n });\n let i = 0;\n return rewrite(masked).replace(new RegExp(PHRASE_HOLE, 'g'), () => phrases[i++]);\n};\n\n/**\n * Put back the operator FTS5 requires around a group. Two terms side by\n * side are an implicit AND (`cats dogs`), but a group is not: `cats (dogs)`\n * is a syntax error where `cats AND (dogs)` is fine. Grouping survives a\n * rewrite that strips the operator which used to sit beside it, so this\n * names the AND that was always meant rather than dropping the parens.\n *\n * Both rules test a *whole* word against the operator list. Matching a\n * prefix instead reads the `D` of a preceding `AND` as a term and inserts\n * a second one beside it.\n *\n * Phrases are masked for the same reason as elsewhere — a phrase is an\n * operand, so `\"a b\" (c)` needs the operator too.\n */\nconst OPERAND_CHAR = String.raw`[\\p{L}\\p{N}_${PHRASE_HOLE}]`;\n\nconst isOperator = (word: string): boolean => /^(?:AND|OR|NOT)$/i.test(word);\n\nconst restoreImplicitAnd = (query: string): string =>\n withPhrasesMasked(query, (masked) =>\n masked\n // \")\" then an operand — \") cats\", \") (\", \") <phrase>\" — unless that\n // operand is an operator, which already joins the two sides.\n .replace(\n new RegExp(String.raw`\\)\\s*(?=${OPERAND_CHAR}|\\()`, 'gu'),\n (match, offset: number, whole: string) => {\n const next = /^\\s*([\\p{L}\\p{N}_]+)/u.exec(whole.slice(offset + match.length));\n return next && isOperator(next[1]) ? match : ') AND ';\n },\n )\n // An operand then \"(\", unless the operand is an operator.\n // The lookbehind pins the match to the start of the operand run.\n // Without it every position inside a run is a start position, and\n // each one re-scans the rest of the run before the lookahead\n // rejects it — quadratic in a long word before a paren.\n .replace(\n new RegExp(String.raw`(?<!${OPERAND_CHAR})(${OPERAND_CHAR}+)\\s*(?=\\()`, 'gu'),\n (match, word: string) => (isOperator(word) ? match : `${word} AND `),\n ),\n );\n\n// -------------------------------------------------------\n// Indexing strategy\n// -------------------------------------------------------\n\n/**\n * FTS5's external-content table needs its special `('delete', rowid,\n * content)` command — with the *old* content — to unindex a row; a plain\n * DELETE leaves stale, still-searchable entries. remove() therefore reads\n * the current rowid/content and must run before the caller's change.\n */\nexport const fts5Strategy = {\n /** Index a record that has no FTS entry yet (used right after an INSERT). */\n insert(exec: SqlExecutor, recordId: string, content: string): void {\n exec.run(`INSERT INTO records_fts(rowid, content) SELECT rowid, ? FROM records WHERE id = ?`, [\n content,\n recordId,\n ]);\n },\n /**\n * Remove a record's FTS entry. MUST be called before the records row's\n * content changes or the row is deleted — see the note above.\n */\n remove(exec: SqlExecutor, recordId: string): void {\n const row = exec.get<{ rowid: number; content: string }>(\n 'SELECT rowid, content FROM records WHERE id = ?',\n [recordId],\n );\n if (!row) return;\n exec.run(`INSERT INTO records_fts(records_fts, rowid, content) VALUES('delete', ?, ?)`, [\n row.rowid,\n row.content,\n ]);\n },\n};\n","/**\n * StackQuery -> SQL. Engine-independent — shared verbatim between\n * SQLite-backed record adapters. The one caveat is full-text search:\n * `f.search` here assumes a `records_fts` virtual table with a MATCH-able\n * `content` column (see fts5.ts).\n *\n * A query compiles to a plan rather than to a single statement, because a\n * content-field sort is two orderings end to end: the records that hold a\n * value at the field, ordered by it, then the records that hold none,\n * ordered by id. Reading them as two statements lets each one walk an\n * index in order and stop at the page boundary; the LEFT JOIN that would\n * express the same result in one statement can only be sorted after the\n * fact, which costs a full pass over the table for every page.\n */\n\nimport { StackQueryError, type StackQuery } from '@haverstack/core';\nimport { contentSortKey, parseContentFilterKey } from '@haverstack/core/adapter';\nimport {\n decodeCursor,\n getSortColumn,\n getSortField,\n type DecodedCursor,\n type SortField,\n} from './cursor.js';\nimport { sanitizeFts5Query } from './fts5.js';\n\n/** One statement plus the parameters it binds, in textual order. */\nexport type QueryStatement = { sql: string; params: unknown[] };\n\n/**\n * A page statement with the row budget its trailing `LIMIT ?` binds.\n * buildQueryPlan leaves that parameter off, so the budget is never one of\n * the parameters the query itself bound: the second partition of a\n * content sort asks for what the first left of the page rather than for a\n * page it then discards.\n */\nexport const atBudget = (page: QueryStatement, rows: number): QueryStatement => ({\n sql: page.sql,\n params: [...page.params, rows],\n});\n\n/**\n * Reduce `sort.direction` to a keyword this module may interpolate into\n * SQL. Core's assertValidSort() already rejects anything else at the\n * invariant layer, but this builder writes the value straight into\n * `ORDER BY` and the cursor comparison, so it re-checks rather than trust\n * an upstream that a future refactor could bypass: an unvalidated direction\n * here is a SQL-injection sink. Anything but \"asc\" is treated as the\n * default \"desc\" only after passing the guard.\n */\nconst sqlDirection = (query: StackQuery): 'ASC' | 'DESC' => {\n const dir = query.sort?.direction ?? 'desc';\n if (dir !== 'asc' && dir !== 'desc') {\n throw new StackQueryError(`Invalid sort direction \"${dir}\": expected \"asc\" or \"desc\".`);\n }\n return dir === 'asc' ? 'ASC' : 'DESC';\n};\n\n/**\n * Normalize a json_each row's value so one array element and one bare\n * value are walked by the same clause: an array stands for its elements,\n * anything else for itself. See docs/spec/data-model.md § Nested content\n * paths.\n */\nconst spread = (alias: string): string =>\n `CASE WHEN ${alias}.type = 'array' THEN ${alias}.value ` +\n `WHEN ${alias}.type = 'object' THEN json_array(json(${alias}.value)) ` +\n `ELSE json_array(${alias}.value) END`;\n\n/**\n * The members of a json_each row that is an object, and none for a row\n * that is not — a path descending through a scalar reaches no value rather\n * than reaching an error.\n */\nconst members = (alias: string): string =>\n `CASE WHEN ${alias}.type = 'object' THEN ${alias}.value ELSE '{}' END`;\n\n/**\n * True when some value reached by `segments` satisfies `leaf`, applied to\n * the alias holding that value. Each segment is a bound parameter matched\n * against json_each's `key`, never interpolated into a path expression, so\n * no key can be read as syntax. See docs/spec/data-model.md § Filter.\n */\nconst contentPathExists = (\n segments: string[],\n leaf: (alias: string) => string,\n params: unknown[],\n nextAlias: () => string,\n): string => {\n // The walk is a flat join list, not a subquery per segment: both SQLite\n // builds cap expression-tree depth far below the segment cap, and\n // nesting spends that budget while a join list spends the join budget\n // the cap is actually sized against.\n let key = nextAlias();\n let value = nextAlias();\n const from = [`json_each(r.content) AS ${key}`, `json_each(${spread(key)}) AS ${value}`];\n const where = [`${key}.key = ?`];\n params.push(segments[0]);\n\n for (const segment of segments.slice(1)) {\n key = nextAlias();\n from.push(`json_each(${members(value)}) AS ${key}`);\n value = nextAlias();\n from.push(`json_each(${spread(key)}) AS ${value}`);\n where.push(`${key}.key = ?`);\n params.push(segment);\n }\n\n where.push(leaf(value));\n return `EXISTS (SELECT 1 FROM ${from.join(', ')} WHERE ${where.join(' AND ')})`;\n};\n\n/**\n * A scalar filter value never matches an object or array stored at the\n * path: json_each exposes those as their JSON text, which would compare\n * equal to a string spelling the same document while every non-SQL adapter\n * compares the value itself.\n */\nconst equalsLeaf = (alias: string): string =>\n `${alias}.type NOT IN ('object', 'array') AND ${alias}.value = ?`;\n\n/** The join alias the content index is read through. */\nconst SORT_ALIAS = 'cs';\n\n/**\n * A cursor names a position in one ordering; carrying it into another\n * would silently resume somewhere arbitrary. The partition matters as\n * much as the field name — a cursor from a numeric page can't be read\n * against text values — so each ordering below accepts only the cursors\n * it can read, and rejecting the rest is what narrows the cursor to them.\n */\nconst cursorMismatch = (cursor: DecodedCursor, field: string): StackQueryError =>\n new StackQueryError(\n `Cursor sort field \"${cursor.field}\" does not match query sort field \"${field}\"`,\n );\n\nconst nativeCursor = (cursor: DecodedCursor, field: SortField) => {\n if (cursor.kind !== 'native' || cursor.field !== field) throw cursorMismatch(cursor, field);\n return cursor;\n};\n\nconst contentCursor = (cursor: DecodedCursor, field: string) => {\n if (cursor.kind === 'native' || cursor.field !== field) throw cursorMismatch(cursor, field);\n return cursor;\n};\n\n/**\n * Every condition on the records row itself — everything a query asks\n * except where in the ordering to resume, which is per-partition and gets\n * appended by the caller.\n */\nconst recordConditions = (query: StackQuery): { conditions: string[]; params: unknown[] } => {\n const conditions: string[] = [\"r.id != '_config'\"];\n const params: unknown[] = [];\n const f = query.filter ?? {};\n\n /**\n * A filter that accepts one value or a list of them, as the `IN` that\n * covers both. Written even for a single value rather than as `= ?`,\n * since SQLite plans a one-element IN identically and one form means one\n * place for the filter's placeholder count and its bindings to agree.\n */\n const inFilter = (column: string, value: string | readonly string[] | undefined): void => {\n if (value === undefined) return;\n const values = Array.isArray(value) ? value : [value as string];\n conditions.push(`r.${column} IN (${values.map(() => '?').join(',')})`);\n params.push(...values);\n };\n\n /** One side of a date range, as the open-ended comparison it is. */\n const rangeFilter = (\n column: string,\n range: { after?: Date; before?: Date } | undefined,\n ): void => {\n if (range?.after) {\n conditions.push(`r.${column} > ?`);\n params.push(range.after.getTime());\n }\n if (range?.before) {\n conditions.push(`r.${column} < ?`);\n params.push(range.before.getTime());\n }\n };\n\n if (!f.includeDeleted) {\n conditions.push('r.deleted_at IS NULL');\n }\n\n if (!f.includeUnlisted) {\n conditions.push('r.unlisted_at IS NULL');\n }\n\n inFilter('type_id', f.typeId);\n\n // Not an inFilter: parentId takes an explicit null for \"at the root\",\n // which is a different SQL predicate rather than a different value.\n if (f.parentId !== undefined) {\n if (f.parentId === null) {\n conditions.push('r.parent_id IS NULL');\n } else {\n conditions.push('r.parent_id = ?');\n params.push(f.parentId);\n }\n }\n\n inFilter('app_id', f.appId);\n inFilter('entity_id', f.entityId);\n inFilter('principal_id', f.principalId);\n\n rangeFilter('created_at', f.createdAt);\n rangeFilter('updated_at', f.updatedAt);\n\n // Every association filter below is a semi-join rather than a correlated\n // EXISTS, so the planner drives from the association side — reading the\n // matching record ids straight out of idx_assoc_kind_label /\n // idx_assoc_kind_file_id / idx_assoc_related / idx_content_index_file,\n // each of which ends with record_id and so needs no table read at all —\n // instead of scanning every record and probing for each. The work is\n // proportional to how many records match, not to how many the stack\n // holds.\n\n /**\n * The semi-join itself. `kind` is one of this module's own literals, never\n * caller text, and each clause carries its own placeholder — so the only\n * thing interpolated here is SQL this file wrote.\n */\n const hasAssociation = (kind: 'tag' | 'attachment' | 'relationship', clauses: string[]): string =>\n `r.id IN (SELECT a.record_id FROM associations a WHERE a.kind = '${kind}'` +\n clauses.map((c) => ` AND ${c}`).join('') +\n `)`;\n\n // Tag filter — record must have ALL specified tags\n if (f.tags?.length) {\n for (const tag of f.tags) {\n conditions.push(hasAssociation('tag', ['a.label = ?']));\n params.push(tag);\n }\n }\n\n // Attachment label filter\n if (f.hasAttachment) {\n conditions.push(hasAssociation('attachment', ['a.label = ?']));\n params.push(f.hasAttachment);\n }\n\n // Attachment file ID filter — find records that reference a specific file,\n // either via an attachment association or a top-level file-ref content field\n if (f.attachmentFileId) {\n conditions.push(\n `(${hasAssociation('attachment', ['a.file_id = ?'])}\n OR r.id IN (SELECT ci.record_id FROM content_index ci WHERE ci.file_id = ?))`,\n );\n params.push(f.attachmentFileId, f.attachmentFileId);\n }\n\n // Relationship filter — each clause is an optional pattern, so a bare\n // label matches every target under it and an external target with no\n // `id` matches its whole namespace (docs/spec/data-model.md § Filter).\n //\n // A record- or entity-scoped target always stores '' in related_ns\n // (see associationKeyColumns). Saying so turns idx_assoc_related's\n // (scope, ns, id) prefix into a contiguous equality run for those\n // scopes instead of leaving the planner to seek on scope alone.\n if (f.relatedTo) {\n const clauses: string[] = [];\n const target = f.relatedTo.target;\n if (f.relatedTo.label !== undefined) {\n clauses.push('a.label = ?');\n params.push(f.relatedTo.label);\n }\n if (target) {\n clauses.push('a.related_scope = ?');\n params.push(target.scope);\n if (target.scope === 'record') {\n clauses.push('a.related_ns = ?', 'a.related_id = ?', 'a.related_stack = ?');\n params.push('', target.recordId, target.stackUrl ?? '');\n } else if (target.scope === 'entity') {\n clauses.push('a.related_ns = ?', 'a.related_id = ?');\n params.push('', target.entityId);\n } else {\n clauses.push('a.related_ns = ?');\n params.push(target.ns);\n if (target.id !== undefined) {\n clauses.push('a.related_id = ?');\n params.push(target.id);\n }\n }\n }\n conditions.push(hasAssociation('relationship', clauses));\n }\n\n // Content field filters — a dot-separated path, matched element-wise\n // through arrays. A `null` value means \"no value at the path, or a value\n // that is null\" (docs/spec/data-model.md § Filter), which is the second\n // arm below: \"some value there is null\" OR \"nothing is there at all\".\n if (f.content) {\n let aliasSeq = 0;\n const nextAlias = () => `cp${aliasSeq++}`;\n for (const [key, value] of Object.entries(f.content)) {\n const segments = parseContentFilterKey(key);\n // undefined is the same absence null names — JSON drops it on the\n // way over the wire, so treating it as a value would make an\n // in-process query and its wire equivalent disagree.\n if (value === null || value === undefined) {\n const isNull = contentPathExists(segments, (a) => `${a}.value IS NULL`, params, nextAlias);\n const anyValue = contentPathExists(\n segments,\n (a) => `${a}.value IS NOT NULL`,\n params,\n nextAlias,\n );\n conditions.push(`(${isNull} OR NOT ${anyValue})`);\n } else {\n const match = contentPathExists(segments, equalsLeaf, params, nextAlias);\n params.push(value);\n conditions.push(match);\n }\n }\n }\n\n // Presence — the question an exact-match value cannot ask. Element-wise\n // like the content filter above: a path holds a value when at least one\n // non-null value is reachable at it. See docs/spec/data-model.md\n // § Filter.\n if (f.contentPresent?.length) {\n let aliasSeq = 0;\n const nextAlias = () => `pp${aliasSeq++}`;\n for (const key of f.contentPresent) {\n conditions.push(\n contentPathExists(\n parseContentFilterKey(key),\n (a) => `${a}.value IS NOT NULL`,\n params,\n nextAlias,\n ),\n );\n }\n }\n\n if (f.search) {\n const sanitized = sanitizeFts5Query(f.search);\n if (sanitized) {\n conditions.push(`r.rowid IN (SELECT rowid FROM records_fts WHERE records_fts MATCH ?)`);\n params.push(sanitized);\n } else {\n // A search that sanitizes to nothing (e.g. \"*\", punctuation-only) is\n // an honest zero-match result, not \"no filter\" — omitting the clause\n // would silently return the full table as the \"search result\".\n conditions.push('0');\n }\n }\n\n return { conditions, params };\n};\n\n/**\n * Everything ordered after the cursor's record within the partition that\n * holds a value: a later value rank, or the same rank past the cursor's\n * value and id. `op` runs the comparison the same way the ORDER BY does,\n * so one form covers both directions — in the direction where the\n * cursor's rank is the last one, the leading disjunct is simply never\n * true.\n */\nconst presentCursorCondition = (\n cursor: Extract<DecodedCursor, { kind: 'num' | 'text' }>,\n op: '>' | '<',\n params: unknown[],\n): string => {\n if (cursor.kind === 'num') {\n params.push(cursor.value, cursor.value, cursor.id);\n return (\n `(${SORT_ALIAS}.value_rank ${op} 0 OR (${SORT_ALIAS}.value_rank = 0 AND ` +\n `(${SORT_ALIAS}.num_value ${op} ? OR (${SORT_ALIAS}.num_value = ? AND ` +\n `${SORT_ALIAS}.record_id ${op} ?))))`\n );\n }\n const key = contentSortKey(cursor.value);\n params.push(key, key, cursor.value, cursor.value, cursor.id);\n return (\n `(${SORT_ALIAS}.value_rank ${op} 1 OR (${SORT_ALIAS}.value_rank = 1 AND ` +\n `(${SORT_ALIAS}.text_key ${op} ? OR (${SORT_ALIAS}.text_key = ? AND ` +\n `(${SORT_ALIAS}.text_value ${op} ? OR (${SORT_ALIAS}.text_value = ? AND ` +\n `${SORT_ALIAS}.record_id ${op} ?))))))`\n );\n};\n\nconst statement = (\n select: string,\n from: string,\n conditions: string[],\n params: unknown[],\n tail = '',\n): QueryStatement => ({\n sql: `SELECT ${select} FROM ${from} WHERE ${conditions.join(' AND ')}${tail}`,\n params,\n});\n\n/**\n * Compile a query into the statements that answer it, read in order and\n * their rows concatenated: the first that fills the page ends the read,\n * so the second is never run for a page that doesn't reach it. Each still\n * needs the row budget its `LIMIT ?` binds — see atBudget.\n */\nexport const buildQueryPlan = (query: StackQuery): QueryStatement[] => {\n const dir = sqlDirection(query);\n const op = dir === 'ASC' ? '>' : '<';\n const decoded = query.cursor ? decodeCursor(query.cursor) : null;\n const contentField = query.sort?.contentField;\n\n if (contentField === undefined) {\n const { conditions, params } = recordConditions(query);\n const col = getSortColumn(getSortField(query));\n if (decoded) {\n const cursor = nativeCursor(decoded, getSortField(query));\n conditions.push(`(r.${col} ${op} ? OR (r.${col} = ? AND r.id ${op} ?))`);\n params.push(cursor.value, cursor.value, cursor.id);\n }\n return [\n statement(\n 'r.*',\n 'records r',\n conditions,\n params,\n ` ORDER BY r.${col} ${dir}, r.id ${dir} LIMIT ?`,\n ),\n ];\n }\n\n const cursor = decoded ? contentCursor(decoded, contentField) : null;\n const pages: QueryStatement[] = [];\n\n // Records holding a value at the field, in that value's order. A cursor\n // sitting in the absent partition has already passed every one of them.\n if (cursor?.kind !== 'absent') {\n const { conditions, params } = recordConditions(query);\n const from = `content_index ${SORT_ALIAS} JOIN records r ON r.id = ${SORT_ALIAS}.record_id`;\n conditions.push(`${SORT_ALIAS}.field = ?`);\n params.push(contentField);\n if (cursor) conditions.push(presentCursorCondition(cursor, op, params));\n // Ordered exactly as idx_content_index_sort stores it, so the page is\n // an ordered walk of the index rather than a sort of the matches.\n const order =\n `${SORT_ALIAS}.value_rank ${dir}, ${SORT_ALIAS}.num_value ${dir}, ` +\n `${SORT_ALIAS}.text_key ${dir}, ${SORT_ALIAS}.text_value ${dir}, ` +\n `${SORT_ALIAS}.record_id ${dir}`;\n pages.push(statement('r.*', from, conditions, params, ` ORDER BY ${order} LIMIT ?`));\n }\n\n // Records holding nothing there, which trail the others whichever way\n // the sort runs (docs/spec/data-model.md § Sorting by a content field).\n {\n const { conditions, params } = recordConditions(query);\n conditions.push(\n `NOT EXISTS (SELECT 1 FROM content_index ${SORT_ALIAS} ` +\n `WHERE ${SORT_ALIAS}.record_id = r.id AND ${SORT_ALIAS}.field = ?)`,\n );\n params.push(contentField);\n if (cursor?.kind === 'absent') {\n conditions.push(`r.id ${op} ?`);\n params.push(cursor.id);\n }\n pages.push(statement('r.*', 'records r', conditions, params, ` ORDER BY r.id ${dir} LIMIT ?`));\n }\n\n return pages;\n};\n","/**\n * Row <-> domain object mappers shared by every SQLite-backed record\n * adapter. Column names and JSON-encoding choices are the storage\n * contract; keeping one copy means the adapters can't drift on them.\n */\n\nimport type {\n StackRecord,\n StackType,\n RecordVersion,\n Association,\n RelationshipTarget,\n} from '@haverstack/core';\n\nexport const toMs = (d: Date): number => d.getTime();\nexport const fromMs = (ms: number): Date => new Date(ms);\n\nexport const rowToRecord = (\n row: Record<string, unknown>,\n associations: Association[],\n): StackRecord => {\n const record: StackRecord = {\n id: row.id as string,\n typeId: row.type_id as string,\n createdAt: fromMs(row.created_at as number),\n updatedAt: fromMs(row.updated_at as number),\n content: JSON.parse(row.content as string),\n version: row.version as number,\n };\n // Presence, never truthiness: SQL NULL is the only spelling of an absent\n // field, so the empty string and the epoch are values like any other.\n // The query predicates beside this read `IS NULL`, and a mapper that\n // disagreed would let a record answer one way to get() and another to\n // the filter that should have found it.\n if (row.parent_id != null) record.parentId = row.parent_id as string;\n if (row.entity_id != null) record.entityId = row.entity_id as string;\n if (row.app_id != null) record.appId = row.app_id as string;\n if (row.principal_id != null) record.principalId = row.principal_id as string;\n if (row.updated_by != null) record.updatedBy = row.updated_by as string;\n if (row.updated_via != null) record.updatedVia = row.updated_via as string;\n if (row.deleted_at != null) record.deletedAt = fromMs(row.deleted_at as number);\n if (row.unlisted_at != null) record.unlistedAt = fromMs(row.unlisted_at as number);\n if (row.permissions != null) record.permissions = JSON.parse(row.permissions as string);\n if (associations.length) record.associations = associations;\n return record;\n};\n\nexport const rowToAssociation = (row: Record<string, unknown>): Association => {\n if (row.kind === 'tag') {\n return { kind: 'tag', label: row.label as string };\n }\n if (row.kind === 'attachment') {\n return {\n kind: 'attachment',\n label: row.label as string,\n fileId: row.file_id as string,\n };\n }\n // relationship\n return {\n kind: 'relationship',\n label: row.label as string,\n target: rowToTarget(row),\n };\n};\n\n/**\n * The five columns that identify an association, in the order every\n * INSERT and DELETE below binds them. One helper because the two must\n * agree exactly — a dissociate that bound them differently would delete\n * nothing and report success.\n */\nexport const associationKeyColumns = (a: Association): [string, string, string, string, string] => {\n if (a.kind === 'attachment') return [a.fileId, '', '', '', ''];\n if (a.kind !== 'relationship') return ['', '', '', '', ''];\n const t = a.target;\n if (t.scope === 'entity') return ['', 'entity', t.entityId, '', ''];\n if (t.scope === 'external') return ['', 'external', t.id, t.ns, ''];\n return ['', 'record', t.recordId, '', t.stackUrl ?? ''];\n};\n\nconst rowToTarget = (row: Record<string, unknown>): RelationshipTarget => {\n const id = row.related_id as string;\n if (row.related_scope === 'entity') return { scope: 'entity', entityId: id };\n if (row.related_scope === 'external') {\n return { scope: 'external', ns: row.related_ns as string, id };\n }\n const stackUrl = row.related_stack as string;\n return { scope: 'record', recordId: id, ...(stackUrl && { stackUrl }) };\n};\n\nexport const rowToType = (row: Record<string, unknown>): StackType => {\n const t: StackType = {\n id: row.id as string,\n baseId: row.base_id as string,\n version: row.version as number,\n name: row.name as string,\n schema: JSON.parse(row.schema as string),\n schemaHash: row.schema_hash as string,\n createdAt: fromMs(row.created_at as number),\n };\n if (row.migrates_from) t.migratesFrom = row.migrates_from as string;\n return t;\n};\n\nexport const rowToVersion = (row: Record<string, unknown>): RecordVersion => {\n const v: RecordVersion = {\n version: row.version as number,\n typeId: row.type_id as string,\n content: JSON.parse(row.content as string),\n updatedAt: fromMs(row.updated_at as number),\n };\n if (row.entity_id != null) v.entityId = row.entity_id as string;\n if (row.updated_by != null) v.updatedBy = row.updated_by as string;\n if (row.updated_via != null) v.updatedVia = row.updated_via as string;\n // Read for presence, not truthiness: the stored 'null' is the root, and\n // only a SQL NULL is a snapshot that claimed no container at all.\n if (row.parent_id != null) v.parentId = row.parent_id as string;\n if (row.associations != null) v.associations = JSON.parse(row.associations as string);\n if (row.permissions != null) v.permissions = JSON.parse(row.permissions as string);\n return v;\n};\n","/**\n * Normalizes a SQLite binding's call convention (array-bind-then-step,\n * spread-args run/get/all, cursor-returning exec) behind one interface,\n * so the actual CRUD/query/version/type/association/token logic can live\n * once in this package instead of being re-typed per engine. Each adapter\n * package provides a thin SqlExecutor implementation over its own\n * database handle.\n *\n * Deliberately synchronous: every binding this targets executes queries\n * in-process without yielding, and an async interface would force the\n * shared logic's transaction sequences to interleave.\n */\nexport interface SqlExecutor {\n /** Run DDL, pragmas, or any statement(s) with no bound params and no results needed. */\n exec(sql: string): void;\n /** Run a single parameterized statement. Returns the number of rows affected (INSERT/UPDATE/DELETE). */\n run(sql: string, params?: readonly unknown[]): number;\n /** Run a parameterized statement and return the first result row, or undefined. */\n get<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T | undefined;\n /** Run a parameterized statement and return all result rows. */\n all<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T[];\n /**\n * Run `fn` atomically: every statement it issues commits together, or\n * none do if it throws. `fn` must be synchronous and call back into\n * this executor only — not every engine's transaction primitive can\n * straddle a suspended call. A binding with a real multi-statement\n * transaction (BEGIN/COMMIT/ROLLBACK) implements this with one; a\n * binding whose transaction primitive is itself a callback wrapper\n * (e.g. a Durable Object's storage.transactionSync) can pass `fn`\n * straight through to it.\n */\n transaction<T>(fn: () => T): T;\n}\n\n/** SQLite reports FK violations with this exact message; verify it holds when adding an engine. */\nexport const isForeignKeyViolation = (err: unknown): boolean =>\n err instanceof Error && err.message.includes('FOREIGN KEY constraint failed');\n\n/** SQLite reports a PRIMARY KEY/UNIQUE collision with this exact message. */\nexport const isUniqueConstraintViolation = (err: unknown): boolean =>\n err instanceof Error && err.message.includes('UNIQUE constraint failed');\n","import type { SqlExecutor } from './executor.js';\n\n/** timezone is optional passthrough app metadata — no default. */\nexport type StackConfig = { entityId: string; timezone: string | undefined };\n\n/** Inserts the singleton _config@1 record. Only valid on a freshly-created database. */\nexport const insertConfigRecord = (\n exec: SqlExecutor,\n entityId: string,\n timezone: string | undefined,\n): void => {\n const now = Date.now();\n exec.run(\n `INSERT INTO records (id, type_id, created_at, updated_at, content, version)\n VALUES ('_config', '_config@1', ?, ?, ?, 1)`,\n [now, now, JSON.stringify({ entityId, timezone })],\n );\n};\n\n/** Reads the singleton _config@1 record. Throws if the database is missing it. */\nexport const readStackConfig = (exec: SqlExecutor): StackConfig => {\n const row = exec.get<{ content: string }>(`SELECT content FROM records WHERE id = '_config'`);\n if (!row) throw new Error('Stack database is missing its config record.');\n const content = JSON.parse(row.content) as { entityId: string; timezone?: string };\n return { entityId: content.entityId, timezone: content.timezone };\n};\n","/**\n * The actual StackRecordAdapter logic (minus lifecycle: initialize/open/\n * close/flush stay per-engine, since schema setup, pragmas, locking, and\n * durability differ there). Every CRUD/query/version/type/association\n * operation lives here exactly once, parametrized over a SqlExecutor\n * (which normalizes each engine's call conventions). Concrete adapters\n * construct one of these and delegate their StackRecordAdapter methods\n * to it — see record-adapter-sqlite.\n */\n\nimport {\n StackConflictError,\n StackVersionConflictError,\n StackNotFoundError,\n StackQueryError,\n applyMergePatch,\n} from '@haverstack/core';\nimport type {\n StackRecord,\n StackType,\n TypeId,\n FileId,\n RecordVersion,\n RecordChanges,\n StackQuery,\n QueryResult,\n Association,\n ActorOptions,\n ExpectedVersionOptions,\n} from '@haverstack/core';\nimport type { SqlExecutor } from './executor.js';\nimport { isForeignKeyViolation, isUniqueConstraintViolation } from './executor.js';\nimport { buildQueryPlan, atBudget } from './query.js';\nimport { fts5Strategy } from './fts5.js';\nimport {\n rowToRecord,\n rowToAssociation,\n rowToType,\n rowToVersion,\n toMs,\n associationKeyColumns,\n} from './mappers.js';\nimport { makeCursor } from './cursor.js';\nimport { contentSortEntry } from '@haverstack/core/adapter';\nimport type { ScalarFieldKind } from '@haverstack/core';\n\n/**\n * Run a query statement, restating an engine parse error as the wire\n * taxonomy's `bad_request` rather than letting it escape as a raw engine\n * error (which a server has no code to map, so it becomes a 500).\n *\n * Scoped to the one filter that carries a query language: `filter.search`\n * is FTS5 source text, and sanitizeFts5Query() repairs the common shapes\n * but claims no completeness against the grammar. Every other clause here\n * is built from parameters, so a parse error in one is this module's bug —\n * rethrown untouched, where it belongs.\n */\nconst asStackQueryError = <T>(query: StackQuery, run: () => T): T => {\n try {\n return run();\n } catch (err) {\n if (!query.filter?.search) throw err;\n throw new StackQueryError(\n `Search text could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n};\n\n/**\n * One spelling of the optimistic-concurrency failure, so the message a\n * caller sees never depends on which of the three places noticed it.\n */\nconst versionConflict = (id: string, expected: number, actual: number): StackVersionConflictError =>\n new StackVersionConflictError(\n `Record \"${id}\" is at version ${actual}, expected ${expected}`,\n id,\n expected,\n actual,\n );\n\n/**\n * Every `versions` column beyond the (record_id, version) key, and the\n * values for them in the same order — one list, so the INSERT that writes a\n * snapshot and the UPDATE that replaces one can't drift apart on which\n * columns a snapshot is made of.\n */\nconst VERSION_COLUMNS = [\n 'type_id',\n 'content',\n 'updated_at',\n 'entity_id',\n 'updated_by',\n 'updated_via',\n 'parent_id',\n 'associations',\n 'permissions',\n] as const;\n\nconst versionRowValues = (version: RecordVersion): unknown[] => [\n version.typeId,\n JSON.stringify(version.content),\n toMs(version.updatedAt),\n version.entityId ?? null,\n version.updatedBy ?? null,\n version.updatedVia ?? null,\n version.parentId ?? null,\n version.associations ? JSON.stringify(version.associations) : null,\n version.permissions ? JSON.stringify(version.permissions) : null,\n];\n\nexport type SharedSqlRecordLogicDeps = {\n exec: SqlExecutor;\n};\n\n/**\n * Top-level scalar fields, by name and declared kind — what content_index\n * covers. Arrays and objects are left out: a value inside one has no\n * single position to order its record by, and no file reference the\n * attachment filter can see.\n */\nconst indexedFieldKinds = (\n schema: Record<string, { kind?: string }>,\n): Map<string, ScalarFieldKind> => {\n const kinds = new Map<string, ScalarFieldKind>();\n for (const [field, def] of Object.entries(schema)) {\n if (!def.kind || def.kind === 'array' || def.kind === 'object') continue;\n kinds.set(field, def.kind as ScalarFieldKind);\n }\n return kinds;\n};\n\nexport class SharedSqlRecordLogic {\n /**\n * Per-typeId cache of the fields content_index covers and their declared\n * kinds, so syncContentIndex() doesn't hit the `types` table and\n * re-parse schema JSON on every write. Populated eagerly in saveType()\n * and lazily via getIndexedFields().\n */\n private readonly indexedFieldsByType = new Map<string, Map<string, ScalarFieldKind>>();\n\n constructor(private readonly deps: SharedSqlRecordLogicDeps) {}\n\n private get exec(): SqlExecutor {\n return this.deps.exec;\n }\n\n /**\n * Precondition check for a mutation that has already read the record —\n * either because it can't fold the check into its own statement\n * (hardDeleteRecord: children reference the row, so the DELETE can't\n * carry it), or because it has to settle the precondition *before*\n * fts5Strategy.remove() runs, which needs the records row still holding\n * the old content. In the latter case versionedUpdate() re-checks it\n * inside the statement, and that is the enforcement; this is what lets\n * the work before it be skipped.\n */\n private checkExpectedVersion(record: StackRecord, expectedVersion: number | undefined): void {\n if (expectedVersion === undefined || record.version === expectedVersion) return;\n throw versionConflict(record.id, expectedVersion, record.version);\n }\n\n /**\n * Called after a version-gated statement affected zero rows.\n * Distinguishes \"record doesn't exist\" (StackNotFoundError) from \"it\n * exists but isn't at expectedVersion\" (StackVersionConflictError, with\n * the actual current version for the caller to act on).\n */\n private throwVersionConflict(id: string, expectedVersion: number | undefined): never {\n const row = this.exec.get<{ version: number }>('SELECT version FROM records WHERE id = ?', [\n id,\n ]);\n if (!row) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n throw versionConflict(id, expectedVersion as number, row.version);\n }\n\n /**\n * The one shape every mutating UPDATE in this class has: whatever columns\n * the caller is changing, then the version bump and the actor/timestamp\n * stamp that every mutation owes, gated on the opt-in `expectedVersion`\n * precondition and failing loudly when nothing matched.\n *\n * The guard rides in the WHERE clause even where the caller has already\n * checked the version against a record it read: that read is outside this\n * statement, so a writer slipping in between the two is caught here\n * rather than silently overwritten.\n */\n private versionedUpdate(\n id: string,\n sets: string[],\n values: unknown[],\n opts: ExpectedVersionOptions & ActorOptions,\n now = toMs(new Date()),\n ): void {\n const guarded = opts.expectedVersion !== undefined;\n const changed = this.exec.run(\n `UPDATE records SET ${[...sets, 'version = version + 1', 'updated_at = ?', 'updated_by = ?', 'updated_via = ?'].join(', ')}` +\n ` WHERE id = ?${guarded ? ' AND version = ?' : ''}`,\n [\n ...values,\n now,\n opts.updatedBy ?? null,\n opts.updatedVia ?? null,\n id,\n ...(guarded ? [opts.expectedVersion] : []),\n ],\n );\n if (changed === 0) this.throwVersionConflict(id, opts.expectedVersion);\n }\n\n /**\n * Read a record back after its own mutation committed, for the caller to\n * return. Its absence is not a \"not found\" for the caller to handle — the\n * mutation just succeeded against it — so it fails as the invariant\n * breach it would be.\n *\n * Synchronous, via readRecord() rather than getRecord(), so the read\n * cannot be separated from the commit by anything: an async caller\n * returning this still hands back a record read in the same tick its\n * transaction committed. See readRecord() for why that matters.\n */\n private reread(id: string, verb: string): StackRecord {\n const updated = this.readRecord(id);\n if (!updated) throw new Error(`Record not found after ${verb}: \"${id}\"`);\n return updated;\n }\n\n // -------------------------------------------------------\n // Records\n // -------------------------------------------------------\n\n /**\n * A duplicate id hits the `records` PK — mapped to StackConflictError\n * instead of surfacing the raw engine exception, mirroring saveVersion's\n * collision mapping below.\n */\n async createRecord(record: StackRecord): Promise<StackRecord> {\n try {\n this.exec.run(\n `INSERT INTO records\n (id, type_id, created_at, updated_at, content, version,\n parent_id, entity_id, app_id, principal_id, updated_by, updated_via,\n deleted_at, unlisted_at, permissions)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n record.id,\n record.typeId,\n toMs(record.createdAt),\n toMs(record.updatedAt),\n JSON.stringify(record.content),\n record.version,\n record.parentId ?? null,\n record.entityId ?? null,\n record.appId ?? null,\n record.principalId ?? null,\n record.updatedBy ?? null,\n record.updatedVia ?? null,\n record.deletedAt ? toMs(record.deletedAt) : null,\n record.unlistedAt ? toMs(record.unlistedAt) : null,\n record.permissions ? JSON.stringify(record.permissions) : null,\n ],\n );\n } catch (err) {\n if (isUniqueConstraintViolation(err)) {\n throw new StackConflictError(`Record already exists: \"${record.id}\"`);\n }\n throw err;\n }\n\n if (record.associations?.length) {\n this.insertAssociations(record.id, record.associations);\n }\n\n fts5Strategy.insert(this.exec, record.id, JSON.stringify(record.content));\n this.syncContentIndex(record.id, record.typeId, record.content);\n return record;\n }\n\n async getRecord(id: string): Promise<StackRecord | null> {\n return this.readRecord(id);\n }\n\n /**\n * The synchronous read behind getRecord(). Callers inside exec.transaction()\n * use this one: an `await` inside that callback yields the microtask queue\n * mid-transaction, and the next operation to run would try to open one of\n * its own — transaction() requires a synchronous callback for exactly this\n * reason (see SqlExecutor.transaction).\n *\n * The same synchrony is what lets the post-commit reads below report the\n * version their own mutation produced: reread() calls this directly, so\n * nothing interleaves between the commit and the read even though the\n * method returning it is async. A backend that made these reads genuinely\n * asynchronous would open that window, and a concurrent mutation could be\n * reported under this one's verb.\n */\n private readRecord(id: string): StackRecord | null {\n const row = this.exec.get<Record<string, unknown>>('SELECT * FROM records WHERE id = ?', [id]);\n if (!row) return null;\n const associations = this.getAssociationsForRecord(id);\n return rowToRecord(row, associations);\n }\n\n /**\n * Apply a change set in one transaction: one UPDATE over the record row\n * with only the columns the change set names, the association set\n * replaced when it carries one, and the snapshot written alongside — so\n * one call is one version whatever it moved.\n *\n * The expectedVersion check is standalone rather than folded into the\n * UPDATE alone, because a content change needs fts.remove() to run\n * *before* the records-table content changes. The guard is still in the\n * UPDATE's WHERE, so a writer that slipped in between the read and the\n * write is caught there rather than overwriting.\n */\n async mutateRecord(\n id: string,\n changes: RecordChanges,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n const existing = await this.getRecord(id);\n if (!existing) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n const merged = changes.contentPatch\n ? applyMergePatch(existing.content, changes.contentPatch)\n : undefined;\n\n // Assembled rather than written out per aspect: every one of these is\n // the same column-and-value pair on one row, and a fixed statement per\n // combination would be 2^5 of them.\n const sets: string[] = [];\n const values: unknown[] = [];\n if (merged !== undefined) {\n sets.push('content = ?');\n values.push(JSON.stringify(merged));\n }\n if (changes.parentId !== undefined) {\n sets.push('parent_id = ?');\n values.push(changes.parentId);\n }\n if (changes.permissions !== undefined) {\n sets.push('permissions = ?');\n values.push(changes.permissions.length ? JSON.stringify(changes.permissions) : null);\n }\n\n const now = toMs(new Date());\n if (changes.unlisted !== undefined) {\n sets.push('unlisted_at = ?');\n // Stamped fresh because this key is only ever present on a\n // transition — Stack narrows a change set to the aspects that\n // actually moved before it reaches an adapter.\n values.push(changes.unlisted ? now : null);\n }\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n if (merged !== undefined) fts5Strategy.remove(this.exec, id);\n\n this.versionedUpdate(id, sets, values, opts, now);\n\n if (changes.associations !== undefined) {\n this.replaceAssociations(id, changes.associations);\n }\n\n if (merged !== undefined) {\n fts5Strategy.insert(this.exec, id, JSON.stringify(merged));\n this.syncContentIndex(id, existing.typeId, merged);\n }\n });\n\n return this.reread(id, 'mutateRecord');\n }\n\n async deleteRecord(\n id: string,\n opts: {\n hard?: boolean;\n expectedVersion?: number;\n snapshot?: RecordVersion;\n } & ActorOptions = {},\n ): Promise<StackRecord | null> {\n if (opts.hard) {\n return this.exec.transaction(() => this.hardDeleteRecord(id, opts.expectedVersion));\n }\n\n // One timestamp for both columns: a soft delete is a single event, and\n // two `new Date()` calls can straddle a millisecond boundary and leave\n // deleted_at and updated_at disagreeing about when it happened.\n const now = toMs(new Date());\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.versionedUpdate(id, ['deleted_at = ?'], [now], opts, now);\n });\n\n return this.reread(id, 'deleteRecord');\n }\n\n /**\n * Deletes a record's FTS entry, associations, versions, file-refs, sort\n * index rows, and row, returning the record as it stood — the last copy that will ever\n * exist, read here so that nothing can overtake it between the read and\n * the deletes. Null when there was no such record. No write() call —\n * callers batch it. expectedVersion is checked first so a lost CAS race\n * leaves nothing touched (children reference the row, so the check can't\n * fold into the final DELETE).\n */\n private hardDeleteRecord(id: string, expectedVersion?: number): StackRecord | null {\n const purged = this.readRecord(id);\n if (!purged) {\n // A CAS against a record that isn't there is a failed precondition,\n // not the \"nothing to delete\" that an unconditional hard delete\n // reports by returning null.\n if (expectedVersion !== undefined) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n return null;\n }\n this.checkExpectedVersion(purged, expectedVersion);\n fts5Strategy.remove(this.exec, id);\n this.exec.run('DELETE FROM associations WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM versions WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM content_index WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM records WHERE id = ?', [id]);\n return purged;\n }\n\n async undeleteRecord(\n id: string,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.versionedUpdate(id, ['deleted_at = NULL'], [], opts);\n });\n\n return this.reread(id, 'undelete');\n }\n\n async restoreVersion(\n id: string,\n version: number,\n opts: {\n expectedVersion?: number;\n snapshot?: RecordVersion;\n restoreAssociations?: boolean;\n } & ActorOptions = {},\n ): Promise<StackRecord> {\n const existing = await this.getRecord(id);\n if (!existing) throw new Error(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n const target = await this.getVersion(id, version);\n if (!target) throw new Error(`Version not found: ${id}@${version}`);\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.rewriteContent(\n id,\n target.typeId,\n target.content,\n opts,\n ['parent_id = ?'],\n [target.parentId ?? null],\n );\n // Whether a restore rolls associations back at all is decided where\n // the record's meaning is known; the snapshot's list is the only one\n // that ever lands here. See StackRecordAdapter.restoreVersion().\n const applied = opts.restoreAssociations === false ? undefined : target.associations;\n if (applied !== undefined) this.replaceAssociations(id, applied);\n });\n\n return this.reread(id, 'restoreVersion');\n }\n\n async commitMigration(\n id: string,\n toTypeId: TypeId,\n content: Record<string, unknown>,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n // Checked against a read record first, rather than left to the\n // UPDATE's WHERE clause alone: fts5Strategy.remove() has to run before\n // the content changes, so the precondition has to settle before that\n // work starts. rewriteContent()'s UPDATE still carries the guard, so a\n // writer slipping in between the two is caught rather than overwritten\n // — same shape as mutateRecord() and restoreVersion().\n const existing = await this.getRecord(id);\n if (!existing) throw new Error(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.rewriteContent(id, toTypeId, content, opts);\n });\n\n return this.reread(id, 'commitMigration');\n }\n\n /**\n * Replace a record's type and content wholesale — what restoreVersion and\n * commitMigration each do, differing only in where the content came from\n * and whether the container moves with it.\n *\n * The order is the constraint: fts5Strategy.remove() has to read the old\n * content off the records row, so it runs before the UPDATE, and the\n * re-index runs after. Every caller must already sit inside\n * exec.transaction() — a failure between the two halves would otherwise\n * leave the record unindexed.\n */\n private rewriteContent(\n id: string,\n typeId: TypeId,\n content: Record<string, unknown>,\n opts: ExpectedVersionOptions & ActorOptions,\n extraSets: string[] = [],\n extraValues: unknown[] = [],\n ): void {\n const json = JSON.stringify(content);\n fts5Strategy.remove(this.exec, id);\n this.versionedUpdate(\n id,\n ['type_id = ?', 'content = ?', ...extraSets],\n [typeId, json, ...extraValues],\n opts,\n );\n fts5Strategy.insert(this.exec, id, json);\n this.syncContentIndex(id, typeId, content);\n }\n\n async queryRecords(query: StackQuery): Promise<QueryResult> {\n const limit = query.limit ?? 50;\n // One extra row, to learn whether a further page follows.\n const fetch = limit + 1;\n\n // A content-field sort answers from two statements, the records that\n // hold a value at the field and then the records that hold none. They\n // read in order, each asking only for the rows the ones before it left\n // of the page, and the second is skipped once the first has filled it —\n // the common case, since a page rarely straddles the boundary.\n const rows: Record<string, unknown>[] = [];\n for (const page of buildQueryPlan(query)) {\n const budget = fetch - rows.length;\n if (budget <= 0) break;\n const statement = atBudget(page, budget);\n rows.push(\n ...asStackQueryError(query, () =>\n this.exec.all<Record<string, unknown>>(statement.sql, statement.params),\n ),\n );\n }\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n\n const records = page.map((row) => {\n const associations = this.getAssociationsForRecord(row.id as string);\n return rowToRecord(row, associations);\n });\n\n const lastRecord = records[records.length - 1];\n const cursor =\n hasMore && lastRecord\n ? makeCursor(lastRecord, query.sort, (record, field) => this.sortFieldKind(record, field))\n : null;\n\n return { records, cursor };\n }\n\n /**\n * Atomically verify fileId is unreferenced, then hard-delete its\n * metadata records across every typeId in `metadataTypeIds` (see\n * deleteUnreferencedAttachmentRecords on the adapter contract). A real\n * SQL transaction of synchronous calls — no `await` between the check\n * and the deletes, so nothing interleaves.\n */\n async deleteUnreferencedAttachmentRecords(\n fileId: FileId,\n metadataTypeIds: TypeId[],\n ): Promise<StackRecord[]> {\n return this.exec.transaction(() => {\n const referenced = this.exec.all<{ found: number }>(\n `SELECT 1 as found FROM associations WHERE kind = 'attachment' AND file_id = ?\n UNION ALL\n SELECT 1 FROM content_index WHERE file_id = ?\n LIMIT 1`,\n [fileId, fileId],\n );\n if (referenced.length) {\n throw new StackConflictError('Attachment is still referenced by one or more records');\n }\n\n // An empty family still owes the caller the reference check above —\n // the conflict is a fact about the file, not about which metadata\n // types happen to be defined.\n if (metadataTypeIds.length === 0) return [];\n\n const placeholders = metadataTypeIds.map(() => '?').join(', ');\n const metaRows = this.exec.all<{ id: string }>(\n `SELECT id FROM records\n WHERE type_id IN (${placeholders}) AND json_extract(content, '$.fileId') = ?`,\n [...metadataTypeIds, fileId],\n );\n const deleted: StackRecord[] = [];\n for (const row of metaRows) {\n const purged = this.hardDeleteRecord(row.id);\n if (purged) deleted.push(purged);\n }\n\n return deleted;\n });\n }\n\n // -------------------------------------------------------\n // Versions\n // -------------------------------------------------------\n\n async getVersions(id: string): Promise<RecordVersion[]> {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM versions WHERE record_id = ? ORDER BY version DESC',\n [id],\n );\n return rows.map(rowToVersion);\n }\n\n async getVersion(id: string, version: number): Promise<RecordVersion | null> {\n const row = this.exec.get<Record<string, unknown>>(\n 'SELECT * FROM versions WHERE record_id = ? AND version = ?',\n [id, version],\n );\n return row ? rowToVersion(row) : null;\n }\n\n /**\n * A (record_id, version) collision is rejected loudly via the UNIQUE\n * constraint, mapped to StackConflictError — never a silently discarded\n * snapshot leaving a hole in rollback history. See\n * docs/spec/versioning.md § Optimistic concurrency (`ifVersion`).\n */\n private insertVersionRow(id: string, version: RecordVersion): void {\n try {\n this.exec.run(\n `INSERT INTO versions\n (record_id, version, ${VERSION_COLUMNS.join(', ')})\n VALUES (?, ?, ${VERSION_COLUMNS.map(() => '?').join(', ')})`,\n [id, version.version, ...versionRowValues(version)],\n );\n } catch (err) {\n if (isUniqueConstraintViolation(err)) {\n throw new StackConflictError(\n `Version ${version.version} already exists for record \"${id}\" — a concurrent ` +\n `writer raced past this version. Use ifVersion to detect this before it happens.`,\n );\n }\n throw err;\n }\n }\n\n /**\n * Replaces every column insertVersionRow writes — structurally, off the\n * same VERSION_COLUMNS list, because a column left out here would keep\n * the replaced row's value and surface later as a restore putting back\n * something the snapshot never said.\n */\n private overwriteVersionRow(id: string, version: RecordVersion): void {\n this.exec.run(\n `UPDATE versions\n SET ${VERSION_COLUMNS.map((c) => `${c} = ?`).join(', ')}\n WHERE record_id = ? AND version = ?`,\n [...versionRowValues(version), id, version.version],\n );\n }\n\n /**\n * Standalone snapshot write for tooling and tests — loud on any\n * collision, since nothing here is about to bump the version. Mutating\n * methods take a `snapshot` option instead; see snapshotBeforeMutation.\n */\n async saveVersion(id: string, version: RecordVersion): Promise<void> {\n this.insertVersionRow(id, version);\n }\n\n /**\n * The snapshot half of a mutating method's atomic snapshot-then-mutate\n * transaction. A collision is a racing-writer conflict, except an orphan\n * row at the record's *current* version — recognized by version number\n * alone, never content — which is overwritten so the interrupted write\n * can complete. See docs/spec/versioning.md § Snapshot atomicity.\n */\n private snapshotBeforeMutation(id: string, version: RecordVersion): void {\n try {\n this.insertVersionRow(id, version);\n } catch (err) {\n if (!(err instanceof StackConflictError)) throw err;\n\n const row = this.exec.get<{ version: number }>('SELECT version FROM records WHERE id = ?', [\n id,\n ]);\n if (!row || row.version !== version.version) throw err;\n\n this.overwriteVersionRow(id, version);\n }\n }\n\n // -------------------------------------------------------\n // Types\n // -------------------------------------------------------\n\n async saveType(type: StackType): Promise<void> {\n this.exec.run(\n `INSERT OR REPLACE INTO types\n (id, base_id, version, name, schema, schema_hash, migrates_from, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n type.id,\n type.baseId,\n type.version,\n type.name,\n JSON.stringify(type.schema),\n type.schemaHash,\n type.migratesFrom ?? null,\n toMs(type.createdAt),\n ],\n );\n const schema = type.schema as Record<string, { kind?: string }>;\n this.indexedFieldsByType.set(type.id, indexedFieldKinds(schema));\n }\n\n async getType(id: TypeId): Promise<StackType | null> {\n const row = this.exec.get<Record<string, unknown>>('SELECT * FROM types WHERE id = ?', [id]);\n return row ? rowToType(row) : null;\n }\n\n async listTypes(): Promise<StackType[]> {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM types ORDER BY base_id, version',\n );\n return rows.map(rowToType);\n }\n\n // -------------------------------------------------------\n // Associations\n // -------------------------------------------------------\n\n async associate(\n recordId: string,\n association: Association,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(recordId, opts.snapshot);\n // Bump (and CAS-check) first, before the associations-table write, so\n // a lost race never partially applies.\n this.versionedUpdate(recordId, [], [], opts);\n this.insertAssociations(recordId, [association]);\n });\n\n return this.reread(recordId, 'associate');\n }\n\n async dissociate(\n recordId: string,\n association: Association,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(recordId, opts.snapshot);\n this.versionedUpdate(recordId, [], [], opts);\n this.exec.run(\n `DELETE FROM associations\n WHERE record_id = ?\n AND kind = ?\n AND label = ?\n AND file_id = ?\n AND related_scope = ?\n AND related_id = ?\n AND related_ns = ?\n AND related_stack = ?`,\n [recordId, association.kind, association.label, ...associationKeyColumns(association)],\n );\n });\n\n return this.reread(recordId, 'dissociate');\n }\n\n /**\n * Swap a record's association set for `associations` wholesale — the\n * \"replace, don't merge\" semantics a change set's association list and a\n * version snapshot's both carry. Caller-transactional, like every write\n * below.\n */\n private replaceAssociations(recordId: string, associations: Association[]): void {\n this.exec.run('DELETE FROM associations WHERE record_id = ?', [recordId]);\n if (associations.length) this.insertAssociations(recordId, associations);\n }\n\n /**\n * FK enforcement (PRAGMA_FOREIGN_KEYS_ON) means inserting an\n * association against a record that doesn't exist throws — mapped\n * here to StackNotFoundError so associate() on a nonexistent record\n * fails loudly instead of silently creating an orphan row.\n */\n private insertAssociations(recordId: string, associations: Association[]): void {\n for (const assoc of associations) {\n try {\n this.exec.run(\n `INSERT OR IGNORE INTO associations\n (record_id, kind, label, file_id, related_scope, related_id, related_ns, related_stack)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n [recordId, assoc.kind, assoc.label, ...associationKeyColumns(assoc)],\n );\n } catch (err) {\n if (isForeignKeyViolation(err)) {\n throw new StackNotFoundError(`Record not found: \"${recordId}\"`);\n }\n throw err;\n }\n }\n }\n\n private getAssociationsForRecord(recordId: string): Association[] {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM associations WHERE record_id = ?',\n [recordId],\n );\n return rows.map(rowToAssociation);\n }\n\n /**\n * The fields content_index covers for typeId, from the in-memory cache\n * — falling back to a `types` lookup (and populating the cache) only for\n * a typeId this process hasn't seen via saveType() yet, e.g. right after\n * open().\n */\n private getIndexedFields(typeId: string): Map<string, ScalarFieldKind> {\n const cached = this.indexedFieldsByType.get(typeId);\n if (cached) return cached;\n\n const typeRow = this.exec.get<{ schema: string }>('SELECT schema FROM types WHERE id = ?', [\n typeId,\n ]);\n const fields = typeRow\n ? indexedFieldKinds(JSON.parse(typeRow.schema) as Record<string, { kind?: string }>)\n : new Map<string, ScalarFieldKind>();\n this.indexedFieldsByType.set(typeId, fields);\n return fields;\n }\n\n /**\n * Replace a record's content_index rows with what its content currently\n * holds, on every write that can change content or typeId, so neither\n * the ordering nor the file-reference lookup can drift from the record.\n * A field holding no orderable value gets no row at all, which is what\n * puts the record at the end of a sort on that field.\n */\n private syncContentIndex(\n recordId: string,\n typeId: string,\n content: Record<string, unknown>,\n ): void {\n this.exec.run('DELETE FROM content_index WHERE record_id = ?', [recordId]);\n\n for (const [field, kind] of this.getIndexedFields(typeId)) {\n const entry = contentSortEntry(kind, content[field]);\n if (!entry) continue;\n const sql = `INSERT OR IGNORE INTO content_index\n (record_id, field, value_rank, num_value, text_key, text_value, file_id)\n VALUES (?, ?, ?, ?, ?, ?, ?)`;\n if (entry.kind === 'num') {\n this.exec.run(sql, [recordId, field, 0, entry.num, null, null, null]);\n } else {\n // A file-ref field's value is its file id, so the row it already\n // needs for ordering also answers the attachment filter — one\n // field is one row, whatever a query reads it for.\n const fileId = kind === 'file-ref' ? entry.text : null;\n this.exec.run(sql, [recordId, field, 1, null, entry.key, entry.text, fileId]);\n }\n }\n }\n\n /** The declared kind of a record's top-level `field`, if it has one. */\n private sortFieldKind(record: StackRecord, field: string): ScalarFieldKind | undefined {\n return this.getIndexedFields(record.typeId).get(field);\n }\n}\n","import type { SqlExecutor } from '@haverstack/sqlite-shared/record';\n\n/**\n * Normalizes a Durable Object's ctx.storage.sql to SqlExecutor.\n *\n * Two things don't map onto node:sqlite's shape the way the rest of this\n * interface does:\n *\n * - There is no get/all/run split — sql.exec() always returns a cursor.\n * get()/all() read it via .toArray(); run() reads .rowsWritten for the\n * affected-row count run()'s contract promises.\n * - Raw BEGIN/COMMIT/ROLLBACK are rejected outright by DO SQLite (verified\n * against the real Workers runtime, not assumed) — its storage has no\n * notion of a transaction left open across separate exec() calls, and\n * each statement auto-commits the instant it runs, so no-op'ing those\n * three strings would silently break atomicity, not preserve it. The\n * platform's real primitive is ctx.storage.transactionSync(fn), which\n * SqlExecutor.transaction() reaches directly — see docs/spec/adapters.md\n * § Concurrency & storage ownership.\n */\nexport class DurableObjectSqliteExecutor implements SqlExecutor {\n constructor(private readonly storage: DurableObjectStorage) {}\n\n private get sql(): SqlStorage {\n return this.storage.sql;\n }\n\n exec(sql: string): void {\n this.sql.exec(sql);\n }\n\n run(sql: string, params: readonly unknown[] = []): number {\n const cursor = this.sql.exec(sql, ...(params as SqlStorageValue[]));\n return cursor.rowsWritten;\n }\n\n get<T = Record<string, unknown>>(sql: string, params: readonly unknown[] = []): T | undefined {\n const rows = this.sql.exec(sql, ...(params as SqlStorageValue[])).toArray();\n return rows[0] as T | undefined;\n }\n\n all<T = Record<string, unknown>>(sql: string, params: readonly unknown[] = []): T[] {\n return this.sql.exec(sql, ...(params as SqlStorageValue[])).toArray() as T[];\n }\n\n transaction<T>(fn: () => T): T {\n return this.storage.transactionSync(fn);\n }\n}\n","/**\n * Haverstack — Durable Object SQLite Record Adapter\n * -------------------------------------------------------\n * Implements StackRecordAdapter over a Cloudflare Durable Object's SQLite\n * storage (ctx.storage.sql). Full-text search uses FTS5, same as\n * record-adapter-sqlite — DO's SQLite build ships it.\n *\n * Ownership and durability come from the platform, not from anything this\n * class does: a Durable Object id maps to exactly one running instance,\n * so there is no separate lock file the way record-adapter-sqlite needs\n * one for real files (see docs/spec/adapters.md § Concurrency & storage\n * ownership) — the DO *is* the lock. There is likewise no persist/flush\n * step: every write through ctx.storage.sql is durable by the time the\n * call returns, so flush()/close() are no-ops kept only to satisfy the\n * optional StackRecordAdapter methods.\n *\n * This class itself is a thin binding: schema setup and the one piece of\n * genuinely engine-specific wiring — SqlExecutor.transaction() reaching\n * ctx.storage.transactionSync() instead of raw SQL BEGIN/COMMIT/ROLLBACK,\n * which DO SQLite rejects outright — live here (see executor.ts). The\n * actual StackRecordAdapter logic lives in @haverstack/sqlite-shared's\n * SharedSqlRecordLogic, exactly as it does for record-adapter-sqlite.\n */\n\nimport type { StackType, TypeId, FileId, RecordVersion, ActorOptions } from '@haverstack/core';\nimport type {\n StackRecord,\n StackQuery,\n QueryResult,\n Association,\n RecordChanges,\n} from '@haverstack/core';\nimport type { StackRecordAdapter, AdapterCapabilities } from '@haverstack/core/adapter';\nimport {\n RECORD_SCHEMA_SQL,\n FTS5_SCHEMA_SQL,\n PRAGMA_FOREIGN_KEYS_ON,\n insertConfigRecord,\n readStackConfig,\n SharedSqlRecordLogic,\n} from '@haverstack/sqlite-shared/record';\nimport { DurableObjectSqliteExecutor } from './executor.js';\n\n// -------------------------------------------------------\n// Types\n// -------------------------------------------------------\n\nexport type DoRecordCreateOptions = {\n /** Entity ID of the stack owner. Ignored if the DO's storage already has a config record. */\n entityId: string;\n /** IANA timezone string e.g. \"America/New_York\". Optional passthrough app metadata — no default. */\n timezone?: string;\n};\n\n// -------------------------------------------------------\n// DoSQLiteRecordAdapter\n// -------------------------------------------------------\n\nexport class DoSQLiteRecordAdapter implements StackRecordAdapter {\n readonly capabilities: AdapterCapabilities = {\n filter: {\n content: 'path',\n contentPresent: true,\n search: true,\n },\n sort: {\n fields: ['createdAt', 'updatedAt', 'version'],\n contentField: true,\n },\n limits: {\n attachmentBytes: null,\n contentBytes: null,\n },\n };\n\n ownerEntityId!: string;\n timezone: string | undefined;\n\n private readonly record: SharedSqlRecordLogic;\n\n private constructor(private readonly exec: DurableObjectSqliteExecutor) {\n this.record = new SharedSqlRecordLogic({ exec });\n }\n\n /**\n * Create (or reattach to) the adapter for a DO instance. There is no\n * initialize()/open() split the way file-based adapters need one: a DO\n * id either already has a config record (a previous call created it —\n * reattach, opts.entityId/timezone ignored in favor of what's stored)\n * or it doesn't (first call — opts.entityId/timezone become the config).\n * Schema DDL is `CREATE TABLE IF NOT EXISTS`, so running it every call\n * is idempotent and cheap.\n */\n static async create(\n storage: DurableObjectStorage,\n opts: DoRecordCreateOptions,\n ): Promise<DoSQLiteRecordAdapter> {\n const exec = new DurableObjectSqliteExecutor(storage);\n exec.exec(RECORD_SCHEMA_SQL);\n exec.exec(FTS5_SCHEMA_SQL);\n exec.exec(PRAGMA_FOREIGN_KEYS_ON);\n // DO SQLite manages its own durability and rejects PRAGMA journal_mode\n // outright (\"not authorized\") — verified against the real runtime, not\n // assumed — so unlike record-adapter-sqlite, no WAL pragma runs here.\n\n const adapter = new DoSQLiteRecordAdapter(exec);\n const existing = exec.get<{ content: string }>(\n `SELECT content FROM records WHERE id = '_config'`,\n );\n if (existing) {\n const config = readStackConfig(exec);\n adapter.ownerEntityId = config.entityId;\n adapter.timezone = config.timezone;\n } else {\n insertConfigRecord(exec, opts.entityId, opts.timezone);\n adapter.ownerEntityId = opts.entityId;\n adapter.timezone = opts.timezone;\n }\n return adapter;\n }\n\n // -------------------------------------------------------\n // Records\n // -------------------------------------------------------\n\n createRecord(record: StackRecord): Promise<StackRecord> {\n return this.record.createRecord(record);\n }\n\n getRecord(id: string): Promise<StackRecord | null> {\n return this.record.getRecord(id);\n }\n\n mutateRecord(\n id: string,\n changes: RecordChanges,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.mutateRecord(id, changes, opts);\n }\n\n deleteRecord(\n id: string,\n opts?: { hard?: boolean; expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord | null> {\n return this.record.deleteRecord(id, opts);\n }\n\n undeleteRecord(\n id: string,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.undeleteRecord(id, opts);\n }\n\n restoreVersion(\n id: string,\n version: number,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & {\n restoreAssociations?: boolean;\n } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.restoreVersion(id, version, opts);\n }\n\n commitMigration(\n id: string,\n toTypeId: TypeId,\n content: Record<string, unknown>,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.commitMigration(id, toTypeId, content, opts);\n }\n\n queryRecords(query: StackQuery): Promise<QueryResult> {\n return this.record.queryRecords(query);\n }\n\n deleteUnreferencedAttachmentRecords(\n fileId: FileId,\n metadataTypeIds: TypeId[],\n ): Promise<StackRecord[]> {\n return this.record.deleteUnreferencedAttachmentRecords(fileId, metadataTypeIds);\n }\n\n // -------------------------------------------------------\n // Versions\n // -------------------------------------------------------\n\n getVersions(id: string): Promise<RecordVersion[]> {\n return this.record.getVersions(id);\n }\n\n getVersion(id: string, version: number): Promise<RecordVersion | null> {\n return this.record.getVersion(id, version);\n }\n\n saveVersion(id: string, version: RecordVersion): Promise<void> {\n return this.record.saveVersion(id, version);\n }\n\n // -------------------------------------------------------\n // Types\n // -------------------------------------------------------\n\n saveType(type: StackType): Promise<void> {\n return this.record.saveType(type);\n }\n\n getType(id: TypeId): Promise<StackType | null> {\n return this.record.getType(id);\n }\n\n listTypes(): Promise<StackType[]> {\n return this.record.listTypes();\n }\n\n // -------------------------------------------------------\n // Associations\n // -------------------------------------------------------\n\n associate(\n recordId: string,\n association: Association,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.associate(recordId, association, opts);\n }\n\n dissociate(\n recordId: string,\n association: Association,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.dissociate(recordId, association, opts);\n }\n\n // -------------------------------------------------------\n // Lifecycle\n // -------------------------------------------------------\n\n /** No-op: every write through ctx.storage.sql is already durable. */\n async flush(): Promise<void> {}\n\n /** No-op: no lock file, no connection to release — the DO's own lifecycle governs storage. */\n async close(): Promise<void> {}\n}\n\nexport { DurableObjectSqliteExecutor } from './executor.js';\n"]}
|
|
1
|
+
{"version":3,"sources":["../../sqlite-shared/src/schema.ts","../../sqlite-shared/src/cursor.ts","../../sqlite-shared/src/fts5.ts","../../sqlite-shared/src/query.ts","../../sqlite-shared/src/mappers.ts","../../sqlite-shared/src/executor.ts","../../sqlite-shared/src/config.ts","../../sqlite-shared/src/record-logic.ts","../../sqlite-shared/src/record-adapter.ts","../src/executor.ts","../src/index.ts"],"names":["StackQueryError","cursor","page","statement","contentSortEntry"],"mappings":";;;;AAUO,IAAM,iBAAA,GAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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A,EAAU,IAAA,CAAK,QAAQ,CAAA;AACnF,IAAA,OAAO,IAAI,sBAAA,CAAsB,IAAA,EAAM,MAAM,CAAA;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAA,GAAuB;AAAA,EAAC;AAAA;AAAA,EAG9B,MAAM,KAAA,GAAuB;AAAA,EAAC;AAChC","file":"index.js","sourcesContent":["import type { SqlExecutor } from './executor.js';\n\n/**\n * Schema DDL shared by SQLite-backed record adapters. TOKENS_SCHEMA_SQL\n * is split out from RECORD_SCHEMA_SQL because token storage lives in its\n * own file, never bundled with records — see NativeTokenStore in\n * record-adapter-sqlite and the StackTokenStore portability rationale\n * (docs/spec/wire-format.md § Authentication).\n */\n\nexport const RECORD_SCHEMA_SQL = `\n CREATE TABLE IF NOT EXISTS records (\n id TEXT PRIMARY KEY,\n type_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n content TEXT NOT NULL CHECK (json_valid(content)),\n version INTEGER NOT NULL DEFAULT 1,\n parent_id TEXT,\n entity_id TEXT,\n app_id TEXT,\n principal_id TEXT,\n updated_by TEXT,\n updated_via TEXT,\n deleted_at INTEGER,\n unlisted_at INTEGER,\n permissions TEXT CHECK (permissions IS NULL OR json_valid(permissions))\n ) STRICT;\n\n -- A relationship's target is (related_scope, related_id) plus one\n -- qualifier: related_stack for a record in another stack, related_ns for\n -- a foreign namespace. All four are in the primary key, so two targets\n -- differing only by namespace are two associations.\n --\n -- The primary key leads with record_id, so its implicit index already\n -- serves every by-record read and delete; the indexes below exist only\n -- for the filter directions it cannot answer.\n CREATE TABLE IF NOT EXISTS associations (\n record_id TEXT NOT NULL REFERENCES records(id),\n kind TEXT NOT NULL CHECK (kind IN ('tag', 'attachment', 'relationship')),\n label TEXT NOT NULL,\n file_id TEXT NOT NULL DEFAULT '',\n related_scope TEXT NOT NULL DEFAULT '' CHECK (related_scope IN ('', 'record', 'entity', 'external')),\n related_id TEXT NOT NULL DEFAULT '',\n related_ns TEXT NOT NULL DEFAULT '',\n related_stack TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (record_id, kind, label, file_id, related_scope, related_id, related_ns, related_stack)\n ) STRICT;\n\n -- parent_id holds the container the record sat in, NULL for the root --\n -- the same encoding records.parent_id uses, since a snapshot states\n -- where the record was rather than an instruction to apply.\n CREATE TABLE IF NOT EXISTS versions (\n record_id TEXT NOT NULL REFERENCES records(id),\n version INTEGER NOT NULL,\n type_id TEXT NOT NULL,\n content TEXT NOT NULL CHECK (json_valid(content)),\n updated_at INTEGER NOT NULL,\n entity_id TEXT,\n updated_by TEXT,\n updated_via TEXT,\n parent_id TEXT,\n associations TEXT CHECK (associations IS NULL OR json_valid(associations)),\n permissions TEXT CHECK (permissions IS NULL OR json_valid(permissions)),\n PRIMARY KEY (record_id, version)\n ) STRICT;\n\n CREATE TABLE IF NOT EXISTS types (\n id TEXT PRIMARY KEY,\n base_id TEXT NOT NULL,\n version INTEGER NOT NULL,\n name TEXT NOT NULL,\n schema TEXT NOT NULL CHECK (json_valid(schema)),\n schema_hash TEXT NOT NULL,\n migrates_from TEXT,\n created_at INTEGER NOT NULL\n ) STRICT;\n\n -- One row per top-level scalar content field a record holds a value at:\n -- what it orders as, and the file it references. See\n -- docs/spec/adapters.md § Adapter backends and\n -- docs/spec/data-model.md § Sorting by a content field.\n --\n -- value_rank is 0 for a numeric value and 1 for a text one — the same\n -- split as \"num_value IS NULL\", but non-null, so one index can carry\n -- the whole ordering. file_id is set only for a 'file-ref' field.\n CREATE TABLE IF NOT EXISTS content_index (\n record_id TEXT NOT NULL REFERENCES records(id),\n field TEXT NOT NULL,\n value_rank INTEGER NOT NULL CHECK (value_rank IN (0, 1)),\n num_value REAL,\n text_key TEXT,\n text_value TEXT,\n file_id TEXT,\n PRIMARY KEY (record_id, field)\n ) STRICT;\n\n -- Indexes. Each filter column continues into (created_at, id) — the\n -- default ordering and its tiebreak — because these columns are\n -- low-cardinality by design, and a narrow index on one leaves the\n -- planner sorting the whole matching set before it can honor LIMIT.\n --\n -- deleted_at and unlisted_at deliberately have none: nothing searches\n -- for the rows they mark, and an index on a column every query tests\n -- for IS NULL only lures the planner off the one answering ORDER BY.\n CREATE INDEX IF NOT EXISTS idx_records_type_id ON records(type_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_parent_id ON records(parent_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_entity_id ON records(entity_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_app_id ON records(app_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_principal_id ON records(principal_id, created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_created_at ON records(created_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_updated_at ON records(updated_at, id);\n CREATE INDEX IF NOT EXISTS idx_records_version ON records(version, id);\n\n -- Each association index ends with record_id so the semi-joins in\n -- query.ts read the matching record ids out of the index alone.\n -- idx_assoc_related carries related_ns ahead of related_id because a\n -- record- or entity-scoped target always stores '' there, which\n -- buildQueryPlan states explicitly to keep the prefix contiguous.\n CREATE INDEX IF NOT EXISTS idx_assoc_kind_label ON associations(kind, label, record_id);\n CREATE INDEX IF NOT EXISTS idx_assoc_kind_file_id ON associations(kind, file_id, record_id);\n CREATE INDEX IF NOT EXISTS idx_assoc_related ON associations(kind, related_scope, related_ns, related_id, record_id);\n CREATE INDEX IF NOT EXISTS idx_types_base_id ON types(base_id, version);\n\n -- The whole content ordering, in index order, for one field at a time:\n -- a content-sorted page is an ordered walk of a slice of this index.\n CREATE INDEX IF NOT EXISTS idx_content_index_sort\n ON content_index(field, value_rank, num_value, text_key, text_value, record_id);\n CREATE INDEX IF NOT EXISTS idx_content_index_file\n ON content_index(file_id, record_id) WHERE file_id IS NOT NULL;\n`;\n\n/**\n * Bearer-token storage backing StackTokenStore. Kept separate from\n * RECORD_SCHEMA_SQL so an adapter can put it in its own file — the\n * portable stack file shouldn't also carry a server's auth material.\n */\nexport const TOKENS_SCHEMA_SQL = `\n CREATE TABLE IF NOT EXISTS tokens (\n id TEXT PRIMARY KEY,\n token_hash TEXT NOT NULL UNIQUE,\n principal_id TEXT NOT NULL,\n subject_id TEXT NOT NULL,\n label TEXT,\n created_at INTEGER NOT NULL,\n expires_at INTEGER\n ) STRICT;\n`;\n\n/**\n * The full-text index behind `StackQuery.filter.search` (see fts5.ts).\n * What `columnsize=0` costs a reader is in docs/spec/adapters.md\n * § Adapter backends. `detail` stays at its default: sanitizeFts5Query\n * passes phrase queries through, and a phrase needs the token positions\n * only that setting records.\n */\nexport const FTS5_SCHEMA_SQL = `\n CREATE VIRTUAL TABLE IF NOT EXISTS records_fts USING fts5(\n content,\n content='records',\n content_rowid='rowid',\n columnsize=0\n );\n`;\n\n/**\n * Enforces the REFERENCES constraints declared above (off by default per\n * SQLite connection), so touching a nonexistent record fails loudly\n * instead of creating an orphan row. Adapters map the constraint\n * violation to StackNotFoundError at the call sites that can trigger it.\n */\nexport const PRAGMA_FOREIGN_KEYS_ON = `PRAGMA foreign_keys = ON;`;\n\n/**\n * WAL journaling: page-level writes, crash-safe without our own\n * temp-file-and-rename dance, and real SQLite file locking. Only\n * meaningful for a real file (a :memory: database silently ignores it).\n */\nexport const PRAGMA_JOURNAL_MODE_WAL = `PRAGMA journal_mode = WAL;`;\n\nexport type RecordSchemaOptions = {\n /**\n * Whether to put the connection in WAL mode. False for an engine that\n * owns its own durability and rejects the pragma outright, as Durable\n * Object storage does.\n */\n wal: boolean;\n};\n\n/**\n * Brings a records database up to the schema every SQLite record adapter\n * expects: foreign keys on, then the tables and the FTS5 index. Every\n * statement is idempotent, so an engine that has no\n * initialize()/open() split can run this on each attach.\n */\nexport const applyRecordSchema = (exec: SqlExecutor, opts: RecordSchemaOptions): void => {\n exec.exec(PRAGMA_FOREIGN_KEYS_ON);\n if (opts.wal) exec.exec(PRAGMA_JOURNAL_MODE_WAL);\n exec.exec(RECORD_SCHEMA_SQL);\n exec.exec(FTS5_SCHEMA_SQL);\n};\n","/**\n * Cursor encode/decode for keyset pagination. The payload is JSON in\n * base64 rather than delimited fields: a content sort carries the field's\n * stored text, and neither a field name nor a text value is constrained\n * to avoid whatever character a delimiter would claim. Uses btoa/atob\n * with an explicit UTF-8 step rather than Node's Buffer, so the codec\n * stays runtime-agnostic and a non-Latin-1 value survives the round trip.\n */\n\nimport { NATIVE_SORT_FIELDS, StackQueryError } from '@haverstack/core';\nimport { contentSortEntry } from '@haverstack/core/adapter';\nimport type { StackRecord, NativeSortField, QuerySort, ScalarFieldKind } from '@haverstack/core';\n\nexport type SortField = NativeSortField;\n\n/**\n * Re-exported under this package's own name rather than re-spelled: the\n * set a cursor's `native` field is narrowed against is the same set core\n * narrows a wire request's sort field to, and a fourth column added there\n * must not need finding here too.\n */\nexport const SORT_FIELDS: readonly SortField[] = NATIVE_SORT_FIELDS;\n\n/**\n * Which partition of the ordering a cursor sits in: a native column or a\n * content field's number, text, or absent value. The three content cases\n * are the boundary keyset pagination has to hold — a page that ended on\n * the last numeric value resumes at the first text one, not back at the\n * top of either.\n */\nexport type CursorKind = 'native' | 'num' | 'text' | 'absent';\n\nexport type DecodedCursor =\n | { kind: 'native'; field: SortField; value: number; id: string }\n | { kind: 'num'; field: string; value: number; id: string }\n | { kind: 'text'; field: string; value: string; id: string }\n | { kind: 'absent'; field: string; id: string };\n\nconst toBase64 = (text: string): string => {\n const bytes = new TextEncoder().encode(text);\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n};\n\nconst fromBase64 = (cursor: string): string => {\n const binary = atob(cursor);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n};\n\nexport const encodeCursor = (decoded: DecodedCursor): string =>\n toBase64(\n JSON.stringify(\n decoded.kind === 'absent'\n ? { k: decoded.kind, f: decoded.field, i: decoded.id }\n : { k: decoded.kind, f: decoded.field, i: decoded.id, v: decoded.value },\n ),\n );\n\n/** Throws StackQueryError for any malformed, corrupt, or unrecognized cursor. */\nexport const decodeCursor = (cursor: string): DecodedCursor => {\n const malformed = () => new StackQueryError(`Invalid cursor: malformed \"${cursor}\"`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64(cursor));\n } catch {\n throw malformed();\n }\n if (!parsed || typeof parsed !== 'object') throw malformed();\n const { k, f, i, v } = parsed as Record<string, unknown>;\n if (typeof f !== 'string' || !f || typeof i !== 'string') throw malformed();\n\n if (k === 'absent') return { kind: 'absent', field: f, id: i };\n if (k === 'text') {\n if (typeof v !== 'string') throw malformed();\n return { kind: 'text', field: f, value: v, id: i };\n }\n if (k === 'num' || k === 'native') {\n if (typeof v !== 'number' || !isFinite(v)) {\n throw new StackQueryError(`Invalid cursor: non-numeric sort value`);\n }\n if (k === 'native') {\n if (!SORT_FIELDS.includes(f as SortField)) {\n throw new StackQueryError(`Invalid cursor: unknown sort field \"${f}\"`);\n }\n return { kind: 'native', field: f as SortField, value: v, id: i };\n }\n return { kind: 'num', field: f, value: v, id: i };\n }\n throw malformed();\n};\n\nexport const getSortField = (query: { sort?: QuerySort }): SortField =>\n query.sort?.field ?? 'createdAt';\n\nexport const getSortColumn = (field: SortField): string =>\n field === 'createdAt' ? 'created_at' : field === 'updatedAt' ? 'updated_at' : 'version';\n\n/**\n * The cursor naming the last record of a page: where the next page\n * resumes. A content sort re-derives the record's ordered value from its\n * stored content rather than reading it back out of the index, so the\n * cursor and the index can only ever disagree if the write path is\n * broken — in which case pagination is not the thing to paper over.\n */\nexport const makeCursor = (\n record: StackRecord,\n sort: QuerySort | undefined,\n kindOf?: (record: StackRecord, field: string) => ScalarFieldKind | undefined,\n): string => {\n const contentField = sort?.contentField;\n if (contentField === undefined) {\n const field = getSortField({ sort });\n const value =\n field === 'updatedAt'\n ? record.updatedAt.getTime()\n : field === 'version'\n ? record.version\n : record.createdAt.getTime();\n return encodeCursor({ kind: 'native', field, value, id: record.id });\n }\n\n const kind = kindOf?.(record, contentField);\n const entry = kind ? contentSortEntry(kind, record.content[contentField]) : null;\n if (!entry) return encodeCursor({ kind: 'absent', field: contentField, id: record.id });\n return entry.kind === 'num'\n ? encodeCursor({ kind: 'num', field: contentField, value: entry.num, id: record.id })\n : encodeCursor({ kind: 'text', field: contentField, value: entry.text, id: record.id });\n};\n","/**\n * FTS5 query sanitization and indexing — the full-text search half of the\n * shared record logic.\n *\n * FTS5's query language supports operators (AND/OR/NOT, phrases, NEAR,\n * wildcards) that can be expensive or cause parse errors with untrusted\n * input, so a search string is rewritten before it reaches the engine:\n *\n * kept: AND/OR/NOT (with a left operand), phrase queries (\"…\"), implicit AND\n * removed: wildcards (*), NEAR(...) (terms kept, wrapper dropped), every\n * character outside the allow-list, bare NOT (no left operand),\n * operators with no right operand\n * capped: parenthesis nesting depth (default: 2)\n * closed: an odd trailing quote\n *\n * Two FTS5 grammar details drive the less obvious rules:\n *\n * - FTS5's NEAR is a function-call form — `NEAR(a b, 10)`. Deleting the\n * whole span would also delete the terms inside it, which can leave a\n * dangling operator when NEAR(...) sits next to AND/OR (e.g. \"x AND\n * NEAR(a b, 5)\" -> \"x AND\" — a syntax error). So this keeps the terms\n * and drops only the NEAR(...) wrapper and distance.\n * - FTS5 has real column-filter syntax and errors hard on any name but\n * the table's actual columns. It is wider than `colname:term`: `-name`\n * and `{a b}` filter columns with no colon at all, so an ordinary\n * hyphenated word is read as one. Since records_fts has exactly one\n * column and callers have no business targeting columns explicitly,\n * everything outside a phrase is reduced to an allow-list rather than\n * validated — see OUTSIDE_PHRASE_DISALLOWED.\n *\n * The rewrite is best-effort and makes no completeness claim against\n * FTS5's grammar — which is why the caller wraps execution as well, so a\n * case this misses surfaces as a StackQueryError rather than a raw engine\n * error. Search text is what a person typed into a box: an unbalanced\n * quote or a trailing \"AND\" is ordinary input, not a malformed request.\n *\n * What this bounds is the grammar, not the cost: a syntactically modest\n * search over a large index can still be expensive, and node:sqlite blocks\n * the calling thread, so there is no timeout to set from inside the call.\n * Bounding execution time belongs to whoever drives the engine under load\n * — see docs/spec/wire-format.md § Bounding query cost for the server-side\n * expectation and the `timeout` wire error that goes with it.\n */\n\nimport type { SqlExecutor } from './executor.js';\n\n/**\n * Outside a phrase, everything but a letter, digit, mark, underscore,\n * whitespace, paren or quote becomes a separator.\n *\n * An allow-list rather than a list of metacharacters to strip, because\n * FTS5's column-filter syntax is wider than it looks and an enumeration\n * kept missing parts of it: `-name` and `{a b}` filter columns with no\n * colon in sight, so `-cats` and even the hyphen inside `cats-dogs` were\n * read as column names and answered \"no such column\". `+` is a bare\n * syntax error. Listing what may pass means the next piece of syntax\n * nobody here anticipated arrives as a separator instead of as an error.\n *\n * Nothing is lost by it: FTS5's default tokenizer already splits terms on\n * these characters, so `cats-dogs` searches for the same two tokens it was\n * indexed as.\n */\nconst OUTSIDE_PHRASE_DISALLOWED = /[^\\p{L}\\p{N}\\p{M}_\\s()\"]/gu;\n\n/**\n * Collapse every whitespace run to a single space.\n *\n * Every rule below that reasons about what sits beside an operator or a\n * paren spells \"beside\" as `\\s*`, and a `\\s*` with a long run to chew on\n * re-tries the whole run once per starting position — quadratic in the\n * run, on text a caller types into a box. Keeping runs collapsed bounds\n * what any of them can backtrack over to a single character. What it does\n * not buy is linearity overall: the rewrite still costs a little more\n * than proportionally as the text grows, which is why bounding a search's\n * length belongs to whoever accepts it.\n *\n * Nothing is lost by it: FTS5's tokenizer splits on whitespace, so a\n * collapsed run tokenizes exactly as the original did — inside a phrase\n * as well as outside, since a phrase matches a sequence of tokens rather\n * than the spacing between them.\n */\nconst collapseWhitespace = (query: string): string => query.replace(/\\s+/g, ' ');\n\nexport const sanitizeFts5Query = (query: string, maxDepth = 2): string => {\n if (!query) return '';\n\n // Drop control characters, inside a phrase as well as outside. A NUL in\n // particular ends the string early for SQLite's C API, so the engine sees\n // an opening quote whose closing one is past the truncation and reports an\n // unterminated string; none of them can match an indexed token anyway.\n let clean = query.replace(/[\\p{Cc}\\p{Cf}]/gu, ' ');\n\n // Remove wildcards\n clean = clean.replace(/\\*/g, '');\n\n // Replace NEAR(terms, distance) with just its terms — see note above.\n //\n // Two things here are about what the engine does when the closing paren\n // never arrives, on text a caller types into a box.\n //\n // No `\\s*` after the paren, though the terms it captures may open with\n // whitespace: `[^,()]*` already matches a space, so a second quantifier\n // that also does gives the engine an ambiguous split to backtrack\n // through. The captured space is collapsed with all the rest on the way\n // out.\n //\n // And neither run crosses a `(`, which bounds where the failure is\n // found: `NEAR(NEAR(NEAR(` used to re-scan to the end of the string once\n // per occurrence. A NEAR's terms are words and phrases and its distance\n // is a number, so neither holds a paren in any input FTS5 would accept.\n clean = clean.replace(/\\bNEAR\\s*\\(([^,()]*)(?:,[^()]*)?\\)/gi, '$1');\n\n // A NEAR( with no closing paren isn't the function-call form the rule\n // above rewrites, and the paren auto-close below would hand FTS5 a NEAR\n // call it never meant to write. Keep the grouping, drop the keyword.\n clean = clean.replace(/\\bNEAR\\s*\\(/gi, '(');\n\n // Reduce to the characters that carry meaning outside a phrase — see note\n // above. Everything else becomes a separator, which is what FTS5's own\n // tokenizer would do with it anyway.\n clean = clean.replace(/\"[^\"]*\"|[^\"]+/g, (span) =>\n span.startsWith('\"') ? span : span.replace(OUTSIDE_PHRASE_DISALLOWED, ' '),\n );\n\n // The reduction above turns every disallowed character into a space, so\n // this is where the long runs come from.\n clean = collapseWhitespace(clean);\n\n // Strip bare NOT with no left operand — FTS5 requires \"term NOT term\", not \"NOT term\"\n clean = clean.replace(/(?:^|\\(\\s*)NOT\\s+/gi, (m) => m.replace(/NOT\\s+/i, ''));\n\n // Enforce max nesting depth; replace excess ( with a space and discard\n // unmatched ). Parens inside a phrase are literal text to FTS5, so the\n // depth count steps over quoted spans rather than reading them as syntax.\n let currentDepth = 0;\n let inPhrase = false;\n let result = '';\n for (const char of clean) {\n if (char === '\"') {\n inPhrase = !inPhrase;\n result += char;\n } else if (inPhrase) {\n result += char;\n } else if (char === '(') {\n if (currentDepth < maxDepth) {\n currentDepth++;\n result += char;\n } else result += ' ';\n } else if (char === ')') {\n if (currentDepth > 0) {\n currentDepth--;\n result += char;\n } else result += ' ';\n } else {\n result += char;\n }\n }\n\n // Close an odd trailing quote before the parens, so the added ) lands\n // outside the phrase rather than becoming a literal character in it.\n if (inPhrase) result += '\"';\n\n // Auto-close any unclosed parens\n if (currentDepth > 0) result += ')'.repeat(currentDepth);\n\n // Remove empty paren pairs left behind by NEAR/NOT stripping, and drop\n // operators left without an operand. Looped together because each can\n // create work for the other: removing an operator can empty a paren pair\n // (\"(a AND)\" -> \"(a)\" -> ...), and removing a pair can strand the\n // operator that pointed at it (\"x AND ()\" -> \"x AND\").\n let prev: string;\n do {\n prev = result;\n // Empty phrases and empty paren pairs, each of which matches nothing,\n // in one rule so that a run of them collapses to a single space\n // rather than to one space apiece — a run of spaces is what the rules\n // below would have to backtrack over. An empty phrase is also the one\n // construct whose quotes can re-pair differently once a rule inserts\n // text beside it, which is why this repeats to a fixpoint.\n result = result.replace(/(?:\"\"|\\(\\s*\\))+/g, ' ');\n result = dropDanglingOperators(result);\n result = restoreImplicitAnd(result);\n } while (result !== prev);\n\n return collapseWhitespace(result).replace(/\\(\\s+/g, '(').replace(/\\s+\\)/g, ')').trim();\n};\n\n/** An operator FTS5 requires a term on both sides of. */\nconst OPERATOR = String.raw`(?:AND|OR|NOT)`;\n\n/**\n * Stands in for a phrase while operators are rewritten. A private-use\n * character is not a word character, so `\\b` still sees the operator\n * beside it, while `^`, `$` and the paren anchors see an operand — which\n * is what a phrase is. Nothing reaches here holding one: `clean` is\n * rewritten from the caller's string, and a literal U+E000 in it would be\n * a term character FTS5 tokenizes away regardless.\n */\nconst PHRASE_HOLE = '\\u{E000}';\n\n/**\n * Drop operators left without an operand — the shape a person types on\n * their way to a longer query (\"cats AND\") or lands on once the rules\n * above have removed a term. FTS5 rejects each of them outright, so what\n * would otherwise be a syntax error becomes the search for the terms that\n * are actually there.\n *\n * Phrases are masked out first: `\"cats AND dogs\"` is literal text to FTS5,\n * and rewriting inside it would change what the user asked for.\n */\nconst dropDanglingOperators = (query: string): string =>\n withPhrasesMasked(query, (masked) => {\n let out = masked;\n let prev: string;\n do {\n prev = out;\n // A run of operators keeps only the first — the rest have no left operand.\n out = out.replace(\n new RegExp(String.raw`\\b(${OPERATOR})\\b(?:\\s+\\b${OPERATOR}\\b)+`, 'gi'),\n '$1',\n );\n // No left operand: at the start of the query or straight after \"(\".\n out = out.replace(new RegExp(String.raw`(^|\\()\\s*\\b${OPERATOR}\\b\\s*`, 'gi'), '$1');\n // No right operand: at the end of the query or straight before \")\".\n // No leading `\\s*` — whitespace before the operator is left for the\n // collapse on the way out, and a `\\s*` here would re-scan a run of\n // spaces once per position in it before failing to find an operator.\n out = out.replace(new RegExp(String.raw`\\b${OPERATOR}\\b\\s*($|\\))`, 'gi'), '$1');\n } while (out !== prev);\n return out;\n });\n\n/**\n * Run `rewrite` over the query with each phrase swapped for PHRASE_HOLE,\n * then put the phrases back in order. Every rule that reasons about what\n * sits beside an operator or a paren needs this: inside a phrase the text\n * is literal, and from outside one the phrase is a single operand.\n */\nconst withPhrasesMasked = (query: string, rewrite: (masked: string) => string): string => {\n const phrases: string[] = [];\n const masked = query.replace(/\"[^\"]*\"/g, (phrase) => {\n phrases.push(phrase);\n return PHRASE_HOLE;\n });\n let i = 0;\n return rewrite(masked).replace(new RegExp(PHRASE_HOLE, 'g'), () => phrases[i++]);\n};\n\n/**\n * Put back the operator FTS5 requires around a group. Two terms side by\n * side are an implicit AND (`cats dogs`), but a group is not: `cats (dogs)`\n * is a syntax error where `cats AND (dogs)` is fine. Grouping survives a\n * rewrite that strips the operator which used to sit beside it, so this\n * names the AND that was always meant rather than dropping the parens.\n *\n * Both rules test a *whole* word against the operator list. Matching a\n * prefix instead reads the `D` of a preceding `AND` as a term and inserts\n * a second one beside it.\n *\n * Phrases are masked for the same reason as elsewhere — a phrase is an\n * operand, so `\"a b\" (c)` needs the operator too.\n */\nconst OPERAND_CHAR = String.raw`[\\p{L}\\p{N}_${PHRASE_HOLE}]`;\n\nconst isOperator = (word: string): boolean => /^(?:AND|OR|NOT)$/i.test(word);\n\nconst restoreImplicitAnd = (query: string): string =>\n withPhrasesMasked(query, (masked) =>\n masked\n // \")\" then an operand — \") cats\", \") (\", \") <phrase>\" — unless that\n // operand is an operator, which already joins the two sides.\n .replace(\n new RegExp(String.raw`\\)\\s*(?=${OPERAND_CHAR}|\\()`, 'gu'),\n (match, offset: number, whole: string) => {\n const next = /^\\s*([\\p{L}\\p{N}_]+)/u.exec(whole.slice(offset + match.length));\n return next && isOperator(next[1]) ? match : ') AND ';\n },\n )\n // An operand then \"(\", unless the operand is an operator.\n // The lookbehind pins the match to the start of the operand run.\n // Without it every position inside a run is a start position, and\n // each one re-scans the rest of the run before the lookahead\n // rejects it — quadratic in a long word before a paren.\n .replace(\n new RegExp(String.raw`(?<!${OPERAND_CHAR})(${OPERAND_CHAR}+)\\s*(?=\\()`, 'gu'),\n (match, word: string) => (isOperator(word) ? match : `${word} AND `),\n ),\n );\n\n// -------------------------------------------------------\n// Indexing strategy\n// -------------------------------------------------------\n\n/**\n * FTS5's external-content table needs its special `('delete', rowid,\n * content)` command — with the *old* content — to unindex a row; a plain\n * DELETE leaves stale, still-searchable entries. remove() therefore reads\n * the current rowid/content and must run before the caller's change.\n */\nexport const fts5Strategy = {\n /** Index a record that has no FTS entry yet (used right after an INSERT). */\n insert(exec: SqlExecutor, recordId: string, content: string): void {\n exec.run(`INSERT INTO records_fts(rowid, content) SELECT rowid, ? FROM records WHERE id = ?`, [\n content,\n recordId,\n ]);\n },\n /**\n * Remove a record's FTS entry. MUST be called before the records row's\n * content changes or the row is deleted — see the note above.\n */\n remove(exec: SqlExecutor, recordId: string): void {\n const row = exec.get<{ rowid: number; content: string }>(\n 'SELECT rowid, content FROM records WHERE id = ?',\n [recordId],\n );\n if (!row) return;\n exec.run(`INSERT INTO records_fts(records_fts, rowid, content) VALUES('delete', ?, ?)`, [\n row.rowid,\n row.content,\n ]);\n },\n};\n","/**\n * StackQuery -> SQL. Engine-independent — shared verbatim between\n * SQLite-backed record adapters. The one caveat is full-text search:\n * `f.search` here assumes a `records_fts` virtual table with a MATCH-able\n * `content` column (see fts5.ts).\n *\n * A query compiles to a plan rather than to a single statement, because a\n * content-field sort is two orderings end to end: the records that hold a\n * value at the field, ordered by it, then the records that hold none,\n * ordered by id. Reading them as two statements lets each one walk an\n * index in order and stop at the page boundary; the LEFT JOIN that would\n * express the same result in one statement can only be sorted after the\n * fact, which costs a full pass over the table for every page.\n */\n\nimport { StackQueryError, type StackQuery } from '@haverstack/core';\nimport { contentSortKey, parseContentFilterKey } from '@haverstack/core/adapter';\nimport {\n decodeCursor,\n getSortColumn,\n getSortField,\n type DecodedCursor,\n type SortField,\n} from './cursor.js';\nimport { sanitizeFts5Query } from './fts5.js';\n\n/** One statement plus the parameters it binds, in textual order. */\nexport type QueryStatement = { sql: string; params: unknown[] };\n\n/**\n * A page statement with the row budget its trailing `LIMIT ?` binds.\n * buildQueryPlan leaves that parameter off, so the budget is never one of\n * the parameters the query itself bound: the second partition of a\n * content sort asks for what the first left of the page rather than for a\n * page it then discards.\n */\nexport const atBudget = (page: QueryStatement, rows: number): QueryStatement => ({\n sql: page.sql,\n params: [...page.params, rows],\n});\n\n/**\n * Reduce `sort.direction` to a keyword this module may interpolate into\n * SQL. Core's assertValidSort() already rejects anything else at the\n * invariant layer, but this builder writes the value straight into\n * `ORDER BY` and the cursor comparison, so it re-checks rather than trust\n * an upstream that a future refactor could bypass: an unvalidated direction\n * here is a SQL-injection sink. Anything but \"asc\" is treated as the\n * default \"desc\" only after passing the guard.\n */\nconst sqlDirection = (query: StackQuery): 'ASC' | 'DESC' => {\n const dir = query.sort?.direction ?? 'desc';\n if (dir !== 'asc' && dir !== 'desc') {\n throw new StackQueryError(`Invalid sort direction \"${dir}\": expected \"asc\" or \"desc\".`);\n }\n return dir === 'asc' ? 'ASC' : 'DESC';\n};\n\n/**\n * Normalize a json_each row's value so one array element and one bare\n * value are walked by the same clause: an array stands for its elements,\n * anything else for itself. See docs/spec/data-model.md § Nested content\n * paths.\n */\nconst spread = (alias: string): string =>\n `CASE WHEN ${alias}.type = 'array' THEN ${alias}.value ` +\n `WHEN ${alias}.type = 'object' THEN json_array(json(${alias}.value)) ` +\n `ELSE json_array(${alias}.value) END`;\n\n/**\n * The members of a json_each row that is an object, and none for a row\n * that is not — a path descending through a scalar reaches no value rather\n * than reaching an error.\n */\nconst members = (alias: string): string =>\n `CASE WHEN ${alias}.type = 'object' THEN ${alias}.value ELSE '{}' END`;\n\n/**\n * True when some value reached by `segments` satisfies `leaf`, applied to\n * the alias holding that value. Each segment is a bound parameter matched\n * against json_each's `key`, never interpolated into a path expression, so\n * no key can be read as syntax. See docs/spec/data-model.md § Filter.\n */\nconst contentPathExists = (\n segments: string[],\n leaf: (alias: string) => string,\n params: unknown[],\n nextAlias: () => string,\n): string => {\n // The walk is a flat join list, not a subquery per segment: both SQLite\n // builds cap expression-tree depth far below the segment cap, and\n // nesting spends that budget while a join list spends the join budget\n // the cap is actually sized against.\n let key = nextAlias();\n let value = nextAlias();\n const from = [`json_each(r.content) AS ${key}`, `json_each(${spread(key)}) AS ${value}`];\n const where = [`${key}.key = ?`];\n params.push(segments[0]);\n\n for (const segment of segments.slice(1)) {\n key = nextAlias();\n from.push(`json_each(${members(value)}) AS ${key}`);\n value = nextAlias();\n from.push(`json_each(${spread(key)}) AS ${value}`);\n where.push(`${key}.key = ?`);\n params.push(segment);\n }\n\n where.push(leaf(value));\n return `EXISTS (SELECT 1 FROM ${from.join(', ')} WHERE ${where.join(' AND ')})`;\n};\n\n/**\n * A scalar filter value never matches an object or array stored at the\n * path: json_each exposes those as their JSON text, which would compare\n * equal to a string spelling the same document while every non-SQL adapter\n * compares the value itself.\n */\nconst equalsLeaf = (alias: string): string =>\n `${alias}.type NOT IN ('object', 'array') AND ${alias}.value = ?`;\n\n/** The join alias the content index is read through. */\nconst SORT_ALIAS = 'cs';\n\n/**\n * A cursor names a position in one ordering; carrying it into another\n * would silently resume somewhere arbitrary. The partition matters as\n * much as the field name — a cursor from a numeric page can't be read\n * against text values — so each ordering below accepts only the cursors\n * it can read, and rejecting the rest is what narrows the cursor to them.\n */\nconst cursorMismatch = (cursor: DecodedCursor, field: string): StackQueryError =>\n new StackQueryError(\n `Cursor sort field \"${cursor.field}\" does not match query sort field \"${field}\"`,\n );\n\nconst nativeCursor = (cursor: DecodedCursor, field: SortField) => {\n if (cursor.kind !== 'native' || cursor.field !== field) throw cursorMismatch(cursor, field);\n return cursor;\n};\n\nconst contentCursor = (cursor: DecodedCursor, field: string) => {\n if (cursor.kind === 'native' || cursor.field !== field) throw cursorMismatch(cursor, field);\n return cursor;\n};\n\n/**\n * Every condition on the records row itself — everything a query asks\n * except where in the ordering to resume, which is per-partition and gets\n * appended by the caller.\n */\nconst recordConditions = (query: StackQuery): { conditions: string[]; params: unknown[] } => {\n const conditions: string[] = [\"r.id != '_config'\"];\n const params: unknown[] = [];\n const f = query.filter ?? {};\n\n /**\n * A filter that accepts one value or a list of them, as the `IN` that\n * covers both. Written even for a single value rather than as `= ?`,\n * since SQLite plans a one-element IN identically and one form means one\n * place for the filter's placeholder count and its bindings to agree.\n */\n const inFilter = (column: string, value: string | readonly string[] | undefined): void => {\n if (value === undefined) return;\n const values = Array.isArray(value) ? value : [value as string];\n conditions.push(`r.${column} IN (${values.map(() => '?').join(',')})`);\n params.push(...values);\n };\n\n /** One side of a date range, as the open-ended comparison it is. */\n const rangeFilter = (\n column: string,\n range: { after?: Date; before?: Date } | undefined,\n ): void => {\n if (range?.after) {\n conditions.push(`r.${column} > ?`);\n params.push(range.after.getTime());\n }\n if (range?.before) {\n conditions.push(`r.${column} < ?`);\n params.push(range.before.getTime());\n }\n };\n\n if (!f.includeDeleted) {\n conditions.push('r.deleted_at IS NULL');\n }\n\n if (!f.includeUnlisted) {\n conditions.push('r.unlisted_at IS NULL');\n }\n\n inFilter('type_id', f.typeId);\n\n // Not an inFilter: parentId takes an explicit null for \"at the root\",\n // which is a different SQL predicate rather than a different value.\n if (f.parentId !== undefined) {\n if (f.parentId === null) {\n conditions.push('r.parent_id IS NULL');\n } else {\n conditions.push('r.parent_id = ?');\n params.push(f.parentId);\n }\n }\n\n inFilter('app_id', f.appId);\n inFilter('entity_id', f.entityId);\n inFilter('principal_id', f.principalId);\n\n rangeFilter('created_at', f.createdAt);\n rangeFilter('updated_at', f.updatedAt);\n\n // Every association filter below is a semi-join rather than a correlated\n // EXISTS, so the planner drives from the association side — reading the\n // matching record ids straight out of idx_assoc_kind_label /\n // idx_assoc_kind_file_id / idx_assoc_related / idx_content_index_file,\n // each of which ends with record_id and so needs no table read at all —\n // instead of scanning every record and probing for each. The work is\n // proportional to how many records match, not to how many the stack\n // holds.\n\n /**\n * The semi-join itself. `kind` is one of this module's own literals, never\n * caller text, and each clause carries its own placeholder — so the only\n * thing interpolated here is SQL this file wrote.\n */\n const hasAssociation = (kind: 'tag' | 'attachment' | 'relationship', clauses: string[]): string =>\n `r.id IN (SELECT a.record_id FROM associations a WHERE a.kind = '${kind}'` +\n clauses.map((c) => ` AND ${c}`).join('') +\n `)`;\n\n // Tag filter — record must have ALL specified tags\n if (f.tags?.length) {\n for (const tag of f.tags) {\n conditions.push(hasAssociation('tag', ['a.label = ?']));\n params.push(tag);\n }\n }\n\n // Attachment label filter\n if (f.hasAttachment) {\n conditions.push(hasAssociation('attachment', ['a.label = ?']));\n params.push(f.hasAttachment);\n }\n\n // Attachment file ID filter — find records that reference a specific file,\n // either via an attachment association or a top-level file-ref content field\n if (f.attachmentFileId) {\n conditions.push(\n `(${hasAssociation('attachment', ['a.file_id = ?'])}\n OR r.id IN (SELECT ci.record_id FROM content_index ci WHERE ci.file_id = ?))`,\n );\n params.push(f.attachmentFileId, f.attachmentFileId);\n }\n\n // Relationship filter — each clause is an optional pattern, so a bare\n // label matches every target under it and an external target with no\n // `id` matches its whole namespace (docs/spec/data-model.md § Filter).\n //\n // A record- or entity-scoped target always stores '' in related_ns\n // (see associationKeyColumns). Saying so turns idx_assoc_related's\n // (scope, ns, id) prefix into a contiguous equality run for those\n // scopes instead of leaving the planner to seek on scope alone.\n if (f.relatedTo) {\n const clauses: string[] = [];\n const target = f.relatedTo.target;\n if (f.relatedTo.label !== undefined) {\n clauses.push('a.label = ?');\n params.push(f.relatedTo.label);\n }\n if (target) {\n clauses.push('a.related_scope = ?');\n params.push(target.scope);\n if (target.scope === 'record') {\n clauses.push('a.related_ns = ?', 'a.related_id = ?', 'a.related_stack = ?');\n params.push('', target.recordId, target.stackUrl ?? '');\n } else if (target.scope === 'entity') {\n clauses.push('a.related_ns = ?', 'a.related_id = ?');\n params.push('', target.entityId);\n } else {\n clauses.push('a.related_ns = ?');\n params.push(target.ns);\n if (target.id !== undefined) {\n clauses.push('a.related_id = ?');\n params.push(target.id);\n }\n }\n }\n conditions.push(hasAssociation('relationship', clauses));\n }\n\n // Content field filters — a dot-separated path, matched element-wise\n // through arrays. A `null` value means \"no value at the path, or a value\n // that is null\" (docs/spec/data-model.md § Filter), which is the second\n // arm below: \"some value there is null\" OR \"nothing is there at all\".\n if (f.content) {\n let aliasSeq = 0;\n const nextAlias = () => `cp${aliasSeq++}`;\n for (const [key, value] of Object.entries(f.content)) {\n const segments = parseContentFilterKey(key);\n // undefined is the same absence null names — JSON drops it on the\n // way over the wire, so treating it as a value would make an\n // in-process query and its wire equivalent disagree.\n if (value === null || value === undefined) {\n const isNull = contentPathExists(segments, (a) => `${a}.value IS NULL`, params, nextAlias);\n const anyValue = contentPathExists(\n segments,\n (a) => `${a}.value IS NOT NULL`,\n params,\n nextAlias,\n );\n conditions.push(`(${isNull} OR NOT ${anyValue})`);\n } else {\n const match = contentPathExists(segments, equalsLeaf, params, nextAlias);\n params.push(value);\n conditions.push(match);\n }\n }\n }\n\n // Presence — the question an exact-match value cannot ask. Element-wise\n // like the content filter above: a path holds a value when at least one\n // non-null value is reachable at it. See docs/spec/data-model.md\n // § Filter.\n if (f.contentPresent?.length) {\n let aliasSeq = 0;\n const nextAlias = () => `pp${aliasSeq++}`;\n for (const key of f.contentPresent) {\n conditions.push(\n contentPathExists(\n parseContentFilterKey(key),\n (a) => `${a}.value IS NOT NULL`,\n params,\n nextAlias,\n ),\n );\n }\n }\n\n if (f.search) {\n const sanitized = sanitizeFts5Query(f.search);\n if (sanitized) {\n conditions.push(`r.rowid IN (SELECT rowid FROM records_fts WHERE records_fts MATCH ?)`);\n params.push(sanitized);\n } else {\n // A search that sanitizes to nothing (e.g. \"*\", punctuation-only) is\n // an honest zero-match result, not \"no filter\" — omitting the clause\n // would silently return the full table as the \"search result\".\n conditions.push('0');\n }\n }\n\n return { conditions, params };\n};\n\n/**\n * Everything ordered after the cursor's record within the partition that\n * holds a value: a later value rank, or the same rank past the cursor's\n * value and id. `op` runs the comparison the same way the ORDER BY does,\n * so one form covers both directions — in the direction where the\n * cursor's rank is the last one, the leading disjunct is simply never\n * true.\n */\nconst presentCursorCondition = (\n cursor: Extract<DecodedCursor, { kind: 'num' | 'text' }>,\n op: '>' | '<',\n params: unknown[],\n): string => {\n if (cursor.kind === 'num') {\n params.push(cursor.value, cursor.value, cursor.id);\n return (\n `(${SORT_ALIAS}.value_rank ${op} 0 OR (${SORT_ALIAS}.value_rank = 0 AND ` +\n `(${SORT_ALIAS}.num_value ${op} ? OR (${SORT_ALIAS}.num_value = ? AND ` +\n `${SORT_ALIAS}.record_id ${op} ?))))`\n );\n }\n const key = contentSortKey(cursor.value);\n params.push(key, key, cursor.value, cursor.value, cursor.id);\n return (\n `(${SORT_ALIAS}.value_rank ${op} 1 OR (${SORT_ALIAS}.value_rank = 1 AND ` +\n `(${SORT_ALIAS}.text_key ${op} ? OR (${SORT_ALIAS}.text_key = ? AND ` +\n `(${SORT_ALIAS}.text_value ${op} ? OR (${SORT_ALIAS}.text_value = ? AND ` +\n `${SORT_ALIAS}.record_id ${op} ?))))))`\n );\n};\n\nconst statement = (\n select: string,\n from: string,\n conditions: string[],\n params: unknown[],\n tail = '',\n): QueryStatement => ({\n sql: `SELECT ${select} FROM ${from} WHERE ${conditions.join(' AND ')}${tail}`,\n params,\n});\n\n/**\n * Compile a query into the statements that answer it, read in order and\n * their rows concatenated: the first that fills the page ends the read,\n * so the second is never run for a page that doesn't reach it. Each still\n * needs the row budget its `LIMIT ?` binds — see atBudget.\n */\nexport const buildQueryPlan = (query: StackQuery): QueryStatement[] => {\n const dir = sqlDirection(query);\n const op = dir === 'ASC' ? '>' : '<';\n const decoded = query.cursor ? decodeCursor(query.cursor) : null;\n const contentField = query.sort?.contentField;\n\n if (contentField === undefined) {\n const { conditions, params } = recordConditions(query);\n const col = getSortColumn(getSortField(query));\n if (decoded) {\n const cursor = nativeCursor(decoded, getSortField(query));\n conditions.push(`(r.${col} ${op} ? OR (r.${col} = ? AND r.id ${op} ?))`);\n params.push(cursor.value, cursor.value, cursor.id);\n }\n return [\n statement(\n 'r.*',\n 'records r',\n conditions,\n params,\n ` ORDER BY r.${col} ${dir}, r.id ${dir} LIMIT ?`,\n ),\n ];\n }\n\n const cursor = decoded ? contentCursor(decoded, contentField) : null;\n const pages: QueryStatement[] = [];\n\n // Records holding a value at the field, in that value's order. A cursor\n // sitting in the absent partition has already passed every one of them.\n if (cursor?.kind !== 'absent') {\n const { conditions, params } = recordConditions(query);\n const from = `content_index ${SORT_ALIAS} JOIN records r ON r.id = ${SORT_ALIAS}.record_id`;\n conditions.push(`${SORT_ALIAS}.field = ?`);\n params.push(contentField);\n if (cursor) conditions.push(presentCursorCondition(cursor, op, params));\n // Ordered exactly as idx_content_index_sort stores it, so the page is\n // an ordered walk of the index rather than a sort of the matches.\n const order =\n `${SORT_ALIAS}.value_rank ${dir}, ${SORT_ALIAS}.num_value ${dir}, ` +\n `${SORT_ALIAS}.text_key ${dir}, ${SORT_ALIAS}.text_value ${dir}, ` +\n `${SORT_ALIAS}.record_id ${dir}`;\n pages.push(statement('r.*', from, conditions, params, ` ORDER BY ${order} LIMIT ?`));\n }\n\n // Records holding nothing there, which trail the others whichever way\n // the sort runs (docs/spec/data-model.md § Sorting by a content field).\n {\n const { conditions, params } = recordConditions(query);\n conditions.push(\n `NOT EXISTS (SELECT 1 FROM content_index ${SORT_ALIAS} ` +\n `WHERE ${SORT_ALIAS}.record_id = r.id AND ${SORT_ALIAS}.field = ?)`,\n );\n params.push(contentField);\n if (cursor?.kind === 'absent') {\n conditions.push(`r.id ${op} ?`);\n params.push(cursor.id);\n }\n pages.push(statement('r.*', 'records r', conditions, params, ` ORDER BY r.id ${dir} LIMIT ?`));\n }\n\n return pages;\n};\n","/**\n * Row <-> domain object mappers shared by every SQLite-backed record\n * adapter. Column names and JSON-encoding choices are the storage\n * contract; keeping one copy means the adapters can't drift on them.\n */\n\nimport type {\n StackRecord,\n StackType,\n RecordVersion,\n Association,\n RelationshipTarget,\n} from '@haverstack/core';\n\nexport const toMs = (d: Date): number => d.getTime();\nexport const fromMs = (ms: number): Date => new Date(ms);\n\nexport const rowToRecord = (\n row: Record<string, unknown>,\n associations: Association[],\n): StackRecord => {\n const record: StackRecord = {\n id: row.id as string,\n typeId: row.type_id as string,\n createdAt: fromMs(row.created_at as number),\n updatedAt: fromMs(row.updated_at as number),\n content: JSON.parse(row.content as string),\n version: row.version as number,\n };\n // Presence, never truthiness: SQL NULL is the only spelling of an absent\n // field, so the empty string and the epoch are values like any other.\n // The query predicates beside this read `IS NULL`, and a mapper that\n // disagreed would let a record answer one way to get() and another to\n // the filter that should have found it.\n if (row.parent_id != null) record.parentId = row.parent_id as string;\n if (row.entity_id != null) record.entityId = row.entity_id as string;\n if (row.app_id != null) record.appId = row.app_id as string;\n if (row.principal_id != null) record.principalId = row.principal_id as string;\n if (row.updated_by != null) record.updatedBy = row.updated_by as string;\n if (row.updated_via != null) record.updatedVia = row.updated_via as string;\n if (row.deleted_at != null) record.deletedAt = fromMs(row.deleted_at as number);\n if (row.unlisted_at != null) record.unlistedAt = fromMs(row.unlisted_at as number);\n if (row.permissions != null) record.permissions = JSON.parse(row.permissions as string);\n if (associations.length) record.associations = associations;\n return record;\n};\n\nexport const rowToAssociation = (row: Record<string, unknown>): Association => {\n if (row.kind === 'tag') {\n return { kind: 'tag', label: row.label as string };\n }\n if (row.kind === 'attachment') {\n return {\n kind: 'attachment',\n label: row.label as string,\n fileId: row.file_id as string,\n };\n }\n // relationship\n return {\n kind: 'relationship',\n label: row.label as string,\n target: rowToTarget(row),\n };\n};\n\n/**\n * The five columns that identify an association, in the order every\n * INSERT and DELETE below binds them. One helper because the two must\n * agree exactly — a dissociate that bound them differently would delete\n * nothing and report success.\n */\nexport const associationKeyColumns = (a: Association): [string, string, string, string, string] => {\n if (a.kind === 'attachment') return [a.fileId, '', '', '', ''];\n if (a.kind !== 'relationship') return ['', '', '', '', ''];\n const t = a.target;\n if (t.scope === 'entity') return ['', 'entity', t.entityId, '', ''];\n if (t.scope === 'external') return ['', 'external', t.id, t.ns, ''];\n return ['', 'record', t.recordId, '', t.stackUrl ?? ''];\n};\n\nconst rowToTarget = (row: Record<string, unknown>): RelationshipTarget => {\n const id = row.related_id as string;\n if (row.related_scope === 'entity') return { scope: 'entity', entityId: id };\n if (row.related_scope === 'external') {\n return { scope: 'external', ns: row.related_ns as string, id };\n }\n const stackUrl = row.related_stack as string;\n return { scope: 'record', recordId: id, ...(stackUrl && { stackUrl }) };\n};\n\nexport const rowToType = (row: Record<string, unknown>): StackType => {\n const t: StackType = {\n id: row.id as string,\n baseId: row.base_id as string,\n version: row.version as number,\n name: row.name as string,\n schema: JSON.parse(row.schema as string),\n schemaHash: row.schema_hash as string,\n createdAt: fromMs(row.created_at as number),\n };\n if (row.migrates_from) t.migratesFrom = row.migrates_from as string;\n return t;\n};\n\nexport const rowToVersion = (row: Record<string, unknown>): RecordVersion => {\n const v: RecordVersion = {\n version: row.version as number,\n typeId: row.type_id as string,\n content: JSON.parse(row.content as string),\n updatedAt: fromMs(row.updated_at as number),\n };\n if (row.entity_id != null) v.entityId = row.entity_id as string;\n if (row.updated_by != null) v.updatedBy = row.updated_by as string;\n if (row.updated_via != null) v.updatedVia = row.updated_via as string;\n // Read for presence, not truthiness: the stored 'null' is the root, and\n // only a SQL NULL is a snapshot that claimed no container at all.\n if (row.parent_id != null) v.parentId = row.parent_id as string;\n if (row.associations != null) v.associations = JSON.parse(row.associations as string);\n if (row.permissions != null) v.permissions = JSON.parse(row.permissions as string);\n return v;\n};\n","/**\n * Normalizes a SQLite binding's call convention (array-bind-then-step,\n * spread-args run/get/all, cursor-returning exec) behind one interface,\n * so the actual CRUD/query/version/type/association/token logic can live\n * once in this package instead of being re-typed per engine. Each adapter\n * package provides a thin SqlExecutor implementation over its own\n * database handle.\n *\n * Deliberately synchronous: every binding this targets executes queries\n * in-process without yielding, and an async interface would force the\n * shared logic's transaction sequences to interleave.\n */\nexport interface SqlExecutor {\n /** Run DDL, pragmas, or any statement(s) with no bound params and no results needed. */\n exec(sql: string): void;\n /** Run a single parameterized statement. Returns the number of rows affected (INSERT/UPDATE/DELETE). */\n run(sql: string, params?: readonly unknown[]): number;\n /** Run a parameterized statement and return the first result row, or undefined. */\n get<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T | undefined;\n /** Run a parameterized statement and return all result rows. */\n all<T = Record<string, unknown>>(sql: string, params?: readonly unknown[]): T[];\n /**\n * Run `fn` atomically: every statement it issues commits together, or\n * none do if it throws. `fn` must be synchronous and call back into\n * this executor only — not every engine's transaction primitive can\n * straddle a suspended call. A binding with a real multi-statement\n * transaction (BEGIN/COMMIT/ROLLBACK) implements this with one; a\n * binding whose transaction primitive is itself a callback wrapper\n * (e.g. a Durable Object's storage.transactionSync) can pass `fn`\n * straight through to it.\n */\n transaction<T>(fn: () => T): T;\n}\n\n/** SQLite reports FK violations with this exact message; verify it holds when adding an engine. */\nexport const isForeignKeyViolation = (err: unknown): boolean =>\n err instanceof Error && err.message.includes('FOREIGN KEY constraint failed');\n\n/** SQLite reports a PRIMARY KEY/UNIQUE collision with this exact message. */\nexport const isUniqueConstraintViolation = (err: unknown): boolean =>\n err instanceof Error && err.message.includes('UNIQUE constraint failed');\n","import type { SqlExecutor } from './executor.js';\n\n/** timezone is optional passthrough app metadata — no default. */\nexport type StackConfig = { entityId: string; timezone: string | undefined };\n\n/** The one place the singleton record's id is spelled. */\nconst CONFIG_ROW_SQL = `SELECT content FROM records WHERE id = '_config'`;\n\n/**\n * Inserts the singleton _config@1 record and returns what it wrote, so a\n * caller that has just created a database reaches the same StackConfig an\n * existing one yields without a read-back. Only valid on a freshly-created\n * database.\n */\nexport const insertConfigRecord = (\n exec: SqlExecutor,\n entityId: string,\n timezone: string | undefined,\n): StackConfig => {\n const now = Date.now();\n exec.run(\n `INSERT INTO records (id, type_id, created_at, updated_at, content, version)\n VALUES ('_config', '_config@1', ?, ?, ?, 1)`,\n [now, now, JSON.stringify({ entityId, timezone })],\n );\n return { entityId, timezone };\n};\n\n/**\n * Reads the singleton _config@1 record, or null if this database has none.\n * Null is the signal an engine with no initialize()/open() split uses to\n * decide between reattaching and creating.\n */\nexport const tryReadStackConfig = (exec: SqlExecutor): StackConfig | null => {\n const row = exec.get<{ content: string }>(CONFIG_ROW_SQL);\n if (!row) return null;\n const content = JSON.parse(row.content) as { entityId: string; timezone?: string };\n return { entityId: content.entityId, timezone: content.timezone };\n};\n\n/** Reads the singleton _config@1 record. Throws if the database is missing it. */\nexport const readStackConfig = (exec: SqlExecutor): StackConfig => {\n const config = tryReadStackConfig(exec);\n if (!config) throw new Error('Stack database is missing its config record.');\n return config;\n};\n","/**\n * The actual StackRecordAdapter logic (minus lifecycle: initialize/open/\n * close/flush stay per-engine, since schema setup, pragmas, locking, and\n * durability differ there). Every CRUD/query/version/type/association\n * operation lives here exactly once, parametrized over a SqlExecutor\n * (which normalizes each engine's call conventions). Concrete adapters\n * construct one of these and delegate their StackRecordAdapter methods\n * to it — see record-adapter-sqlite.\n */\n\nimport {\n StackConflictError,\n StackVersionConflictError,\n StackNotFoundError,\n StackQueryError,\n applyMergePatch,\n} from '@haverstack/core';\nimport type {\n StackRecord,\n StackType,\n TypeId,\n FileId,\n RecordVersion,\n RecordChanges,\n StackQuery,\n QueryResult,\n Association,\n ActorOptions,\n ExpectedVersionOptions,\n} from '@haverstack/core';\nimport type { SqlExecutor } from './executor.js';\nimport { isForeignKeyViolation, isUniqueConstraintViolation } from './executor.js';\nimport { buildQueryPlan, atBudget } from './query.js';\nimport { fts5Strategy } from './fts5.js';\nimport {\n rowToRecord,\n rowToAssociation,\n rowToType,\n rowToVersion,\n toMs,\n associationKeyColumns,\n} from './mappers.js';\nimport { makeCursor } from './cursor.js';\nimport { contentSortEntry } from '@haverstack/core/adapter';\nimport type { ScalarFieldKind } from '@haverstack/core';\n\n/**\n * Run a query statement, restating an engine parse error as the wire\n * taxonomy's `bad_request` rather than letting it escape as a raw engine\n * error (which a server has no code to map, so it becomes a 500).\n *\n * Scoped to the one filter that carries a query language: `filter.search`\n * is FTS5 source text, and sanitizeFts5Query() repairs the common shapes\n * but claims no completeness against the grammar. Every other clause here\n * is built from parameters, so a parse error in one is this module's bug —\n * rethrown untouched, where it belongs.\n */\nconst asStackQueryError = <T>(query: StackQuery, run: () => T): T => {\n try {\n return run();\n } catch (err) {\n if (!query.filter?.search) throw err;\n throw new StackQueryError(\n `Search text could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n};\n\n/**\n * One spelling of the optimistic-concurrency failure, so the message a\n * caller sees never depends on which of the three places noticed it.\n */\nconst versionConflict = (id: string, expected: number, actual: number): StackVersionConflictError =>\n new StackVersionConflictError(\n `Record \"${id}\" is at version ${actual}, expected ${expected}`,\n id,\n expected,\n actual,\n );\n\n/**\n * Every `versions` column beyond the (record_id, version) key, and the\n * values for them in the same order — one list, so the INSERT that writes a\n * snapshot and the UPDATE that replaces one can't drift apart on which\n * columns a snapshot is made of.\n */\nconst VERSION_COLUMNS = [\n 'type_id',\n 'content',\n 'updated_at',\n 'entity_id',\n 'updated_by',\n 'updated_via',\n 'parent_id',\n 'associations',\n 'permissions',\n] as const;\n\nconst versionRowValues = (version: RecordVersion): unknown[] => [\n version.typeId,\n JSON.stringify(version.content),\n toMs(version.updatedAt),\n version.entityId ?? null,\n version.updatedBy ?? null,\n version.updatedVia ?? null,\n version.parentId ?? null,\n version.associations ? JSON.stringify(version.associations) : null,\n version.permissions ? JSON.stringify(version.permissions) : null,\n];\n\nexport type SharedSqlRecordLogicDeps = {\n exec: SqlExecutor;\n};\n\n/**\n * Top-level scalar fields, by name and declared kind — what content_index\n * covers. Arrays and objects are left out: a value inside one has no\n * single position to order its record by, and no file reference the\n * attachment filter can see.\n */\nconst indexedFieldKinds = (\n schema: Record<string, { kind?: string }>,\n): Map<string, ScalarFieldKind> => {\n const kinds = new Map<string, ScalarFieldKind>();\n for (const [field, def] of Object.entries(schema)) {\n if (!def.kind || def.kind === 'array' || def.kind === 'object') continue;\n kinds.set(field, def.kind as ScalarFieldKind);\n }\n return kinds;\n};\n\nexport class SharedSqlRecordLogic {\n /**\n * Per-typeId cache of the fields content_index covers and their declared\n * kinds, so syncContentIndex() doesn't hit the `types` table and\n * re-parse schema JSON on every write. Populated eagerly in saveType()\n * and lazily via getIndexedFields().\n */\n private readonly indexedFieldsByType = new Map<string, Map<string, ScalarFieldKind>>();\n\n constructor(private readonly deps: SharedSqlRecordLogicDeps) {}\n\n private get exec(): SqlExecutor {\n return this.deps.exec;\n }\n\n /**\n * Precondition check for a mutation that has already read the record —\n * either because it can't fold the check into its own statement\n * (hardDeleteRecord: children reference the row, so the DELETE can't\n * carry it), or because it has to settle the precondition *before*\n * fts5Strategy.remove() runs, which needs the records row still holding\n * the old content. In the latter case versionedUpdate() re-checks it\n * inside the statement, and that is the enforcement; this is what lets\n * the work before it be skipped.\n */\n private checkExpectedVersion(record: StackRecord, expectedVersion: number | undefined): void {\n if (expectedVersion === undefined || record.version === expectedVersion) return;\n throw versionConflict(record.id, expectedVersion, record.version);\n }\n\n /**\n * Called after a version-gated statement affected zero rows.\n * Distinguishes \"record doesn't exist\" (StackNotFoundError) from \"it\n * exists but isn't at expectedVersion\" (StackVersionConflictError, with\n * the actual current version for the caller to act on).\n */\n private throwVersionConflict(id: string, expectedVersion: number | undefined): never {\n const row = this.exec.get<{ version: number }>('SELECT version FROM records WHERE id = ?', [\n id,\n ]);\n if (!row) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n throw versionConflict(id, expectedVersion as number, row.version);\n }\n\n /**\n * The one shape every mutating UPDATE in this class has: whatever columns\n * the caller is changing, then the version bump and the actor/timestamp\n * stamp that every mutation owes, gated on the opt-in `expectedVersion`\n * precondition and failing loudly when nothing matched.\n *\n * The guard rides in the WHERE clause even where the caller has already\n * checked the version against a record it read: that read is outside this\n * statement, so a writer slipping in between the two is caught here\n * rather than silently overwritten.\n */\n private versionedUpdate(\n id: string,\n sets: string[],\n values: unknown[],\n opts: ExpectedVersionOptions & ActorOptions,\n now = toMs(new Date()),\n ): void {\n const guarded = opts.expectedVersion !== undefined;\n const changed = this.exec.run(\n `UPDATE records SET ${[...sets, 'version = version + 1', 'updated_at = ?', 'updated_by = ?', 'updated_via = ?'].join(', ')}` +\n ` WHERE id = ?${guarded ? ' AND version = ?' : ''}`,\n [\n ...values,\n now,\n opts.updatedBy ?? null,\n opts.updatedVia ?? null,\n id,\n ...(guarded ? [opts.expectedVersion] : []),\n ],\n );\n if (changed === 0) this.throwVersionConflict(id, opts.expectedVersion);\n }\n\n /**\n * Read a record back after its own mutation committed, for the caller to\n * return. Its absence is not a \"not found\" for the caller to handle — the\n * mutation just succeeded against it — so it fails as the invariant\n * breach it would be.\n *\n * Synchronous, via readRecord() rather than getRecord(), so the read\n * cannot be separated from the commit by anything: an async caller\n * returning this still hands back a record read in the same tick its\n * transaction committed. See readRecord() for why that matters.\n */\n private reread(id: string, verb: string): StackRecord {\n const updated = this.readRecord(id);\n if (!updated) throw new Error(`Record not found after ${verb}: \"${id}\"`);\n return updated;\n }\n\n // -------------------------------------------------------\n // Records\n // -------------------------------------------------------\n\n /**\n * A duplicate id hits the `records` PK — mapped to StackConflictError\n * instead of surfacing the raw engine exception, mirroring saveVersion's\n * collision mapping below.\n */\n async createRecord(record: StackRecord): Promise<StackRecord> {\n try {\n this.exec.run(\n `INSERT INTO records\n (id, type_id, created_at, updated_at, content, version,\n parent_id, entity_id, app_id, principal_id, updated_by, updated_via,\n deleted_at, unlisted_at, permissions)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n record.id,\n record.typeId,\n toMs(record.createdAt),\n toMs(record.updatedAt),\n JSON.stringify(record.content),\n record.version,\n record.parentId ?? null,\n record.entityId ?? null,\n record.appId ?? null,\n record.principalId ?? null,\n record.updatedBy ?? null,\n record.updatedVia ?? null,\n record.deletedAt ? toMs(record.deletedAt) : null,\n record.unlistedAt ? toMs(record.unlistedAt) : null,\n record.permissions ? JSON.stringify(record.permissions) : null,\n ],\n );\n } catch (err) {\n if (isUniqueConstraintViolation(err)) {\n throw new StackConflictError(`Record already exists: \"${record.id}\"`);\n }\n throw err;\n }\n\n if (record.associations?.length) {\n this.insertAssociations(record.id, record.associations);\n }\n\n fts5Strategy.insert(this.exec, record.id, JSON.stringify(record.content));\n this.syncContentIndex(record.id, record.typeId, record.content);\n return record;\n }\n\n async getRecord(id: string): Promise<StackRecord | null> {\n return this.readRecord(id);\n }\n\n /**\n * The synchronous read behind getRecord(). Callers inside exec.transaction()\n * use this one: an `await` inside that callback yields the microtask queue\n * mid-transaction, and the next operation to run would try to open one of\n * its own — transaction() requires a synchronous callback for exactly this\n * reason (see SqlExecutor.transaction).\n *\n * The same synchrony is what lets the post-commit reads below report the\n * version their own mutation produced: reread() calls this directly, so\n * nothing interleaves between the commit and the read even though the\n * method returning it is async. A backend that made these reads genuinely\n * asynchronous would open that window, and a concurrent mutation could be\n * reported under this one's verb.\n */\n private readRecord(id: string): StackRecord | null {\n const row = this.exec.get<Record<string, unknown>>('SELECT * FROM records WHERE id = ?', [id]);\n if (!row) return null;\n const associations = this.getAssociationsForRecord(id);\n return rowToRecord(row, associations);\n }\n\n /**\n * Apply a change set in one transaction: one UPDATE over the record row\n * with only the columns the change set names, the association set\n * replaced when it carries one, and the snapshot written alongside — so\n * one call is one version whatever it moved.\n *\n * The expectedVersion check is standalone rather than folded into the\n * UPDATE alone, because a content change needs fts.remove() to run\n * *before* the records-table content changes. The guard is still in the\n * UPDATE's WHERE, so a writer that slipped in between the read and the\n * write is caught there rather than overwriting.\n */\n async mutateRecord(\n id: string,\n changes: RecordChanges,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n const existing = await this.getRecord(id);\n if (!existing) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n const merged = changes.contentPatch\n ? applyMergePatch(existing.content, changes.contentPatch)\n : undefined;\n\n // Assembled rather than written out per aspect: every one of these is\n // the same column-and-value pair on one row, and a fixed statement per\n // combination would be 2^5 of them.\n const sets: string[] = [];\n const values: unknown[] = [];\n if (merged !== undefined) {\n sets.push('content = ?');\n values.push(JSON.stringify(merged));\n }\n if (changes.parentId !== undefined) {\n sets.push('parent_id = ?');\n values.push(changes.parentId);\n }\n if (changes.permissions !== undefined) {\n sets.push('permissions = ?');\n values.push(changes.permissions.length ? JSON.stringify(changes.permissions) : null);\n }\n\n const now = toMs(new Date());\n if (changes.unlisted !== undefined) {\n sets.push('unlisted_at = ?');\n // Stamped fresh because this key is only ever present on a\n // transition — Stack narrows a change set to the aspects that\n // actually moved before it reaches an adapter.\n values.push(changes.unlisted ? now : null);\n }\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n if (merged !== undefined) fts5Strategy.remove(this.exec, id);\n\n this.versionedUpdate(id, sets, values, opts, now);\n\n if (changes.associations !== undefined) {\n this.replaceAssociations(id, changes.associations);\n }\n\n if (merged !== undefined) {\n fts5Strategy.insert(this.exec, id, JSON.stringify(merged));\n this.syncContentIndex(id, existing.typeId, merged);\n }\n });\n\n return this.reread(id, 'mutateRecord');\n }\n\n async deleteRecord(\n id: string,\n opts: {\n hard?: boolean;\n expectedVersion?: number;\n snapshot?: RecordVersion;\n } & ActorOptions = {},\n ): Promise<StackRecord | null> {\n if (opts.hard) {\n return this.exec.transaction(() => this.hardDeleteRecord(id, opts.expectedVersion));\n }\n\n // One timestamp for both columns: a soft delete is a single event, and\n // two `new Date()` calls can straddle a millisecond boundary and leave\n // deleted_at and updated_at disagreeing about when it happened.\n const now = toMs(new Date());\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.versionedUpdate(id, ['deleted_at = ?'], [now], opts, now);\n });\n\n return this.reread(id, 'deleteRecord');\n }\n\n /**\n * Deletes a record's FTS entry, associations, versions, file-refs, sort\n * index rows, and row, returning the record as it stood — the last copy that will ever\n * exist, read here so that nothing can overtake it between the read and\n * the deletes. Null when there was no such record. No write() call —\n * callers batch it. expectedVersion is checked first so a lost CAS race\n * leaves nothing touched (children reference the row, so the check can't\n * fold into the final DELETE).\n */\n private hardDeleteRecord(id: string, expectedVersion?: number): StackRecord | null {\n const purged = this.readRecord(id);\n if (!purged) {\n // A CAS against a record that isn't there is a failed precondition,\n // not the \"nothing to delete\" that an unconditional hard delete\n // reports by returning null.\n if (expectedVersion !== undefined) throw new StackNotFoundError(`Record not found: \"${id}\"`);\n return null;\n }\n this.checkExpectedVersion(purged, expectedVersion);\n fts5Strategy.remove(this.exec, id);\n this.exec.run('DELETE FROM associations WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM versions WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM content_index WHERE record_id = ?', [id]);\n this.exec.run('DELETE FROM records WHERE id = ?', [id]);\n return purged;\n }\n\n async undeleteRecord(\n id: string,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.versionedUpdate(id, ['deleted_at = NULL'], [], opts);\n });\n\n return this.reread(id, 'undelete');\n }\n\n async restoreVersion(\n id: string,\n version: number,\n opts: {\n expectedVersion?: number;\n snapshot?: RecordVersion;\n restoreAssociations?: boolean;\n } & ActorOptions = {},\n ): Promise<StackRecord> {\n const existing = await this.getRecord(id);\n if (!existing) throw new Error(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n const target = await this.getVersion(id, version);\n if (!target) throw new Error(`Version not found: ${id}@${version}`);\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.rewriteContent(\n id,\n target.typeId,\n target.content,\n opts,\n ['parent_id = ?'],\n [target.parentId ?? null],\n );\n // Whether a restore rolls associations back at all is decided where\n // the record's meaning is known; the snapshot's list is the only one\n // that ever lands here. See StackRecordAdapter.restoreVersion().\n const applied = opts.restoreAssociations === false ? undefined : target.associations;\n if (applied !== undefined) this.replaceAssociations(id, applied);\n });\n\n return this.reread(id, 'restoreVersion');\n }\n\n async commitMigration(\n id: string,\n toTypeId: TypeId,\n content: Record<string, unknown>,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n // Checked against a read record first, rather than left to the\n // UPDATE's WHERE clause alone: fts5Strategy.remove() has to run before\n // the content changes, so the precondition has to settle before that\n // work starts. rewriteContent()'s UPDATE still carries the guard, so a\n // writer slipping in between the two is caught rather than overwritten\n // — same shape as mutateRecord() and restoreVersion().\n const existing = await this.getRecord(id);\n if (!existing) throw new Error(`Record not found: \"${id}\"`);\n this.checkExpectedVersion(existing, opts.expectedVersion);\n\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(id, opts.snapshot);\n this.rewriteContent(id, toTypeId, content, opts);\n });\n\n return this.reread(id, 'commitMigration');\n }\n\n /**\n * Replace a record's type and content wholesale — what restoreVersion and\n * commitMigration each do, differing only in where the content came from\n * and whether the container moves with it.\n *\n * The order is the constraint: fts5Strategy.remove() has to read the old\n * content off the records row, so it runs before the UPDATE, and the\n * re-index runs after. Every caller must already sit inside\n * exec.transaction() — a failure between the two halves would otherwise\n * leave the record unindexed.\n */\n private rewriteContent(\n id: string,\n typeId: TypeId,\n content: Record<string, unknown>,\n opts: ExpectedVersionOptions & ActorOptions,\n extraSets: string[] = [],\n extraValues: unknown[] = [],\n ): void {\n const json = JSON.stringify(content);\n fts5Strategy.remove(this.exec, id);\n this.versionedUpdate(\n id,\n ['type_id = ?', 'content = ?', ...extraSets],\n [typeId, json, ...extraValues],\n opts,\n );\n fts5Strategy.insert(this.exec, id, json);\n this.syncContentIndex(id, typeId, content);\n }\n\n async queryRecords(query: StackQuery): Promise<QueryResult> {\n const limit = query.limit ?? 50;\n // One extra row, to learn whether a further page follows.\n const fetch = limit + 1;\n\n // A content-field sort answers from two statements, the records that\n // hold a value at the field and then the records that hold none. They\n // read in order, each asking only for the rows the ones before it left\n // of the page, and the second is skipped once the first has filled it —\n // the common case, since a page rarely straddles the boundary.\n const rows: Record<string, unknown>[] = [];\n for (const page of buildQueryPlan(query)) {\n const budget = fetch - rows.length;\n if (budget <= 0) break;\n const statement = atBudget(page, budget);\n rows.push(\n ...asStackQueryError(query, () =>\n this.exec.all<Record<string, unknown>>(statement.sql, statement.params),\n ),\n );\n }\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n\n const records = page.map((row) => {\n const associations = this.getAssociationsForRecord(row.id as string);\n return rowToRecord(row, associations);\n });\n\n const lastRecord = records[records.length - 1];\n const cursor =\n hasMore && lastRecord\n ? makeCursor(lastRecord, query.sort, (record, field) => this.sortFieldKind(record, field))\n : null;\n\n return { records, cursor };\n }\n\n /**\n * Atomically verify fileId is unreferenced, then hard-delete its\n * metadata records across every typeId in `metadataTypeIds` (see\n * deleteUnreferencedAttachmentRecords on the adapter contract). A real\n * SQL transaction of synchronous calls — no `await` between the check\n * and the deletes, so nothing interleaves.\n */\n async deleteUnreferencedAttachmentRecords(\n fileId: FileId,\n metadataTypeIds: TypeId[],\n ): Promise<StackRecord[]> {\n return this.exec.transaction(() => {\n const referenced = this.exec.all<{ found: number }>(\n `SELECT 1 as found FROM associations WHERE kind = 'attachment' AND file_id = ?\n UNION ALL\n SELECT 1 FROM content_index WHERE file_id = ?\n LIMIT 1`,\n [fileId, fileId],\n );\n if (referenced.length) {\n throw new StackConflictError('Attachment is still referenced by one or more records');\n }\n\n // An empty family still owes the caller the reference check above —\n // the conflict is a fact about the file, not about which metadata\n // types happen to be defined.\n if (metadataTypeIds.length === 0) return [];\n\n const placeholders = metadataTypeIds.map(() => '?').join(', ');\n const metaRows = this.exec.all<{ id: string }>(\n `SELECT id FROM records\n WHERE type_id IN (${placeholders}) AND json_extract(content, '$.fileId') = ?`,\n [...metadataTypeIds, fileId],\n );\n const deleted: StackRecord[] = [];\n for (const row of metaRows) {\n const purged = this.hardDeleteRecord(row.id);\n if (purged) deleted.push(purged);\n }\n\n return deleted;\n });\n }\n\n // -------------------------------------------------------\n // Versions\n // -------------------------------------------------------\n\n async getVersions(id: string): Promise<RecordVersion[]> {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM versions WHERE record_id = ? ORDER BY version DESC',\n [id],\n );\n return rows.map(rowToVersion);\n }\n\n async getVersion(id: string, version: number): Promise<RecordVersion | null> {\n const row = this.exec.get<Record<string, unknown>>(\n 'SELECT * FROM versions WHERE record_id = ? AND version = ?',\n [id, version],\n );\n return row ? rowToVersion(row) : null;\n }\n\n /**\n * A (record_id, version) collision is rejected loudly via the UNIQUE\n * constraint, mapped to StackConflictError — never a silently discarded\n * snapshot leaving a hole in rollback history. See\n * docs/spec/versioning.md § Optimistic concurrency (`ifVersion`).\n */\n private insertVersionRow(id: string, version: RecordVersion): void {\n try {\n this.exec.run(\n `INSERT INTO versions\n (record_id, version, ${VERSION_COLUMNS.join(', ')})\n VALUES (?, ?, ${VERSION_COLUMNS.map(() => '?').join(', ')})`,\n [id, version.version, ...versionRowValues(version)],\n );\n } catch (err) {\n if (isUniqueConstraintViolation(err)) {\n throw new StackConflictError(\n `Version ${version.version} already exists for record \"${id}\" — a concurrent ` +\n `writer raced past this version. Use ifVersion to detect this before it happens.`,\n );\n }\n throw err;\n }\n }\n\n /**\n * Replaces every column insertVersionRow writes — structurally, off the\n * same VERSION_COLUMNS list, because a column left out here would keep\n * the replaced row's value and surface later as a restore putting back\n * something the snapshot never said.\n */\n private overwriteVersionRow(id: string, version: RecordVersion): void {\n this.exec.run(\n `UPDATE versions\n SET ${VERSION_COLUMNS.map((c) => `${c} = ?`).join(', ')}\n WHERE record_id = ? AND version = ?`,\n [...versionRowValues(version), id, version.version],\n );\n }\n\n /**\n * Standalone snapshot write for tooling and tests — loud on any\n * collision, since nothing here is about to bump the version. Mutating\n * methods take a `snapshot` option instead; see snapshotBeforeMutation.\n */\n async saveVersion(id: string, version: RecordVersion): Promise<void> {\n this.insertVersionRow(id, version);\n }\n\n /**\n * The snapshot half of a mutating method's atomic snapshot-then-mutate\n * transaction. A collision is a racing-writer conflict, except an orphan\n * row at the record's *current* version — recognized by version number\n * alone, never content — which is overwritten so the interrupted write\n * can complete. See docs/spec/versioning.md § Snapshot atomicity.\n */\n private snapshotBeforeMutation(id: string, version: RecordVersion): void {\n try {\n this.insertVersionRow(id, version);\n } catch (err) {\n if (!(err instanceof StackConflictError)) throw err;\n\n const row = this.exec.get<{ version: number }>('SELECT version FROM records WHERE id = ?', [\n id,\n ]);\n if (!row || row.version !== version.version) throw err;\n\n this.overwriteVersionRow(id, version);\n }\n }\n\n // -------------------------------------------------------\n // Types\n // -------------------------------------------------------\n\n async saveType(type: StackType): Promise<void> {\n this.exec.run(\n `INSERT OR REPLACE INTO types\n (id, base_id, version, name, schema, schema_hash, migrates_from, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n type.id,\n type.baseId,\n type.version,\n type.name,\n JSON.stringify(type.schema),\n type.schemaHash,\n type.migratesFrom ?? null,\n toMs(type.createdAt),\n ],\n );\n const schema = type.schema as Record<string, { kind?: string }>;\n this.indexedFieldsByType.set(type.id, indexedFieldKinds(schema));\n }\n\n async getType(id: TypeId): Promise<StackType | null> {\n const row = this.exec.get<Record<string, unknown>>('SELECT * FROM types WHERE id = ?', [id]);\n return row ? rowToType(row) : null;\n }\n\n async listTypes(): Promise<StackType[]> {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM types ORDER BY base_id, version',\n );\n return rows.map(rowToType);\n }\n\n // -------------------------------------------------------\n // Associations\n // -------------------------------------------------------\n\n async associate(\n recordId: string,\n association: Association,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(recordId, opts.snapshot);\n // Bump (and CAS-check) first, before the associations-table write, so\n // a lost race never partially applies.\n this.versionedUpdate(recordId, [], [], opts);\n this.insertAssociations(recordId, [association]);\n });\n\n return this.reread(recordId, 'associate');\n }\n\n async dissociate(\n recordId: string,\n association: Association,\n opts: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions = {},\n ): Promise<StackRecord> {\n this.exec.transaction(() => {\n if (opts.snapshot) this.snapshotBeforeMutation(recordId, opts.snapshot);\n this.versionedUpdate(recordId, [], [], opts);\n this.exec.run(\n `DELETE FROM associations\n WHERE record_id = ?\n AND kind = ?\n AND label = ?\n AND file_id = ?\n AND related_scope = ?\n AND related_id = ?\n AND related_ns = ?\n AND related_stack = ?`,\n [recordId, association.kind, association.label, ...associationKeyColumns(association)],\n );\n });\n\n return this.reread(recordId, 'dissociate');\n }\n\n /**\n * Swap a record's association set for `associations` wholesale — the\n * \"replace, don't merge\" semantics a change set's association list and a\n * version snapshot's both carry. Caller-transactional, like every write\n * below.\n */\n private replaceAssociations(recordId: string, associations: Association[]): void {\n this.exec.run('DELETE FROM associations WHERE record_id = ?', [recordId]);\n if (associations.length) this.insertAssociations(recordId, associations);\n }\n\n /**\n * FK enforcement (PRAGMA_FOREIGN_KEYS_ON) means inserting an\n * association against a record that doesn't exist throws — mapped\n * here to StackNotFoundError so associate() on a nonexistent record\n * fails loudly instead of silently creating an orphan row.\n */\n private insertAssociations(recordId: string, associations: Association[]): void {\n for (const assoc of associations) {\n try {\n this.exec.run(\n `INSERT OR IGNORE INTO associations\n (record_id, kind, label, file_id, related_scope, related_id, related_ns, related_stack)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n [recordId, assoc.kind, assoc.label, ...associationKeyColumns(assoc)],\n );\n } catch (err) {\n if (isForeignKeyViolation(err)) {\n throw new StackNotFoundError(`Record not found: \"${recordId}\"`);\n }\n throw err;\n }\n }\n }\n\n private getAssociationsForRecord(recordId: string): Association[] {\n const rows = this.exec.all<Record<string, unknown>>(\n 'SELECT * FROM associations WHERE record_id = ?',\n [recordId],\n );\n return rows.map(rowToAssociation);\n }\n\n /**\n * The fields content_index covers for typeId, from the in-memory cache\n * — falling back to a `types` lookup (and populating the cache) only for\n * a typeId this process hasn't seen via saveType() yet, e.g. right after\n * open().\n */\n private getIndexedFields(typeId: string): Map<string, ScalarFieldKind> {\n const cached = this.indexedFieldsByType.get(typeId);\n if (cached) return cached;\n\n const typeRow = this.exec.get<{ schema: string }>('SELECT schema FROM types WHERE id = ?', [\n typeId,\n ]);\n const fields = typeRow\n ? indexedFieldKinds(JSON.parse(typeRow.schema) as Record<string, { kind?: string }>)\n : new Map<string, ScalarFieldKind>();\n this.indexedFieldsByType.set(typeId, fields);\n return fields;\n }\n\n /**\n * Replace a record's content_index rows with what its content currently\n * holds, on every write that can change content or typeId, so neither\n * the ordering nor the file-reference lookup can drift from the record.\n * A field holding no orderable value gets no row at all, which is what\n * puts the record at the end of a sort on that field.\n */\n private syncContentIndex(\n recordId: string,\n typeId: string,\n content: Record<string, unknown>,\n ): void {\n this.exec.run('DELETE FROM content_index WHERE record_id = ?', [recordId]);\n\n for (const [field, kind] of this.getIndexedFields(typeId)) {\n const entry = contentSortEntry(kind, content[field]);\n if (!entry) continue;\n const sql = `INSERT OR IGNORE INTO content_index\n (record_id, field, value_rank, num_value, text_key, text_value, file_id)\n VALUES (?, ?, ?, ?, ?, ?, ?)`;\n if (entry.kind === 'num') {\n this.exec.run(sql, [recordId, field, 0, entry.num, null, null, null]);\n } else {\n // A file-ref field's value is its file id, so the row it already\n // needs for ordering also answers the attachment filter — one\n // field is one row, whatever a query reads it for.\n const fileId = kind === 'file-ref' ? entry.text : null;\n this.exec.run(sql, [recordId, field, 1, null, entry.key, entry.text, fileId]);\n }\n }\n }\n\n /** The declared kind of a record's top-level `field`, if it has one. */\n private sortFieldKind(record: StackRecord, field: string): ScalarFieldKind | undefined {\n return this.getIndexedFields(record.typeId).get(field);\n }\n}\n","/**\n * The engine-independent half of a SQLite-backed StackRecordAdapter: the\n * capability declaration and the delegation of all seventeen\n * StackRecordAdapter methods onto SharedSqlRecordLogic. Every method here\n * is a forward with no engine-specific content, so an adapter that owns a\n * SqlExecutor already knows how to answer all of them.\n *\n * What a concrete adapter is left to supply is exactly what differs\n * between bindings: constructing the database handle, applying the\n * schema, and its own lifecycle (flush/close) — hence those two being the\n * only abstract members.\n *\n * Lives in record.js's barrel rather than index.js's, so an adapter that\n * imports it never pulls in token-logic.ts's `node:crypto` — see the note\n * at the top of record.ts.\n */\n\nimport type {\n StackType,\n TypeId,\n FileId,\n RecordVersion,\n ActorOptions,\n StackRecord,\n StackQuery,\n QueryResult,\n Association,\n RecordChanges,\n} from '@haverstack/core';\nimport type { StackRecordAdapter, AdapterCapabilities } from '@haverstack/core/adapter';\nimport type { SqlExecutor } from './executor.js';\nimport type { StackConfig } from './config.js';\nimport { SharedSqlRecordLogic } from './record-logic.js';\n\n/**\n * What every engine running SharedSqlRecordLogic's query builder supports.\n * It describes the shared SQL, not the binding, so it is the same for each\n * of them — an engine whose SQLite build lacked FTS5 would override\n * `filter.search` rather than restate the whole declaration.\n */\nexport const SQLITE_RECORD_CAPABILITIES: AdapterCapabilities = {\n filter: {\n content: 'path',\n contentPresent: true,\n search: true,\n },\n sort: {\n fields: ['createdAt', 'updatedAt', 'version'],\n contentField: true,\n },\n limits: {\n attachmentBytes: null,\n contentBytes: null,\n },\n};\n\nexport abstract class SharedSqlRecordAdapter implements StackRecordAdapter {\n readonly capabilities: AdapterCapabilities = SQLITE_RECORD_CAPABILITIES;\n\n readonly ownerEntityId: string;\n readonly timezone: string | undefined;\n\n private readonly record: SharedSqlRecordLogic;\n\n protected constructor(exec: SqlExecutor, config: StackConfig) {\n this.record = new SharedSqlRecordLogic({ exec });\n this.ownerEntityId = config.entityId;\n this.timezone = config.timezone;\n }\n\n // -------------------------------------------------------\n // Records\n // -------------------------------------------------------\n\n createRecord(record: StackRecord): Promise<StackRecord> {\n return this.record.createRecord(record);\n }\n\n getRecord(id: string): Promise<StackRecord | null> {\n return this.record.getRecord(id);\n }\n\n mutateRecord(\n id: string,\n changes: RecordChanges,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.mutateRecord(id, changes, opts);\n }\n\n deleteRecord(\n id: string,\n opts?: { hard?: boolean; expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord | null> {\n return this.record.deleteRecord(id, opts);\n }\n\n undeleteRecord(\n id: string,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.undeleteRecord(id, opts);\n }\n\n restoreVersion(\n id: string,\n version: number,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & {\n restoreAssociations?: boolean;\n } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.restoreVersion(id, version, opts);\n }\n\n commitMigration(\n id: string,\n toTypeId: TypeId,\n content: Record<string, unknown>,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.commitMigration(id, toTypeId, content, opts);\n }\n\n queryRecords(query: StackQuery): Promise<QueryResult> {\n return this.record.queryRecords(query);\n }\n\n deleteUnreferencedAttachmentRecords(\n fileId: FileId,\n metadataTypeIds: TypeId[],\n ): Promise<StackRecord[]> {\n return this.record.deleteUnreferencedAttachmentRecords(fileId, metadataTypeIds);\n }\n\n // -------------------------------------------------------\n // Versions\n // -------------------------------------------------------\n\n getVersions(id: string): Promise<RecordVersion[]> {\n return this.record.getVersions(id);\n }\n\n getVersion(id: string, version: number): Promise<RecordVersion | null> {\n return this.record.getVersion(id, version);\n }\n\n saveVersion(id: string, version: RecordVersion): Promise<void> {\n return this.record.saveVersion(id, version);\n }\n\n // -------------------------------------------------------\n // Types\n // -------------------------------------------------------\n\n saveType(type: StackType): Promise<void> {\n return this.record.saveType(type);\n }\n\n getType(id: TypeId): Promise<StackType | null> {\n return this.record.getType(id);\n }\n\n listTypes(): Promise<StackType[]> {\n return this.record.listTypes();\n }\n\n // -------------------------------------------------------\n // Associations\n // -------------------------------------------------------\n\n associate(\n recordId: string,\n association: Association,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.associate(recordId, association, opts);\n }\n\n dissociate(\n recordId: string,\n association: Association,\n opts?: { expectedVersion?: number; snapshot?: RecordVersion } & ActorOptions,\n ): Promise<StackRecord> {\n return this.record.dissociate(recordId, association, opts);\n }\n\n // -------------------------------------------------------\n // Lifecycle\n // -------------------------------------------------------\n\n abstract flush(): Promise<void>;\n abstract close(): Promise<void>;\n}\n","import type { SqlExecutor } from '@haverstack/sqlite-shared/record';\n\n/**\n * Normalizes a Durable Object's ctx.storage.sql to SqlExecutor.\n *\n * Two things don't map onto node:sqlite's shape the way the rest of this\n * interface does:\n *\n * - There is no get/all/run split — sql.exec() always returns a cursor.\n * get()/all() read it via .toArray(); run() reads .rowsWritten for the\n * affected-row count run()'s contract promises.\n * - Raw BEGIN/COMMIT/ROLLBACK are rejected outright by DO SQLite (verified\n * against the real Workers runtime, not assumed) — its storage has no\n * notion of a transaction left open across separate exec() calls, and\n * each statement auto-commits the instant it runs, so no-op'ing those\n * three strings would silently break atomicity, not preserve it. The\n * platform's real primitive is ctx.storage.transactionSync(fn), which\n * SqlExecutor.transaction() reaches directly — see docs/spec/adapters.md\n * § Concurrency & storage ownership.\n */\nexport class DurableObjectSqliteExecutor implements SqlExecutor {\n constructor(private readonly storage: DurableObjectStorage) {}\n\n private get sql(): SqlStorage {\n return this.storage.sql;\n }\n\n exec(sql: string): void {\n this.sql.exec(sql);\n }\n\n run(sql: string, params: readonly unknown[] = []): number {\n const cursor = this.sql.exec(sql, ...(params as SqlStorageValue[]));\n return cursor.rowsWritten;\n }\n\n get<T = Record<string, unknown>>(sql: string, params: readonly unknown[] = []): T | undefined {\n const rows = this.sql.exec(sql, ...(params as SqlStorageValue[])).toArray();\n return rows[0] as T | undefined;\n }\n\n all<T = Record<string, unknown>>(sql: string, params: readonly unknown[] = []): T[] {\n return this.sql.exec(sql, ...(params as SqlStorageValue[])).toArray() as T[];\n }\n\n transaction<T>(fn: () => T): T {\n return this.storage.transactionSync(fn);\n }\n}\n","/**\n * Haverstack — Durable Object SQLite Record Adapter\n * -------------------------------------------------------\n * Implements StackRecordAdapter over a Cloudflare Durable Object's SQLite\n * storage (ctx.storage.sql). Full-text search uses FTS5, same as\n * record-adapter-sqlite — DO's SQLite build ships it.\n *\n * Ownership and durability come from the platform, not from anything this\n * class does: a Durable Object id maps to exactly one running instance,\n * so there is no separate lock file the way record-adapter-sqlite needs\n * one for real files (see docs/spec/adapters.md § Concurrency & storage\n * ownership) — the DO *is* the lock. There is likewise no persist/flush\n * step: every write through ctx.storage.sql is durable by the time the\n * call returns, so flush()/close() are no-ops kept only to satisfy the\n * optional StackRecordAdapter methods.\n *\n * This class itself is a thin binding: the one piece of genuinely\n * engine-specific wiring — SqlExecutor.transaction() reaching\n * ctx.storage.transactionSync() instead of raw SQL BEGIN/COMMIT/ROLLBACK,\n * which DO SQLite rejects outright — lives in executor.ts. Everything\n * above storage comes from @haverstack/sqlite-shared's\n * SharedSqlRecordAdapter, exactly as it does for record-adapter-sqlite.\n */\n\nimport {\n applyRecordSchema,\n insertConfigRecord,\n tryReadStackConfig,\n SharedSqlRecordAdapter,\n type StackConfig,\n} from '@haverstack/sqlite-shared/record';\nimport { DurableObjectSqliteExecutor } from './executor.js';\n\n// -------------------------------------------------------\n// Types\n// -------------------------------------------------------\n\nexport type DoRecordCreateOptions = {\n /** Entity ID of the stack owner. Ignored if the DO's storage already has a config record. */\n entityId: string;\n /** IANA timezone string e.g. \"America/New_York\". Optional passthrough app metadata — no default. */\n timezone?: string;\n};\n\n// -------------------------------------------------------\n// DoSQLiteRecordAdapter\n// -------------------------------------------------------\n\nexport class DoSQLiteRecordAdapter extends SharedSqlRecordAdapter {\n private constructor(exec: DurableObjectSqliteExecutor, config: StackConfig) {\n super(exec, config);\n }\n\n /**\n * Create (or reattach to) the adapter for a DO instance. There is no\n * initialize()/open() split the way file-based adapters need one: a DO\n * id either already has a config record (a previous call created it —\n * reattach, opts.entityId/timezone ignored in favor of what's stored)\n * or it doesn't (first call — opts.entityId/timezone become the config).\n * Schema DDL is `CREATE TABLE IF NOT EXISTS`, so running it every call\n * is idempotent and cheap.\n *\n * DO SQLite manages its own durability and rejects PRAGMA journal_mode\n * outright (\"not authorized\") — verified against the real runtime, not\n * assumed — hence `wal: false`, unlike record-adapter-sqlite.\n */\n static async create(\n storage: DurableObjectStorage,\n opts: DoRecordCreateOptions,\n ): Promise<DoSQLiteRecordAdapter> {\n const exec = new DurableObjectSqliteExecutor(storage);\n applyRecordSchema(exec, { wal: false });\n const config =\n tryReadStackConfig(exec) ?? insertConfigRecord(exec, opts.entityId, opts.timezone);\n return new DoSQLiteRecordAdapter(exec, config);\n }\n\n // -------------------------------------------------------\n // Lifecycle\n // -------------------------------------------------------\n\n /** No-op: every write through ctx.storage.sql is already durable. */\n async flush(): Promise<void> {}\n\n /** No-op: no lock file, no connection to release — the DO's own lifecycle governs storage. */\n async close(): Promise<void> {}\n}\n\nexport { DurableObjectSqliteExecutor } from './executor.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@haverstack/record-adapter-do-sqlite",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Cloudflare Durable Objects (SQLite storage) StackRecordAdapter for Haverstack — Workers, FTS5, single-writer by construction",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"storage"
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@haverstack/core": "^0.
|
|
35
|
+
"@haverstack/core": "^0.31.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@cloudflare/vitest-pool-workers": "^0.22.0",
|