@fadhilp/stateql 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/src/adapters.d.ts +17 -25
  2. package/dist/src/adapters.js +15 -95
  3. package/dist/src/catalog.d.ts +6 -0
  4. package/dist/src/catalog.js +52 -0
  5. package/dist/src/cli.js +8 -3
  6. package/dist/src/connect.d.ts +16 -0
  7. package/dist/src/connect.js +205 -0
  8. package/dist/src/core.d.ts +78 -0
  9. package/dist/src/core.js +477 -0
  10. package/dist/src/execution.d.ts +27 -0
  11. package/dist/src/execution.js +87 -0
  12. package/dist/src/filter.js +3 -1
  13. package/dist/src/index.d.ts +2 -1
  14. package/dist/src/index.js +1 -0
  15. package/dist/src/migrations.d.ts +1 -1
  16. package/dist/src/mongodb.d.ts +4 -2
  17. package/dist/src/mongodb.js +5 -56
  18. package/dist/src/os-credentials.d.ts +6 -1
  19. package/dist/src/os-credentials.js +171 -10
  20. package/dist/src/panel.d.ts +64 -0
  21. package/dist/src/panel.js +316 -0
  22. package/dist/src/plans.d.ts +31 -0
  23. package/dist/src/plans.js +275 -0
  24. package/dist/src/reads.d.ts +35 -0
  25. package/dist/src/reads.js +184 -0
  26. package/dist/src/redis.d.ts +4 -2
  27. package/dist/src/redis.js +7 -33
  28. package/dist/src/response-data.d.ts +1 -0
  29. package/dist/src/response-data.js +13 -10
  30. package/dist/src/results.d.ts +10 -0
  31. package/dist/src/results.js +153 -0
  32. package/dist/src/sqlite-process.js +16 -9
  33. package/dist/src/stateql.d.ts +7 -58
  34. package/dist/src/stateql.js +150 -2663
  35. package/dist/src/table-editor.js +2 -2
  36. package/dist/src/transactions.d.ts +8 -0
  37. package/dist/src/transactions.js +186 -0
  38. package/dist/src/types.d.ts +3 -17
  39. package/dist/src/writes.d.ts +48 -0
  40. package/dist/src/writes.js +320 -0
  41. package/docs/databases.md +2 -1
  42. package/docs/results.md +5 -0
  43. package/package.json +5 -3
@@ -1,19 +1,18 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import { randomUUID } from "node:crypto";
3
- import { compileTableUpdate, editableRow, parseTableUpdate, parseTableUpdates } from "./table-editor.js";
4
- import { writeFileSync } from "node:fs";
5
- import { basename, resolve } from "node:path";
6
1
  import { env } from "node:process";
7
- import { AdapterExecutionError, AdapterWriteError, BatchWriteError, createAdapter, createAdapterContext, } from "./adapters.js";
8
- import { confidence, credentialSource, databaseIdentity, databaseUrlHasSecret, detectDriver, isEnvironmentName, injectPassword, mongoDatabaseName, redisDatabaseName, normalizeSqliteSource, validateCredentialRef, validatePasswordReferenceTarget, validateProfileName, version, } from "./connection.js";
9
- import { asStateQLError, CredentialResolutionError, isTransientDatabaseError, StateQLError, } from "./errors.js";
10
- import { analyzeMongoWriteSafety, deserializeMongoWriteCommand, serializeMongoCommand, validateMongoReadCommand, validateMongoWriteCommand, MongoAdapter, } from "./mongodb.js";
11
- import { deserializeRedisCommand, RedisAdapter, serializeRedisCommand, validateRedisReadCommand, validateRedisWriteCommand, } from "./redis.js";
12
- import { filterMaterializedRows, prepareFilterStatement, validateFilterParameters, } from "./filter.js";
13
- import { operationData, paginationWarnings, profileData, rowsToCsv, sessionData, transactionData, } from "./response-data.js";
14
- import { analyzeSql, matchedRowsCount } from "./sql.js";
15
- import { StateStore, } from "./store.js";
16
- import { compactRows, compactValue, defaultHome, hash, isSqlParameters, parseJson, redact, } from "./util.js";
2
+ import { describeObject, inspectSchema, listObjects } from "./catalog.js";
3
+ import { connect, validatedProfileSource } from "./connect.js";
4
+ import { confidence, validateProfileName, version, } from "./connection.js";
5
+ import { Core, errorMessage, executionTimeout, mergeCommandExecutionContext, nonNegativeInteger, parseCommandOrigin, parseHistoryCategory, positiveInteger, } from "./core.js";
6
+ import { StateQLError } from "./errors.js";
7
+ import { Panel } from "./panel.js";
8
+ import { applyPlan, prepareMongoPlan, prepareRedisPlan, prepareSqlPlan, runPlan } from "./plans.js";
9
+ import { prepareMongoRead, prepareRedisRead, prepareSqlRead, queryPreviewRows, runRead, } from "./reads.js";
10
+ import { operationData, profileData, sessionData } from "./response-data.js";
11
+ import { countResult, exportResult, filterResult, resultColumns, resultRows, showResult, summarizeResult, } from "./results.js";
12
+ import { StateStore } from "./store.js";
13
+ import { beginTransaction, commitTransaction, rollbackTransaction, transactionStatus, } from "./transactions.js";
14
+ import { defaultHome } from "./util.js";
15
+ import { prepareMongoWrite, prepareRedisWrite, prepareSqlWrite, runWrite } from "./writes.js";
17
16
  const DEFAULT_SNAPSHOT_HISTORY_LIMIT = 50;
18
17
  const MAX_SNAPSHOT_HISTORY_LIMIT = 100;
19
18
  const DEFAULT_CREDENTIAL_RESOLUTION_TIMEOUT_MS = 120_000;
@@ -53,54 +52,38 @@ export class StateQL {
53
52
  [WORKSPACE_BOOTSTRAP]: true,
54
53
  });
55
54
  }
55
+ core;
56
56
  store;
57
- sessionName;
58
- actorId;
59
- previewRows;
60
- cacheTtlSeconds;
61
- resultTtlSeconds;
62
- maxCellCharacters;
63
- maxResultRows;
64
- maxResultBytes;
65
- timeoutMs;
66
- credentialTimeoutMs;
67
- signal;
68
- commandContexts = new AsyncLocalStorage();
69
- credentialResolver;
70
- now;
57
+ panel;
71
58
  closed = false;
