@happyvertical/smrt-core 0.43.10 → 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -8
- package/agents/generators.md +104 -0
- package/agents/revision-guard.md +66 -0
- package/agents/schema-paths.md +99 -0
- package/dist/cascade.d.ts +5 -9
- package/dist/cascade.d.ts.map +1 -1
- package/dist/cascade.js +65 -30
- package/dist/cascade.js.map +1 -1
- package/dist/embedded-write-queue.d.ts +8 -0
- package/dist/embedded-write-queue.d.ts.map +1 -1
- package/dist/embedded-write-queue.js +12 -2
- package/dist/embedded-write-queue.js.map +1 -1
- package/dist/generators/custom-action.d.ts.map +1 -1
- package/dist/generators/custom-action.js +1 -1
- package/dist/generators/custom-action.js.map +1 -1
- package/dist/generators/index.d.ts +1 -0
- package/dist/generators/index.d.ts.map +1 -1
- package/dist/generators/index.js +2 -1
- package/dist/generators/preflight-route.d.ts +151 -0
- package/dist/generators/preflight-route.d.ts.map +1 -0
- package/dist/generators/preflight-route.js +194 -0
- package/dist/generators/preflight-route.js.map +1 -0
- package/dist/generators/rest.d.ts +12 -0
- package/dist/generators/rest.d.ts.map +1 -1
- package/dist/generators/rest.js +12 -15
- package/dist/generators/rest.js.map +1 -1
- package/dist/generators.js +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/knowledge.d.ts +17 -1
- package/dist/knowledge.d.ts.map +1 -1
- package/dist/knowledge.js +33 -3
- package/dist/knowledge.js.map +1 -1
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +6 -2
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +8 -2
- package/dist/migrations/differ.d.ts +49 -0
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +220 -4
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/orchestrate.d.ts +23 -0
- package/dist/migrations/orchestrate.d.ts.map +1 -1
- package/dist/migrations/orchestrate.js +12 -3
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/object.d.ts +31 -1
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +57 -9
- package/dist/object.js.map +1 -1
- package/dist/registry/types.d.ts +8 -3
- package/dist/registry/types.d.ts.map +1 -1
- package/dist/revision-guard.d.ts +84 -0
- package/dist/revision-guard.d.ts.map +1 -0
- package/dist/revision-guard.js +120 -0
- package/dist/revision-guard.js.map +1 -0
- package/dist/schema/foreign-key-ddl.d.ts +7 -0
- package/dist/schema/foreign-key-ddl.d.ts.map +1 -1
- package/dist/schema/foreign-key-ddl.js +7 -1
- package/dist/schema/foreign-key-ddl.js.map +1 -1
- package/dist/schema/schema-manager.d.ts +15 -0
- package/dist/schema/schema-manager.d.ts.map +1 -1
- package/dist/schema/schema-manager.js +52 -9
- package/dist/schema/schema-manager.js.map +1 -1
- package/dist/schema/types.d.ts +10 -0
- package/dist/schema/types.d.ts.map +1 -1
- package/dist/schema/uuid-convergence.d.ts +142 -0
- package/dist/schema/uuid-convergence.d.ts.map +1 -0
- package/dist/schema/uuid-convergence.js +0 -0
- package/dist/schema/uuid-convergence.js.map +1 -0
- package/dist/smrt-knowledge.json +18 -9
- package/dist/utils/scanner-module.d.ts +44 -0
- package/dist/utils/scanner-module.d.ts.map +1 -1
- package/dist/vite-plugin/index.d.ts +14 -1
- package/dist/vite-plugin/index.d.ts.map +1 -1
- package/dist/vite-plugin/index.js +54 -2
- package/dist/vite-plugin/index.js.map +1 -1
- package/dist/vite-plugin.js +3 -2
- package/package.json +4 -4
|
@@ -155,4 +155,27 @@ export declare function getPendingSchemaStatements(db: DatabaseInterface, option
|
|
|
155
155
|
* field, the result would look indistinguishable from "already in sync."
|
|
156
156
|
*/
|
|
157
157
|
export declare function migrateSmrtSchemas(options: MigrateSmrtSchemasOptions): Promise<MigrateSmrtSchemasResult>;
|
|
158
|
+
/**
|
|
159
|
+
* Materialize the diff into the engine-correct SQL statements.
|
|
160
|
+
*
|
|
161
|
+
* For new tables we delegate to the engine's `DDLStrategy` so column types
|
|
162
|
+
* (`REAL` → `DOUBLE PRECISION` on Postgres, `JSON` → `JSONB`, etc.),
|
|
163
|
+
* partial-index `WHERE` clauses, and trigger syntax all match what the
|
|
164
|
+
* SchemaComparer would expect on subsequent runs. Emitting the raw
|
|
165
|
+
* abstract `SchemaDefinition.ddl` here would cause immediate type-drift
|
|
166
|
+
* migrations on Postgres/DuckDB.
|
|
167
|
+
*
|
|
168
|
+
* Column/index/trigger changes for existing tables continue to come from
|
|
169
|
+
* `getSQLFromDiff`, which is already engine-aware via the differ's per-
|
|
170
|
+
* change `sqlStatements`.
|
|
171
|
+
*
|
|
172
|
+
* Exported for statement-ordering tests; it is not part of the package's
|
|
173
|
+
* public entry point (`migrations/index.ts` re-exports names explicitly).
|
|
174
|
+
*
|
|
175
|
+
* @param diff - Schema diff to materialize.
|
|
176
|
+
* @param db - Database whose URL selects the DDL strategy.
|
|
177
|
+
* @param engineHint - Explicit engine when `db.url` is empty or ambiguous.
|
|
178
|
+
* @returns Ordered, executable DDL statements.
|
|
179
|
+
*/
|
|
180
|
+
export declare function collectStatementsFromDiff(diff: Awaited<ReturnType<typeof generateSchemaDiff>>, db: DatabaseInterface, engineHint?: DatabaseEngine): string[];
|
|
158
181
|
//# sourceMappingURL=orchestrate.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrate.d.ts","sourceRoot":"","sources":["../../src/migrations/orchestrate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAG5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;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AyB,CACvC,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,kBAAkB,CAAC,CAAC,EACpD,EAAE,EAAE,iBAAiB,EACrB,UAAU,CAAC,EAAE,cAAc,GAC1B,MAAM,EAAE,CAwCV"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { detectEngine, getDDLStrategy } from "../schema/ddl/index.js";
|
|
2
2
|
import { ObjectRegistry } from "../registry.js";
|
|
3
3
|
import { planForeignKeyCreation } from "../schema/foreign-key-planner.js";
|
|
4
|
-
import { generateSchemaDiff,
|
|
4
|
+
import { generateSchemaDiff, getSQLFromChanges, hasActionableChanges } from "./differ.js";
|
|
5
5
|
import { createMigrationDefinition, generateMigrationTimestamp } from "./generator.js";
|
|
6
6
|
import { MigrationTracker } from "./tracker.js";
|
|
7
7
|
//#region src/migrations/orchestrate.ts
|
|
@@ -135,18 +135,27 @@ function resolveDatabaseUrl(db) {
|
|
|
135
135
|
* Column/index/trigger changes for existing tables continue to come from
|
|
136
136
|
* `getSQLFromDiff`, which is already engine-aware via the differ's per-
|
|
137
137
|
* change `sqlStatements`.
|
|
138
|
+
*
|
|
139
|
+
* Exported for statement-ordering tests; it is not part of the package's
|
|
140
|
+
* public entry point (`migrations/index.ts` re-exports names explicitly).
|
|
141
|
+
*
|
|
142
|
+
* @param diff - Schema diff to materialize.
|
|
143
|
+
* @param db - Database whose URL selects the DDL strategy.
|
|
144
|
+
* @param engineHint - Explicit engine when `db.url` is empty or ambiguous.
|
|
145
|
+
* @returns Ordered, executable DDL statements.
|
|
138
146
|
*/
|
|
139
147
|
function collectStatementsFromDiff(diff, db, engineHint) {
|
|
140
148
|
const strategy = getDDLStrategy(detectEngine(resolveDatabaseUrl(db), engineHint));
|
|
141
149
|
const statements = [];
|
|
142
150
|
const tablePlan = planForeignKeyCreation(diff.added_tables, strategy.engine);
|
|
151
|
+
statements.push(...getSQLFromChanges(diff.changes.filter((change) => change.phase === "pre_foreign_key")));
|
|
143
152
|
for (const schema of tablePlan.schemas) {
|
|
144
153
|
statements.push(strategy.generateCreateTable(schema));
|
|
145
154
|
statements.push(...strategy.generateIndexes(schema));
|
|
146
155
|
statements.push(...strategy.generateTriggers(schema));
|
|
147
156
|
}
|
|
148
157
|
statements.push(...tablePlan.deferredStatements);
|
|
149
|
-
statements.push(...
|
|
158
|
+
statements.push(...getSQLFromChanges(diff.changes.filter((change) => change.phase !== "pre_foreign_key")));
|
|
150
159
|
return statements.filter((statement) => {
|
|
151
160
|
const trimmed = statement.trim();
|
|
152
161
|
if (trimmed.length === 0) return false;
|
|
@@ -216,6 +225,6 @@ function collectUnactionableChanges(diff) {
|
|
|
216
225
|
return unactionable;
|
|
217
226
|
}
|
|
218
227
|
//#endregion
|
|
219
|
-
export { getPendingSchemaStatements, migrateSmrtSchemas };
|
|
228
|
+
export { collectStatementsFromDiff, getPendingSchemaStatements, migrateSmrtSchemas };
|
|
220
229
|
|
|
221
230
|
//# sourceMappingURL=orchestrate.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrate.js","names":[],"sources":["../../src/migrations/orchestrate.ts"],"sourcesContent":["/**\n * High-level \"make my SMRT app's schema match its database\" orchestration.\n *\n * Wraps `ObjectRegistry.getAllSchemasAsDefinitions()` → `generateSchemaDiff`\n * → `MigrationTracker.applyAll`. Apps that just want to run pending\n * schema changes call `migrateSmrtSchemas({ db, packageName, version })`\n * and don't have to assemble the migration definition by hand.\n *\n * The migration name is timestamped, so re-running on an up-to-date\n * database is a no-op (the diff is empty, no statements are generated,\n * `applied: false` is returned).\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { ObjectRegistry } from '../registry.js';\nimport { detectEngine, getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport { planForeignKeyCreation } from '../schema/foreign-key-planner.js';\nimport type { MigrationResult, SchemaChange } from '../schema/types.js';\nimport {\n generateSchemaDiff,\n getSQLFromDiff,\n hasActionableChanges,\n} from './differ.js';\nimport {\n createMigrationDefinition,\n generateMigrationTimestamp,\n} from './generator.js';\nimport { MigrationTracker } from './tracker.js';\n\nexport interface MigrateSmrtSchemasOptions {\n db: DatabaseInterface;\n /** Stored on the migration record so the audit log shows which app applied it. */\n packageName: string;\n /**\n * Stored on the migration record. Typically the app's package.json\n * version. Optional because most apps don't have a runtime-readable\n * version handy and would hardcode a stale string if forced to supply\n * one — `'unknown'` is honest. Pass an explicit value when you can\n * (e.g. `version: process.env.APP_VERSION`).\n */\n version?: string;\n /** Override the description on the synthetic migration definition. */\n description?: string;\n /** Override the migration name (default: `<timestamp>_smrt_schema_sync`). */\n name?: string;\n /** Forwarded to MigrationTracker — defaults to true for pg-safe runs. */\n postgresSafe?: boolean;\n /** Forwarded to MigrationTracker — defaults to true. */\n reconcile?: boolean;\n /** Forwarded to MigrationTracker — defaults to true for `CREATE INDEX CONCURRENTLY`. */\n useConcurrentIndexes?: boolean;\n /**\n * Forwarded to MigrationTracker (Postgres lock timeout, milliseconds).\n * Lets apps that customize tracker timeouts directly preserve their\n * tuning when going through the orchestrator. Falls back to the\n * tracker's default (30000ms) when omitted.\n */\n lockTimeout?: number;\n /**\n * Forwarded to MigrationTracker (Postgres statement timeout, ms). Falls\n * back to the tracker's default (60000ms) when omitted.\n */\n statementTimeout?: number;\n /**\n * Explicit engine hint forwarded to `detectEngine`, `SchemaComparer`, and\n * `MigrationTracker`. Useful when `db.url` doesn't unambiguously identify\n * the engine (e.g. the JSON adapter, which uses DuckDB internally and may\n * not be recognizable by URL alone). All three layers honor the same hint\n * so the generated DDL, drift comparison, and execution path stay\n * consistent — without it, an empty-URL connection could produce\n * Postgres-flavored DDL but run through the SQLite tracker path.\n *\n * Typed as `DatabaseEngine` so unsupported values (e.g. `'mysql'`) fail at\n * compile time rather than silently falling back to `'sqlite'` at runtime.\n */\n engineHint?: DatabaseEngine;\n /**\n * Confirm that historical PostgreSQL Date writers used UTC wall times before\n * reinterpreting legacy TIMESTAMP/TEXT/JSON columns as TIMESTAMPTZ.\n */\n postgresTimestampMigration?: { legacyTimezone: 'UTC' };\n}\n\nexport interface MigrateSmrtSchemasResult {\n applied: boolean;\n results: MigrationResult[];\n statements: string[];\n schemaCount: number;\n /**\n * Schema changes the orchestrator detected but cannot apply automatically\n * (incompatible type mismatches, SQLite type upgrades that require table\n * recreation, etc.). Empty when the schema is fully reconciled. Inspect\n * this to surface a \"manual migration required\" warning in CLI output.\n */\n unactionableChanges: SchemaChange[];\n /**\n * Convenience: `unactionableChanges.length > 0`. Lets a caller write\n * `if (result.hasManualDrift) ...` without iterating the array first,\n * and makes the case visible to anyone scanning the result shape (the\n * full array is easy to gloss over when `applied: false`).\n */\n hasManualDrift: boolean;\n}\n\nexport interface PendingSchemaStatementsResult {\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>;\n statements: string[];\n schemaCount: number;\n hasChanges: boolean;\n /**\n * Schema changes the differ detected but that have no executable SQL\n * (incompatible `type_mismatch` entries, or `type_upgrade` entries whose\n * only generated SQL is an advisory comment because the engine cannot\n * upgrade the column in place — e.g. SQLite type widening). Surfacing\n * these lets status commands distinguish \"no drift\" from \"drift the\n * orchestrator can't fix on its own.\"\n */\n unactionableChanges: SchemaChange[];\n /**\n * Convenience: `unactionableChanges.length > 0`. Mirrors the\n * `MigrateSmrtSchemasResult.hasManualDrift` shortcut.\n */\n hasManualDrift: boolean;\n}\n\n/**\n * Compute the SQL statements needed to bring `db` in sync with the\n * currently-registered SMRT object schemas. Pure inspection — no writes.\n *\n * Useful for status commands (\"how far behind is the schema?\") and as the\n * inner step of `migrateSmrtSchemas`.\n *\n * **Note on the returned `statements`:** these are the engine-correct DDL\n * statements as the differ + DDL strategy produce them, *prior to* any\n * Postgres-specific rewrites the `MigrationTracker` applies at execution\n * time (e.g. rewriting `CREATE INDEX` → `CREATE INDEX CONCURRENTLY` and\n * moving CONCURRENTLY statements outside the surrounding transaction).\n * The list is suitable for preview/status/\"what would change?\" use cases.\n * For the exact byte-for-byte SQL the tracker ran, inspect the\n * `MigrationResult`s from `migrateSmrtSchemas` or the tracker's own logs.\n */\nexport async function getPendingSchemaStatements(\n db: DatabaseInterface,\n options: {\n engineHint?: DatabaseEngine;\n postgresTimestampMigration?: { legacyTimezone: 'UTC' };\n } = {},\n): Promise<PendingSchemaStatementsResult> {\n const schemas = ObjectRegistry.getAllSchemasAsDefinitions();\n // Forward engineHint into the diff itself so the SchemaComparer's\n // existing-table SQL (ALTER/index drift) uses the same DDL strategy\n // we use for newly-added tables — otherwise the two halves of the\n // statement list can land on different engines (split-brain) when\n // `db.url` is empty or ambiguous.\n const diff = await generateSchemaDiff(db, schemas, {\n engineHint: options.engineHint,\n postgresTimestampMigration: options.postgresTimestampMigration,\n });\n const statements = collectStatementsFromDiff(diff, db, options.engineHint);\n const unactionableChanges = collectUnactionableChanges(diff);\n return {\n diff,\n schemaCount: Object.keys(schemas).length,\n statements,\n hasChanges: hasActionableChanges(diff),\n unactionableChanges,\n hasManualDrift: unactionableChanges.length > 0,\n };\n}\n\n/**\n * Apply any pending schema changes from `ObjectRegistry` to `db`.\n *\n * Returns `applied: false` (with no error) if the database is already in\n * sync. Throws on the first migration failure with the underlying error\n * preserved (callers should let it propagate to the CLI).\n *\n * **Note on the returned `statements`:** mirrors `getPendingSchemaStatements`\n * — the list is the planned DDL, prior to Postgres-specific tracker rewrites\n * (CONCURRENTLY, transaction reordering). The actual executed SQL is\n * tracked in the returned `results`.\n *\n * **Note on `applied` semantics under `reconcile: true` (the default):**\n * the tracker may re-execute a migration that is already in `completed`\n * state when the checksum matches — that counts as `applied: true` in the\n * returned `MigrationResult`. So `result.applied === true` means \"the\n * tracker ran the migration\", not specifically \"the database changed for\n * the first time.\" Pass `reconcile: false` if you need to distinguish a\n * fresh apply from a reconcile-replay over an existing completed record.\n *\n * **Note on repeated failures:** the migration name defaults to a fresh\n * timestamp on every call, so a sequence of failed runs leaves one\n * `failed` row in `_smrt_schema_migrations` per attempt. Pass an explicit\n * `name` if you want to overwrite the same record across retries.\n *\n * **Note on `unactionableChanges`:** the differ can detect schema drift\n * the migration step can't auto-resolve — incompatible type mismatches,\n * SQLite type widening that needs table recreation, etc. Those changes\n * appear in `result.unactionableChanges` and are NOT applied (the\n * statements list is filtered to executable DDL only). When the diff\n * contains *only* unactionable changes, the function returns\n * `applied: false` with a populated `unactionableChanges` so callers can\n * surface a \"manual migration required\" signal. Without inspecting that\n * field, the result would look indistinguishable from \"already in sync.\"\n */\nexport async function migrateSmrtSchemas(\n options: MigrateSmrtSchemasOptions,\n): Promise<MigrateSmrtSchemasResult> {\n const pending = await getPendingSchemaStatements(options.db, {\n engineHint: options.engineHint,\n postgresTimestampMigration: options.postgresTimestampMigration,\n });\n if (!pending.hasChanges || pending.statements.length === 0) {\n return {\n applied: false,\n results: [],\n statements: [],\n schemaCount: pending.schemaCount,\n unactionableChanges: pending.unactionableChanges,\n hasManualDrift: pending.hasManualDrift,\n };\n }\n\n const tracker = new MigrationTracker({\n db: options.db,\n engineHint: options.engineHint,\n lockTimeout: options.lockTimeout,\n statementTimeout: options.statementTimeout,\n useConcurrentIndexes: options.useConcurrentIndexes ?? true,\n });\n const migration = createMigrationDefinition(\n options.name ?? `${generateMigrationTimestamp()}_smrt_schema_sync`,\n pending.statements,\n [],\n {\n description: options.description ?? 'Synchronize SMRT object schemas',\n packageName: options.packageName,\n version: options.version ?? 'unknown',\n },\n );\n\n const results = await tracker.applyAll([migration], {\n postgresSafe: options.postgresSafe ?? true,\n reconcile: options.reconcile ?? true,\n });\n\n const failed = results.find((result) => !result.success);\n if (failed) {\n throw failed.error instanceof Error\n ? failed.error\n : new Error(String(failed.error ?? `Migration ${failed.name} failed`));\n }\n\n const applied = results.some(\n (result) => result.applied !== false && result.skipped !== true,\n );\n\n return {\n applied,\n results,\n statements: pending.statements,\n schemaCount: pending.schemaCount,\n unactionableChanges: pending.unactionableChanges,\n hasManualDrift: pending.hasManualDrift,\n };\n}\n\n/** Mirror of the `getDatabaseUrl` helper in class.ts — some adapters\n * (JSON, certain in-memory wrappers) leave `db.url` undefined and expose\n * the URL on `db.config?.url` instead. Detecting the engine from a raw\n * `db.url` would throw or silently fall through to the sqlite default.\n */\nfunction resolveDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseInterface & {\n config?: { url?: string };\n };\n return db.url || dbWithConfig.config?.url || '';\n}\n\n/**\n * Materialize the diff into the engine-correct SQL statements.\n *\n * For new tables we delegate to the engine's `DDLStrategy` so column types\n * (`REAL` → `DOUBLE PRECISION` on Postgres, `JSON` → `JSONB`, etc.),\n * partial-index `WHERE` clauses, and trigger syntax all match what the\n * SchemaComparer would expect on subsequent runs. Emitting the raw\n * abstract `SchemaDefinition.ddl` here would cause immediate type-drift\n * migrations on Postgres/DuckDB.\n *\n * Column/index/trigger changes for existing tables continue to come from\n * `getSQLFromDiff`, which is already engine-aware via the differ's per-\n * change `sqlStatements`.\n */\nfunction collectStatementsFromDiff(\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>,\n db: DatabaseInterface,\n engineHint?: DatabaseEngine,\n): string[] {\n const strategy = getDDLStrategy(\n detectEngine(resolveDatabaseUrl(db), engineHint),\n );\n const statements: string[] = [];\n const tablePlan = planForeignKeyCreation(diff.added_tables, strategy.engine);\n for (const schema of tablePlan.schemas) {\n statements.push(strategy.generateCreateTable(schema));\n statements.push(...strategy.generateIndexes(schema));\n statements.push(...strategy.generateTriggers(schema));\n }\n statements.push(...tablePlan.deferredStatements);\n statements.push(...getSQLFromDiff(diff));\n // Drop empty and comment-only entries. SQLite type-widening upgrades\n // surface as `-- SQLite: Type upgrade for X requires table recreation`\n // — passing those through to the tracker records a successful migration\n // without actually fixing the column, so the same drift re-appears on\n // every subsequent run. Those changes are surfaced separately via\n // `unactionableChanges` so callers can prompt for manual remediation.\n return statements.filter((statement) => {\n const trimmed = statement.trim();\n if (trimmed.length === 0) return false;\n return !isCommentOnlySql(trimmed);\n });\n}\n\n/**\n * True if `sql` contains no executable DDL — only line comments (`--`)\n * and/or block comments (`/* … */`). Used to discard advisory comments\n * the differ emits when a column upgrade can't be performed in place\n * (e.g. SQLite type widening). Defensive: strips block comments first so\n * a future differ that emits `/* type_upgrade: no-op */` doesn't slip\n * through.\n */\nfunction isCommentOnlySql(sql: string): boolean {\n // Strip /* ... */ block comments (non-greedy, spans newlines).\n const withoutBlockComments = sql.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const lines = withoutBlockComments\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n if (lines.length === 0) return sql.trim().length > 0;\n return lines.every((line) => line.startsWith('--'));\n}\n\n/**\n * True if `sql` is an advisory comment that says *nothing needs to happen* —\n * as opposed to one that says a human has to act.\n *\n * The differ emits both kinds. \"This SQLite column already stores JSON as\n * TEXT\" and \"#2370: this column is rebuilt together with its sibling\" are\n * no-ops; \"requires table recreation\" / \"blocked: …\" are real manual drift.\n * Treating the first kind as drift makes a fully auto-repairable migration\n * report `hasManualDrift: true`.\n *\n * Keep in sync with `classifyTypeUpgradeSql`'s `noop` arm in\n * `@happyvertical/smrt-cli` (`src/commands/db-migrate-actions.ts`), which\n * applies the same rule on the CLI side.\n */\nfunction isNoOpAdvisorySql(sql: string): boolean {\n const trimmed = sql.trim();\n return (\n /no change needed/i.test(trimmed) || /already stores .* as /i.test(trimmed)\n );\n}\n\n/**\n * Surface changes the differ produced but that the migrator cannot apply\n * automatically — `type_mismatch` entries (the differ explicitly gives up on\n * these), `type_upgrade`/`alter_column` entries whose generated SQL is\n * advisory-comment-only (a SQLite rebuild that would be unsafe, an in-place\n * constraint change SQLite cannot perform), and warning-level report-only\n * advisories (an orphan NOT NULL column that will break inserts, a required\n * column that could not be enforced, a stale unique constraint, a relaxation\n * the caller has not opted into). Info-level advisories (a harmless orphan\n * column, a stale default) and comments that mean \"already handled\" (the\n * no-op advisories a table rebuild leaves on covered siblings, #2370) are\n * deliberately excluded so `hasManualDrift` keeps meaning \"something needs\n * an operator\". Callers use this to distinguish \"schema is in sync\" from\n * \"schema is drifted but we can't fix it from here\".\n */\nfunction collectUnactionableChanges(\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>,\n): SchemaChange[] {\n const unactionable: SchemaChange[] = [];\n for (const change of diff.changes) {\n if (change.type === 'type_mismatch') {\n unactionable.push(change);\n continue;\n }\n const statements = change.sqlStatements ?? (change.sql ? [change.sql] : []);\n if (statements.length === 0) {\n if (change.advisory?.severity === 'warning') {\n unactionable.push(change);\n }\n continue;\n }\n if (\n statements.every((stmt) => isCommentOnlySql(stmt.trim())) &&\n !statements.every((stmt) => isNoOpAdvisorySql(stmt))\n ) {\n unactionable.push(change);\n }\n }\n return unactionable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6IA,eAAsB,2BACpB,IACA,UAGI,CAAC,GACmC;CACxC,MAAM,UAAU,eAAe,2BAA2B;CAM1D,MAAM,OAAO,MAAM,mBAAmB,IAAI,SAAS;EACjD,YAAY,QAAQ;EACpB,4BAA4B,QAAQ;CACtC,CAAC;CACD,MAAM,aAAa,0BAA0B,MAAM,IAAI,QAAQ,UAAU;CACzE,MAAM,sBAAsB,2BAA2B,IAAI;CAC3D,OAAO;EACL;EACA,aAAa,OAAO,KAAK,OAAO,CAAC,CAAC;EAClC;EACA,YAAY,qBAAqB,IAAI;EACrC;EACA,gBAAgB,oBAAoB,SAAS;CAC/C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,mBACpB,SACmC;CACnC,MAAM,UAAU,MAAM,2BAA2B,QAAQ,IAAI;EAC3D,YAAY,QAAQ;EACpB,4BAA4B,QAAQ;CACtC,CAAC;CACD,IAAI,CAAC,QAAQ,cAAc,QAAQ,WAAW,WAAW,GACvD,OAAO;EACL,SAAS;EACT,SAAS,CAAC;EACV,YAAY,CAAC;EACb,aAAa,QAAQ;EACrB,qBAAqB,QAAQ;EAC7B,gBAAgB,QAAQ;CAC1B;CAGF,MAAM,UAAU,IAAI,iBAAiB;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rate.js","names":[],"sources":["../../src/migrations/orchestrate.ts"],"sourcesContent":["/**\n * High-level \"make my SMRT app's schema match its database\" orchestration.\n *\n * Wraps `ObjectRegistry.getAllSchemasAsDefinitions()` → `generateSchemaDiff`\n * → `MigrationTracker.applyAll`. Apps that just want to run pending\n * schema changes call `migrateSmrtSchemas({ db, packageName, version })`\n * and don't have to assemble the migration definition by hand.\n *\n * The migration name is timestamped, so re-running on an up-to-date\n * database is a no-op (the diff is empty, no statements are generated,\n * `applied: false` is returned).\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { ObjectRegistry } from '../registry.js';\nimport { detectEngine, getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport { planForeignKeyCreation } from '../schema/foreign-key-planner.js';\nimport type { MigrationResult, SchemaChange } from '../schema/types.js';\nimport {\n generateSchemaDiff,\n getSQLFromChanges,\n hasActionableChanges,\n} from './differ.js';\nimport {\n createMigrationDefinition,\n generateMigrationTimestamp,\n} from './generator.js';\nimport { MigrationTracker } from './tracker.js';\n\nexport interface MigrateSmrtSchemasOptions {\n db: DatabaseInterface;\n /** Stored on the migration record so the audit log shows which app applied it. */\n packageName: string;\n /**\n * Stored on the migration record. Typically the app's package.json\n * version. Optional because most apps don't have a runtime-readable\n * version handy and would hardcode a stale string if forced to supply\n * one — `'unknown'` is honest. Pass an explicit value when you can\n * (e.g. `version: process.env.APP_VERSION`).\n */\n version?: string;\n /** Override the description on the synthetic migration definition. */\n description?: string;\n /** Override the migration name (default: `<timestamp>_smrt_schema_sync`). */\n name?: string;\n /** Forwarded to MigrationTracker — defaults to true for pg-safe runs. */\n postgresSafe?: boolean;\n /** Forwarded to MigrationTracker — defaults to true. */\n reconcile?: boolean;\n /** Forwarded to MigrationTracker — defaults to true for `CREATE INDEX CONCURRENTLY`. */\n useConcurrentIndexes?: boolean;\n /**\n * Forwarded to MigrationTracker (Postgres lock timeout, milliseconds).\n * Lets apps that customize tracker timeouts directly preserve their\n * tuning when going through the orchestrator. Falls back to the\n * tracker's default (30000ms) when omitted.\n */\n lockTimeout?: number;\n /**\n * Forwarded to MigrationTracker (Postgres statement timeout, ms). Falls\n * back to the tracker's default (60000ms) when omitted.\n */\n statementTimeout?: number;\n /**\n * Explicit engine hint forwarded to `detectEngine`, `SchemaComparer`, and\n * `MigrationTracker`. Useful when `db.url` doesn't unambiguously identify\n * the engine (e.g. the JSON adapter, which uses DuckDB internally and may\n * not be recognizable by URL alone). All three layers honor the same hint\n * so the generated DDL, drift comparison, and execution path stay\n * consistent — without it, an empty-URL connection could produce\n * Postgres-flavored DDL but run through the SQLite tracker path.\n *\n * Typed as `DatabaseEngine` so unsupported values (e.g. `'mysql'`) fail at\n * compile time rather than silently falling back to `'sqlite'` at runtime.\n */\n engineHint?: DatabaseEngine;\n /**\n * Confirm that historical PostgreSQL Date writers used UTC wall times before\n * reinterpreting legacy TIMESTAMP/TEXT/JSON columns as TIMESTAMPTZ.\n */\n postgresTimestampMigration?: { legacyTimezone: 'UTC' };\n}\n\nexport interface MigrateSmrtSchemasResult {\n applied: boolean;\n results: MigrationResult[];\n statements: string[];\n schemaCount: number;\n /**\n * Schema changes the orchestrator detected but cannot apply automatically\n * (incompatible type mismatches, SQLite type upgrades that require table\n * recreation, etc.). Empty when the schema is fully reconciled. Inspect\n * this to surface a \"manual migration required\" warning in CLI output.\n */\n unactionableChanges: SchemaChange[];\n /**\n * Convenience: `unactionableChanges.length > 0`. Lets a caller write\n * `if (result.hasManualDrift) ...` without iterating the array first,\n * and makes the case visible to anyone scanning the result shape (the\n * full array is easy to gloss over when `applied: false`).\n */\n hasManualDrift: boolean;\n}\n\nexport interface PendingSchemaStatementsResult {\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>;\n statements: string[];\n schemaCount: number;\n hasChanges: boolean;\n /**\n * Schema changes the differ detected but that have no executable SQL\n * (incompatible `type_mismatch` entries, or `type_upgrade` entries whose\n * only generated SQL is an advisory comment because the engine cannot\n * upgrade the column in place — e.g. SQLite type widening). Surfacing\n * these lets status commands distinguish \"no drift\" from \"drift the\n * orchestrator can't fix on its own.\"\n */\n unactionableChanges: SchemaChange[];\n /**\n * Convenience: `unactionableChanges.length > 0`. Mirrors the\n * `MigrateSmrtSchemasResult.hasManualDrift` shortcut.\n */\n hasManualDrift: boolean;\n}\n\n/**\n * Compute the SQL statements needed to bring `db` in sync with the\n * currently-registered SMRT object schemas. Pure inspection — no writes.\n *\n * Useful for status commands (\"how far behind is the schema?\") and as the\n * inner step of `migrateSmrtSchemas`.\n *\n * **Note on the returned `statements`:** these are the engine-correct DDL\n * statements as the differ + DDL strategy produce them, *prior to* any\n * Postgres-specific rewrites the `MigrationTracker` applies at execution\n * time (e.g. rewriting `CREATE INDEX` → `CREATE INDEX CONCURRENTLY` and\n * moving CONCURRENTLY statements outside the surrounding transaction).\n * The list is suitable for preview/status/\"what would change?\" use cases.\n * For the exact byte-for-byte SQL the tracker ran, inspect the\n * `MigrationResult`s from `migrateSmrtSchemas` or the tracker's own logs.\n */\nexport async function getPendingSchemaStatements(\n db: DatabaseInterface,\n options: {\n engineHint?: DatabaseEngine;\n postgresTimestampMigration?: { legacyTimezone: 'UTC' };\n } = {},\n): Promise<PendingSchemaStatementsResult> {\n const schemas = ObjectRegistry.getAllSchemasAsDefinitions();\n // Forward engineHint into the diff itself so the SchemaComparer's\n // existing-table SQL (ALTER/index drift) uses the same DDL strategy\n // we use for newly-added tables — otherwise the two halves of the\n // statement list can land on different engines (split-brain) when\n // `db.url` is empty or ambiguous.\n const diff = await generateSchemaDiff(db, schemas, {\n engineHint: options.engineHint,\n postgresTimestampMigration: options.postgresTimestampMigration,\n });\n const statements = collectStatementsFromDiff(diff, db, options.engineHint);\n const unactionableChanges = collectUnactionableChanges(diff);\n return {\n diff,\n schemaCount: Object.keys(schemas).length,\n statements,\n hasChanges: hasActionableChanges(diff),\n unactionableChanges,\n hasManualDrift: unactionableChanges.length > 0,\n };\n}\n\n/**\n * Apply any pending schema changes from `ObjectRegistry` to `db`.\n *\n * Returns `applied: false` (with no error) if the database is already in\n * sync. Throws on the first migration failure with the underlying error\n * preserved (callers should let it propagate to the CLI).\n *\n * **Note on the returned `statements`:** mirrors `getPendingSchemaStatements`\n * — the list is the planned DDL, prior to Postgres-specific tracker rewrites\n * (CONCURRENTLY, transaction reordering). The actual executed SQL is\n * tracked in the returned `results`.\n *\n * **Note on `applied` semantics under `reconcile: true` (the default):**\n * the tracker may re-execute a migration that is already in `completed`\n * state when the checksum matches — that counts as `applied: true` in the\n * returned `MigrationResult`. So `result.applied === true` means \"the\n * tracker ran the migration\", not specifically \"the database changed for\n * the first time.\" Pass `reconcile: false` if you need to distinguish a\n * fresh apply from a reconcile-replay over an existing completed record.\n *\n * **Note on repeated failures:** the migration name defaults to a fresh\n * timestamp on every call, so a sequence of failed runs leaves one\n * `failed` row in `_smrt_schema_migrations` per attempt. Pass an explicit\n * `name` if you want to overwrite the same record across retries.\n *\n * **Note on `unactionableChanges`:** the differ can detect schema drift\n * the migration step can't auto-resolve — incompatible type mismatches,\n * SQLite type widening that needs table recreation, etc. Those changes\n * appear in `result.unactionableChanges` and are NOT applied (the\n * statements list is filtered to executable DDL only). When the diff\n * contains *only* unactionable changes, the function returns\n * `applied: false` with a populated `unactionableChanges` so callers can\n * surface a \"manual migration required\" signal. Without inspecting that\n * field, the result would look indistinguishable from \"already in sync.\"\n */\nexport async function migrateSmrtSchemas(\n options: MigrateSmrtSchemasOptions,\n): Promise<MigrateSmrtSchemasResult> {\n const pending = await getPendingSchemaStatements(options.db, {\n engineHint: options.engineHint,\n postgresTimestampMigration: options.postgresTimestampMigration,\n });\n if (!pending.hasChanges || pending.statements.length === 0) {\n return {\n applied: false,\n results: [],\n statements: [],\n schemaCount: pending.schemaCount,\n unactionableChanges: pending.unactionableChanges,\n hasManualDrift: pending.hasManualDrift,\n };\n }\n\n const tracker = new MigrationTracker({\n db: options.db,\n engineHint: options.engineHint,\n lockTimeout: options.lockTimeout,\n statementTimeout: options.statementTimeout,\n useConcurrentIndexes: options.useConcurrentIndexes ?? true,\n });\n const migration = createMigrationDefinition(\n options.name ?? `${generateMigrationTimestamp()}_smrt_schema_sync`,\n pending.statements,\n [],\n {\n description: options.description ?? 'Synchronize SMRT object schemas',\n packageName: options.packageName,\n version: options.version ?? 'unknown',\n },\n );\n\n const results = await tracker.applyAll([migration], {\n postgresSafe: options.postgresSafe ?? true,\n reconcile: options.reconcile ?? true,\n });\n\n const failed = results.find((result) => !result.success);\n if (failed) {\n throw failed.error instanceof Error\n ? failed.error\n : new Error(String(failed.error ?? `Migration ${failed.name} failed`));\n }\n\n const applied = results.some(\n (result) => result.applied !== false && result.skipped !== true,\n );\n\n return {\n applied,\n results,\n statements: pending.statements,\n schemaCount: pending.schemaCount,\n unactionableChanges: pending.unactionableChanges,\n hasManualDrift: pending.hasManualDrift,\n };\n}\n\n/** Mirror of the `getDatabaseUrl` helper in class.ts — some adapters\n * (JSON, certain in-memory wrappers) leave `db.url` undefined and expose\n * the URL on `db.config?.url` instead. Detecting the engine from a raw\n * `db.url` would throw or silently fall through to the sqlite default.\n */\nfunction resolveDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseInterface & {\n config?: { url?: string };\n };\n return db.url || dbWithConfig.config?.url || '';\n}\n\n/**\n * Materialize the diff into the engine-correct SQL statements.\n *\n * For new tables we delegate to the engine's `DDLStrategy` so column types\n * (`REAL` → `DOUBLE PRECISION` on Postgres, `JSON` → `JSONB`, etc.),\n * partial-index `WHERE` clauses, and trigger syntax all match what the\n * SchemaComparer would expect on subsequent runs. Emitting the raw\n * abstract `SchemaDefinition.ddl` here would cause immediate type-drift\n * migrations on Postgres/DuckDB.\n *\n * Column/index/trigger changes for existing tables continue to come from\n * `getSQLFromDiff`, which is already engine-aware via the differ's per-\n * change `sqlStatements`.\n *\n * Exported for statement-ordering tests; it is not part of the package's\n * public entry point (`migrations/index.ts` re-exports names explicitly).\n *\n * @param diff - Schema diff to materialize.\n * @param db - Database whose URL selects the DDL strategy.\n * @param engineHint - Explicit engine when `db.url` is empty or ambiguous.\n * @returns Ordered, executable DDL statements.\n */\nexport function collectStatementsFromDiff(\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>,\n db: DatabaseInterface,\n engineHint?: DatabaseEngine,\n): string[] {\n const strategy = getDDLStrategy(\n detectEngine(resolveDatabaseUrl(db), engineHint),\n );\n const statements: string[] = [];\n const tablePlan = planForeignKeyCreation(diff.added_tables, strategy.engine);\n // #2608: the pre-R11 uuid convergence has to precede *every* foreign-key\n // statement. `planForeignKeyCreation` only defers the constraints inside a\n // mutual cycle, so an acyclic new child table keeps its FK **inline in\n // CREATE TABLE** — a fresh `uuid` child pointing at a legacy `text` parent\n // would fail with SQLSTATE 42804 before the parent could be converted.\n // Conversions only ever rewrite columns that already exist, so they are\n // safe to run ahead of every CREATE TABLE in this batch.\n statements.push(\n ...getSQLFromChanges(\n diff.changes.filter((change) => change.phase === 'pre_foreign_key'),\n ),\n );\n for (const schema of tablePlan.schemas) {\n statements.push(strategy.generateCreateTable(schema));\n statements.push(...strategy.generateIndexes(schema));\n statements.push(...strategy.generateTriggers(schema));\n }\n statements.push(...tablePlan.deferredStatements);\n statements.push(\n ...getSQLFromChanges(\n diff.changes.filter((change) => change.phase !== 'pre_foreign_key'),\n ),\n );\n // Drop empty and comment-only entries. SQLite type-widening upgrades\n // surface as `-- SQLite: Type upgrade for X requires table recreation`\n // — passing those through to the tracker records a successful migration\n // without actually fixing the column, so the same drift re-appears on\n // every subsequent run. Those changes are surfaced separately via\n // `unactionableChanges` so callers can prompt for manual remediation.\n return statements.filter((statement) => {\n const trimmed = statement.trim();\n if (trimmed.length === 0) return false;\n return !isCommentOnlySql(trimmed);\n });\n}\n\n/**\n * True if `sql` contains no executable DDL — only line comments (`--`)\n * and/or block comments (`/* … */`). Used to discard advisory comments\n * the differ emits when a column upgrade can't be performed in place\n * (e.g. SQLite type widening). Defensive: strips block comments first so\n * a future differ that emits `/* type_upgrade: no-op */` doesn't slip\n * through.\n */\nfunction isCommentOnlySql(sql: string): boolean {\n // Strip /* ... */ block comments (non-greedy, spans newlines).\n const withoutBlockComments = sql.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const lines = withoutBlockComments\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n if (lines.length === 0) return sql.trim().length > 0;\n return lines.every((line) => line.startsWith('--'));\n}\n\n/**\n * True if `sql` is an advisory comment that says *nothing needs to happen* —\n * as opposed to one that says a human has to act.\n *\n * The differ emits both kinds. \"This SQLite column already stores JSON as\n * TEXT\" and \"#2370: this column is rebuilt together with its sibling\" are\n * no-ops; \"requires table recreation\" / \"blocked: …\" are real manual drift.\n * Treating the first kind as drift makes a fully auto-repairable migration\n * report `hasManualDrift: true`.\n *\n * Keep in sync with `classifyTypeUpgradeSql`'s `noop` arm in\n * `@happyvertical/smrt-cli` (`src/commands/db-migrate-actions.ts`), which\n * applies the same rule on the CLI side.\n */\nfunction isNoOpAdvisorySql(sql: string): boolean {\n const trimmed = sql.trim();\n return (\n /no change needed/i.test(trimmed) || /already stores .* as /i.test(trimmed)\n );\n}\n\n/**\n * Surface changes the differ produced but that the migrator cannot apply\n * automatically — `type_mismatch` entries (the differ explicitly gives up on\n * these), `type_upgrade`/`alter_column` entries whose generated SQL is\n * advisory-comment-only (a SQLite rebuild that would be unsafe, an in-place\n * constraint change SQLite cannot perform), and warning-level report-only\n * advisories (an orphan NOT NULL column that will break inserts, a required\n * column that could not be enforced, a stale unique constraint, a relaxation\n * the caller has not opted into). Info-level advisories (a harmless orphan\n * column, a stale default) and comments that mean \"already handled\" (the\n * no-op advisories a table rebuild leaves on covered siblings, #2370) are\n * deliberately excluded so `hasManualDrift` keeps meaning \"something needs\n * an operator\". Callers use this to distinguish \"schema is in sync\" from\n * \"schema is drifted but we can't fix it from here\".\n */\nfunction collectUnactionableChanges(\n diff: Awaited<ReturnType<typeof generateSchemaDiff>>,\n): SchemaChange[] {\n const unactionable: SchemaChange[] = [];\n for (const change of diff.changes) {\n if (change.type === 'type_mismatch') {\n unactionable.push(change);\n continue;\n }\n const statements = change.sqlStatements ?? (change.sql ? [change.sql] : []);\n if (statements.length === 0) {\n if (change.advisory?.severity === 'warning') {\n unactionable.push(change);\n }\n continue;\n }\n if (\n statements.every((stmt) => isCommentOnlySql(stmt.trim())) &&\n !statements.every((stmt) => isNoOpAdvisorySql(stmt))\n ) {\n unactionable.push(change);\n }\n }\n return unactionable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6IA,eAAsB,2BACpB,IACA,UAGI,CAAC,GACmC;CACxC,MAAM,UAAU,eAAe,2BAA2B;CAM1D,MAAM,OAAO,MAAM,mBAAmB,IAAI,SAAS;EACjD,YAAY,QAAQ;EACpB,4BAA4B,QAAQ;CACtC,CAAC;CACD,MAAM,aAAa,0BAA0B,MAAM,IAAI,QAAQ,UAAU;CACzE,MAAM,sBAAsB,2BAA2B,IAAI;CAC3D,OAAO;EACL;EACA,aAAa,OAAO,KAAK,OAAO,CAAC,CAAC;EAClC;EACA,YAAY,qBAAqB,IAAI;EACrC;EACA,gBAAgB,oBAAoB,SAAS;CAC/C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,mBACpB,SACmC;CACnC,MAAM,UAAU,MAAM,2BAA2B,QAAQ,IAAI;EAC3D,YAAY,QAAQ;EACpB,4BAA4B,QAAQ;CACtC,CAAC;CACD,IAAI,CAAC,QAAQ,cAAc,QAAQ,WAAW,WAAW,GACvD,OAAO;EACL,SAAS;EACT,SAAS,CAAC;EACV,YAAY,CAAC;EACb,aAAa,QAAQ;EACrB,qBAAqB,QAAQ;EAC7B,gBAAgB,QAAQ;CAC1B;CAGF,MAAM,UAAU,IAAI,iBAAiB;EACnC,IAAI,QAAQ;EACZ,YAAY,QAAQ;EACpB,aAAa,QAAQ;EACrB,kBAAkB,QAAQ;EAC1B,sBAAsB,QAAQ,wBAAwB;CACxD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package/dist/object.d.ts
CHANGED
|
@@ -11,6 +11,14 @@ export interface SmrtSaveOptions {
|
|
|
11
11
|
*/
|
|
12
12
|
expectedUpdatedAt?: Date | string;
|
|
13
13
|
}
|
|
14
|
+
/** Optional optimistic-concurrency guard for irreversible deletes. */
|
|
15
|
+
export interface SmrtDeleteOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Delete only when the stored row still has this revision. A mismatch throws
|
|
18
|
+
* `RUNTIME_REVISION_CONFLICT` before any durable cascade is committed.
|
|
19
|
+
*/
|
|
20
|
+
expectedUpdatedAt?: Date | string;
|
|
21
|
+
}
|
|
14
22
|
/**
|
|
15
23
|
* Options for SmrtObject initialization
|
|
16
24
|
*/
|
|
@@ -673,6 +681,28 @@ export declare class SmrtObject extends SmrtClass {
|
|
|
673
681
|
* and other after-save consumers all see authoritative state.
|
|
674
682
|
*/
|
|
675
683
|
protected completePersistedUpdate(durableRow: Record<string, unknown>): Promise<void>;
|
|
684
|
+
/**
|
|
685
|
+
* Build the compare-and-swap condition that pins a guarded UPDATE or DELETE
|
|
686
|
+
* to the revision this writer loaded.
|
|
687
|
+
*
|
|
688
|
+
* PostgreSQL stores `updated_at` as `timestamp(6) WITHOUT time zone` and `pg`
|
|
689
|
+
* hydrates it in the process zone, so neither the precision nor the wall clock
|
|
690
|
+
* of a JavaScript `Date` survives the round trip. Exact string equality was
|
|
691
|
+
* therefore unsatisfiable for any row last written by raw SQL, and for every
|
|
692
|
+
* row on a non-UTC host, turning a lost-race guard into a permanent
|
|
693
|
+
* `RUNTIME_REVISION_CONFLICT` (#2620). See `revision-guard.ts` for how the
|
|
694
|
+
* PostgreSQL condition restores both correctness and lost-race semantics.
|
|
695
|
+
*
|
|
696
|
+
* The guarded `delete({ expectedUpdatedAt })` predicate is built here too:
|
|
697
|
+
* it bound the same exact equality into its final `DELETE`, so a microsecond
|
|
698
|
+
* or non-UTC row was permanently undeletable under a revision guard for the
|
|
699
|
+
* same reason.
|
|
700
|
+
*
|
|
701
|
+
* Other server dialects (remote LibSQL) store ISO text that round-trips
|
|
702
|
+
* exactly, and embedded engines never reach here — they take the
|
|
703
|
+
* compare/upsert fallback in {@link usesEmbeddedRevisionFallback}.
|
|
704
|
+
*/
|
|
705
|
+
private revisionPredicate;
|
|
676
706
|
private revisionPredicateValue;
|
|
677
707
|
private revisionsEqual;
|
|
678
708
|
private nextRevisionTimestamp;
|
|
@@ -999,7 +1029,7 @@ export declare class SmrtObject extends SmrtClass {
|
|
|
999
1029
|
*
|
|
1000
1030
|
* @see {@link foreignKey} for declaring `onDelete` on the referencing side
|
|
1001
1031
|
*/
|
|
1002
|
-
delete(): Promise<void>;
|
|
1032
|
+
delete(options?: SmrtDeleteOptions): Promise<void>;
|
|
1003
1033
|
/**
|
|
1004
1034
|
* Invalidate cached collection reads after a successful mutation
|
|
1005
1035
|
* (issue #1498).
|
package/dist/object.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAOpC,OAAO,EAGL,KAAK,2BAA2B,EACjC,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAOpC,OAAO,EAGL,KAAK,2BAA2B,EACjC,MAAM,aAAa,CAAC;AAWrB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MA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,GAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;KACnB,GACL,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IA+ChC;;;;;;;;;;;;;;;;;;OAkBG;IACU,MAAM,CAAC,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAa3E;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACU,WAAW,CAAC,OAAO,EAAE;QAChC,KAAK,EAAE,MAAM,CAAC;QACd,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B,GAAG,OAAO,CAAC,MAAM,CAAC;IA0BnB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACU,kBAAkB,CAC7B,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,IAAI,CAAC;IAkJhB;;;;;;;;;;;;;;;;;OAiBG;IACU,YAAY,CACvB,SAAS,EAAE,MAAM,EACjB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IA8C3B;;;;;;;;;;;;;;OAcG;IACU,kBAAkB,IAAI,OAAO,CAAC,OAAO,CAAC;IA4EnD;;;;;;;;;;;;OAYG;IACU,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;CAW9C"}
|
package/dist/object.js
CHANGED
|
@@ -3,7 +3,7 @@ import { DatabaseError, ErrorUtils, RuntimeError, SmrtError, TenantIsolationErro
|
|
|
3
3
|
import { toSnakeCase } from "./utils/naming.js";
|
|
4
4
|
import { runCascadeDelete } from "./cascade.js";
|
|
5
5
|
import { broadcastCacheInvalidation, hasCrossProcessCacheInterest, invalidateCollectionCache, resolveDbCacheKey } from "./collection-cache.js";
|
|
6
|
-
import { isEmbeddedDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction } from "./embedded-write-queue.js";
|
|
6
|
+
import { isEmbeddedDatabase, isPostgresDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction } from "./embedded-write-queue.js";
|
|
7
7
|
import { GlobalInterceptors, createInterceptorContext, resolveGetStringFilter } from "./interceptors.js";
|
|
8
8
|
import { detectEngine } from "./schema/ddl/index.js";
|
|
9
9
|
import { CHANGE_FEED_WAS_PERSISTED_KEY, recordInstanceChange } from "./change-feed.js";
|
|
@@ -11,6 +11,7 @@ import { SmrtClass } from "./class.js";
|
|
|
11
11
|
import { EmbeddingProvider } from "./embeddings/provider.js";
|
|
12
12
|
import { EmbeddingStorage } from "./embeddings/storage.js";
|
|
13
13
|
import { ContentHasher } from "./embeddings/hash.js";
|
|
14
|
+
import { postgresRevisionCondition } from "./revision-guard.js";
|
|
14
15
|
import { verifyPersistenceTable } from "./schema/table-verifier.js";
|
|
15
16
|
import { executeToolCall } from "./tools/tool-executor.js";
|
|
16
17
|
import { fieldsFromClass, keysToSnakeCase, tableNameFromClass } from "./utils.js";
|
|
@@ -1177,7 +1178,7 @@ var SmrtObject = class SmrtObject extends SmrtClass {
|
|
|
1177
1178
|
}
|
|
1178
1179
|
const updateResult = useEmbeddedRevisionFallback ? await this.db.upsert(this.tableName, ["id"], data) : await this.db.update(this.tableName, {
|
|
1179
1180
|
id: data.id,
|
|
1180
|
-
...revisionGuard !== void 0 ?
|
|
1181
|
+
...revisionGuard !== void 0 ? this.revisionPredicate(revisionGuard) : {}
|
|
1181
1182
|
}, updateData);
|
|
1182
1183
|
if (revisionGuard !== void 0 && updateResult.affected !== 1) {
|
|
1183
1184
|
revisionMatched = false;
|
|
@@ -1259,7 +1260,7 @@ var SmrtObject = class SmrtObject extends SmrtClass {
|
|
|
1259
1260
|
updated_at: updatedAt.toISOString()
|
|
1260
1261
|
}) : await this.db.update(this.tableName, {
|
|
1261
1262
|
id: this.id,
|
|
1262
|
-
|
|
1263
|
+
...this.revisionPredicate(expectedUpdatedAt)
|
|
1263
1264
|
}, { updated_at: updatedAt.toISOString() });
|
|
1264
1265
|
});
|
|
1265
1266
|
if (!revisionMatched || result?.affected !== 1) throw new RuntimeError(`Revision conflict while claiming ${className}`, "RUNTIME_REVISION_CONFLICT", {
|
|
@@ -1287,6 +1288,31 @@ var SmrtObject = class SmrtObject extends SmrtClass {
|
|
|
1287
1288
|
};
|
|
1288
1289
|
await GlobalInterceptors.executeAfterSave(this, context);
|
|
1289
1290
|
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Build the compare-and-swap condition that pins a guarded UPDATE or DELETE
|
|
1293
|
+
* to the revision this writer loaded.
|
|
1294
|
+
*
|
|
1295
|
+
* PostgreSQL stores `updated_at` as `timestamp(6) WITHOUT time zone` and `pg`
|
|
1296
|
+
* hydrates it in the process zone, so neither the precision nor the wall clock
|
|
1297
|
+
* of a JavaScript `Date` survives the round trip. Exact string equality was
|
|
1298
|
+
* therefore unsatisfiable for any row last written by raw SQL, and for every
|
|
1299
|
+
* row on a non-UTC host, turning a lost-race guard into a permanent
|
|
1300
|
+
* `RUNTIME_REVISION_CONFLICT` (#2620). See `revision-guard.ts` for how the
|
|
1301
|
+
* PostgreSQL condition restores both correctness and lost-race semantics.
|
|
1302
|
+
*
|
|
1303
|
+
* The guarded `delete({ expectedUpdatedAt })` predicate is built here too:
|
|
1304
|
+
* it bound the same exact equality into its final `DELETE`, so a microsecond
|
|
1305
|
+
* or non-UTC row was permanently undeletable under a revision guard for the
|
|
1306
|
+
* same reason.
|
|
1307
|
+
*
|
|
1308
|
+
* Other server dialects (remote LibSQL) store ISO text that round-trips
|
|
1309
|
+
* exactly, and embedded engines never reach here — they take the
|
|
1310
|
+
* compare/upsert fallback in {@link usesEmbeddedRevisionFallback}.
|
|
1311
|
+
*/
|
|
1312
|
+
revisionPredicate(revision) {
|
|
1313
|
+
if (isPostgresDatabase(this.db)) return postgresRevisionCondition(revision);
|
|
1314
|
+
return { updated_at: this.revisionPredicateValue(revision) };
|
|
1315
|
+
}
|
|
1290
1316
|
revisionPredicateValue(revision) {
|
|
1291
1317
|
return revision instanceof Date ? revision.toISOString() : revision;
|
|
1292
1318
|
}
|
|
@@ -1804,16 +1830,38 @@ var SmrtObject = class SmrtObject extends SmrtClass {
|
|
|
1804
1830
|
*
|
|
1805
1831
|
* @see {@link foreignKey} for declaring `onDelete` on the referencing side
|
|
1806
1832
|
*/
|
|
1807
|
-
async delete() {
|
|
1833
|
+
async delete(options = {}) {
|
|
1834
|
+
const className = this.getResolvedClassName();
|
|
1835
|
+
const expectedUpdatedAt = options.expectedUpdatedAt;
|
|
1836
|
+
if (expectedUpdatedAt !== void 0 && (!this._persisted || !this.id)) throw RuntimeError.invalidState("A revision-guarded delete requires a persisted object", { className });
|
|
1808
1837
|
const interceptorContext = createInterceptorContext(this.constructor.name, "delete");
|
|
1809
1838
|
await GlobalInterceptors.executeBeforeDelete(this, interceptorContext);
|
|
1810
1839
|
await this.runHook("beforeDelete");
|
|
1811
1840
|
await this.verifyStorageReady();
|
|
1812
|
-
const
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1841
|
+
const embeddedRevisionGuard = expectedUpdatedAt !== void 0 && usesEmbeddedRevisionFallback(this.db);
|
|
1842
|
+
const { affectedTables, affectedTableClasses } = await withEmbeddedWriteQueue(this.db, isEmbeddedDatabase(this.db), async () => {
|
|
1843
|
+
if (embeddedRevisionGuard) {
|
|
1844
|
+
const current = await this.getCanonicalPersistedRow({ id: this.id });
|
|
1845
|
+
if (!current || !this.revisionsEqual(current.updated_at, expectedUpdatedAt)) throw new RuntimeError(`Revision conflict while deleting ${className}`, "RUNTIME_REVISION_CONFLICT", {
|
|
1846
|
+
className,
|
|
1847
|
+
id: this.id
|
|
1848
|
+
});
|
|
1849
|
+
}
|
|
1850
|
+
return runCascadeDelete(this.db, ObjectRegistry, {
|
|
1851
|
+
className: this.getResolvedQualifiedName(),
|
|
1852
|
+
tableName: this.tableName,
|
|
1853
|
+
id: this.id
|
|
1854
|
+
}, async (db) => {
|
|
1855
|
+
const result = await db.delete(this.tableName, {
|
|
1856
|
+
id: this.id,
|
|
1857
|
+
...expectedUpdatedAt !== void 0 && !embeddedRevisionGuard ? this.revisionPredicate(expectedUpdatedAt) : {}
|
|
1858
|
+
});
|
|
1859
|
+
if (expectedUpdatedAt !== void 0 && result.affected !== 1) throw new RuntimeError(`Revision conflict while deleting ${className}`, "RUNTIME_REVISION_CONFLICT", {
|
|
1860
|
+
className,
|
|
1861
|
+
id: this.id
|
|
1862
|
+
});
|
|
1863
|
+
});
|
|
1864
|
+
});
|
|
1817
1865
|
this._persisted = false;
|
|
1818
1866
|
this.invalidateCollectionReadCache();
|
|
1819
1867
|
for (const table of affectedTables) this.invalidateCollectionReadCache(table, affectedTableClasses.get(table));
|