72
- tableResults = new Map();
73
- editTokens = new Map();
74
- // ponytail: cache one bounded immutable result; use indexed result storage if larger results are needed.
75
- panelRows;
76
59
  constructor(options = {}) {
77
- this.now = options.now ?? (() => new Date());
78
- this.sessionName = options.session ?? env.STQL_SESSION ?? "default";
79
- this.actorId = options.actor ?? this.sessionName;
80
- if (!this.actorId.trim()) {
60
+ const now = options.now ?? (() => new Date());
61
+ const sessionName = options.session ?? env.STQL_SESSION ?? "default";
62
+ const actorId = options.actor ?? sessionName;
63
+ if (!actorId.trim()) {
81
64
  throw new StateQLError("INVALID_COMMAND", "Actor ID is required.");
82
65
  }
83
- this.previewRows = nonNegativeInteger(options.previewRows ?? 5, "previewRows");
84
- this.cacheTtlSeconds = nonNegativeInteger(options.cacheTtlSeconds ?? 300, "cacheTtlSeconds");
85
- this.resultTtlSeconds = positiveInteger(options.resultTtlSeconds ?? 86_400, "resultTtlSeconds");
86
- this.maxCellCharacters = positiveInteger(options.maxCellCharacters ?? 200, "maxCellCharacters");
87
- this.maxResultRows = positiveInteger(options.maxResultRows ?? 10_000, "maxResultRows");
88
- this.maxResultBytes = positiveInteger(options.maxResultBytes ?? 16 * 1024 * 1024, "maxResultBytes");
89
- this.timeoutMs = executionTimeout(options.timeoutMs ?? 30_000);
90
- this.credentialTimeoutMs = executionTimeout(options.credentialTimeoutMs ?? DEFAULT_CREDENTIAL_RESOLUTION_TIMEOUT_MS, "credentialTimeoutMs");
66
+ const settings = {
67
+ previewRows: nonNegativeInteger(options.previewRows ?? 5, "previewRows"),
68
+ cacheTtlSeconds: nonNegativeInteger(options.cacheTtlSeconds ?? 300, "cacheTtlSeconds"),
69
+ resultTtlSeconds: positiveInteger(options.resultTtlSeconds ?? 86_400, "resultTtlSeconds"),
70
+ maxCellCharacters: positiveInteger(options.maxCellCharacters ?? 200, "maxCellCharacters"),
71
+ maxResultRows: positiveInteger(options.maxResultRows ?? 10_000, "maxResultRows"),
72
+ maxResultBytes: positiveInteger(options.maxResultBytes ?? 16 * 1024 * 1024, "maxResultBytes"),
73
+ timeoutMs: executionTimeout(options.timeoutMs ?? 30_000),
74
+ credentialTimeoutMs: executionTimeout(options.credentialTimeoutMs ?? DEFAULT_CREDENTIAL_RESOLUTION_TIMEOUT_MS, "credentialTimeoutMs"),
75
+ };
91
76
  const maxStateBytes = positiveInteger(options.maxStateBytes ?? 256 * 1024 * 1024, "maxStateBytes");
92
- this.signal = options.signal;
93
- this.credentialResolver = options.credentialResolver;
94
- if (this.maxResultRows >= Number.MAX_SAFE_INTEGER) {
77
+ if (settings.maxResultRows >= Number.MAX_SAFE_INTEGER) {
95
78
  throw new StateQLError("INVALID_COMMAND", "maxResultRows is too large.");
96
79
  }
97
- const store = new StateStore(options.home ?? defaultHome(), this.now, maxStateBytes);
80
+ const store = new StateStore(options.home ?? defaultHome(), now, maxStateBytes);
98
81
  try {
99
82
  if (options[WORKSPACE_BOOTSTRAP]) {
100
- store.bootstrapWorkspace(this.sessionName, this.actorId);
83
+ store.bootstrapWorkspace(sessionName, actorId);
101
84
  }
102
85
  else {
103
- store.bootstrapSession(this.sessionName, this.actorId, options.actor === undefined);
86
+ store.bootstrapSession(sessionName, actorId, options.actor === undefined);
104
87
  }
105
88
  }
106
89
  catch (error) {
@@ -108,194 +91,24 @@ export class StateQL {
108
91
  throw error;
109
92
  }
110
93
  this.store = store;
94
+ this.core = new Core(store, settings, sessionName, actorId, now, options.signal, options.credentialResolver);
95
+ this.panel = new Panel(this.core, this);
111
96
  }
112
97
  close() {
113
98
  if (this.closed)
114
99
  return;
115
100
  this.closed = true;
116
- this.panelRows = undefined;
117
- this.tableResults.clear();
118
- this.editTokens.clear();
101
+ this.panel.clear();
119
102
  this.store.close();
120
103
  }
121
104
  [Symbol.dispose]() {
122
105
  this.close();
123
106
  }
124
107
  async connect(target, options = {}) {
125
- return this.run("connect", async (session) => {
126
- if (session.active_transaction_id) {
127
- throw new StateQLError("TRANSACTION_FAILED", "Commit or roll back the active transaction before connecting again.");
128
- }
129
- const sourceCount = [
130
- target,
131
- options.profile,
132
- options.secretEnv,
133
- options.credentialRef,
134
- ].filter((value) => value !== undefined).length;
135
- if (sourceCount !== 1) {
136
- throw new StateQLError("INVALID_COMMAND", "Use exactly one connection target, profile, secret environment variable, or credential reference.");
137
- }
138
- if (options.passwordRef !== undefined &&
139
- (target === undefined || options.profile !== undefined ||
140
- options.secretEnv !== undefined || options.credentialRef !== undefined)) {
141
- throw new StateQLError("INVALID_COMMAND", "A password reference requires a literal remote connection target.");
142
- }
143
- const implicitProfile = !options.profile && !options.secretEnv && !options.credentialRef &&
144
- options.passwordRef === undefined && target
145
- ? this.store.getProfile(target)
146
- : undefined;
147
- const profile = options.profile
148
- ? this.store.getProfile(options.profile)
149
- : implicitProfile;
150
- if (options.profile && !profile) {
151
- throw new StateQLError("CONNECTION_NOT_FOUND", `Profile "${options.profile}" was not found.`, { suggestedAction: "Run stql profile list." });
152
- }
153
- if (profile &&
154
- ([profile.target, profile.secret_env, profile.credential_ref]
155
- .filter((value) => value !== null).length !== 1 ||
156
- (profile.password_ref !== null && profile.target === null))) {
157
- throw new StateQLError("STATE_CORRUPTED", `Profile "${profile.name}" has an invalid connection source.`);
158
- }
159
- const resolvedTarget = profile?.target ?? target;
160
- const secretEnv = options.secretEnv ?? profile?.secret_env ?? undefined;
161
- const credentialRef = options.credentialRef ?? profile?.credential_ref ?? undefined;
162
- const passwordRef = options.passwordRef ?? profile?.password_ref ?? undefined;
163
- if (secretEnv !== undefined && !isEnvironmentName(secretEnv)) {
164
- throw new StateQLError("INVALID_COMMAND", "Secret environment variable name is invalid.");
165
- }
166
- if (credentialRef !== undefined)
167
- validateCredentialRef(credentialRef);
168
- if (passwordRef !== undefined) {
169
- validateCredentialRef(passwordRef);
170
- if (!resolvedTarget) {
171
- throw new StateQLError("INVALID_COMMAND", "A password reference requires a literal remote connection target.");
172
- }
173
- validatePasswordReferenceTarget(resolvedTarget);
174
- }
175
- const credentialReference = secretEnv ?? credentialRef;
176
- const credentialReferenceSource = secretEnv !== undefined
177
- ? "secret_env"
178
- : credentialRef !== undefined ? "credential_ref" : undefined;
179
- const readOnly = options.readOnly ??
180
- (profile ? Boolean(profile.read_only) : true);
181
- const context = this.executionContext(options);
182
- let adapterSource;
183
- let driver;
184
- if (passwordRef !== undefined) {
185
- const password = await this.resolveCredential(passwordRef, "password_ref", session, "connect", readOnly ? "read" : "write", context, {
186
- ...(profile ? { profile: { name: profile.name } } : {}),
187
- requestedReadOnly: readOnly,
188
- }, resolvedTarget);
189
- ({ driver, source: adapterSource } = injectPassword(resolvedTarget, password));
190
- }
191
- else {
192
- const secret = credentialReference && credentialReferenceSource
193
- ? await this.resolveCredential(credentialReference, credentialReferenceSource, session, "connect", readOnly ? "read" : "write", context, {
194
- ...(profile ? { profile: { name: profile.name } } : {}),
195
- requestedReadOnly: readOnly,
196
- })
197
- : resolvedTarget;
198
- if (!secret) {
199
- throw new StateQLError("INVALID_COMMAND", "Connection target is required.");
200
- }
201
- const resolvedSource = credentialReferenceSource
202
- ? credentialSource(secret, undefined, credentialReferenceSource)
203
- : { driver: detectDriver(secret), source: secret };
204
- driver = resolvedSource.driver;
205
- if (driver !== "sqlite" &&
206
- !credentialReference &&
207
- databaseUrlHasSecret(secret)) {
208
- throw new StateQLError("PERMISSION_DENIED", `Credential-bearing ${databaseDisplayName(driver)} URLs must use --env or --credential-ref.`, {
209
- suggestedAction: "Use an environment variable or trusted host credential reference.",
210
- });
211
- }
212
- adapterSource = credentialReferenceSource
213
- ? resolvedSource.source
214
- : driver === "sqlite" ? normalizeSqliteSource(secret) : secret;
215
- }
216
- const persistedSource = passwordRef !== undefined
217
- ? resolvedTarget
218
- : driver === "sqlite"
219
- ? adapterSource
220
- : credentialReferenceSource
221
- ? redact(adapterSource)
222
- : adapterSource;
223
- const identitySource = passwordRef !== undefined ? resolvedTarget : adapterSource;
224
- const databaseName = driver === "sqlite"
225
- ? basename(adapterSource)
226
- : driver === "mongodb"
227
- ? mongoDatabaseName(identitySource)
228
- : driver === "redis"
229
- ? redisDatabaseName(identitySource)
230
- : new URL(identitySource).pathname.replace(/^\//, "") || driver;
231
- const draft = {
232
- id: "pending",
233
- session_id: session.id,
234
- name: options.name ?? profile?.name ?? databaseName,
235
- driver,
236
- database_name: databaseName,
237
- source: persistedSource,
238
- secret_env: secretEnv ?? null,
239
- credential_ref: credentialRef ?? null,
240
- password_ref: passwordRef ?? null,
241
- read_only: readOnly ? 1 : 0,
242
- version: 0,
243
- created_at: this.now().toISOString(),
244
- };
245
- const adapter = driver === "mongodb"
246
- ? await this.openMongoAdapter(draft, context, adapterSource)
247
- : driver === "redis"
248
- ? await this.openRedisAdapter(draft, context, adapterSource)
249
- : await this.openAdapter(draft, context, adapterSource);
250
- try {
251
- await adapter.ping();
252
- }
253
- catch (error) {
254
- if (error instanceof AdapterExecutionError) {
255
- throw stoppedStateQLError(error, false);
256
- }
257
- throw new StateQLError("CONNECTION_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true });
258
- }
259
- finally {
260
- await closeAdapterQuietly(adapter);
261
- }
262
- const connection = this.store.addConnection({
263
- sessionId: session.id,
264
- actorId: this.actorId,
265
- name: draft.name,
266
- driver,
267
- databaseName,
268
- source: persistedSource,
269
- ...(secretEnv ? { secretEnv } : {}),
270
- ...(credentialRef ? { credentialRef } : {}),
271
- ...(passwordRef !== undefined ? { passwordRef } : {}),
272
- readOnly,
273
- });
274
- if (!connection) {
275
- throw new StateQLError("TRANSACTION_FAILED", "A transaction became active while changing the connection.");
276
- }
277
- return {
278
- data: {
279
- connection_id: connection.id,
280
- alias: connection.alias,
281
- display_alias: connection.alias,
282
- driver,
283
- database: databaseName,
284
- name: connection.name,
285
- profile: profile?.name ?? null,
286
- read_only: readOnly,
287
- state_version: "sv_0",
288
- state_confidence: driver === "sqlite" ? "database_reported" : "ttl_based",
289
- },
290
- handle: connection.id,
291
- executed: true,
292
- stateVersion: "sv_0",
293
- confidence: driver === "sqlite" ? "database_reported" : "ttl_based",
294
- };
295
- });
108
+ return this.core.run("connect", (session) => connect(this.core, session, target, options));
296
109
  }
297
110
  async addProfile(name, target, options = {}) {
298
- return this.run("profile.add", async () => {
111
+ return this.core.run("profile.add", async () => {
299
112
  validateProfileName(name);
300
113
  if (this.store.getProfile(name)) {
301
114
  throw new StateQLError("INVALID_COMMAND", `Profile "${name}" already exists.`);
@@ -322,7 +135,7 @@ export class StateQL {
322
135
  });
323
136
  }
324
137
  async updateProfile(name, changes) {
325
- return this.run("profile.update", async () => {
138
+ return this.core.run("profile.update", async () => {
326
139
  validateProfileName(name);
327
140
  const existing = this.store.getProfile(name);
328
141
  if (!existing)
@@ -362,12 +175,12 @@ export class StateQL {
362
175
  });
363
176
  }
364
177
  async listProfiles() {
365
- return this.run("profile.list", async () => ({
178
+ return this.core.run("profile.list", async () => ({
366
179
  data: { profiles: this.store.listProfiles().map(profileData) },
367
180
  }));
368
181
  }
369
182
  async showProfile(name) {
370
- return this.run("profile.show", async () => {
183
+ return this.core.run("profile.show", async () => {
371
184
  const profile = this.store.getProfile(name);
372
185
  if (!profile) {
373
186
  throw new StateQLError("CONNECTION_NOT_FOUND", `Profile "${name}" was not found.`);
@@ -379,7 +192,7 @@ export class StateQL {
379
192
  });
380
193
  }
381
194
  async removeProfile(name) {
382
- return this.run("profile.remove", async () => {
195
+ return this.core.run("profile.remove", async () => {
383
196
  if (!this.store.removeProfile(name)) {
384
197
  throw new StateQLError("CONNECTION_NOT_FOUND", `Profile "${name}" was not found.`);
385
198
  }
@@ -391,11 +204,11 @@ export class StateQL {
391
204
  });
392
205
  }
393
206
  async disconnect() {
394
- return this.run("disconnect", async (session) => {
207
+ return this.core.run("disconnect", async (session) => {
395
208
  if (session.active_transaction_id) {
396
209
  throw new StateQLError("TRANSACTION_FAILED", "Commit or roll back the active transaction before disconnecting.");
397
210
  }
398
- if (!this.store.disconnect(session.id, this.actorId)) {
211
+ if (!this.store.disconnect(session.id, this.core.actorId)) {
399
212
  throw new StateQLError("TRANSACTION_FAILED", "A transaction became active while disconnecting.");
400
213
  }
401
214
  return { data: { disconnected: true }, executed: true };
@@ -404,14 +217,14 @@ export class StateQL {
404
217
  snapshot(options = {}) {
405
218
  const session = this.store
406
219
  .listSessions()
407
- .find((candidate) => candidate.name === this.sessionName);
220
+ .find((candidate) => candidate.name === this.core.sessionName);
408
221
  if (!session) {
409
222
  throw new StateQLError("INVALID_COMMAND", "The active session was not found.");
410
223
  }
411
- if (!this.store.isSessionMember(session.id, this.actorId)) {
412
- throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
224
+ if (!this.store.isSessionMember(session.id, this.core.actorId)) {
225
+ throw new StateQLError("PERMISSION_DENIED", `Actor "${this.core.actorId}" is not attached to session "${session.name}".`);
413
226
  }
414
- const actor = this.store.getActor(session.id, this.actorId);
227
+ const actor = this.store.getActor(session.id, this.core.actorId);
415
228
  const connection = this.store.activeConnection(session);
416
229
  const transaction = session.active_transaction_id
417
230
  ? this.store.getTransaction(session.active_transaction_id)
@@ -433,7 +246,7 @@ export class StateQL {
433
246
  name: session.name,
434
247
  status: session.status,
435
248
  },
436
- actor_id: this.actorId,
249
+ actor_id: this.core.actorId,
437
250
  actor_name: actor.actor_name,
438
251
  connection: connection
439
252
  ? {
@@ -476,17 +289,17 @@ export class StateQL {
476
289
  };
477
290
  }
478
291
  async status() {
479
- return this.run("status", async (session) => {
292
+ return this.core.run("status", async (session) => {
480
293
  const connection = this.store.activeConnection(session);
481
294
  const transaction = session.active_transaction_id
482
295
  ? this.store.getTransaction(session.active_transaction_id)
483
296
  : undefined;
484
- const actor = this.store.getActor(session.id, this.actorId);
297
+ const actor = this.store.getActor(session.id, this.core.actorId);
485
298
  return {
486
299
  data: {
487
300
  session_id: session.id,
488
301
  session_name: session.name,
489
- actor_id: this.actorId,
302
+ actor_id: this.core.actorId,
490
303
  actor_name: actor.actor_name,
491
304
  connection: connection
492
305
  ? {
@@ -512,15 +325,15 @@ export class StateQL {
512
325
  });
513
326
  }
514
327
  async linkActor(session, actorId) {
515
- return this.run("actor.link", async (current) => {
328
+ return this.core.run("actor.link", async (current) => {
516
329
  this.requireSelectedSession(current, session);
517
330
  this.validateActorId(actorId);
518
- const result = this.store.linkActor(current.id, this.actorId, actorId);
331
+ const result = this.store.linkActor(current.id, this.core.actorId, actorId);
519
332
  if (result === "actor_conflict") {
520
333
  throw new StateQLError("PERMISSION_DENIED", `Actor "${actorId}" is already attached to another session.`);
521
334
  }
522
335
  if (result === "denied")
523
- this.throwMembershipDenied(current);
336
+ this.core.throwMembershipDenied(current);
524
337
  return {
525
338
  data: {
526
339
  session_id: current.id,
@@ -532,15 +345,15 @@ export class StateQL {
532
345
  });
533
346
  }
534
347
  async unlinkActor(session, actorId) {
535
- return this.run("actor.unlink", async (current) => {
348
+ return this.core.run("actor.unlink", async (current) => {
536
349
  this.requireSelectedSession(current, session);
537
350
  this.validateActorId(actorId);
538
- const result = this.store.unlinkActor(current.id, this.actorId, actorId);
351
+ const result = this.store.unlinkActor(current.id, this.core.actorId, actorId);
539
352
  if (result === "owns_transaction") {
540
353
  throw new StateQLError("TRANSACTION_FAILED", `Actor "${actorId}" owns the active transaction.`);
541
354
  }
542
355
  if (result === "denied")
543
- this.throwMembershipDenied(current);
356
+ this.core.throwMembershipDenied(current);
544
357
  return {
545
358
  data: {
546
359
  session_id: current.id,
@@ -552,8 +365,8 @@ export class StateQL {
552
365
  });
553
366
  }
554
367
  async showActor() {
555
- return this.run("actor.show", async (current) => {
556
- const actor = this.store.getActor(current.id, this.actorId);
368
+ return this.core.run("actor.show", async (current) => {
369
+ const actor = this.store.getActor(current.id, this.core.actorId);
557
370
  return {
558
371
  data: {
559
372
  actor_id: actor.actor_id,
@@ -564,9 +377,9 @@ export class StateQL {
564
377
  });
565
378
  }
566
379
  async setActorName(name) {
567
- return this.run("actor.set-name", async (current) => {
380
+ return this.core.run("actor.set-name", async (current) => {
568
381
  const actorName = this.validateActorName(name);
569
- const existing = this.store.getActor(current.id, this.actorId);
382
+ const existing = this.store.getActor(current.id, this.core.actorId);
570
383
  if (existing.actor_name === actorName) {
571
384
  return {
572
385
  data: {
@@ -576,7 +389,7 @@ export class StateQL {
576
389
  },
577
390
  };
578
391
  }
579
- const actor = this.store.setActorName(current.id, this.actorId, actorName);
392
+ const actor = this.store.setActorName(current.id, this.core.actorId, actorName);
580
393
  return {
581
394
  data: {
582
395
  actor_id: actor.actor_id,
@@ -588,7 +401,7 @@ export class StateQL {
588
401
  }, undefined, actorNameHistoryTarget(name));
589
402
  }
590
403
  async listActors(session) {
591
- return this.run("actor.list", async (current) => {
404
+ return this.core.run("actor.list", async (current) => {
592
405
  this.requireSelectedSession(current, session);
593
406
  return {
594
407
  data: {
@@ -603,7 +416,7 @@ export class StateQL {
603
416
  });
604
417
  }
605
418
  async resolveActor(actorId) {
606
- return this.run("actor.resolve", async () => {
419
+ return this.core.run("actor.resolve", async () => {
607
420
  this.validateActorId(actorId);
608
421
  const session = this.store.resolveActor(actorId);
609
422
  return {
@@ -621,7 +434,7 @@ export class StateQL {
621
434
  });
622
435
  }
623
436
  async startSession(name) {
624
- return this.run("session.start", async () => {
437
+ return this.core.run("session.start", async () => {
625
438
  if (!name.trim()) {
626
439
  throw new StateQLError("INVALID_COMMAND", "Session name is required.");
627
440
  }
@@ -638,7 +451,7 @@ export class StateQL {
638
451
  });
639
452
  }
640
453
  async listSessions() {
641
- return this.run("session.list", async () => ({
454
+ return this.core.run("session.list", async () => ({
642
455
  data: {
643
456
  sessions: this.store.listSessions().map((session) => ({
644
457
  session_id: session.id,
@@ -650,8 +463,8 @@ export class StateQL {
650
463
  },
651
464
  }));
652
465
  }
653
- async showSession(idOrName = this.sessionName) {
654
- return this.run("session.show", async () => {
466
+ async showSession(idOrName = this.core.sessionName) {
467
+ return this.core.run("session.show", async () => {
655
468
  const session = this.store.getSession(idOrName);
656
469
  if (!session) {
657
470
  throw new StateQLError("INVALID_COMMAND", `Session "${idOrName}" was not found.`);
@@ -660,7 +473,7 @@ export class StateQL {
660
473
  });
661
474
  }
662
475
  async sessionSummary() {
663
- return this.run("session.summary", async (session) => {
476
+ return this.core.run("session.summary", async (session) => {
664
477
  const connection = this.store.activeConnection(session);
665
478
  return {
666
479
  data: {
@@ -690,11 +503,11 @@ export class StateQL {
690
503
  });
691
504
  }
692
505
  async closeSession() {
693
- return this.run("session.close", async (session) => {
506
+ return this.core.run("session.close", async (session) => {
694
507
  if (session.active_transaction_id) {
695
508
  throw new StateQLError("TRANSACTION_FAILED", "Roll back or commit the active transaction first.");
696
509
  }
697
- if (!this.store.closeSession(session.id, this.actorId)) {
510
+ if (!this.store.closeSession(session.id, this.core.actorId)) {
698
511
  throw new StateQLError("TRANSACTION_FAILED", "A transaction became active while closing the session.");
699
512
  }
700
513
  return {
@@ -705,379 +518,51 @@ export class StateQL {
705
518
  });
706
519
  }
707
520
  async query(sql, options = {}) {
708
- return this.run("query", async (session) => {
709
- const previewRows = options.previewRows === undefined
710
- ? this.previewRows
711
- : queryPreviewRows(options.previewRows);
712
- const connection = this.requireConnection(session);
713
- this.rejectMongoSql(connection, "mongoQuery");
714
- this.rejectDuringStagedTransaction(session, "Queries");
715
- const analysis = analyzeSql(sql, connection.driver);
716
- if (!analysis.read) {
717
- throw new StateQLError("INVALID_SQL", "query accepts read statements only; use exec for writes.");
718
- }
719
- const cacheMode = options.cache ?? "auto";
720
- if (!analysis.cacheable && cacheMode === "require") {
721
- throw new StateQLError("CACHE_MISS", "This statement is not cacheable.", {
722
- retryable: true,
723
- suggestedAction: "Run with --cache auto or --cache bypass.",
724
- });
725
- }
726
- const parameters = options.params ?? [];
727
- if (analysis.requiresAutocommit && sqlParametersLength(parameters) > 0) {
728
- throw new StateQLError("INVALID_SQL", "Autocommit diagnostic statements do not accept StateQL parameters.");
729
- }
730
- const context = this.executionContext(options);
731
- const adapterSource = await this.resolveConnectionSource(connection, session, "query", "read", context);
732
- const adapter = await this.openAdapter(connection, context, adapterSource);
733
- try {
734
- const stateVersion = version(connection);
735
- const stateSignature = await adapter.signature();
736
- const fingerprint = hash({
737
- sql: analysis.normalized,
738
- parameters,
739
- driver: connection.driver,
740
- connection: connection.id,
741
- database: connection.database_name,
742
- transaction: session.active_transaction_id,
743
- stateVersion,
744
- });
745
- const cached = this.store.findResult(fingerprint);
746
- if (analysis.cacheable &&
747
- cacheMode !== "bypass" &&
748
- cached &&
749
- cached.row_count <= this.maxResultRows &&
750
- this.cacheValid(cached, stateVersion, stateSignature)) {
751
- return {
752
- data: this.resultData(cached, true, previewRows),
753
- handle: cached.id,
754
- cached: true,
755
- warnings: paginationWarnings(analysis.ordered),
756
- stateVersion,
757
- confidence: cached.state_confidence,
758
- };
759
- }
760
- if (cacheMode === "require") {
761
- throw new StateQLError("CACHE_MISS", "No valid cached result exists.", {
762
- retryable: true,
763
- suggestedAction: "Run with --cache auto or --cache bypass.",
764
- });
765
- }
766
- const executionSql = analysis.wrapForLimit
767
- ? boundedReadSql(analysis.limitSql ?? sql, this.maxResultRows + 1)
768
- : sql;
769
- if (analysis.requiresAutocommit && !adapter.readAutocommit) {
770
- throw new StateQLError("UNSUPPORTED_DRIVER", `${analysis.statementType.toUpperCase()} requires adapter autocommit reads.`);
771
- }
772
- const result = analysis.requiresAutocommit
773
- ? await adapter.readAutocommit(executionSql, parameters)
774
- : await adapter.read(executionSql, parameters);
775
- if (result.rows.length > this.maxResultRows) {
776
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", `Query exceeds the ${this.maxResultRows}-row materialization limit.`, { suggestedAction: "Add a narrower WHERE clause or LIMIT." });
777
- }
778
- const resultBytes = Buffer.byteLength(JSON.stringify(parameters), "utf8") +
779
- Buffer.byteLength(JSON.stringify(result.rows), "utf8") +
780
- Buffer.byteLength(JSON.stringify(result.columns), "utf8");
781
- if (resultBytes > this.maxResultBytes) {
782
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", `Query exceeds the ${this.maxResultBytes}-byte materialization limit.`, { suggestedAction: "Select fewer rows or smaller columns." });
783
- }
784
- const expiresAt = new Date(this.now().getTime() + this.resultTtlSeconds * 1000).toISOString();
785
- const saved = this.store.saveResult({
786
- sessionId: session.id,
787
- connectionId: connection.id,
788
- fingerprint,
789
- sql,
790
- parameters,
791
- rows: result.rows,
792
- columns: result.columns,
793
- stateVersion,
794
- stateSignature,
795
- stateConfidence: adapter.confidence,
796
- expiresAt,
797
- });
798
- return {
799
- data: this.resultData(saved, false, previewRows),
800
- handle: saved.id,
801
- executed: true,
802
- warnings: paginationWarnings(analysis.ordered),
803
- stateVersion,
804
- confidence: adapter.confidence,
805
- };
806
- }
807
- catch (error) {
808
- if (error instanceof StateQLError)
809
- throw error;
810
- if (error instanceof AdapterExecutionError) {
811
- throw stoppedStateQLError(error, true);
812
- }
813
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), {
814
- retryable: isTransientDatabaseError(error),
815
- executed: true,
816
- });
817
- }
818
- finally {
819
- await closeAdapterQuietly(adapter);
820
- }
521
+ return this.core.run("query", async (session) => {
522
+ const previewRows = options.previewRows === undefined ? undefined : queryPreviewRows(options.previewRows);
523
+ const connection = this.core.requireSqlConnection(session, "query");
524
+ this.core.rejectDuringStagedTransaction(session, "Queries");
525
+ const statement = prepareSqlRead(connection, sql, options.params ?? []);
526
+ return runRead(this.core, session, connection, statement, { ...options, previewRows });
821
527
  }, sql);
822
528
  }
823
529
  async mongoQuery(command, options = {}) {
824
- return this.run("mongo.query", async (session) => {
825
- const value = validatedMongoRead(command);
826
- const serializedCommand = serializeMongoCommand(value);
827
- const connection = this.requireMongoConnection(session, "mongoQuery");
828
- this.rejectDuringStagedTransaction(session, "MongoDB queries");
829
- const context = this.executionContext(options);
830
- const adapterSource = await this.resolveConnectionSource(connection, session, "query", "read", context);
831
- const adapter = await this.openMongoAdapter(connection, context, adapterSource);
832
- try {
833
- const stateVersion = version(connection);
834
- const stateSignature = await adapter.signature();
835
- const fingerprint = hash({
836
- command: serializedCommand,
837
- driver: connection.driver,
838
- connection: connection.id,
839
- database: connection.database_name,
840
- transaction: session.active_transaction_id,
841
- stateVersion,
842
- });
843
- const cached = this.store.findResult(fingerprint);
844
- const cacheMode = options.cache ?? "auto";
845
- const warnings = mongoPaginationWarnings(value);
846
- if (cacheMode !== "bypass" &&
847
- cached &&
848
- cached.row_count <= this.maxResultRows &&
849
- this.cacheValid(cached, stateVersion, stateSignature)) {
850
- return {
851
- data: this.resultData(cached, true),
852
- handle: cached.id,
853
- cached: true,
854
- warnings,
855
- stateVersion,
856
- confidence: cached.state_confidence,
857
- };
858
- }
859
- if (cacheMode === "require") {
860
- throw new StateQLError("CACHE_MISS", "No valid cached result exists.", {
861
- retryable: true,
862
- suggestedAction: "Run with cache auto or cache bypass.",
863
- });
864
- }
865
- const result = await adapter.read(value, this.maxResultRows + 1);
866
- if (result.rows.length > this.maxResultRows) {
867
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", `Query exceeds the ${this.maxResultRows}-row materialization limit.`, { suggestedAction: "Use a narrower filter or limit." });
868
- }
869
- const parameters = [serializedCommand];
870
- const resultBytes = Buffer.byteLength(JSON.stringify(parameters), "utf8") +
871
- Buffer.byteLength(JSON.stringify(result.rows), "utf8") +
872
- Buffer.byteLength(JSON.stringify(result.columns), "utf8");
873
- if (resultBytes > this.maxResultBytes) {
874
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", `Query exceeds the ${this.maxResultBytes}-byte materialization limit.`, { suggestedAction: "Return fewer or smaller documents." });
875
- }
876
- const expiresAt = new Date(this.now().getTime() + this.resultTtlSeconds * 1000).toISOString();
877
- const saved = this.store.saveResult({
878
- sessionId: session.id,
879
- connectionId: connection.id,
880
- fingerprint,
881
- sql: mongoDescriptor(value.operation),
882
- parameters,
883
- rows: result.rows,
884
- columns: result.columns,
885
- stateVersion,
886
- stateSignature,
887
- stateConfidence: adapter.confidence,
888
- expiresAt,
889
- });
890
- return {
891
- data: this.resultData(saved, false),
892
- handle: saved.id,
893
- executed: true,
894
- warnings,
895
- stateVersion,
896
- confidence: adapter.confidence,
897
- };
898
- }
899
- catch (error) {
900
- if (error instanceof StateQLError)
901
- throw error;
902
- if (error instanceof AdapterExecutionError) {
903
- throw stoppedStateQLError(error, true);
904
- }
905
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
906
- }
907
- finally {
908
- await closeAdapterQuietly(adapter);
909
- }
530
+ return this.core.run("mongo.query", async (session) => {
531
+ const statement = prepareMongoRead(command);
532
+ const connection = this.core.requireNativeConnection(session, "mongodb", "query");
533
+ this.core.rejectDuringStagedTransaction(session, "MongoDB queries");
534
+ return runRead(this.core, session, connection, statement, options);
910
535
  });
911
536
  }
912
537
  async redisQuery(command, options = {}) {
913
- return this.run("redis.query", async (session) => {
914
- const value = validatedRedisRead(command);
915
- const serialized = serializeRedisCommand(value);
916
- const connection = this.requireRedisConnection(session, "redisQuery");
917
- this.rejectDuringStagedTransaction(session, "Redis queries");
918
- const context = this.executionContext(options);
919
- const source = await this.resolveConnectionSource(connection, session, "query", "read", context);
920
- const adapter = await this.openRedisAdapter(connection, context, source);
921
- try {
922
- const stateVersion = version(connection);
923
- const stateSignature = await adapter.signature();
924
- const fingerprint = hash({ command: serialized, connection: connection.id, database: connection.database_name, stateVersion });
925
- const cached = this.store.findResult(fingerprint);
926
- const cacheMode = options.cache ?? "auto";
927
- if (cacheMode !== "bypass" && cached && cached.row_count <= this.maxResultRows && this.cacheValid(cached, stateVersion, stateSignature)) {
928
- return { data: this.resultData(cached, true), handle: cached.id, cached: true, stateVersion, confidence: cached.state_confidence };
929
- }
930
- if (cacheMode === "require")
931
- throw new StateQLError("CACHE_MISS", "No valid cached Redis result exists.", { retryable: true });
932
- const result = await adapter.read(value);
933
- const parameters = [serialized, result.nextCursor ?? null];
934
- const resultBytes = Buffer.byteLength(JSON.stringify(parameters), "utf8") + Buffer.byteLength(JSON.stringify(result.rows), "utf8") + Buffer.byteLength(JSON.stringify(result.columns), "utf8");
935
- if (result.rows.length > this.maxResultRows || resultBytes > this.maxResultBytes)
936
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Redis response exceeds materialization limits.");
937
- const saved = this.store.saveResult({
938
- sessionId: session.id, connectionId: connection.id, fingerprint,
939
- sql: `Redis native ${value.command}`, parameters, rows: result.rows, columns: result.columns,
940
- stateVersion, stateSignature, stateConfidence: adapter.confidence,
941
- expiresAt: new Date(this.now().getTime() + this.resultTtlSeconds * 1000).toISOString(),
942
- });
943
- return { data: this.resultData(saved, false), handle: saved.id, executed: true, stateVersion, confidence: adapter.confidence };
944
- }
945
- catch (error) {
946
- if (error instanceof StateQLError)
947
- throw error;
948
- if (error instanceof AdapterExecutionError)
949
- throw stoppedStateQLError(error, true);
950
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { retryable: isTransientDatabaseError(error), executed: true });
951
- }
952
- finally {
953
- await closeAdapterQuietly(adapter);
954
- }
538
+ return this.core.run("redis.query", async (session) => {
539
+ const statement = prepareRedisRead(command);
540
+ const connection = this.core.requireNativeConnection(session, "redis", "query");
541
+ this.core.rejectDuringStagedTransaction(session, "Redis queries");
542
+ return runRead(this.core, session, connection, statement, options);
955
543
  });
956
544
  }
957
545
  async show(idOrAlias) {
958
- return this.withResult("show", idOrAlias, async (result) => ({
959
- data: this.resultData(result, true),
960
- handle: result.id,
961
- cached: true,
962
- stateVersion: result.state_version,
963
- confidence: result.state_confidence,
964
- }));
546
+ return this.core.withResult("show", idOrAlias, async (result) => showResult(this.core, result));
965
547
  }
966
548
  async filter(idOrAlias, predicate, options = {}) {
967
- return this.withResult("filter", idOrAlias, async (source) => {
968
- const columns = this.store.resultColumns(source);
969
- const filter = prepareFilterStatement(columns, predicate);
970
- const parameters = options.params ?? [];
971
- validateFilterParameters(filter, parameters);
972
- const fingerprint = hash({
973
- command: "filter",
974
- source: source.id,
975
- predicate: filter.normalized,
976
- parameters,
977
- });
978
- const cached = this.store.findResult(fingerprint);
979
- if (cached &&
980
- cached.session_id === source.session_id &&
981
- cached.connection_id === source.connection_id &&
982
- Date.parse(cached.expires_at) > this.now().getTime()) {
983
- return {
984
- data: this.resultData(cached, true),
985
- handle: cached.id,
986
- cached: true,
987
- stateVersion: cached.state_version,
988
- confidence: cached.state_confidence,
989
- };
990
- }
991
- const rows = filterMaterializedRows(this.store.resultRows(source), filter, parameters);
992
- const saved = this.store.saveResult({
993
- sessionId: source.session_id,
994
- connectionId: source.connection_id,
995
- fingerprint,
996
- sql: `FILTER ${source.id} WHERE ${predicate.trim()}`,
997
- parameters,
998
- rows,
999
- columns,
1000
- stateVersion: source.state_version,
1001
- stateSignature: source.state_signature,
1002
- stateConfidence: source.state_confidence,
1003
- expiresAt: source.expires_at,
1004
- });
1005
- return {
1006
- data: this.resultData(saved, false),
1007
- handle: saved.id,
1008
- executed: true,
1009
- stateVersion: saved.state_version,
1010
- confidence: saved.state_confidence,
1011
- };
1012
- });
549
+ return this.core.withResult("filter", idOrAlias, async (source) => filterResult(this.core, source, predicate, options));
1013
550
  }
1014
551
  async rows(idOrAlias, options = {}) {
1015
- return this.withResult("rows", idOrAlias, async (result) => {
1016
- const offset = nonNegativeInteger(options.offset ?? 0, "offset");
1017
- const limit = positiveInteger(options.limit ?? 20, "limit");
1018
- if (limit > 1_000) {
1019
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "limit cannot exceed 1000 rows.", { suggestedAction: "Fetch another page or use export." });
1020
- }
1021
- const allRows = this.store.resultRows(result);
1022
- const rows = selectColumns(allRows.slice(offset, offset + limit), this.store.resultColumns(result), options.columns);
1023
- return {
1024
- data: {
1025
- result_id: result.id,
1026
- offset,
1027
- limit,
1028
- rows: compactRows(rows, this.maxCellCharacters),
1029
- returned: rows.length,
1030
- total: result.row_count,
1031
- truncated: offset + rows.length < result.row_count,
1032
- next_offset: offset + rows.length < result.row_count ? offset + rows.length : null,
1033
- },
1034
- handle: result.id,
1035
- cached: true,
1036
- stateVersion: result.state_version,
1037
- confidence: result.state_confidence,
1038
- };
1039
- });
552
+ return this.core.withResult("rows", idOrAlias, async (result) => resultRows(this.core, result, options));
1040
553
  }
1041
554
  async count(idOrAlias) {
1042
- return this.withResult("count", idOrAlias, async (result) => ({
1043
- data: { result_id: result.id, rows: result.row_count },
1044
- handle: result.id,
1045
- cached: true,
1046
- stateVersion: result.state_version,
1047
- confidence: result.state_confidence,
1048
- }));
555
+ return this.core.withResult("count", idOrAlias, async (result) => countResult(result));
1049
556
  }
1050
557
  async columns(idOrAlias) {
1051
- return this.withResult("columns", idOrAlias, async (result) => ({
1052
- data: {
1053
- result_id: result.id,
1054
- columns: this.store.resultColumns(result),
1055
- },
1056
- handle: result.id,
1057
- cached: true,
1058
- stateVersion: result.state_version,
1059
- confidence: result.state_confidence,
1060
- }));
558
+ return this.core.withResult("columns", idOrAlias, async (result) => resultColumns(this.core, result));
1061
559
  }
1062
560
  async summarize(idOrAlias) {
1063
- return this.withResult("summarize", idOrAlias, async (result) => {
1064
- const rows = this.store.resultRows(result);
1065
- return {
1066
- data: {
1067
- result_id: result.id,
1068
- total: result.row_count,
1069
- columns: this.store.resultColumns(result).map((column) => summarizeColumn(column.name, rows, this.maxCellCharacters)),
1070
- },
1071
- handle: result.id,
1072
- cached: true,
1073
- stateVersion: result.state_version,
1074
- confidence: result.state_confidence,
1075
- };
1076
- });
561
+ return this.core.withResult("summarize", idOrAlias, async (result) => summarizeResult(this.core, result));
1077
562
  }
1078
563
  async setAlias(name, id) {
1079
- return this.run("alias.set", async (session) => {
1080
- const result = this.requireResult(id, session);
564
+ return this.core.run("alias.set", async (session) => {
565
+ const result = this.core.requireResult(id, session);
1081
566
  this.store.setAlias(session.id, name, result.id);
1082
567
  return {
1083
568
  data: { alias: name, result_id: result.id },
@@ -1088,301 +573,51 @@ export class StateQL {
1088
573
  }
1089
574
  /** Owned, full-value pages for host UIs. Reading a page does not add a command to history. */
1090
575
  readMaterialized(id, options = {}) {
1091
- options.signal?.throwIfAborted();
1092
- const result = this.panelResult(id);
1093
- const offset = nonNegativeInteger(options.offset ?? 0, "offset");
1094
- const limit = positiveInteger(options.limit ?? 100, "limit");
1095
- if (limit > 100 || offset > 10_000)
1096
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Page bounds exceeded.");
1097
- const all = this.fullResultRows(result);
1098
- const rows = [];
1099
- let bytes = 0;
1100
- for (const row of all.slice(offset, offset + limit)) {
1101
- const size = Buffer.byteLength(JSON.stringify(row), "utf8");
1102
- if (bytes + size > 200 * 1024) {
1103
- if (!rows.length)
1104
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "A row exceeds the browser page limit. Export this result instead.");
1105
- break;
1106
- }
1107
- rows.push(row);
1108
- bytes += size;
1109
- }
1110
- const next = offset + rows.length;
1111
- const metadata = this.tableResults.get(id);
1112
- const connection = this.store.activeConnection(this.store.ensureSession(this.sessionName));
1113
- const eligible = metadata && connection?.id === result.connection_id && !connection.read_only && version(connection) === result.state_version;
1114
- const rowTokens = rows.map(row => {
1115
- if (!eligible || !editableRow(metadata, row))
1116
- return null;
1117
- const token = randomUUID();
1118
- for (const [key, entry] of this.editTokens)
1119
- if (entry.expires <= this.now().getTime())
1120
- this.editTokens.delete(key);
1121
- if (this.editTokens.size >= 1000)
1122
- this.editTokens.delete(this.editTokens.keys().next().value);
1123
- this.editTokens.set(token, { metadata, original: structuredClone(row), sessionId: result.session_id, connectionId: result.connection_id, stateVersion: result.state_version, expires: this.now().getTime() + 10 * 60_000 });
1124
- return token;
1125
- });
1126
- const writable = metadata?.driver === "mongodb" ? [...new Set(rows.flatMap(row => Object.keys(row)))].filter(name => name !== "_id")
1127
- : metadata?.columns.filter(column => !column.key && !column.generated).map(column => column.name) ?? [];
1128
- return { row_tokens: rowTokens, writable_columns: writable, ...(!metadata?.writable ? { editing_reason: metadata?.reason ?? "Query results are read-only." } : {}),
1129
- result_id: result.id, offset, limit, rows: structuredClone(rows), columns: this.store.resultColumns(result),
1130
- returned: rows.length, total: all.length, truncated: next < all.length, next_offset: next < all.length ? next : null };
576
+ return this.panel.readMaterialized(id, options);
1131
577
  }
1132
578
  /** No caller-selected filesystem paths. The host delivers these bounded attachment bytes. */
1133
579
  async serializeResult(id, format, signal, origin = "api") {
1134
- return this.commandContexts.run(mergeCommandExecutionContext(this.commandContexts.getStore(), { signal, origin }), () => this.run("export", async () => {
1135
- if (!["json", "jsonl", "csv"].includes(format))
1136
- throw new StateQLError("INVALID_COMMAND", "Unsupported export format.");
1137
- const result = this.panelResult(id);
1138
- const rows = this.fullResultRows(result);
1139
- const columns = this.store.resultColumns(result).map(column => column.name);
1140
- const chunks = [];
1141
- let bytes = 0;
1142
- const append = (chunk) => {
1143
- bytes += Buffer.byteLength(chunk, "utf8");
1144
- if (bytes > 32 * 1024 * 1024)
1145
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Export exceeds 32 MiB.");
1146
- chunks.push(chunk);
1147
- };
1148
- const csvCell = (value) => {
1149
- let valueText = value === null || value === undefined ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
1150
- if (typeof value !== "number" && /^[\s\u0000-\u001f]*[=+@-]|^[\t\r\n]/u.test(valueText))
1151
- valueText = "'" + valueText;
1152
- return /[",\r\n]/u.test(valueText) ? '"' + valueText.replaceAll('"', '""') + '"' : valueText;
1153
- };
1154
- if (format === "json")
1155
- append("[");
1156
- if (format === "csv")
1157
- append(columns.map(csvCell).join(",") + "\n");
1158
- const deadline = Date.now() + 30_000;
1159
- for (let index = 0; index < rows.length; index++) {
1160
- if (index % 100 === 0) {
1161
- await new Promise(resolve => setImmediate(resolve));
1162
- signal?.throwIfAborted();
1163
- this.signal?.throwIfAborted();
1164
- if (Date.now() > deadline)
1165
- throw new StateQLError("DEADLINE_EXCEEDED", "Export preparation timed out.");
1166
- }
1167
- const row = rows[index];
1168
- append(format === "csv" ? columns.map(column => csvCell(row[column])).join(",") + "\n"
1169
- : (format === "json" && index ? "," : "") + JSON.stringify(row) + (format === "jsonl" ? "\n" : ""));
1170
- }
1171
- signal?.throwIfAborted();
1172
- if (format === "json")
1173
- append("]\n");
1174
- this.panelResult(id);
1175
- return { data: { content: chunks.join(""), format, rows: rows.length }, handle: id };
1176
- }));
580
+ return this.panel.serializeResult(id, format, signal, origin);
1177
581
  }
1178
582
  async readTable(table, limit = 1000, options = {}) {
1179
- return this.commandContexts.run(mergeCommandExecutionContext(this.commandContexts.getStore(), { signal: options.signal, origin: options.origin ?? "api", internal: true }), async () => {
1180
- if (!table || typeof table.name !== "string" || !table.name || table.name.length > 500 || table.name.includes("\0") ||
1181
- (table.schema !== undefined && (typeof table.schema !== "string" || !table.schema || table.schema.length > 500 || table.schema.includes("\0"))) ||
1182
- !Number.isSafeInteger(limit) || limit < 1 || limit > 10_000)
1183
- throw new StateQLError("INVALID_COMMAND", "Invalid table or sample limit.");
1184
- const snapshot = this.snapshot({ historyLimit: 1 });
1185
- const driver = snapshot.connection?.driver;
1186
- if (!driver)
1187
- throw new StateQLError("CONNECTION_NOT_FOUND", "Connect to a database first.");
1188
- if (driver === "sqlite" && table.schema && table.schema !== "main")
1189
- throw new StateQLError("INVALID_COMMAND", "Only the main SQLite schema is supported.");
1190
- if (driver === "mongodb" && table.schema)
1191
- throw new StateQLError("INVALID_COMMAND", "MongoDB collections do not accept a schema.");
1192
- if (driver === "redis")
1193
- throw new StateQLError("INVALID_COMMAND", "Redis keys are not SQL tables; use redisQuery and describeObject.");
1194
- const quote = (name) => driver === "mysql" ? "\`" + name.replaceAll("\`", "\`\`") + "\`" : '"' + name.replaceAll('"', '""') + '"';
1195
- const qualified = [table.schema, table.name].filter((part) => Boolean(part)).map(quote).join(".");
1196
- const query = driver === "mongodb" ? JSON.stringify({ operation: "find", collection: table.name, options: { limit } }, null, 2)
1197
- : "SELECT * FROM " + qualified + " LIMIT " + limit;
1198
- const metadata = await this.editableMetadata(table, options);
1199
- const response = driver === "mongodb"
1200
- ? await this.mongoQuery({ operation: "find", collection: table.name, options: { limit } }, options)
1201
- : await this.query(query, options);
1202
- if (!response.ok)
1203
- return response;
1204
- if (this.tableResults.size >= 20)
1205
- this.tableResults.delete(this.tableResults.keys().next().value);
1206
- this.tableResults.set(response.data.result_id, metadata);
1207
- return { ...response, data: { ...response.data, table, sample_limit: limit, query } };
1208
- });
583
+ return this.panel.readTable(table, limit, options);
1209
584
  }
1210
585
  async planTableUpdate(token, changes, options = {}) {
1211
- return this.commandContexts.run(mergeCommandExecutionContext(this.commandContexts.getStore(), { signal: options.signal, origin: options.origin ?? "api" }), () => this.run("table.plan", async (session) => {
1212
- this.rejectDuringStagedTransaction(session, "Table edits");
1213
- const connection = this.requireConnection(session);
1214
- const original = this.editTokens.get(token);
1215
- if (!original || original.sessionId !== session.id || original.connectionId !== connection.id ||
1216
- original.stateVersion !== version(connection) || original.expires <= this.now().getTime())
1217
- throw new StateQLError("STALE_PLAN", "Row identity expired or the connection changed. Reload the row.");
1218
- if (connection.read_only)
1219
- throw new StateQLError("READ_ONLY_CONNECTION", "This connection is read-only.");
1220
- const metadata = await this.editableMetadata(original.metadata.table, options);
1221
- if (JSON.stringify(metadata) !== JSON.stringify(original.metadata))
1222
- throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload the table.");
1223
- const update = { metadata, original: original.original, changes };
1224
- const compiled = compileTableUpdate(update);
1225
- const context = this.executionContext(options);
1226
- const source = await this.resolveConnectionSource(connection, session, "plan", "read", context);
1227
- const adapter = connection.driver === "mongodb" ? await this.openMongoAdapter(connection, context, source) : await this.openAdapter(connection, context, source);
1228
- try {
1229
- const plan = this.store.savePlan({ sessionId: session.id, ownerActorId: this.actorId, connectionId: connection.id,
1230
- sql: compiled.sql, parameters: [JSON.stringify(update)], statementType: "table.update", stateVersion: version(connection),
1231
- stateSignature: await adapter.signature(), destructive: false, allowUnbounded: false, allowDestructive: false,
1232
- expiresAt: new Date(original.expires).toISOString() });
1233
- return { data: { plan_id: plan.id, statement_type: plan.statement_type, destructive: false, requires_confirmation: true, required_overrides: [],
1234
- state_version: plan.state_version, owner_actor_id: this.actorId, expires_at: plan.expires_at }, handle: plan.id };
1235
- }
1236
- finally {
1237
- await closeAdapterQuietly(adapter);
1238
- }
1239
- }));
586
+ return this.panel.planTableUpdate(token, changes, options);
1240
587
  }
1241
588
  async planTableUpdates(changes, options = {}) {
1242
- return this.commandContexts.run(mergeCommandExecutionContext(this.commandContexts.getStore(), { signal: options.signal, origin: options.origin ?? "api" }), () => this.run("table.plan", async (session) => {
1243
- this.rejectDuringStagedTransaction(session, "Table edits");
1244
- if (!Array.isArray(changes) || changes.length < 1 || changes.length > 100 || Buffer.byteLength(JSON.stringify(changes), "utf8") > 256 * 1024) {
1245
- throw new StateQLError("INVALID_COMMAND", "Table edit batch must contain 1-100 bounded rows.");
1246
- }
1247
- const connection = this.requireConnection(session);
1248
- if (connection.read_only)
1249
- throw new StateQLError("READ_ONLY_CONNECTION", "This connection is read-only.");
1250
- if (connection.driver === "redis")
1251
- throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support table edits.");
1252
- const now = this.now().getTime();
1253
- const tokens = new Set();
1254
- const identities = new Set();
1255
- const updates = [];
1256
- let expires = Number.MAX_SAFE_INTEGER;
1257
- const metadataByTable = new Map();
1258
- for (const item of changes) {
1259
- if (!item || typeof item.row_token !== "string" || tokens.has(item.row_token))
1260
- throw new StateQLError("INVALID_COMMAND", "Table edit row tokens must be unique.");
1261
- tokens.add(item.row_token);
1262
- const original = this.editTokens.get(item.row_token);
1263
- if (!original || original.sessionId !== session.id || original.connectionId !== connection.id || original.stateVersion !== version(connection) || original.expires <= now) {
1264
- throw new StateQLError("STALE_PLAN", "A row identity expired or the connection changed. Reload the rows.");
1265
- }
1266
- const tableKey = JSON.stringify(original.metadata.table);
1267
- let metadata = metadataByTable.get(tableKey);
1268
- if (!metadata) {
1269
- metadata = await this.editableMetadata(original.metadata.table, options);
1270
- metadataByTable.set(tableKey, metadata);
1271
- }
1272
- if (JSON.stringify(metadata) !== JSON.stringify(original.metadata))
1273
- throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload the table.");
1274
- const identity = tableUpdateIdentity(metadata, original.original);
1275
- if (identities.has(identity))
1276
- throw new StateQLError("INVALID_COMMAND", "The same row cannot appear twice in one edit batch.");
1277
- identities.add(identity);
1278
- const update = { metadata, original: original.original, changes: item.changes };
1279
- compileTableUpdate(update);
1280
- updates.push(update);
1281
- expires = Math.min(expires, original.expires);
1282
- }
1283
- const payload = JSON.stringify({ version: 1, updates });
1284
- const context = this.executionContext(options);
1285
- const source = await this.resolveConnectionSource(connection, session, "plan", "read", context);
1286
- const adapter = connection.driver === "mongodb" ? await this.openMongoAdapter(connection, context, source) : await this.openAdapter(connection, context, source);
1287
- try {
1288
- const plan = this.store.savePlan({
1289
- sessionId: session.id, ownerActorId: this.actorId, connectionId: connection.id,
1290
- sql: `Conditional table update batch (${updates.length} rows)`, parameters: [payload], statementType: "table.updates",
1291
- stateVersion: version(connection), stateSignature: await adapter.signature(), destructive: false,
1292
- allowUnbounded: false, allowDestructive: false, expiresAt: new Date(expires).toISOString(),
1293
- });
1294
- return { data: { plan_id: plan.id, statement_type: plan.statement_type, destructive: false, requires_confirmation: true,
1295
- required_overrides: [], state_version: plan.state_version, owner_actor_id: plan.owner_actor_id, expires_at: plan.expires_at },
1296
- handle: plan.id, executed: true, stateVersion: plan.state_version, confidence: adapter.confidence };
1297
- }
1298
- finally {
1299
- await closeAdapterQuietly(adapter);
1300
- }
1301
- }));
1302
- }
1303
- async editableMetadata(table, options) {
1304
- const snapshot = this.snapshot({ historyLimit: 1 });
1305
- const driver = snapshot.connection.driver;
1306
- const unavailable = { table, driver, columns: [], writable: false, reason: "This table or its values cannot be edited safely." };
1307
- // The legacy inspection API splits qualified names. Fail closed for ambiguous names.
1308
- if (table.name.includes(".") || table.schema?.includes("."))
1309
- return { ...unavailable, reason: "Editing identifiers containing dots is not supported." };
1310
- const name = driver === "sqlite" || driver === "mongodb" ? table.name : [table.schema, table.name].filter(Boolean).join(".");
1311
- const response = await this.inspect("editable", name, options);
1312
- if (!response.ok)
1313
- return { ...unavailable, reason: response.error.code };
1314
- const value = response.data;
1315
- if (!value || !Array.isArray(value.columns) || value.columns.length > 100)
1316
- return unavailable;
1317
- return { table, driver, columns: value.columns, writable: value.writable === true && !snapshot.connection.read_only,
1318
- ...(value.writable ? {} : { reason: "Only ordinary tables with transactional writes and a primary key can be edited." }) };
1319
- }
1320
- panelResult(id) {
1321
- if (typeof id !== "string" || !id || id.length > 200)
1322
- throw new StateQLError("INVALID_COMMAND", "A result ID is required.");
1323
- const session = this.store.ensureSession(this.sessionName);
1324
- if (!this.store.isSessionMember(session.id, this.actorId))
1325
- this.throwMembershipDenied(session);
1326
- const result = this.requireResult(id, session);
1327
- if (result.id !== id)
1328
- throw new StateQLError("INVALID_COMMAND", "Use an immutable result ID, not an alias.");
1329
- if (Date.parse(result.expires_at) <= this.now().getTime())
1330
- throw new StateQLError("RESULT_EXPIRED", "Result expired. Run the query again.");
1331
- if (result.row_count > 10_000 || Buffer.byteLength(result.rows_json, "utf8") > 16 * 1024 * 1024)
1332
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "Stored result exceeds browser limits.");
1333
- return result;
1334
- }
1335
- fullResultRows(result) {
1336
- if (this.panelRows?.id !== result.id || this.panelRows.json !== result.rows_json)
1337
- this.panelRows = { id: result.id, json: result.rows_json, rows: this.store.resultRows(result) };
1338
- return this.panelRows.rows;
589
+ return this.panel.planTableUpdates(changes, options);
1339
590
  }
1340
591
  async exportResult(idOrAlias, output, format = "csv", columns) {
1341
- return this.withResult("export", idOrAlias, async (result) => {
1342
- const resultColumns = this.store.resultColumns(result);
1343
- const rows = selectColumns(this.store.resultRows(result), resultColumns, columns);
1344
- const content = format === "json"
1345
- ? `${JSON.stringify(rows, null, 2)}\n`
1346
- : format === "jsonl"
1347
- ? `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`
1348
- : rowsToCsv(rows, columns ?? resultColumns.map((column) => column.name));
1349
- writeFileSync(resolve(output), content, "utf8");
1350
- return {
1351
- data: {
1352
- result_id: result.id,
1353
- output: resolve(output),
1354
- format,
1355
- rows: rows.length,
1356
- },
1357
- handle: result.id,
1358
- executed: true,
1359
- };
1360
- });
592
+ return this.core.withResult("export", idOrAlias, async (result) => exportResult(this.core, result, output, format, columns));
1361
593
  }
1362
594
  async exec(sql, options = {}) {
1363
- return this.run("exec", async (session) => {
1364
- const connection = this.requireConnection(session);
1365
- this.rejectMongoSql(connection, "mongoExec");
1366
- return this.performExec(session, connection, sql, options, this.executionContext(options));
595
+ return this.core.run("exec", async (session) => {
596
+ const connection = this.core.requireSqlConnection(session, "exec");
597
+ this.core.requireWritable(connection);
598
+ const statement = prepareSqlWrite(connection, sql, options.params ?? [], options);
599
+ return runWrite(this.core, session, connection, statement, options, this.core.executionContext(options));
1367
600
  }, sql);
1368
601
  }
1369
602
  async mongoExec(command, options = {}) {
1370
- return this.run("mongo.exec", async (session) => {
1371
- const value = validatedMongoWrite(command);
1372
- const connection = this.requireMongoConnection(session, "mongoExec");
1373
- return this.performMongoExec(session, connection, value, options, this.executionContext(options));
603
+ return this.core.run("mongo.exec", async (session) => {
604
+ const connection = this.core.requireNativeConnection(session, "mongodb", "exec");
605
+ this.core.requireWritable(connection);
606
+ const statement = prepareMongoWrite(connection, command, options);
607
+ return runWrite(this.core, session, connection, statement, options, this.core.executionContext(options));
1374
608
  });
1375
609
  }
1376
610
  async redisExec(command, options = {}) {
1377
- return this.run("redis.exec", async (session) => {
1378
- const value = validatedRedisWrite(command);
1379
- const connection = this.requireRedisConnection(session, "redisExec");
1380
- this.rejectDuringStagedTransaction(session, "Redis writes");
1381
- return this.performRedisExec(session, connection, value, options, this.executionContext(options));
611
+ return this.core.run("redis.exec", async (session) => {
612
+ const connection = this.core.requireNativeConnection(session, "redis", "exec");
613
+ this.core.rejectDuringStagedTransaction(session, "Redis writes");
614
+ this.core.requireWritable(connection);
615
+ const statement = prepareRedisWrite(connection, command);
616
+ return runWrite(this.core, session, connection, statement, options, this.core.executionContext(options));
1382
617
  });
1383
618
  }
1384
619
  async receipt(id) {
1385
- return this.run("receipt", async (session) => {
620
+ return this.core.run("receipt", async (session) => {
1386
621
  const operation = this.store.getOperation(id);
1387
622
  if (!operation || operation.session_id !== session.id) {
1388
623
  throw new StateQLError("RESULT_NOT_FOUND", `Operation "${id}" was not found.`);
@@ -1395,557 +630,56 @@ export class StateQL {
1395
630
  });
1396
631
  }
1397
632
  async beginTransaction(isolation) {
1398
- return this.run("transaction.begin", async (session) => {
1399
- const connection = this.requireConnection(session);
1400
- if (connection.driver === "redis")
1401
- throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support staged StateQL transactions; use redisPlan/apply for one guarded mutation.");
1402
- if (connection.read_only) {
1403
- throw new StateQLError("READ_ONLY_CONNECTION", "Cannot begin a write transaction on a read-only connection.");
1404
- }
1405
- if (session.active_transaction_id) {
1406
- throw new StateQLError("TRANSACTION_FAILED", `Transaction "${session.active_transaction_id}" is already active.`);
1407
- }
1408
- const normalizedIsolation = normalizeIsolation(isolation ?? (connection.driver === "mongodb" ? "snapshot" : "serializable"), connection.driver);
1409
- const transaction = this.store.createTransaction({
1410
- sessionId: session.id,
1411
- actorId: this.actorId,
1412
- connectionId: connection.id,
1413
- isolation: normalizedIsolation,
1414
- });
1415
- if (!transaction) {
1416
- throw new StateQLError("TRANSACTION_FAILED", "Another actor acquired the active transaction.");
1417
- }
1418
- return {
1419
- data: transactionData(transaction, 0),
1420
- handle: transaction.id,
1421
- executed: true,
1422
- stateVersion: transaction.start_version,
1423
- };
1424
- });
633
+ return this.core.run("transaction.begin", async (session) => beginTransaction(this.core, session, isolation));
1425
634
  }
1426
635
  async transactionStatus(id) {
1427
- return this.run("transaction.status", async (session) => {
1428
- const transactionId = id ?? session.active_transaction_id;
1429
- if (!transactionId) {
1430
- throw new StateQLError("TRANSACTION_NOT_FOUND", "No active transaction.");
1431
- }
1432
- const transaction = this.store.getTransaction(transactionId);
1433
- if (!transaction || transaction.session_id !== session.id) {
1434
- throw new StateQLError("TRANSACTION_NOT_FOUND", `Transaction "${transactionId}" was not found.`);
1435
- }
1436
- const operations = this.store.transactionOperations(transaction.id);
1437
- return {
1438
- data: transactionData(transaction, operations.length),
1439
- handle: transaction.id,
1440
- stateVersion: transaction.start_version,
1441
- };
1442
- });
636
+ return this.core.run("transaction.status", async (session) => transactionStatus(this.core, session, id));
1443
637
  }
1444
638
  async commitTransaction(id, options = {}) {
1445
- return this.run("transaction.commit", async (session) => {
1446
- const transaction = this.requireActiveTransaction(session, id);
1447
- const connection = this.store.getConnection(transaction.connection_id);
1448
- if (!connection) {
1449
- throw new StateQLError("CONNECTION_NOT_FOUND", "Transaction connection was not found.");
1450
- }
1451
- if (version(connection) !== transaction.start_version) {
1452
- throw new StateQLError("TRANSACTION_FAILED", "Connection state changed after the transaction began.", { suggestedAction: "Roll back and begin a new transaction." });
1453
- }
1454
- // Validate durable payloads before opening a database adapter or changing
1455
- // the transaction state.
1456
- const operations = this.store.validatedTransactionOperations(transaction.id);
1457
- if (operations.some((operation) => operation.connection_id !== connection.id)) {
1458
- throw new StateQLError("TRANSACTION_FAILED", "Transaction contains writes staged for another connection.");
1459
- }
1460
- const mongoCommands = connection.driver === "mongodb"
1461
- ? operations.map(storedMongoOperation)
1462
- : undefined;
1463
- if (connection.driver !== "mongodb" &&
1464
- operations.some((operation) => operation.statement_type.startsWith("mongo."))) {
1465
- throw new StateQLError("TRANSACTION_FAILED", "Transaction contains native MongoDB writes for a SQL connection.");
1466
- }
1467
- const context = this.executionContext(options);
1468
- const adapterSource = await this.resolveConnectionSource(connection, session, "transaction.commit", "write", context);
1469
- const adapter = connection.driver === "mongodb"
1470
- ? await this.openMongoAdapter(connection, context, adapterSource)
1471
- : await this.openAdapter(connection, context, adapterSource);
1472
- try {
1473
- if (!this.store.claimTransactionForCommit(transaction.id, session.id, this.actorId, operations)) {
1474
- throw new StateQLError("TRANSACTION_FAILED", "Transaction is no longer active.");
1475
- }
1476
- let results;
1477
- try {
1478
- results = mongoCommands
1479
- ? await adapter.writeBatch(mongoCommands, transaction.isolation_level)
1480
- : await adapter.writeBatch(operations, transaction.isolation_level);
1481
- }
1482
- catch (error) {
1483
- if ((error instanceof BatchWriteError && !error.outcomeUnknown) ||
1484
- (error instanceof AdapterExecutionError && !error.outcomeUnknown)) {
1485
- this.store.finishTransaction(transaction.id, session.id, this.actorId, "failed");
1486
- if (error instanceof AdapterExecutionError) {
1487
- throw stoppedStateQLError(error, false);
1488
- }
1489
- throw new StateQLError("TRANSACTION_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true });
1490
- }
1491
- markTransactionOutcomeUnknown(this.store, transaction.id, session.id, this.actorId);
1492
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, adapterSource), {
1493
- executed: true,
1494
- suggestedAction: "Inspect database state before issuing any replacement write.",
1495
- });
1496
- }
1497
- if (results.length !== operations.length) {
1498
- markTransactionOutcomeUnknown(this.store, transaction.id, session.id, this.actorId);
1499
- throw new StateQLError("OUTCOME_UNKNOWN", "Database returned an incomplete transaction result.", {
1500
- executed: true,
1501
- suggestedAction: "Inspect database state before issuing any replacement write.",
1502
- });
1503
- }
1504
- let stateVersion;
1505
- try {
1506
- stateVersion = this.store.commitTransactionMetadata({
1507
- transactionId: transaction.id,
1508
- sessionId: session.id,
1509
- actorId: this.actorId,
1510
- connectionId: connection.id,
1511
- operations: operations.map((operation, index) => ({
1512
- id: operation.id,
1513
- affectedRows: results[index].affectedRows,
1514
- ...(results[index].outcome
1515
- ? { outcome: results[index].outcome }
1516
- : {}),
1517
- })),
1518
- });
1519
- }
1520
- catch (error) {
1521
- markTransactionOutcomeUnknown(this.store, transaction.id, session.id, this.actorId);
1522
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, adapterSource), {
1523
- executed: true,
1524
- suggestedAction: "Inspect database state before issuing any replacement write.",
1525
- });
1526
- }
1527
- return {
1528
- data: {
1529
- transaction_id: transaction.id,
1530
- state: "committed",
1531
- statements_executed: operations.length,
1532
- affected_rows: results.reduce((total, result) => total + result.affectedRows, 0),
1533
- state_version: stateVersion,
1534
- },
1535
- handle: transaction.id,
1536
- executed: true,
1537
- stateVersion,
1538
- confidence: adapter.confidence,
1539
- };
1540
- }
1541
- finally {
1542
- try {
1543
- await adapter.close();
1544
- }
1545
- catch {
1546
- // Transaction outcome and metadata are already recorded.
1547
- }
1548
- }
1549
- });
639
+ return this.core.run("transaction.commit", (session) => commitTransaction(this.core, session, id, options));
1550
640
  }
1551
641
  async rollbackTransaction(id) {
1552
- return this.run("transaction.rollback", async (session) => {
1553
- const transaction = this.requireActiveTransaction(session, id);
1554
- const count = this.store.transactionOperations(transaction.id).length;
1555
- if (!this.store.finishTransaction(transaction.id, session.id, this.actorId, "rolled_back")) {
1556
- throw new StateQLError("TRANSACTION_FAILED", "Transaction is no longer active.");
1557
- }
1558
- return {
1559
- data: {
1560
- transaction_id: transaction.id,
1561
- state: "rolled_back",
1562
- discarded_statements: count,
1563
- },
1564
- handle: transaction.id,
1565
- executed: true,
1566
- stateVersion: transaction.start_version,
1567
- };
1568
- });
642
+ return this.core.run("transaction.rollback", async (session) => rollbackTransaction(this.core, session, id));
1569
643
  }
1570
644
  async inspect(kind, table, options = {}) {
1571
- return this.run(`inspect.${kind}`, async (session) => {
1572
- const connection = this.requireConnection(session);
1573
- this.rejectDuringStagedTransaction(session, "Schema inspection");
1574
- const context = this.executionContext(options);
1575
- const adapterSource = await this.resolveConnectionSource(connection, session, "inspect", "read", context);
1576
- if (connection.driver === "redis")
1577
- throw new StateQLError("INVALID_COMMAND", "Legacy inspect is not supported for Redis; use listObjects or describeObject.");
1578
- const adapter = connection.driver === "mongodb"
1579
- ? await this.openMongoAdapter(connection, context, adapterSource)
1580
- : await this.openAdapter(connection, context, adapterSource);
1581
- try {
1582
- const data = await adapter.inspect(kind, table);
1583
- return {
1584
- data,
1585
- executed: true,
1586
- stateVersion: version(connection),
1587
- confidence: adapter.confidence,
1588
- };
1589
- }
1590
- catch (error) {
1591
- if (error instanceof AdapterExecutionError) {
1592
- throw stoppedStateQLError(error, true);
1593
- }
1594
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), {
1595
- retryable: false,
1596
- executed: true,
1597
- });
1598
- }
1599
- finally {
1600
- await closeAdapterQuietly(adapter);
1601
- }
1602
- }, undefined, table);
645
+ return this.core.run(`inspect.${kind}`, (session) => inspectSchema(this.core, session, kind, table, options), undefined, table);
1603
646
  }
1604
647
  async listObjects(filter = {}, options = {}) {
1605
- return this.run("objects.list", async (session) => {
1606
- validateCatalogFilter(filter);
1607
- const connection = this.requireConnection(session);
1608
- this.rejectDuringStagedTransaction(session, "Catalog discovery");
1609
- const context = this.executionContext(options);
1610
- const source = await this.resolveConnectionSource(connection, session, "inspect", "read", context);
1611
- const adapter = connection.driver === "mongodb"
1612
- ? await this.openMongoAdapter(connection, context, source)
1613
- : connection.driver === "redis"
1614
- ? await this.openRedisAdapter(connection, context, source)
1615
- : await this.openAdapter(connection, context, source);
1616
- try {
1617
- return { data: await adapter.listObjects(filter), executed: true, stateVersion: version(connection), confidence: adapter.confidence };
1618
- }
1619
- catch (error) {
1620
- if (error instanceof AdapterExecutionError)
1621
- throw stoppedStateQLError(error, true);
1622
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
1623
- }
1624
- finally {
1625
- await closeAdapterQuietly(adapter);
1626
- }
1627
- });
648
+ return this.core.run("objects.list", (session) => listObjects(this.core, session, filter, options));
1628
649
  }
1629
650
  async describeObject(object, options = {}) {
1630
- return this.run("object.describe", async (session) => {
1631
- validateCatalogObject(object);
1632
- const connection = this.requireConnection(session);
1633
- this.rejectDuringStagedTransaction(session, "Catalog description");
1634
- const context = this.executionContext(options);
1635
- const source = await this.resolveConnectionSource(connection, session, "inspect", "read", context);
1636
- const adapter = connection.driver === "mongodb"
1637
- ? await this.openMongoAdapter(connection, context, source)
1638
- : connection.driver === "redis"
1639
- ? await this.openRedisAdapter(connection, context, source)
1640
- : await this.openAdapter(connection, context, source);
1641
- try {
1642
- return { data: await adapter.describeObject(object), executed: true, stateVersion: version(connection), confidence: adapter.confidence };
1643
- }
1644
- catch (error) {
1645
- if (error instanceof AdapterExecutionError)
1646
- throw stoppedStateQLError(error, true);
1647
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
1648
- }
1649
- finally {
1650
- await closeAdapterQuietly(adapter);
1651
- }
1652
- });
651
+ return this.core.run("object.describe", (session) => describeObject(this.core, session, object, options));
1653
652
  }
1654
653
  async plan(sql, options = {}) {
1655
- return this.run("plan", async (session) => {
1656
- const connection = this.requireConnection(session);
1657
- this.rejectMongoSql(connection, "mongoPlan");
1658
- this.rejectDuringStagedTransaction(session, "Plans");
1659
- const analysis = analyzeSql(sql, connection.driver);
1660
- if (analysis.read) {
1661
- throw new StateQLError("INVALID_SQL", "plan accepts write statements only.");
1662
- }
1663
- const context = this.executionContext(options);
1664
- const adapterSource = await this.resolveConnectionSource(connection, session, "plan", "read", context);
1665
- const adapter = await this.openAdapter(connection, context, adapterSource);
1666
- try {
1667
- const stateSignature = await adapter.signature();
1668
- const estimatedRows = await countMatchedRows(adapter, matchedRowsCount(analysis, options.params ?? [], connection.driver));
1669
- const expiresAt = new Date(this.now().getTime() + 10 * 60_000).toISOString();
1670
- const plan = this.store.savePlan({
1671
- sessionId: session.id,
1672
- ownerActorId: this.actorId,
1673
- connectionId: connection.id,
1674
- sql,
1675
- parameters: options.params ?? [],
1676
- statementType: analysis.statementType,
1677
- stateVersion: version(connection),
1678
- stateSignature,
1679
- destructive: analysis.destructive || analysis.unboundedMutation,
1680
- allowUnbounded: options.allowUnbounded ?? false,
1681
- allowDestructive: options.allowDestructive ?? false,
1682
- expiresAt,
1683
- });
1684
- return {
1685
- data: {
1686
- plan_id: plan.id,
1687
- statement_type: plan.statement_type,
1688
- destructive: Boolean(plan.destructive),
1689
- requires_confirmation: (analysis.unboundedMutation && !Boolean(plan.allow_unbounded)) ||
1690
- (analysis.destructive && !Boolean(plan.allow_destructive)),
1691
- required_overrides: [
1692
- ...(analysis.unboundedMutation && !Boolean(plan.allow_unbounded)
1693
- ? ["--allow-unbounded"]
1694
- : []),
1695
- ...(analysis.destructive && !Boolean(plan.allow_destructive)
1696
- ? ["--allow-destructive"]
1697
- : []),
1698
- ],
1699
- state_version: plan.state_version,
1700
- owner_actor_id: plan.owner_actor_id,
1701
- expires_at: plan.expires_at,
1702
- ...(estimatedRows === undefined ? {} : { estimated_rows: estimatedRows }),
1703
- },
1704
- handle: plan.id,
1705
- executed: true,
1706
- stateVersion: plan.state_version,
1707
- confidence: adapter.confidence,
1708
- };
1709
- }
1710
- catch (error) {
1711
- if (error instanceof StateQLError)
1712
- throw error;
1713
- if (error instanceof AdapterExecutionError) {
1714
- throw stoppedStateQLError(error, true);
1715
- }
1716
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1717
- }
1718
- finally {
1719
- await closeAdapterQuietly(adapter);
1720
- }
654
+ return this.core.run("plan", async (session) => {
655
+ const connection = this.core.requireSqlConnection(session, "plan");
656
+ this.core.rejectDuringStagedTransaction(session, "Plans");
657
+ return runPlan(this.core, session, connection, prepareSqlPlan(connection, sql, options), options);
1721
658
  }, sql);
1722
659
  }
1723
660
  async mongoPlan(command, options = {}) {
1724
- return this.run("mongo.plan", async (session) => {
1725
- const value = validatedMongoWrite(command);
1726
- const serializedCommand = serializeMongoCommand(value);
1727
- const connection = this.requireMongoConnection(session, "mongoPlan");
1728
- this.rejectDuringStagedTransaction(session, "Plans");
1729
- const safety = analyzeMongoWriteSafety(value);
1730
- const context = this.executionContext(options);
1731
- const adapterSource = await this.resolveConnectionSource(connection, session, "plan", "read", context);
1732
- const adapter = await this.openMongoAdapter(connection, context, adapterSource);
1733
- try {
1734
- const stateSignature = await adapter.signature();
1735
- const expiresAt = new Date(this.now().getTime() + 10 * 60_000).toISOString();
1736
- const plan = this.store.savePlan({
1737
- sessionId: session.id,
1738
- ownerActorId: this.actorId,
1739
- connectionId: connection.id,
1740
- sql: mongoDescriptor(value.operation),
1741
- parameters: [serializedCommand],
1742
- statementType: `mongo.${value.operation}`,
1743
- stateVersion: version(connection),
1744
- stateSignature,
1745
- destructive: safety.destructive || safety.unbounded,
1746
- allowUnbounded: options.allowUnbounded ?? false,
1747
- allowDestructive: options.allowDestructive ?? false,
1748
- expiresAt,
1749
- });
1750
- return {
1751
- data: {
1752
- plan_id: plan.id,
1753
- statement_type: plan.statement_type,
1754
- destructive: Boolean(plan.destructive),
1755
- requires_confirmation: (safety.unbounded && !Boolean(plan.allow_unbounded)) ||
1756
- (safety.destructive && !Boolean(plan.allow_destructive)),
1757
- required_overrides: [
1758
- ...(safety.unbounded && !Boolean(plan.allow_unbounded)
1759
- ? ["--allow-unbounded"]
1760
- : []),
1761
- ...(safety.destructive && !Boolean(plan.allow_destructive)
1762
- ? ["--allow-destructive"]
1763
- : []),
1764
- ],
1765
- state_version: plan.state_version,
1766
- owner_actor_id: plan.owner_actor_id,
1767
- expires_at: plan.expires_at,
1768
- },
1769
- handle: plan.id,
1770
- executed: true,
1771
- stateVersion: plan.state_version,
1772
- confidence: adapter.confidence,
1773
- };
1774
- }
1775
- catch (error) {
1776
- if (error instanceof StateQLError)
1777
- throw error;
1778
- if (error instanceof AdapterExecutionError) {
1779
- throw stoppedStateQLError(error, true);
1780
- }
1781
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1782
- }
1783
- finally {
1784
- await closeAdapterQuietly(adapter);
1785
- }
661
+ return this.core.run("mongo.plan", async (session) => {
662
+ const statement = prepareMongoPlan(command, options);
663
+ const connection = this.core.requireNativeConnection(session, "mongodb", "plan");
664
+ this.core.rejectDuringStagedTransaction(session, "Plans");
665
+ return runPlan(this.core, session, connection, statement, options);
1786
666
  });
1787
667
  }
1788
668
  async redisPlan(command, options = {}) {
1789
- return this.run("redis.plan", async (session) => {
1790
- const value = validatedRedisWrite(command);
1791
- const connection = this.requireRedisConnection(session, "redisPlan");
1792
- this.rejectDuringStagedTransaction(session, "Plans");
1793
- if (connection.read_only)
1794
- throw new StateQLError("READ_ONLY_CONNECTION", "Connection is read-only.");
1795
- const context = this.executionContext(options);
1796
- const source = await this.resolveConnectionSource(connection, session, "plan", "read", context);
1797
- const adapter = await this.openRedisAdapter(connection, context, source);
1798
- try {
1799
- const precondition = await adapter.precondition(value);
1800
- const payload = JSON.stringify({ command: serializeRedisCommand(value), precondition });
1801
- const plan = this.store.savePlan({
1802
- sessionId: session.id, ownerActorId: this.actorId, connectionId: connection.id,
1803
- sql: `Redis native ${value.command}`, parameters: [payload], statementType: `redis.${value.command.toLowerCase()}`,
1804
- stateVersion: version(connection), stateSignature: await adapter.signature(), destructive: value.command === "DEL",
1805
- allowUnbounded: false, allowDestructive: true,
1806
- expiresAt: new Date(this.now().getTime() + 10 * 60_000).toISOString(),
1807
- });
1808
- return { data: { plan_id: plan.id, statement_type: plan.statement_type, destructive: Boolean(plan.destructive),
1809
- requires_confirmation: true, required_overrides: [], state_version: plan.state_version,
1810
- owner_actor_id: plan.owner_actor_id, expires_at: plan.expires_at }, handle: plan.id, executed: true,
1811
- stateVersion: plan.state_version, confidence: adapter.confidence };
1812
- }
1813
- catch (error) {
1814
- if (error instanceof StateQLError)
1815
- throw error;
1816
- if (error instanceof AdapterExecutionError)
1817
- throw stoppedStateQLError(error, true);
1818
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
1819
- }
1820
- finally {
1821
- await closeAdapterQuietly(adapter);
1822
- }
669
+ return this.core.run("redis.plan", async (session) => {
670
+ const statement = prepareRedisPlan(command);
671
+ const connection = this.core.requireNativeConnection(session, "redis", "plan");
672
+ this.core.rejectDuringStagedTransaction(session, "Plans");
673
+ this.core.requireWritable(connection);
674
+ return runPlan(this.core, session, connection, statement, options);
1823
675
  });
1824
676
  }
1825
677
  async apply(planId, options = {}) {
1826
678
  let historySql;
1827
- return this.run("apply", async (session) => {
1828
- this.rejectDuringStagedTransaction(session, "Plans");
1829
- const plan = this.store.getPlan(planId);
1830
- if (!plan || plan.session_id !== session.id) {
1831
- throw new StateQLError("STALE_PLAN", `Plan "${planId}" was not found.`);
1832
- }
1833
- if (plan.owner_actor_id !== this.actorId) {
1834
- throw new StateQLError("PERMISSION_DENIED", "Only the actor that created this plan may apply it.");
1835
- }
1836
- if (plan.applied_operation_id) {
1837
- throw new StateQLError("STALE_PLAN", "Plan was already applied.", {
1838
- extra: { previous_operation_id: plan.applied_operation_id },
1839
- });
1840
- }
1841
- if (Date.parse(plan.expires_at) <= this.now().getTime()) {
1842
- throw new StateQLError("STALE_PLAN", "Plan has expired.");
1843
- }
1844
- const tableUpdate = plan.statement_type === "table.update" ? parseTableUpdate(plan.parameters) : undefined;
1845
- const tableUpdates = plan.statement_type === "table.updates" ? parseTableUpdates(plan.parameters) : undefined;
1846
- const compiled = tableUpdate ? compileTableUpdate(tableUpdate) : undefined;
1847
- const compiledUpdates = tableUpdates?.map(compileTableUpdate);
1848
- if (compiled && compiled.sql !== plan.sql)
1849
- throw new StateQLError("STALE_PLAN", "Stored update does not match its plan.");
1850
- const mongoPlan = tableUpdate?.metadata.driver === "mongodb" || tableUpdates?.[0]?.metadata.driver === "mongodb" || plan.statement_type.startsWith("mongo.");
1851
- const redisPlan = plan.statement_type.startsWith("redis.");
1852
- const nativePlan = Boolean(mongoPlan || redisPlan);
1853
- historySql = nativePlan || tableUpdates ? undefined : plan.sql;
1854
- const mongoCommand = compiled?.mongo ?? (plan.statement_type.startsWith("mongo.")
1855
- ? storedMongoPlan(plan.parameters, plan.statement_type, plan.id)
1856
- : undefined);
1857
- const redisStored = redisPlan ? storedRedisPlan(plan.parameters, plan.statement_type, plan.id) : undefined;
1858
- const planParameters = compiled?.params ?? (nativePlan || tableUpdates
1859
- ? undefined
1860
- : parseJson(plan.parameters, `plan "${plan.id}" parameters`, isSqlParameters));
1861
- const claimToken = this.store.randomId("claim");
1862
- const claimed = this.store.claimPlan(plan.id, session.id, this.actorId, claimToken);
1863
- if (!claimed) {
1864
- throw new StateQLError("STALE_PLAN", "Plan is already being applied.");
1865
- }
1866
- let retainClaim = false;
1867
- try {
1868
- const connection = this.requireConnection(session);
1869
- if (connection.id !== claimed.connection_id ||
1870
- version(connection) !== claimed.state_version) {
1871
- throw new StateQLError("STALE_PLAN", "Database state changed after this plan was created.");
1872
- }
1873
- if (mongoPlan && connection.driver !== "mongodb") {
1874
- throw new StateQLError("STALE_PLAN", "MongoDB plan is not attached to a MongoDB connection.");
1875
- }
1876
- if (redisPlan && connection.driver !== "redis") {
1877
- throw new StateQLError("STALE_PLAN", "Redis plan is not attached to a Redis connection.");
1878
- }
1879
- if (!nativePlan && (connection.driver === "mongodb" || connection.driver === "redis")) {
1880
- this.rejectMongoSql(connection, "mongoPlan");
1881
- }
1882
- if (tableUpdate && JSON.stringify(await this.editableMetadata(tableUpdate.metadata.table, options)) !== JSON.stringify(tableUpdate.metadata))
1883
- throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload and plan again.");
1884
- if (tableUpdates) {
1885
- for (const update of tableUpdates) {
1886
- if (JSON.stringify(await this.editableMetadata(update.metadata.table, options)) !== JSON.stringify(update.metadata))
1887
- throw new StateQLError("STALE_PLAN", "Table metadata changed. Reload and plan again.");
1888
- }
1889
- }
1890
- const context = this.executionContext(options);
1891
- const adapterSource = await this.resolveConnectionSource(connection, session, "apply", "write", context);
1892
- const adapter = mongoPlan
1893
- ? await this.openMongoAdapter(connection, context, adapterSource)
1894
- : redisPlan
1895
- ? await this.openRedisAdapter(connection, context, adapterSource)
1896
- : await this.openAdapter(connection, context, adapterSource);
1897
- try {
1898
- if ((await adapter.signature()) !== claimed.state_signature) {
1899
- throw new StateQLError("STALE_PLAN", "Database state changed after this plan was created.");
1900
- }
1901
- }
1902
- catch (error) {
1903
- if (error instanceof StateQLError)
1904
- throw error;
1905
- if (error instanceof AdapterExecutionError) {
1906
- throw stoppedStateQLError(error, true);
1907
- }
1908
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1909
- }
1910
- finally {
1911
- await closeAdapterQuietly(adapter);
1912
- }
1913
- const result = tableUpdates && compiledUpdates
1914
- ? await this.performTableBatch(session, connection, tableUpdates, compiledUpdates, context, { planId: claimed.id, claimToken }, adapterSource)
1915
- : redisStored
1916
- ? await this.performRedisExec(session, connection, redisStored.command, {}, context, { planId: claimed.id, claimToken }, adapterSource, redisStored.precondition)
1917
- : mongoCommand
1918
- ? await this.performMongoExec(session, connection, mongoCommand, {
1919
- allowUnbounded: Boolean(claimed.allow_unbounded),
1920
- allowDestructive: Boolean(claimed.allow_destructive),
1921
- ...(tableUpdate ? { expectedRows: 1 } : {}),
1922
- }, context, { planId: claimed.id, claimToken }, adapterSource)
1923
- : await this.performExec(session, connection, claimed.sql, {
1924
- params: planParameters,
1925
- ...(tableUpdate ? { expectedRows: 1 } : {}),
1926
- allowUnbounded: Boolean(claimed.allow_unbounded),
1927
- allowDestructive: Boolean(claimed.allow_destructive),
1928
- }, context, { planId: claimed.id, claimToken }, adapterSource);
1929
- return {
1930
- ...result,
1931
- data: { plan_id: claimed.id, ...result.data },
1932
- };
1933
- }
1934
- catch (error) {
1935
- if (error instanceof StateQLError &&
1936
- error.details.code === "OUTCOME_UNKNOWN") {
1937
- retainClaim = true;
1938
- }
1939
- throw error;
1940
- }
1941
- finally {
1942
- if (!retainClaim)
1943
- this.store.releasePlanClaim(plan.id, claimToken);
1944
- }
1945
- }, () => historySql);
679
+ return this.core.run("apply", (session) => applyPlan(this.core, session, planId, options, (table, metadataOptions) => this.panel.editableMetadata(table, metadataOptions), (sql) => { historySql = sql; }), () => historySql);
1946
680
  }
1947
681
  async history(limit = 20, options = {}) {
1948
- return this.run("history", async (session) => {
682
+ return this.core.run("history", async (session) => {
1949
683
  if (options.internal !== undefined && typeof options.internal !== "boolean")
1950
684
  throw new StateQLError("INVALID_COMMAND", "History internal filter must be boolean.");
1951
685
  return {
@@ -1963,12 +697,12 @@ export class StateQL {
1963
697
  });
1964
698
  }
1965
699
  async doctor() {
1966
- return this.run("doctor", async (session) => ({
700
+ return this.core.run("doctor", async (session) => ({
1967
701
  data: this.store.diagnostics(session.id),
1968
702
  }));
1969
703
  }
1970
704
  async purge(scope = "expired") {
1971
- return this.run("purge", async (session) => {
705
+ return this.core.run("purge", async (session) => {
1972
706
  if (!["expired", "results", "history", "all"].includes(scope)) {
1973
707
  throw new StateQLError("INVALID_COMMAND", `Unknown purge scope "${scope}".`);
1974
708
  }
@@ -1982,7 +716,7 @@ export class StateQL {
1982
716
  });
1983
717
  }
1984
718
  async capabilities() {
1985
- return this.run("capabilities", async () => ({
719
+ return this.core.run("capabilities", async () => ({
1986
720
  data: {
1987
721
  drivers: ["mongodb", "mysql", "postgres", "redis", "sqlite"],
1988
722
  features: {
@@ -2034,12 +768,12 @@ export class StateQL {
2034
768
  async executeCommand(command, context = {}) {
2035
769
  let activeContext;
2036
770
  try {
2037
- activeContext = mergeCommandExecutionContext(this.commandContexts.getStore(), context);
771
+ activeContext = mergeCommandExecutionContext(this.core.commandContexts.getStore(), context);
2038
772
  }
2039
773
  catch (error) {
2040
774
  return this.batchFailure(errorMessage(error));
2041
775
  }
2042
- return this.commandContexts.run(activeContext, async () => {
776
+ return this.core.commandContexts.run(activeContext, async () => {
2043
777
  if (!command || typeof command !== "object") {
2044
778
  return this.batchFailure("Batch command must be an object.");
2045
779
  }
@@ -2273,611 +1007,11 @@ export class StateQL {
2273
1007
  return;
2274
1008
  }
2275
1009
  }
2276
- async performExec(session, connection, sql, options, context, planClaim, resolvedSource) {
2277
- this.rejectMongoSql(connection, "mongoExec");
2278
- if (connection.read_only) {
2279
- throw new StateQLError("READ_ONLY_CONNECTION", "Connection is read-only.", { suggestedAction: "Reconnect with --read-write." });
2280
- }
2281
- const analysis = analyzeSql(sql, connection.driver);
2282
- if (analysis.read) {
2283
- throw new StateQLError("INVALID_SQL", "exec accepts write statements only; use query for reads.");
2284
- }
2285
- if (analysis.unboundedMutation && !options.allowUnbounded) {
2286
- throw new StateQLError("UNBOUNDED_MUTATION", "Mutation has no WHERE clause.", { extra: { override_flag: "--allow-unbounded" } });
2287
- }
2288
- if (analysis.destructive && !options.allowDestructive) {
2289
- throw new StateQLError("DESTRUCTIVE_OPERATION_BLOCKED", "Destructive operation requires an explicit override.", { extra: { override_flag: "--allow-destructive" } });
2290
- }
2291
- if (options.idempotencyKey !== undefined &&
2292
- !options.idempotencyKey.trim()) {
2293
- throw new StateQLError("INVALID_COMMAND", "Idempotency key cannot be empty.");
2294
- }
2295
- const parameters = options.params ?? [];
2296
- if (analysis.requiresAutocommit &&
2297
- (options.expectedRows !== undefined || sqlParametersLength(parameters) > 0)) {
2298
- throw new StateQLError("INVALID_SQL", "Autocommit maintenance statements do not accept StateQL parameters or row-count preconditions.");
2299
- }
2300
- const transactionId = session.active_transaction_id ?? undefined;
2301
- if (analysis.requiresAutocommit && transactionId) {
2302
- throw new StateQLError("TRANSACTION_FAILED", `${analysis.statementType.toUpperCase()} cannot be staged in a transaction.`, { suggestedAction: "Rollback or commit the staged transaction, then run the maintenance statement separately." });
2303
- }
2304
- const fingerprint = hash({
2305
- sql: analysis.normalized,
2306
- parameters,
2307
- database: databaseIdentity(connection),
2308
- });
2309
- if (transactionId) {
2310
- const transaction = this.store.getTransaction(transactionId);
2311
- if (!transaction ||
2312
- transaction.session_id !== session.id ||
2313
- transaction.state !== "active" ||
2314
- transaction.connection_id !== connection.id) {
2315
- throw new StateQLError("TRANSACTION_FAILED", "Active transaction does not match the active connection.");
2316
- }
2317
- if (transaction.owner_actor_id !== this.actorId) {
2318
- throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
2319
- }
2320
- }
2321
- const reservation = this.store.reserveOperation({
2322
- sessionId: session.id,
2323
- actorId: this.actorId,
2324
- connectionId: connection.id,
2325
- fingerprint,
2326
- sql,
2327
- parameters,
2328
- statementType: analysis.statementType,
2329
- status: transactionId ? "pending" : "executing",
2330
- transactionId,
2331
- replay: options.replay ?? false,
2332
- idempotencyKey: options.idempotencyKey,
2333
- stateVersionBefore: version(connection),
2334
- });
2335
- if (reservation.denied === "membership") {
2336
- throw new StateQLError("PERMISSION_DENIED", "Actor membership changed before the write was reserved.");
2337
- }
2338
- if (reservation.denied === "transaction") {
2339
- const active = this.store.getSession(session.id)?.active_transaction_id;
2340
- const transaction = active ? this.store.getTransaction(active) : undefined;
2341
- if (transaction && transaction.owner_actor_id !== this.actorId) {
2342
- throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
2343
- }
2344
- throw new StateQLError("TRANSACTION_FAILED", "The active transaction changed before the write was reserved.");
2345
- }
2346
- const previous = reservation.previous;
2347
- if (previous &&
2348
- options.idempotencyKey &&
2349
- !options.replay &&
2350
- previous.fingerprint !== fingerprint) {
2351
- throw new StateQLError("IDEMPOTENCY_CONFLICT", "Idempotency key was already used for a different write.", { extra: { previous_operation_id: previous.id } });
2352
- }
2353
- if (previous && !reservation.operation) {
2354
- if (previous.status === "executing" ||
2355
- previous.status === "outcome_unknown") {
2356
- throw new StateQLError("OUTCOME_UNKNOWN", "A matching write has an unknown outcome.", {
2357
- executed: true,
2358
- suggestedAction: "Inspect database state, then use --replay only if another execution is safe.",
2359
- extra: { previous_operation_id: previous.id },
2360
- });
2361
- }
2362
- if (options.idempotencyKey) {
2363
- return {
2364
- data: {
2365
- ...operationData(previous),
2366
- duplicate: true,
2367
- duplicate_of: previous.id,
2368
- idempotency_key: options.idempotencyKey,
2369
- },
2370
- handle: previous.id,
2371
- cached: true,
2372
- stateVersion: previous.state_version_after ?? previous.state_version_before,
2373
- };
2374
- }
2375
- throw new StateQLError("POTENTIAL_DUPLICATE_WRITE", "An equivalent operation was previously applied.", {
2376
- extra: {
2377
- previous_operation_id: previous.id,
2378
- replay_required: true,
2379
- },
2380
- });
2381
- }
2382
- const operation = reservation.operation;
2383
- if (transactionId) {
2384
- return {
2385
- data: operationData(operation),
2386
- handle: operation.id,
2387
- executed: false,
2388
- stateVersion: version(connection),
2389
- };
2390
- }
2391
- let adapter;
2392
- let adapterSource;
2393
- try {
2394
- adapterSource =
2395
- resolvedSource ??
2396
- (await this.resolveConnectionSource(connection, session, "exec", "write", context));
2397
- adapter = await this.openAdapter(connection, context, adapterSource);
2398
- }
2399
- catch (error) {
2400
- this.store.failOperation(operation.id);
2401
- if (error instanceof StateQLError)
2402
- throw error;
2403
- throw new StateQLError("CONNECTION_FAILED", "Database connection failed.", {
2404
- retryable: true,
2405
- });
2406
- }
2407
- try {
2408
- if (analysis.requiresAutocommit && !adapter.writeAutocommit) {
2409
- throw new AdapterWriteError(`${analysis.statementType.toUpperCase()} requires adapter autocommit execution.`, false);
2410
- }
2411
- const write = analysis.requiresAutocommit
2412
- ? await adapter.writeAutocommit(sql, parameters)
2413
- : await adapter.write(sql, parameters, options.expectedRows);
2414
- try {
2415
- const finalized = planClaim
2416
- ? this.store.finishPlannedOperation({
2417
- planId: planClaim.planId,
2418
- claimToken: planClaim.claimToken,
2419
- operationId: operation.id,
2420
- connectionId: connection.id,
2421
- affectedRows: write.affectedRows,
2422
- })
2423
- : (() => {
2424
- const stateVersion = this.store.bumpVersion(connection.id);
2425
- return {
2426
- operation: this.store.finishOperation(operation.id, write.affectedRows, stateVersion),
2427
- stateVersion,
2428
- };
2429
- })();
2430
- const committed = finalized.operation;
2431
- const after = finalized.stateVersion;
2432
- return {
2433
- data: {
2434
- ...operationData(committed),
2435
- duplicate: Boolean(previous),
2436
- duplicate_override: Boolean(previous),
2437
- },
2438
- handle: committed.id,
2439
- executed: true,
2440
- stateVersion: after,
2441
- confidence: adapter.confidence,
2442
- };
2443
- }
2444
- catch (error) {
2445
- this.store.markOperationOutcomeUnknown(operation.id);
2446
- throw new StateQLError("OUTCOME_UNKNOWN", errorMessage(error), {
2447
- executed: true,
2448
- suggestedAction: "Inspect database state before issuing any replacement write.",
2449
- });
2450
- }
2451
- }
2452
- catch (error) {
2453
- if (error instanceof StateQLError)
2454
- throw error;
2455
- if (error instanceof AdapterExecutionError && !error.outcomeUnknown) {
2456
- this.store.failOperation(operation.id);
2457
- throw stoppedStateQLError(error, false);
2458
- }
2459
- if (error instanceof AdapterWriteError && !error.outcomeUnknown) {
2460
- this.store.failOperation(operation.id);
2461
- if (error.message.startsWith("ROW_CONFLICT:"))
2462
- throw new StateQLError("ROW_CONFLICT", "The row changed or no longer matches. Reload before editing.");
2463
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { executed: true });
2464
- }
2465
- this.store.markOperationOutcomeUnknown(operation.id);
2466
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, adapterSource), {
2467
- executed: true,
2468
- suggestedAction: "Inspect database state, then use --replay only if another execution is safe.",
2469
- });
2470
- }
2471
- finally {
2472
- try {
2473
- await adapter.close();
2474
- }
2475
- catch {
2476
- // Write outcome and metadata are already recorded.
2477
- }
2478
- }
2479
- }
2480
- async performMongoExec(session, connection, command, options, context, planClaim, resolvedSource) {
2481
- const value = validatedMongoWrite(command);
2482
- if (connection.driver !== "mongodb") {
2483
- throw new StateQLError("INVALID_COMMAND", "mongoExec requires an active MongoDB connection.");
2484
- }
2485
- if (connection.read_only) {
2486
- throw new StateQLError("READ_ONLY_CONNECTION", "Connection is read-only.", { suggestedAction: "Reconnect with --read-write." });
2487
- }
2488
- const safety = analyzeMongoWriteSafety(value);
2489
- if (safety.unbounded && !options.allowUnbounded) {
2490
- throw new StateQLError("UNBOUNDED_MUTATION", "MongoDB mutation has an empty filter.", { extra: { override_flag: "--allow-unbounded" } });
2491
- }
2492
- if (safety.destructive && !options.allowDestructive) {
2493
- throw new StateQLError("DESTRUCTIVE_OPERATION_BLOCKED", "Destructive MongoDB operation requires an explicit override.", { extra: { override_flag: "--allow-destructive" } });
2494
- }
2495
- if (options.idempotencyKey !== undefined &&
2496
- !options.idempotencyKey.trim()) {
2497
- throw new StateQLError("INVALID_COMMAND", "Idempotency key cannot be empty.");
2498
- }
2499
- const serializedCommand = serializeMongoCommand(value);
2500
- const parameters = [serializedCommand];
2501
- const fingerprint = hash({
2502
- command: serializedCommand,
2503
- database: databaseIdentity(connection),
2504
- });
2505
- const transactionId = session.active_transaction_id ?? undefined;
2506
- if (transactionId) {
2507
- const transaction = this.store.getTransaction(transactionId);
2508
- if (!transaction ||
2509
- transaction.session_id !== session.id ||
2510
- transaction.state !== "active" ||
2511
- transaction.connection_id !== connection.id) {
2512
- throw new StateQLError("TRANSACTION_FAILED", "Active transaction does not match the active connection.");
2513
- }
2514
- if (transaction.owner_actor_id !== this.actorId) {
2515
- throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
2516
- }
2517
- }
2518
- const reservation = this.store.reserveOperation({
2519
- sessionId: session.id,
2520
- actorId: this.actorId,
2521
- connectionId: connection.id,
2522
- fingerprint,
2523
- sql: mongoDescriptor(value.operation),
2524
- parameters,
2525
- statementType: `mongo.${value.operation}`,
2526
- status: transactionId ? "pending" : "executing",
2527
- transactionId,
2528
- replay: options.replay ?? false,
2529
- idempotencyKey: options.idempotencyKey,
2530
- stateVersionBefore: version(connection),
2531
- });
2532
- if (reservation.denied === "membership") {
2533
- throw new StateQLError("PERMISSION_DENIED", "Actor membership changed before the write was reserved.");
2534
- }
2535
- if (reservation.denied === "transaction") {
2536
- const active = this.store.getSession(session.id)?.active_transaction_id;
2537
- const transaction = active ? this.store.getTransaction(active) : undefined;
2538
- if (transaction && transaction.owner_actor_id !== this.actorId) {
2539
- throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may stage writes.");
2540
- }
2541
- throw new StateQLError("TRANSACTION_FAILED", "The active transaction changed before the write was reserved.");
2542
- }
2543
- const previous = reservation.previous;
2544
- if (previous &&
2545
- options.idempotencyKey &&
2546
- !options.replay &&
2547
- previous.fingerprint !== fingerprint) {
2548
- throw new StateQLError("IDEMPOTENCY_CONFLICT", "Idempotency key was already used for a different write.", { extra: { previous_operation_id: previous.id } });
2549
- }
2550
- if (previous && !reservation.operation) {
2551
- if (previous.status === "executing" ||
2552
- previous.status === "outcome_unknown") {
2553
- throw new StateQLError("OUTCOME_UNKNOWN", "A matching write has an unknown outcome.", {
2554
- executed: true,
2555
- suggestedAction: "Inspect database state, then use --replay only if another execution is safe.",
2556
- extra: { previous_operation_id: previous.id },
2557
- });
2558
- }
2559
- if (options.idempotencyKey) {
2560
- return {
2561
- data: {
2562
- ...operationData(previous),
2563
- duplicate: true,
2564
- duplicate_of: previous.id,
2565
- idempotency_key: options.idempotencyKey,
2566
- },
2567
- handle: previous.id,
2568
- cached: true,
2569
- stateVersion: previous.state_version_after ?? previous.state_version_before,
2570
- };
2571
- }
2572
- throw new StateQLError("POTENTIAL_DUPLICATE_WRITE", "An equivalent operation was previously applied.", {
2573
- extra: {
2574
- previous_operation_id: previous.id,
2575
- replay_required: true,
2576
- },
2577
- });
2578
- }
2579
- const operation = reservation.operation;
2580
- if (transactionId) {
2581
- return {
2582
- data: operationData(operation),
2583
- handle: operation.id,
2584
- executed: false,
2585
- stateVersion: version(connection),
2586
- };
2587
- }
2588
- let adapter;
2589
- let adapterSource;
2590
- try {
2591
- adapterSource =
2592
- resolvedSource ??
2593
- (await this.resolveConnectionSource(connection, session, "exec", "write", context));
2594
- adapter = await this.openMongoAdapter(connection, context, adapterSource);
2595
- }
2596
- catch (error) {
2597
- this.store.failOperation(operation.id);
2598
- if (error instanceof StateQLError)
2599
- throw error;
2600
- throw new StateQLError("CONNECTION_FAILED", "Database connection failed.", {
2601
- retryable: true,
2602
- });
2603
- }
2604
- try {
2605
- const write = await adapter.write(value, options.expectedRows);
2606
- try {
2607
- const finalized = planClaim
2608
- ? this.store.finishPlannedOperation({
2609
- planId: planClaim.planId,
2610
- claimToken: planClaim.claimToken,
2611
- operationId: operation.id,
2612
- connectionId: connection.id,
2613
- affectedRows: write.affectedRows,
2614
- outcome: write.outcome,
2615
- })
2616
- : (() => {
2617
- const stateVersion = this.store.bumpVersion(connection.id);
2618
- return {
2619
- operation: this.store.finishOperation(operation.id, write.affectedRows, stateVersion, write.outcome),
2620
- stateVersion,
2621
- };
2622
- })();
2623
- const committed = finalized.operation;
2624
- const after = finalized.stateVersion;
2625
- return {
2626
- data: {
2627
- ...operationData(committed),
2628
- duplicate: Boolean(previous),
2629
- duplicate_override: Boolean(previous),
2630
- },
2631
- handle: committed.id,
2632
- executed: true,
2633
- stateVersion: after,
2634
- confidence: adapter.confidence,
2635
- };
2636
- }
2637
- catch (error) {
2638
- this.store.markOperationOutcomeUnknown(operation.id);
2639
- throw new StateQLError("OUTCOME_UNKNOWN", errorMessage(error), {
2640
- executed: true,
2641
- suggestedAction: "Inspect database state before issuing any replacement write.",
2642
- });
2643
- }
2644
- }
2645
- catch (error) {
2646
- if (error instanceof StateQLError)
2647
- throw error;
2648
- if (error instanceof AdapterExecutionError && !error.outcomeUnknown) {
2649
- this.store.failOperation(operation.id);
2650
- throw stoppedStateQLError(error, false);
2651
- }
2652
- if (error instanceof AdapterWriteError && !error.outcomeUnknown) {
2653
- this.store.failOperation(operation.id);
2654
- if (error.message.startsWith("ROW_CONFLICT:"))
2655
- throw new StateQLError("ROW_CONFLICT", "The document changed or was removed. Reload before editing.");
2656
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { executed: true });
2657
- }
2658
- this.store.markOperationOutcomeUnknown(operation.id);
2659
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, adapterSource), {
2660
- executed: true,
2661
- suggestedAction: "Inspect database state, then use --replay only if another execution is safe.",
2662
- });
2663
- }
2664
- finally {
2665
- try {
2666
- await adapter.close();
2667
- }
2668
- catch {
2669
- // Write outcome and metadata are already recorded.
2670
- }
2671
- }
2672
- }
2673
- async performRedisExec(session, connection, command, options, context, planClaim, resolvedSource, precondition) {
2674
- const value = validatedRedisWrite(command);
2675
- if (connection.driver !== "redis")
2676
- throw new StateQLError("INVALID_COMMAND", "redisExec requires an active Redis connection.");
2677
- if (connection.read_only)
2678
- throw new StateQLError("READ_ONLY_CONNECTION", "Connection is read-only.");
2679
- if (options.idempotencyKey !== undefined && !options.idempotencyKey.trim())
2680
- throw new StateQLError("INVALID_COMMAND", "Idempotency key cannot be empty.");
2681
- const serialized = serializeRedisCommand(value);
2682
- const fingerprint = hash({ command: serialized, database: databaseIdentity(connection) });
2683
- const reservation = this.store.reserveOperation({
2684
- sessionId: session.id, actorId: this.actorId, connectionId: connection.id, fingerprint,
2685
- sql: `Redis native ${value.command}`, parameters: [serialized], statementType: `redis.${value.command.toLowerCase()}`,
2686
- status: "executing", replay: options.replay ?? false, idempotencyKey: options.idempotencyKey,
2687
- stateVersionBefore: version(connection),
2688
- });
2689
- if (reservation.denied)
2690
- throw new StateQLError(reservation.denied === "membership" ? "PERMISSION_DENIED" : "TRANSACTION_FAILED", "Redis write reservation was denied.");
2691
- const previous = reservation.previous;
2692
- if (previous && options.idempotencyKey && !options.replay && previous.fingerprint !== fingerprint) {
2693
- throw new StateQLError("IDEMPOTENCY_CONFLICT", "Idempotency key was already used for a different write.");
2694
- }
2695
- if (previous && !reservation.operation) {
2696
- if (previous.status === "executing" || previous.status === "outcome_unknown")
2697
- throw new StateQLError("OUTCOME_UNKNOWN", "A matching Redis write has an unknown outcome.", { executed: true });
2698
- if (options.idempotencyKey)
2699
- return { data: { ...operationData(previous), duplicate: true, duplicate_of: previous.id, idempotency_key: options.idempotencyKey }, handle: previous.id, cached: true, stateVersion: previous.state_version_after ?? previous.state_version_before };
2700
- throw new StateQLError("POTENTIAL_DUPLICATE_WRITE", "An equivalent Redis operation was previously applied.", { extra: { previous_operation_id: previous.id, replay_required: true } });
2701
- }
2702
- const operation = reservation.operation;
2703
- let adapter;
2704
- let source;
2705
- try {
2706
- source = resolvedSource ?? await this.resolveConnectionSource(connection, session, "exec", "write", context);
2707
- adapter = await this.openRedisAdapter(connection, context, source);
2708
- }
2709
- catch (error) {
2710
- this.store.failOperation(operation.id);
2711
- if (error instanceof StateQLError)
2712
- throw error;
2713
- throw new StateQLError("CONNECTION_FAILED", "Redis connection failed.", { retryable: true });
2714
- }
2715
- try {
2716
- const write = await adapter.write(value, precondition);
2717
- try {
2718
- const finalized = planClaim
2719
- ? this.store.finishPlannedOperation({ planId: planClaim.planId, claimToken: planClaim.claimToken, operationId: operation.id,
2720
- connectionId: connection.id, affectedRows: write.affectedRows, outcome: write.outcome })
2721
- : (() => { const stateVersion = this.store.bumpVersion(connection.id); return { operation: this.store.finishOperation(operation.id, write.affectedRows, stateVersion, write.outcome), stateVersion }; })();
2722
- return { data: { ...operationData(finalized.operation), duplicate: Boolean(previous), duplicate_override: Boolean(previous) },
2723
- handle: finalized.operation.id, executed: true, stateVersion: finalized.stateVersion, confidence: adapter.confidence };
2724
- }
2725
- catch (error) {
2726
- this.store.markOperationOutcomeUnknown(operation.id);
2727
- throw new StateQLError("OUTCOME_UNKNOWN", errorMessage(error), { executed: true, suggestedAction: "Inspect Redis state before issuing a replacement write." });
2728
- }
2729
- }
2730
- catch (error) {
2731
- if (error instanceof StateQLError)
2732
- throw error;
2733
- if ((error instanceof AdapterExecutionError || error instanceof AdapterWriteError) && !error.outcomeUnknown) {
2734
- this.store.failOperation(operation.id);
2735
- if (error.message.startsWith("ROW_CONFLICT:"))
2736
- throw new StateQLError("ROW_CONFLICT", "The Redis key changed. Reload and plan again.");
2737
- throw error instanceof AdapterExecutionError ? stoppedStateQLError(error, false) : new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
2738
- }
2739
- this.store.markOperationOutcomeUnknown(operation.id);
2740
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, source), { executed: true, suggestedAction: "Inspect Redis state before issuing a replacement write." });
2741
- }
2742
- finally {
2743
- await closeAdapterQuietly(adapter);
2744
- }
2745
- }
2746
- async performTableBatch(session, connection, updates, compiled, context, planClaim, source) {
2747
- if (connection.driver === "redis")
2748
- throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support table edit batches.");
2749
- const reservation = this.store.reserveOperation({
2750
- sessionId: session.id, actorId: this.actorId, connectionId: connection.id,
2751
- fingerprint: hash({ plan: planClaim.planId, updates }), sql: `Conditional table update batch (${updates.length} rows)`,
2752
- parameters: [JSON.stringify({ version: 1, updates })], statementType: "table.updates", status: "executing",
2753
- replay: true, stateVersionBefore: version(connection),
2754
- });
2755
- if (!reservation.operation)
2756
- throw new StateQLError("STALE_PLAN", "Table edit batch could not be reserved.");
2757
- const operation = reservation.operation;
2758
- const adapter = connection.driver === "mongodb"
2759
- ? await this.openMongoAdapter(connection, context, source)
2760
- : await this.openAdapter(connection, context, source);
2761
- try {
2762
- let affectedRows;
2763
- if (connection.driver === "mongodb") {
2764
- const commands = compiled.map((item) => {
2765
- if (!item.mongo)
2766
- throw new StateQLError("STALE_PLAN", "Table edit batch contains mixed drivers.");
2767
- return item.mongo;
2768
- });
2769
- const results = await adapter.writeBatch(commands, "snapshot", true);
2770
- affectedRows = results.reduce((sum, item) => sum + item.affectedRows, 0);
2771
- }
2772
- else {
2773
- const operations = compiled.map((item, index) => ({
2774
- ...operation, id: `${operation.id}:${index}`, sql: item.sql, parameters: JSON.stringify(item.params), statement_type: "update", expectedRows: 1,
2775
- }));
2776
- const results = await adapter.writeBatch(operations, "serializable");
2777
- affectedRows = results.reduce((sum, item) => sum + item.affectedRows, 0);
2778
- }
2779
- try {
2780
- const finalized = this.store.finishPlannedOperation({ planId: planClaim.planId, claimToken: planClaim.claimToken,
2781
- operationId: operation.id, connectionId: connection.id, affectedRows });
2782
- return { data: operationData(finalized.operation), handle: finalized.operation.id, executed: true,
2783
- stateVersion: finalized.stateVersion, confidence: adapter.confidence };
2784
- }
2785
- catch (error) {
2786
- this.store.markOperationOutcomeUnknown(operation.id);
2787
- throw new StateQLError("OUTCOME_UNKNOWN", errorMessage(error), { executed: true, suggestedAction: "Inspect every edited row before retrying." });
2788
- }
2789
- }
2790
- catch (error) {
2791
- if (error instanceof StateQLError)
2792
- throw error;
2793
- if ((error instanceof BatchWriteError || error instanceof AdapterExecutionError) && !error.outcomeUnknown) {
2794
- this.store.failOperation(operation.id);
2795
- if (error.message.startsWith("ROW_CONFLICT:"))
2796
- throw new StateQLError("ROW_CONFLICT", "At least one row changed; the entire edit batch was rolled back.");
2797
- throw error instanceof AdapterExecutionError ? stoppedStateQLError(error, false) : new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { executed: true });
2798
- }
2799
- this.store.markOperationOutcomeUnknown(operation.id);
2800
- throw new StateQLError("OUTCOME_UNKNOWN", safeCredentialErrorMessage(error, source), { executed: true, suggestedAction: "Inspect every edited row before retrying." });
2801
- }
2802
- finally {
2803
- await closeAdapterQuietly(adapter);
2804
- }
2805
- }
2806
1010
  batchFailure(message) {
2807
- return this.run("batch", async () => {
1011
+ return this.core.run("batch", async () => {
2808
1012
  throw new StateQLError("INVALID_COMMAND", message);
2809
1013
  });
2810
1014
  }
2811
- async withResult(command, idOrAlias, action) {
2812
- return this.run(command, async (session) => {
2813
- const result = this.requireResult(idOrAlias, session);
2814
- if (Date.parse(result.expires_at) <= this.now().getTime()) {
2815
- throw new StateQLError("RESULT_EXPIRED", `Result "${result.id}" has expired.`, {
2816
- retryable: true,
2817
- suggestedAction: "Run the original query again.",
2818
- });
2819
- }
2820
- return action(result, session);
2821
- });
2822
- }
2823
- rejectDuringStagedTransaction(session, operation) {
2824
- if (!session.active_transaction_id)
2825
- return;
2826
- throw new StateQLError("TRANSACTION_FAILED", `${operation} cannot run while a staged transaction is active.`, { suggestedAction: "Commit or roll back the transaction first." });
2827
- }
2828
- requireResult(idOrAlias, session) {
2829
- const result = this.store.getResult(idOrAlias, session.id);
2830
- if (!result) {
2831
- throw new StateQLError("RESULT_NOT_FOUND", `Result "${idOrAlias}" was not found.`);
2832
- }
2833
- return result;
2834
- }
2835
- requireConnection(session) {
2836
- const connection = this.store.activeConnection(session);
2837
- if (!connection) {
2838
- throw new StateQLError("CONNECTION_NOT_FOUND", "No active connection.", { suggestedAction: "Run stql connect first." });
2839
- }
2840
- return connection;
2841
- }
2842
- requireMongoConnection(session, method) {
2843
- const connection = this.requireConnection(session);
2844
- if (connection.driver !== "mongodb") {
2845
- throw new StateQLError("INVALID_COMMAND", `${method} requires an active MongoDB connection.`);
2846
- }
2847
- return connection;
2848
- }
2849
- requireRedisConnection(session, method) {
2850
- const connection = this.requireConnection(session);
2851
- if (connection.driver !== "redis")
2852
- throw new StateQLError("INVALID_COMMAND", `${method} requires an active Redis connection.`);
2853
- return connection;
2854
- }
2855
- rejectMongoSql(connection, nativeMethod) {
2856
- if (connection.driver !== "mongodb" && connection.driver !== "redis")
2857
- return;
2858
- const method = connection.driver === "redis"
2859
- ? nativeMethod === "mongoQuery" ? "redisQuery" : nativeMethod === "mongoExec" ? "redisExec" : "redisPlan"
2860
- : nativeMethod;
2861
- const name = connection.driver === "redis" ? "Redis" : "MongoDB";
2862
- throw new StateQLError("INVALID_COMMAND", `SQL is not supported for ${name} connections; use ${method} instead.`, { suggestedAction: `Use ${method} with a native ${name} command.` });
2863
- }
2864
- requireActiveTransaction(session, id) {
2865
- const transactionId = id ?? session.active_transaction_id;
2866
- if (!transactionId) {
2867
- throw new StateQLError("TRANSACTION_NOT_FOUND", "No active transaction.");
2868
- }
2869
- const transaction = this.store.getTransaction(transactionId);
2870
- if (!transaction ||
2871
- transaction.session_id !== session.id ||
2872
- transaction.state !== "active" ||
2873
- session.active_transaction_id !== transaction.id) {
2874
- throw new StateQLError("TRANSACTION_NOT_FOUND", `Active transaction "${transactionId}" was not found.`);
2875
- }
2876
- if (transaction.owner_actor_id !== this.actorId) {
2877
- throw new StateQLError("PERMISSION_DENIED", "Only the transaction owner may control it.");
2878
- }
2879
- return transaction;
2880
- }
2881
1015
  requireSelectedSession(current, selected) {
2882
1016
  if (selected !== current.id && selected !== current.name) {
2883
1017
  throw new StateQLError("PERMISSION_DENIED", "Membership can only be managed for the selected session.");
@@ -2903,242 +1037,6 @@ export class StateQL {
2903
1037
  }
2904
1038
  return name;
2905
1039
  }
2906
- throwMembershipDenied(session) {
2907
- throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
2908
- }
2909
- async resolveConnectionSource(connection, session, operation, access, context) {
2910
- const references = [connection.secret_env, connection.credential_ref, connection.password_ref]
2911
- .filter((value) => value !== null);
2912
- if (references.length > 1) {
2913
- throw new StateQLError("STATE_CORRUPTED", "Connection has ambiguous credential references.");
2914
- }
2915
- if (connection.password_ref !== null) {
2916
- validateCredentialRef(connection.password_ref);
2917
- const driver = validatePasswordReferenceTarget(connection.source);
2918
- if (driver !== connection.driver) {
2919
- throw new StateQLError("STATE_CORRUPTED", "Password-reference target driver does not match the stored connection.");
2920
- }
2921
- const password = await this.resolveCredential(connection.password_ref, "password_ref", session, operation, access, context, {
2922
- connection: {
2923
- id: connection.id,
2924
- name: connection.name,
2925
- driver: connection.driver,
2926
- database: connection.database_name,
2927
- readOnly: Boolean(connection.read_only),
2928
- },
2929
- }, connection.source);
2930
- return injectPassword(connection.source, password).source;
2931
- }
2932
- const reference = connection.secret_env ?? connection.credential_ref;
2933
- if (!reference)
2934
- return connection.source;
2935
- const source = connection.secret_env
2936
- ? "secret_env"
2937
- : "credential_ref";
2938
- const value = await this.resolveCredential(reference, source, session, operation, access, context, {
2939
- connection: {
2940
- id: connection.id,
2941
- name: connection.name,
2942
- driver: connection.driver,
2943
- database: connection.database_name,
2944
- readOnly: Boolean(connection.read_only),
2945
- },
2946
- });
2947
- return credentialSource(value, connection.driver, source).source;
2948
- }
2949
- async resolveCredential(reference, source, session, operation, access, context, details = {}, passwordTarget) {
2950
- const resolver = this.credentialResolver;
2951
- const credentialContext = createAdapterContext(this.credentialTimeoutMs, context.signal);
2952
- let value;
2953
- if (!resolver) {
2954
- if (credentialContext.signal?.aborted) {
2955
- throw credentialStateQLError(reference, new CredentialResolutionError("cancelled"));
2956
- }
2957
- if (credentialContext.deadline <= Date.now()) {
2958
- throw credentialStateQLError(reference, new CredentialResolutionError("timeout"));
2959
- }
2960
- if (source === "secret_env")
2961
- value = env[reference];
2962
- }
2963
- else {
2964
- const baseRequest = {
2965
- reference,
2966
- actorId: this.actorId,
2967
- session: { id: session.id, name: session.name },
2968
- operation,
2969
- access,
2970
- ...(context.signal ? { signal: context.signal } : {}),
2971
- ...details,
2972
- };
2973
- const request = source === "password_ref"
2974
- ? { ...baseRequest, source, target: passwordTarget }
2975
- : { ...baseRequest, source };
2976
- try {
2977
- value = await resolveCredentialBeforeDeadline(resolver, request, credentialContext);
2978
- }
2979
- catch (error) {
2980
- throw credentialStateQLError(reference, error);
2981
- }
2982
- }
2983
- if (value === undefined || (source !== "password_ref" && value === "")) {
2984
- throw credentialStateQLError(reference, new CredentialResolutionError("unavailable"));
2985
- }
2986
- context.deadline = Date.now() + (context.timeoutMs ?? this.timeoutMs);
2987
- return value;
2988
- }
2989
- async openAdapter(connection, context, source) {
2990
- try {
2991
- return await createAdapter(connection, context, { source });
2992
- }
2993
- catch (error) {
2994
- if (error instanceof StateQLError)
2995
- throw error;
2996
- throw new StateQLError("CONNECTION_FAILED", safeCredentialErrorMessage(error, source), { retryable: true });
2997
- }
2998
- }
2999
- async openMongoAdapter(connection, context, source) {
3000
- try {
3001
- return new MongoAdapter(connection, context, { source });
3002
- }
3003
- catch (error) {
3004
- if (error instanceof StateQLError)
3005
- throw error;
3006
- throw new StateQLError("CONNECTION_FAILED", safeCredentialErrorMessage(error, source), { retryable: true });
3007
- }
3008
- }
3009
- async openRedisAdapter(connection, context, source) {
3010
- try {
3011
- if (connection.driver !== "redis")
3012
- throw new Error("Redis adapter requires a Redis connection.");
3013
- return new RedisAdapter(source, Boolean(connection.read_only), context);
3014
- }
3015
- catch (error) {
3016
- if (error instanceof StateQLError)
3017
- throw error;
3018
- throw new StateQLError("CONNECTION_FAILED", safeCredentialErrorMessage(error, source), { retryable: true });
3019
- }
3020
- }
3021
- executionContext(options) {
3022
- return createAdapterContext(executionTimeout(options.timeoutMs ?? this.timeoutMs), combineAbortSignals(options.signal, this.commandContexts.getStore()?.signal, this.signal));
3023
- }
3024
- resultData(result, cached, previewRows = this.previewRows) {
3025
- const rows = this.store.resultRows(result);
3026
- const preview = compactRows(rows.slice(0, previewRows), this.maxCellCharacters);
3027
- return {
3028
- result_id: result.id,
3029
- alias: result.alias ?? this.store.generatedAlias(result.id),
3030
- display_alias: result.alias ?? this.store.generatedAlias(result.id),
3031
- rows: result.row_count,
3032
- columns: this.store.resultColumns(result),
3033
- preview,
3034
- preview_count: preview.length,
3035
- truncated: preview.length < result.row_count,
3036
- cached,
3037
- ...(cached ? { duplicate_of: result.id } : {}),
3038
- ...(result.sql.startsWith("Redis native ") ? { next_cursor: redisResultCursor(result.parameters) } : {}),
3039
- state_version: result.state_version,
3040
- storage: {
3041
- mode: "materialized",
3042
- expires_at: result.expires_at,
3043
- },
3044
- };
3045
- }
3046
- cacheValid(result, stateVersion, stateSignature) {
3047
- return (Date.parse(result.expires_at) > this.now().getTime() &&
3048
- Date.parse(result.created_at) + this.cacheTtlSeconds * 1000 >
3049
- this.now().getTime() &&
3050
- result.state_version === stateVersion &&
3051
- result.state_signature === stateSignature);
3052
- }
3053
- async run(command, action, historySql, historyTarget) {
3054
- const started = performance.now();
3055
- const commandContext = this.commandContexts.getStore();
3056
- const origin = commandContext?.origin ?? "legacy";
3057
- const category = historyCategory(command);
3058
- const internal = commandContext?.internal ?? false;
3059
- let session = this.store.ensureSession(this.sessionName);
3060
- if (!this.store.isSessionMember(session.id, this.actorId)) {
3061
- const commandId = this.store.randomId("cmd");
3062
- const error = new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
3063
- return {
3064
- ok: false,
3065
- command_id: commandId,
3066
- session_id: session.id,
3067
- error: error.details,
3068
- meta: {
3069
- duration_ms: Math.round((performance.now() - started) * 1000) / 1000,
3070
- },
3071
- };
3072
- }
3073
- const actorName = this.store.getActor(session.id, this.actorId).actor_name;
3074
- try {
3075
- const result = await action(session);
3076
- const responseSession = result.session ?? session;
3077
- const sqlText = resolveHistorySql(historySql);
3078
- const history = this.store.addHistory({
3079
- sessionId: session.id,
3080
- actorId: this.actorId,
3081
- actorName,
3082
- origin,
3083
- category,
3084
- internal,
3085
- command,
3086
- target: historyTarget,
3087
- ...(result.handle ? { handle: result.handle } : {}),
3088
- ...(sqlText !== undefined ? { sql: sqlText } : {}),
3089
- executed: result.executed ?? false,
3090
- cached: result.cached ?? false,
3091
- success: true,
3092
- });
3093
- return {
3094
- ok: true,
3095
- command_id: history.id,
3096
- session_id: responseSession.id,
3097
- data: result.data,
3098
- warnings: result.warnings ?? [],
3099
- meta: {
3100
- duration_ms: Math.round((performance.now() - started) * 1000) / 1000,
3101
- ...(result.stateVersion
3102
- ? { state_version: result.stateVersion }
3103
- : {}),
3104
- ...(result.confidence
3105
- ? { state_confidence: result.confidence }
3106
- : {}),
3107
- },
3108
- };
3109
- }
3110
- catch (error) {
3111
- const stateqlError = asStateQLError(error);
3112
- const sqlText = resolveHistorySql(historySql);
3113
- const history = this.store.addHistory({
3114
- sessionId: session.id,
3115
- actorId: this.actorId,
3116
- actorName,
3117
- origin,
3118
- category,
3119
- internal,
3120
- command,
3121
- target: historyTarget,
3122
- ...(sqlText !== undefined ? { sql: sqlText } : {}),
3123
- executed: stateqlError.details.executed,
3124
- cached: false,
3125
- success: false,
3126
- errorCode: stateqlError.details.code,
3127
- });
3128
- return {
3129
- ok: false,
3130
- command_id: history.id,
3131
- session_id: session.id,
3132
- error: stateqlError.details,
3133
- meta: {
3134
- duration_ms: Math.round((performance.now() - started) * 1000) / 1000,
3135
- },
3136
- };
3137
- }
3138
- }
3139
- }
3140
- function resolveHistorySql(sql) {
3141
- return typeof sql === "function" ? sql() : sql;
3142
1040
  }
3143
1041
  function historyEntry(item) {
3144
1042
  return {
@@ -3166,419 +1064,8 @@ function actorNameHistoryTarget(value) {
3166
1064
  const name = value.trim();
3167
1065
  return name ? [...name].slice(0, 80).join("") : undefined;
3168
1066
  }
3169
- const COMMAND_ORIGINS = new Set([
3170
- "legacy",
3171
- "user",
3172
- "model",
3173
- "system",
3174
- "api",
3175
- ]);
3176
- function parseCommandOrigin(value) {
3177
- if (typeof value === "string" && COMMAND_ORIGINS.has(value)) {
3178
- return value;
3179
- }
3180
- throw new StateQLError("INVALID_COMMAND", `Unknown command origin "${String(value)}".`);
3181
- }
3182
- function mergeCommandExecutionContext(inherited, supplied) {
3183
- if (!supplied || typeof supplied !== "object") {
3184
- throw new StateQLError("INVALID_COMMAND", "Command execution context must be an object.");
3185
- }
3186
- if (supplied.signal !== undefined && !(supplied.signal instanceof AbortSignal)) {
3187
- throw new StateQLError("INVALID_COMMAND", "Command execution context signal must be an AbortSignal.");
3188
- }
3189
- if (supplied.internal !== undefined && typeof supplied.internal !== "boolean") {
3190
- throw new StateQLError("INVALID_COMMAND", "Command execution context internal must be boolean.");
3191
- }
3192
- return {
3193
- signal: combineAbortSignals(inherited?.signal, supplied.signal),
3194
- origin: supplied.origin === undefined
3195
- ? inherited?.origin
3196
- : parseCommandOrigin(supplied.origin),
3197
- internal: supplied.internal ?? inherited?.internal,
3198
- };
3199
- }
3200
- function combineAbortSignals(...signals) {
3201
- const present = signals.filter((signal) => signal !== undefined);
3202
- if (present.length === 0)
3203
- return undefined;
3204
- if (present.length === 1)
3205
- return present[0];
3206
- return AbortSignal.any(present);
3207
- }
3208
- function markTransactionOutcomeUnknown(store, transactionId, sessionId, actorId) {
3209
- try {
3210
- store.markTransactionOutcomeUnknown(transactionId, sessionId, actorId);
3211
- }
3212
- catch {
3213
- // A stale committing transaction is recovered as unknown after five minutes.
3214
- }
3215
- }
3216
- function sqlParametersLength(parameters) {
3217
- return Array.isArray(parameters)
3218
- ? parameters.length
3219
- : Object.keys(parameters).length;
3220
- }
3221
- function boundedReadSql(sql, limit) {
3222
- const statement = sql.trim().replace(/;\s*$/, "");
3223
- return `SELECT * FROM (${statement}) AS _stateql_bounded LIMIT ${limit}`;
3224
- }
3225
- function validatedMongoRead(command) {
3226
- try {
3227
- return validateMongoReadCommand(command);
3228
- }
3229
- catch (error) {
3230
- throw new StateQLError("INVALID_COMMAND", errorMessage(error));
3231
- }
3232
- }
3233
- function validatedMongoWrite(command) {
3234
- try {
3235
- return validateMongoWriteCommand(command);
3236
- }
3237
- catch (error) {
3238
- throw new StateQLError("INVALID_COMMAND", errorMessage(error));
3239
- }
3240
- }
3241
- function validatedRedisRead(command) {
3242
- try {
3243
- return validateRedisReadCommand(command);
3244
- }
3245
- catch (error) {
3246
- throw new StateQLError("INVALID_COMMAND", errorMessage(error));
3247
- }
3248
- }
3249
- function validatedRedisWrite(command) {
3250
- try {
3251
- return validateRedisWriteCommand(command);
3252
- }
3253
- catch (error) {
3254
- throw new StateQLError("INVALID_COMMAND", errorMessage(error));
3255
- }
3256
- }
3257
- function mongoDescriptor(operation) {
3258
- return `MongoDB native ${operation}`;
3259
- }
3260
- function mongoPaginationWarnings(command) {
3261
- const ordered = command.operation === "find"
3262
- ? command.options?.sort !== undefined
3263
- : command.pipeline.some((stage) => Object.prototype.hasOwnProperty.call(stage, "$sort"));
3264
- return ordered
3265
- ? []
3266
- : [{
3267
- code: "NON_DETERMINISTIC_PAGINATION",
3268
- message: "MongoDB result has no explicit sort.",
3269
- }];
3270
- }
3271
- function storedMongoOperation(operation) {
3272
- if (!operation.statement_type.startsWith("mongo.")) {
3273
- throw new StateQLError("TRANSACTION_FAILED", "MongoDB transaction contains a mixed or corrupt native payload.");
3274
- }
3275
- return storedMongoWrite(operation.parameters, operation.statement_type, `operation "${operation.id}"`, "TRANSACTION_FAILED");
3276
- }
3277
- function storedMongoPlan(parameters, statementType, planId) {
3278
- return storedMongoWrite(parameters, statementType, `plan "${planId}"`, "STALE_PLAN");
3279
- }
3280
- function storedMongoWrite(parameters, statementType, label, errorCode) {
3281
- try {
3282
- const payload = JSON.parse(parameters);
3283
- if (!Array.isArray(payload) ||
3284
- payload.length !== 1 ||
3285
- typeof payload[0] !== "string") {
3286
- throw new Error("payload must contain one EJSON command string");
3287
- }
3288
- const command = deserializeMongoWriteCommand(payload[0]);
3289
- if (statementType !== `mongo.${command.operation}`) {
3290
- throw new Error("operation does not match its statement type");
3291
- }
3292
- return command;
3293
- }
3294
- catch {
3295
- throw new StateQLError(errorCode, `Stored MongoDB ${label} payload is invalid.`);
3296
- }
3297
- }
3298
- function storedRedisPlan(parameters, statementType, planId) {
3299
- try {
3300
- const outer = JSON.parse(parameters);
3301
- if (!Array.isArray(outer) || outer.length !== 1 || typeof outer[0] !== "string")
3302
- throw new Error();
3303
- const payload = JSON.parse(outer[0]);
3304
- if (typeof payload.command !== "string" || !payload.precondition || typeof payload.precondition !== "object")
3305
- throw new Error();
3306
- const command = deserializeRedisCommand(payload.command);
3307
- const precondition = payload.precondition;
3308
- if (typeof precondition.key !== "string" || typeof precondition.fingerprint !== "string" || typeof precondition.expiresAt !== "number" || !Number.isFinite(precondition.expiresAt) || statementType !== `redis.${command.command.toLowerCase()}`)
3309
- throw new Error();
3310
- return { command, precondition };
3311
- }
3312
- catch {
3313
- throw new StateQLError("STALE_PLAN", `Stored Redis plan "${planId}" payload is invalid.`);
3314
- }
3315
- }
3316
- function redisResultCursor(parameters) {
3317
- try {
3318
- const value = JSON.parse(parameters);
3319
- return Array.isArray(value) && (typeof value[1] === "string" || value[1] === null) ? value[1] : null;
3320
- }
3321
- catch {
3322
- return null;
3323
- }
3324
- }
3325
- function tableUpdateIdentity(metadata, row) {
3326
- const identity = metadata.driver === "mongodb"
3327
- ? { table: metadata.table, id: row._id }
3328
- : { table: metadata.table, keys: metadata.columns.filter((column) => column.key > 0).sort((a, b) => a.key - b.key).map((column) => [column.name, row[column.name]]) };
3329
- return hash(identity);
3330
- }
3331
- function validateCatalogFilter(filter) {
3332
- if (!filter || typeof filter !== "object" || Array.isArray(filter) || Object.keys(filter).some((key) => !["kind", "schema", "search", "offset", "limit"].includes(key)))
3333
- throw new StateQLError("INVALID_COMMAND", "Catalog filter contains unknown fields.");
3334
- if (filter.kind !== undefined && !["table", "view", "collection", "function", "trigger", "enum", "key"].includes(filter.kind))
3335
- throw new StateQLError("INVALID_COMMAND", "Unknown catalog object kind.");
3336
- for (const [name, value] of [["schema", filter.schema], ["search", filter.search]])
3337
- if (value !== undefined && (typeof value !== "string" || !value || value.length > 200 || value.includes("\0")))
3338
- throw new StateQLError("INVALID_COMMAND", `Catalog ${name} is invalid.`);
3339
- if (filter.offset !== undefined && !((typeof filter.offset === "number" && Number.isSafeInteger(filter.offset) && filter.offset >= 0) || (typeof filter.offset === "string" && /^\d+$/.test(filter.offset))))
3340
- throw new StateQLError("INVALID_COMMAND", "Catalog offset is invalid.");
3341
- if (filter.limit !== undefined && (!Number.isSafeInteger(filter.limit) || filter.limit < 1 || filter.limit > 200))
3342
- throw new StateQLError("INVALID_COMMAND", "Catalog limit must be 1-200.");
3343
- }
3344
- function validateCatalogObject(object) {
3345
- if (!object || typeof object !== "object" || Array.isArray(object) || !["table", "view", "collection", "function", "trigger", "enum", "key"].includes(object.kind) || typeof object.name !== "string" || !object.name || object.name.length > 500 || object.name.includes("\0") || (object.schema !== undefined && (typeof object.schema !== "string" || !object.schema || object.schema.length > 500 || object.schema.includes("\0"))) || (object.identity !== undefined && (typeof object.identity !== "string" || !object.identity || object.identity.length > 1000 || object.identity.includes("\0"))))
3346
- throw new StateQLError("INVALID_COMMAND", "Catalog object identity is invalid.");
3347
- }
3348
- function databaseDisplayName(driver) {
3349
- if (driver === "mongodb")
3350
- return "MongoDB";
3351
- if (driver === "redis")
3352
- return "Redis";
3353
- return driver === "postgres" ? "PostgreSQL" : "MySQL";
3354
- }
3355
- function normalizeIsolation(isolation, driver) {
3356
- const normalized = isolation.trim().toLowerCase().replace(/[_-]+/g, " ")
3357
- .replace(/\s+/g, " ");
3358
- if (driver === "redis")
3359
- throw new StateQLError("UNSUPPORTED_DRIVER", "Redis does not support staged SQL-style transactions.");
3360
- if (driver === "mongodb") {
3361
- if (normalized === "snapshot")
3362
- return normalized;
3363
- throw new StateQLError("INVALID_COMMAND", `MongoDB does not support isolation level "${normalized}".`);
3364
- }
3365
- const supported = new Set([
3366
- "serializable",
3367
- "repeatable read",
3368
- "read committed",
3369
- "read uncommitted",
3370
- ]);
3371
- if (!supported.has(normalized)) {
3372
- throw new StateQLError("INVALID_COMMAND", `Unsupported isolation level "${isolation}".`);
3373
- }
3374
- if (driver === "sqlite" && normalized !== "serializable") {
3375
- throw new StateQLError("INVALID_COMMAND", `SQLite does not support isolation level "${normalized}".`);
3376
- }
3377
- return normalized;
3378
- }
3379
1067
  function batchString(value, name) {
3380
1068
  if (value?.trim())
3381
1069
  return value;
3382
1070
  throw new StateQLError("INVALID_COMMAND", `Batch command requires "${name}".`);
3383
1071
  }
3384
- function nonNegativeInteger(value, name) {
3385
- if (Number.isInteger(value) && value >= 0)
3386
- return value;
3387
- throw new StateQLError("INVALID_COMMAND", `${name} must be a non-negative integer.`);
3388
- }
3389
- function queryPreviewRows(value) {
3390
- const previewRows = nonNegativeInteger(value, "previewRows");
3391
- if (previewRows <= 200)
3392
- return previewRows;
3393
- throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "previewRows cannot exceed 200 rows.");
3394
- }
3395
- function positiveInteger(value, name) {
3396
- if (Number.isInteger(value) && value > 0)
3397
- return value;
3398
- throw new StateQLError("INVALID_COMMAND", `${name} must be a positive integer.`);
3399
- }
3400
- function selectColumns(rows, available, selected) {
3401
- if (!selected)
3402
- return rows;
3403
- const names = available.map((column) => column.name);
3404
- const unknown = selected.filter((name) => !names.includes(name));
3405
- if (selected.length === 0 || unknown.length > 0) {
3406
- throw new StateQLError("INVALID_COMMAND", unknown.length > 0 ? `Unknown column: ${unknown.join(", ")}.` : "columns cannot be empty.", { suggestedAction: `Use one or more of: ${names.join(", ")}.` });
3407
- }
3408
- // Keep missing keys missing, so MongoDB documents still distinguish missing from null.
3409
- return rows.map((row) => Object.fromEntries(selected.filter((name) => name in row).map((name) => [name, row[name]])));
3410
- }
3411
- function summarizeColumn(name, rows, maxCellCharacters) {
3412
- const values = rows
3413
- .map((row) => row[name])
3414
- .filter((value) => value !== null && value !== undefined);
3415
- const [min, max] = valueRange(values);
3416
- return {
3417
- name,
3418
- nulls: rows.length - values.length,
3419
- distinct: new Set(values.map((value) => JSON.stringify(value))).size,
3420
- min: compactValue(min, maxCellCharacters),
3421
- max: compactValue(max, maxCellCharacters),
3422
- };
3423
- }
3424
- const NUMERIC_TEXT = /^-?\d+(?:\.\d+)?$/;
3425
- // Exact numerics (PostgreSQL numeric/bigint, MySQL DECIMAL) arrive as strings, so compare them as numbers.
3426
- function valueRange(values) {
3427
- const numeric = values.every((value) => typeof value === "number" || (typeof value === "string" && NUMERIC_TEXT.test(value)));
3428
- const text = values.every((value) => typeof value === "string");
3429
- if (values.length === 0)
3430
- return [null, null];
3431
- if (!numeric && !text)
3432
- return [null, null];
3433
- const compare = numeric
3434
- ? (left, right) => Number(left) - Number(right)
3435
- : (left, right) => (String(left) < String(right) ? -1 : String(left) > String(right) ? 1 : 0);
3436
- let min = values[0];
3437
- let max = values[0];
3438
- for (const value of values) {
3439
- if (compare(value, min) < 0)
3440
- min = value;
3441
- if (compare(value, max) > 0)
3442
- max = value;
3443
- }
3444
- return [min, max];
3445
- }
3446
- async function countMatchedRows(adapter, count) {
3447
- if (!count)
3448
- return undefined;
3449
- try {
3450
- const { rows } = await adapter.read(count.sql, count.params);
3451
- const value = Number(Object.values(rows[0] ?? {})[0]);
3452
- return Number.isSafeInteger(value) ? value : undefined;
3453
- }
3454
- catch (error) {
3455
- if (error instanceof AdapterExecutionError)
3456
- throw error;
3457
- // The estimate is advisory; a count the parser cannot express must not block the plan.
3458
- return undefined;
3459
- }
3460
- }
3461
- async function closeAdapterQuietly(adapter) {
3462
- try {
3463
- await adapter.close();
3464
- }
3465
- catch {
3466
- // Preserve the operation result or primary sanitized error.
3467
- }
3468
- }
3469
- async function resolveCredentialBeforeDeadline(resolver, request, context) {
3470
- if (context.signal?.aborted) {
3471
- throw new CredentialResolutionError("cancelled");
3472
- }
3473
- const remaining = context.deadline - Date.now();
3474
- if (remaining <= 0)
3475
- throw new CredentialResolutionError("timeout");
3476
- return new Promise((resolve, reject) => {
3477
- let settled = false;
3478
- const finish = (action, value) => {
3479
- if (settled)
3480
- return;
3481
- settled = true;
3482
- clearTimeout(timer);
3483
- context.signal?.removeEventListener("abort", abort);
3484
- action(value);
3485
- };
3486
- const abort = () => finish(() => reject(new CredentialResolutionError("cancelled")));
3487
- const timer = setTimeout(() => finish(() => reject(new CredentialResolutionError("timeout"))), remaining);
3488
- context.signal?.addEventListener("abort", abort, { once: true });
3489
- Promise.resolve()
3490
- .then(() => resolver(request))
3491
- .then((value) => finish(resolve, value), (error) => finish(() => reject(error)));
3492
- });
3493
- }
3494
- function credentialStateQLError(reference, error) {
3495
- if (error instanceof CredentialResolutionError) {
3496
- switch (error.reason) {
3497
- case "unavailable":
3498
- return new StateQLError("CREDENTIAL_UNAVAILABLE", `Credential reference "${reference}" is unavailable.`, { retryable: true });
3499
- case "denied":
3500
- return new StateQLError("PERMISSION_DENIED", `Credential access for "${reference}" was denied.`);
3501
- case "cancelled":
3502
- return new StateQLError("OPERATION_CANCELLED", "Credential resolution was cancelled.", { retryable: true });
3503
- case "timeout":
3504
- return new StateQLError("DEADLINE_EXCEEDED", "Credential resolution exceeded the credential deadline.", { retryable: true });
3505
- }
3506
- }
3507
- return new StateQLError("CREDENTIAL_RESOLUTION_FAILED", `Credential reference "${reference}" could not be resolved.`, { retryable: true });
3508
- }
3509
- function safeCredentialErrorMessage(error, source) {
3510
- let message = errorMessage(error).split(source).join("[credential redacted]");
3511
- const authority = /^[a-z][a-z\d+.-]*:\/\/([^/?#]*)/i.exec(source)?.[1];
3512
- if (authority) {
3513
- const at = authority.lastIndexOf("@");
3514
- const colon = at < 0 ? -1 : authority.slice(0, at).indexOf(":");
3515
- const password = colon < 0 ? "" : authority.slice(colon + 1, at);
3516
- const secrets = new Set([password]);
3517
- try {
3518
- secrets.add(decodeURIComponent(password));
3519
- }
3520
- catch { /* malformed values stay encoded */ }
3521
- for (const secret of secrets) {
3522
- if (secret)
3523
- message = message.split(secret).join("[credential redacted]");
3524
- }
3525
- }
3526
- return redact(message)
3527
- .replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s\/@]+(?::[^\s\/@]*)?@/giu, "$1***@");
3528
- }
3529
- function executionTimeout(value, name = "timeoutMs") {
3530
- const timeout = positiveInteger(value, name);
3531
- if (timeout > 2_147_483_647) {
3532
- throw new StateQLError("INVALID_COMMAND", `${name} cannot exceed 2147483647 milliseconds.`);
3533
- }
3534
- return timeout;
3535
- }
3536
- function stoppedStateQLError(error, executed) {
3537
- return new StateQLError(error.reason === "timeout" ? "DEADLINE_EXCEEDED" : "OPERATION_CANCELLED", error.message, { retryable: true, executed });
3538
- }
3539
- function validatedProfileSource(input) {
3540
- const sourceCount = [input.target, input.secretEnv, input.credentialRef].filter((value) => value !== undefined).length;
3541
- if (sourceCount !== 1 || input.target === "" || input.secretEnv === "" || input.credentialRef === "") {
3542
- throw new StateQLError("INVALID_COMMAND", "Profile requires exactly one target, secret environment variable, or credential reference.");
3543
- }
3544
- if (input.secretEnv !== undefined && !isEnvironmentName(input.secretEnv))
3545
- throw new StateQLError("INVALID_COMMAND", "Secret environment variable name is invalid.");
3546
- if (input.credentialRef !== undefined)
3547
- validateCredentialRef(input.credentialRef);
3548
- if (input.passwordRef !== undefined)
3549
- validateCredentialRef(input.passwordRef);
3550
- let target = input.target ?? null;
3551
- if (input.passwordRef !== undefined && target === null) {
3552
- throw new StateQLError("INVALID_COMMAND", "A password reference requires a literal remote profile target.");
3553
- }
3554
- if (target) {
3555
- const driver = input.passwordRef !== undefined
3556
- ? validatePasswordReferenceTarget(target)
3557
- : detectDriver(target);
3558
- if (input.passwordRef === undefined && driver !== "sqlite" && databaseUrlHasSecret(target))
3559
- throw new StateQLError("PERMISSION_DENIED", `Credential-bearing ${databaseDisplayName(driver)} URLs must use --env or --credential-ref.`);
3560
- if (driver === "sqlite")
3561
- target = normalizeSqliteSource(target);
3562
- }
3563
- return {
3564
- target,
3565
- secretEnv: input.secretEnv ?? null,
3566
- credentialRef: input.credentialRef ?? null,
3567
- passwordRef: input.passwordRef ?? null,
3568
- };
3569
- }
3570
- function historyCategory(command) {
3571
- if (["query", "exec", "plan", "apply", "mongo.query", "mongo.exec", "mongo.plan", "redis.query", "redis.exec", "redis.plan", "filter"].includes(command))
3572
- return "statement";
3573
- if (command.startsWith("inspect.") || ["objects.list", "object.describe", "table.read"].includes(command))
3574
- return "introspection";
3575
- return "management";
3576
- }
3577
- function parseHistoryCategory(value) {
3578
- if (value === "statement" || value === "introspection" || value === "management")
3579
- return value;
3580
- throw new StateQLError("INVALID_COMMAND", `Unknown history category "${String(value)}".`);
3581
- }
3582
- function errorMessage(error) {
3583
- return error instanceof Error ? error.message : String(error);
3584
- }