@lunora/d1 1.0.0-alpha.232 → 1.0.0-alpha.234

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -170,6 +170,15 @@ declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promis
170
170
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
171
171
  /** The distinct values of one D1 column over the active view. */
172
172
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
173
+ /**
174
+ * The line comment that confirms a migration's destructive statement is intended, matched exactly. It counts only on
175
+ * its own line before that statement; `lunora migrate generate` writes it there for each statement it confirms, so it
176
+ * stays with that statement when a generated file is split into one `Migration` per statement.
177
+ *
178
+ * Shared rather than imported from `@lunora/d1` by `@lunora/cli`, because the two are released independently: a CLI
179
+ * that read it from `@lunora/d1` at runtime could not load next to a published D1 that predates the export.
180
+ */
181
+ declare const ALLOW_DESTRUCTIVE_MARKER = "-- lunora:allow-destructive";
173
182
  interface Migration {
174
183
  /** Human-readable name, e.g. `001_init` (used in logs). */
175
184
  name: string;
@@ -356,4 +365,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
356
365
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
357
366
  */
358
367
  declare const sqliteDialect: SqlDialect;
359
- export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
368
+ export { ALLOW_DESTRUCTIVE_MARKER, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.d.ts CHANGED
@@ -170,6 +170,15 @@ declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promis
170
170
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
171
171
  /** The distinct values of one D1 column over the active view. */
172
172
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
173
+ /**
174
+ * The line comment that confirms a migration's destructive statement is intended, matched exactly. It counts only on
175
+ * its own line before that statement; `lunora migrate generate` writes it there for each statement it confirms, so it
176
+ * stays with that statement when a generated file is split into one `Migration` per statement.
177
+ *
178
+ * Shared rather than imported from `@lunora/d1` by `@lunora/cli`, because the two are released independently: a CLI
179
+ * that read it from `@lunora/d1` at runtime could not load next to a published D1 that predates the export.
180
+ */
181
+ declare const ALLOW_DESTRUCTIVE_MARKER = "-- lunora:allow-destructive";
173
182
  interface Migration {
174
183
  /** Human-readable name, e.g. `001_init` (used in logs). */
175
184
  name: string;
@@ -356,4 +365,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
356
365
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
357
366
  */
358
367
  declare const sqliteDialect: SqlDialect;
359
- export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
368
+ export { ALLOW_DESTRUCTIVE_MARKER, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportGlobalRows as o,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as b,runD1GlobalTableMigrations as g,runD1RankMigrations as m,runD1SearchMigrations as c,sweepD1CdcRetention as f}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as C,listGlobalTables as d,readGlobalTablePage as G}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as y}from"./packem_shared/MigrationRunner-DADTo9Q8.mjs";import{d1QueryTag as R,emitD1QueryCost as h,readD1QueryCost as w}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as E,isTransientD1Error as Q,retryingExec as k,withD1Retry as q}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as I}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as j}from"@lunora/shard-engine";import{createSqlCtxDb as z,selectGlobalTables as B}from"@lunora/sql-store";export{l as D1Client,i as D1Session,E as D1TimeoutError,y as MigrationRunner,j as applyCdcChanges,s as backfillD1SearchIndexes,D as createD1CtxDb,z as createSqlCtxDb,R as d1QueryTag,h as emitD1QueryCost,o as exportGlobalRows,C as facetGlobalColumn,t as importGlobalRows,Q as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,w as readD1QueryCost,G as readGlobalTablePage,k as retryingExec,x as runD1AggregateMigrations,b as runD1CdcMigration,g as runD1GlobalTableMigrations,m as runD1RankMigrations,c as runD1SearchMigrations,B as selectGlobalTables,I as sqliteDialect,f as sweepD1CdcRetention,q as withD1Retry};
1
+ import{exportGlobalRows as o,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as m,runD1GlobalTableMigrations as b,runD1RankMigrations as f,runD1SearchMigrations as g,sweepD1CdcRetention as c}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as u,listGlobalTables as d,readGlobalTablePage as R}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as G}from"./packem_shared/MigrationRunner-CDF339nT.mjs";import{d1QueryTag as y,emitD1QueryCost as E,readD1QueryCost as h}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as w,isTransientD1Error as A,retryingExec as Q,withD1Retry as k}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as I}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as _}from"@lunora/shard-engine";import{ALLOW_DESTRUCTIVE_MARKER as O}from"./packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{createSqlCtxDb as U,selectGlobalTables as V}from"@lunora/sql-store";export{O as ALLOW_DESTRUCTIVE_MARKER,l as D1Client,i as D1Session,w as D1TimeoutError,G as MigrationRunner,_ as applyCdcChanges,s as backfillD1SearchIndexes,D as createD1CtxDb,U as createSqlCtxDb,y as d1QueryTag,E as emitD1QueryCost,o as exportGlobalRows,u as facetGlobalColumn,t as importGlobalRows,A as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,h as readD1QueryCost,R as readGlobalTablePage,Q as retryingExec,x as runD1AggregateMigrations,m as runD1CdcMigration,b as runD1GlobalTableMigrations,f as runD1RankMigrations,g as runD1SearchMigrations,V as selectGlobalTables,I as sqliteDialect,c as sweepD1CdcRetention,k as withD1Retry};
@@ -0,0 +1 @@
1
+ const o="-- lunora:allow-destructive";export{o as ALLOW_DESTRUCTIVE_MARKER};
@@ -0,0 +1,8 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{sql as w}from"drizzle-orm";import{ALLOW_DESTRUCTIVE_MARKER as v}from"./ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs";import{D1Client as N}from"./D1Client-CzS0Qfa6.mjs";const R="__drizzle_migrations",D=`CREATE TABLE IF NOT EXISTS ${R} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,U=`CREATE UNIQUE INDEX IF NOT EXISTS ${R}_version ON ${R} (version)`,p=/\s/u,y=/[$\w]/u,A=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,z=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/u,P=new RegExp(String.raw`^CREATE${A}+(?:TEMP${A}+|TEMPORARY${A}+)?TRIGGER\b`,"iu"),b=/^[0-9a-f]{64}$/u,S=String.raw`[$\w\u{80}-\u{10FFFF}]`,$=`${S}+`,f=n=>new RegExp(String.raw`(?<!${S})${n.replaceAll(" ",String.raw`\s+`)}(?!${S})`,"iu"),L=n=>new RegExp(String.raw`^\s*ALTER\s+TABLE\s+${$}(?:\s*\.\s*${$})?\s+${n}\b`,"iu"),G=[["DROP",/^\s*DROP\s+(?:TABLE|INDEX|VIEW|TRIGGER)\b/iu],["DROP",L("DROP")],["RENAME",L("RENAME")],["TRUNCATE",/^\s*TRUNCATE\b/iu],["INSERT OR REPLACE",f("INSERT OR REPLACE")],["REPLACE INTO",f("REPLACE INTO")],["UPDATE OR REPLACE",f("UPDATE OR REPLACE")],["ON CONFLICT REPLACE",f("ON CONFLICT REPLACE")]],B=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/iu,V={'"':'"',"'":"'","[":"]","`":"`"},F=new RegExp(String.raw`UNIQUE constraint failed:\s*${R}\.(?:hash|version)`,"iu"),C=n=>`Migration "${n.name}" (v${String(n.version)})`,O=(n,e,t)=>({codeIndex:e,ownLine:n.slice(n.lastIndexOf(`
2
+ `,e-1)+1,e).trim()==="",text:t}),H=(n,e)=>{const t=P.test(n.slice(z.exec(n)?.[0].length??0)),c=[];let i="",l,o,a=0,d=0,r,s="",h=!1,T=!1;for(let m=0;m<n.length;m+=1){const E=n.charAt(m),g=n.charAt(m+1);if(o==="line"){E===`
3
+ `&&(c.push(O(i,d,n.slice(a,m))),o=void 0),i+=E===`
4
+ `?`
5
+ `:" ";continue}if(o==="block"){i+=" ",E==="*"&&g==="/"&&(i+=" ",o=void 0,m+=1);continue}if(l!==void 0){i+=" ",E===l&&l!=="]"&&g===l?(i+=" ",m+=1):E===l&&(l=void 0);continue}if(E==="-"&&g==="-"||E==="/"&&g==="*"){o=E==="-"?"line":"block",a=m,d=i.length,i+=" ",m+=1;continue}if(r!==void 0){if(!p.test(E))throw new u("INTERNAL",`${e} contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);i+=E;continue}if(t){if(y.test(E)){s+=E,i+=E;continue}const I=s.toUpperCase();s="",I!==""?(h=T&&I==="END",T=!1):E!==";"&&!p.test(E)&&(h=!1,T=!1)}if(l=V[E],l!==void 0){i+=" _ ";continue}i+=E,E===";"&&(t&&!h?T=!0:r=m)}return o==="line"&&c.push(O(i,d,n.slice(a))),{code:i,lineComments:c,statementText:n.slice(0,r??n.length).trim()}},x=(n,e)=>{if(B.test(e.code))throw new u("INTERNAL",`${n} is transaction control (BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE). Each migration already runs atomically with its tracking row in one batch(); remove it.`);let t;for(const[i,l]of G){const o=l.exec(e.code),a=o===null?void 0:o.index+o[0].length-o[0].trimStart().length;a!==void 0&&(t===void 0||a<t.index)&&(t={index:a,statement:i})}if(t===void 0)return;if(!e.lineComments.some(i=>i.ownLine&&i.codeIndex<t.index&&i.text.trimEnd()===v))throw new u("MIGRATION_DESTRUCTIVE",`${n} has not run yet and contains a destructive statement (${t.statement}). If it is meant to discard data or rename what readers depend on, add a \`${v}\` line comment on its own line before the statement. Only pending migrations are checked, so never add it to one that already ran: that changes its hash and is refused as drift.`)},_=async n=>{const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(c=>c.toString(16).padStart(2,"0")).join("")},k=/^\uFEFF/u,q=n=>{let e=n.length;for(;e>0&&n[e-1]===`
6
+ `;)e-=1;return n.slice(0,e)},M=n=>q(n.replace(k,"").replaceAll(`\r
7
+ `,`
8
+ `)),Q=async n=>({normalized:await _(M(n)),raw:await _(n)}),K=(n,e)=>n===e?.normalized||n===e?.raw;class J{client;migrations;constructor(e,t){this.client=e instanceof N?e:new N(e),this.migrations=[...t].toSorted((c,i)=>c.version-i.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async r=>Q(r.sql))),t=await this.readTrackingRows(e),c=new Map(t.filter(r=>r.version!==null).map(r=>[r.version,r.hash])),i=[];for(const[r,s]of this.migrations.entries()){const h=c.get(s.version),T=String(e[r]?.normalized);if(h===void 0)i.push({hash:T,migration:s});else if(!K(h,e[r]))throw new u("MIGRATION_DRIFT",`${C(s)} was already applied from different SQL (recorded sha256 ${h}, now ${T}). An applied migration is never re-run: revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new text as applied: UPDATE ${R} SET hash = '${T}' WHERE version = ${String(s.version)};`)}const l=t.filter(r=>r.version===null);if(i.length>0&&l.length>0){const r=i.map(({migration:s})=>s.version);throw new u("MIGRATION_DRIFT",`${R} holds ${String(l.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${l.map(s=>String(s.id)).join(", ")}), and ${r.map(s=>`v${String(s)}`).join(", ")} ${r.length===1?"is":"are"} not recorded as applied — one of them may be an edited copy of what already ran. Refusing to guess: give each row the version it recorded (UPDATE ${R} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`)}const o=new Map(i.map(({hash:r,migration:s})=>{const h=C(s),T=H(s.sql,h);return x(h,T),[s.version,{hash:r,migration:s,statementText:T.statementText}]})),a=[],d=[];for(const r of this.migrations){const s=o.get(r.version),h={name:r.name,version:r.version};if(s===void 0){d.push(h);continue}await this.applyOne(s)?a.push(h):d.push(h)}return{applied:a,skipped:d}}async hasVersionColumn(){return(await this.client.drizzle.all(w.raw(`SELECT name FROM pragma_table_info('${R}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(w.raw(D)),!await this.hasVersionColumn())try{await this.client.drizzle.run(w.raw(`ALTER TABLE ${R} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(w.raw(U))}async readTrackingRows(e){const t=w.raw(`SELECT id, hash, version FROM ${R} ORDER BY id`),c=await this.client.drizzle.all(t),i=new Map(this.migrations.flatMap((a,d)=>[[String(e[d]?.raw),a.version],[String(e[d]?.normalized),a.version]])),l=new Set(c.map(a=>a.version).filter(a=>a!==null));let o=!1;for(const a of c){const d=a.version===null?i.get(a.hash):void 0;d===void 0||l.has(d)||(await this.client.drizzle.run(w`UPDATE ${w.raw(R)} SET version = ${d} WHERE id = ${a.id} AND version IS NULL`),l.add(d),o=!0)}return o?await this.client.drizzle.all(t):c}async applyOne({hash:e,migration:t,statementText:c}){if(!b.test(e))throw new u("INTERNAL",`migration "${t.name}" produced a non-hex hash; refusing to inline into SQL`);const i=`INSERT INTO ${R} (hash, created_at, version) VALUES ('${e}', ${String(Date.now())}, ${String(t.version)})`,l=[this.client.drizzle.run(w.raw(c)),this.client.drizzle.run(w.raw(i))];try{await this.client.batch(l)}catch(o){if(F.test(o instanceof Error?o.message:String(o)))return!1;throw o}return!0}assertUniqueVersions(){const e=new Set;for(const t of this.migrations){if(!Number.isSafeInteger(t.version))throw new u("INTERNAL",`Migration "${t.name}" has version ${String(t.version)}; a version must be an integer`);if(e.has(t.version))throw new u("INTERNAL",`Duplicate migration version ${String(t.version)}`);e.add(t.version)}}assertUniqueSql(){const e=new Map;for(const t of this.migrations){const c=M(t.sql),i=e.get(c);if(i!==void 0)throw new u("INTERNAL",`Migrations ${String(i)} and ${String(t.version)} have identical SQL — bump the content, not just the version.`);e.set(c,t.version)}}}export{v as ALLOW_DESTRUCTIVE_MARKER,J as MigrationRunner,R as TRACKING_TABLE_NAME};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/d1",
3
- "version": "1.0.0-alpha.232",
3
+ "version": "1.0.0-alpha.234",
4
4
  "description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -52,8 +52,8 @@
52
52
  "dependencies": {
53
53
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
54
54
  "@lunora/platform": "1.0.0-alpha.80",
55
- "@lunora/shard-engine": "1.0.0-alpha.186",
56
- "@lunora/sql-store": "1.0.0-alpha.233",
55
+ "@lunora/shard-engine": "^1.0.0-alpha.187",
56
+ "@lunora/sql-store": "^1.0.0-alpha.234",
57
57
  "drizzle-orm": "1.0.0-rc.5"
58
58
  },
59
59
  "engines": {
@@ -1,5 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as w}from"drizzle-orm";import{D1Client as S}from"./D1Client-CzS0Qfa6.mjs";const d="__drizzle_migrations",A=`CREATE TABLE IF NOT EXISTS ${d} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC, version INTEGER)`,$=`CREATE UNIQUE INDEX IF NOT EXISTS ${d}_version ON ${d} (version)`,p=/\s/u,_=/[$\w]/u,T=String.raw`(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)`,y=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/u,L=new RegExp(String.raw`^CREATE${T}+(?:TEMP${T}+|TEMPORARY${T}+)?TRIGGER\b`,"iu"),z=/^[0-9a-f]{64}$/u,C=new RegExp(String.raw`UNIQUE constraint failed:\s*${d}\.(?:hash|version)`,"iu"),U=o=>{const e=o.sql,n=L.test(e.slice(y.exec(e)?.[0].length??0));let s=!1,a=!1,h=!1,f=!1,t=!1,c=!1,i,l="",E=!1,v=!1;for(let u=0;u<e.length;u+=1){const r=e[u],m=e[u+1];if(t){r===`
2
- `&&(t=!1);continue}if(c){r==="*"&&m==="/"&&(c=!1,u+=1);continue}if(s){r==="'"&&(m==="'"?u+=1:s=!1);continue}if(a){r==='"'&&(m==='"'?u+=1:a=!1);continue}if(h){r==="]"&&(h=!1);continue}if(f){r==="`"&&(m==="`"?u+=1:f=!1);continue}if(r==="-"&&m==="-"){t=!0,u+=1;continue}if(r==="/"&&m==="*"){c=!0,u+=1;continue}if(i!==void 0){if(r!==void 0&&!p.test(r))throw new g("INTERNAL",`Migration "${o.name}" (v${String(o.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);continue}if(n&&r!==void 0){if(_.test(r)){l+=r;continue}const R=l.toUpperCase();l="",R!==""?(E=v&&R==="END",v=!1):r!==";"&&!p.test(r)&&(E=!1,v=!1)}if(r==="'"){s=!0;continue}if(r==='"'){a=!0;continue}if(r==="["){h=!0;continue}if(r==="`"){f=!0;continue}if(r===";"){if(n&&!E){v=!0;continue}i=u}}return i},I=async o=>{const e=new TextEncoder().encode(o),n=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")},M=/^\uFEFF/u,D=o=>{let e=o.length;for(;e>0&&o[e-1]===`
3
- `;)e-=1;return o.slice(0,e)},N=o=>D(o.replace(M,"").replaceAll(`\r
4
- `,`
5
- `)),O=async o=>({normalized:await I(N(o)),raw:await I(o)}),H=(o,e)=>o===e?.normalized||o===e?.raw;class q{client;migrations;constructor(e,n){this.client=e instanceof S?e:new S(e),this.migrations=[...n].toSorted((s,a)=>s.version-a.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.ensureTrackingTable();const e=await Promise.all(this.migrations.map(async i=>O(i.sql))),n=await this.readTrackingRows(e),s=new Map(n.filter(i=>i.version!==null).map(i=>[i.version,i.hash])),a=i=>String(e[i]?.normalized),h=this.migrations.filter((i,l)=>{const E=s.get(i.version);if(E!==void 0&&!H(E,e[l]))throw new g("MIGRATION_DRIFT",`Migration "${i.name}" (v${String(i.version)}) was already applied from different SQL (recorded sha256 ${E}, now ${a(l)}). An applied migration is never re-run: revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new text as applied: UPDATE ${d} SET hash = '${a(l)}' WHERE version = ${String(i.version)};`);return E===void 0}),f=n.filter(i=>i.version===null);if(h.length>0&&f.length>0)throw new g("MIGRATION_DRIFT",`${d} holds ${String(f.length)} row(s) recorded before versions were tracked whose SQL matches no current migration (id ${f.map(i=>String(i.id)).join(", ")}), and ${h.map(i=>`v${String(i.version)}`).join(", ")} ${h.length===1?"is":"are"} not recorded as applied — one of them may be an edited copy of what already ran. Refusing to guess: give each row the version it recorded (UPDATE ${d} SET version = <n> WHERE id = <id>; for a migration that no longer exists, any version no current migration uses), then run again.`);const t=[],c=[];for(const[i,l]of this.migrations.entries()){const E=a(i);if(!h.includes(l)){c.push({name:l.name,version:l.version});continue}await this.applyOne(l,E)?t.push({name:l.name,version:l.version}):c.push({name:l.name,version:l.version})}return{applied:t,skipped:c}}async hasVersionColumn(){return(await this.client.drizzle.all(w.raw(`SELECT name FROM pragma_table_info('${d}') WHERE name = 'version'`))).length>0}async ensureTrackingTable(){if(await this.client.drizzle.run(w.raw(A)),!await this.hasVersionColumn())try{await this.client.drizzle.run(w.raw(`ALTER TABLE ${d} ADD COLUMN version INTEGER`))}catch(e){if(!await this.hasVersionColumn())throw e}await this.client.drizzle.run(w.raw($))}async readTrackingRows(e){const n=w.raw(`SELECT id, hash, version FROM ${d} ORDER BY id`),s=await this.client.drizzle.all(n),a=new Map(this.migrations.flatMap((t,c)=>[[String(e[c]?.raw),t.version],[String(e[c]?.normalized),t.version]])),h=new Set(s.map(t=>t.version).filter(t=>t!==null));let f=!1;for(const t of s){const c=t.version===null?a.get(t.hash):void 0;c===void 0||h.has(c)||(await this.client.drizzle.run(w`UPDATE ${w.raw(d)} SET version = ${c} WHERE id = ${t.id} AND version IS NULL`),h.add(c),f=!0)}return f?await this.client.drizzle.all(n):s}async applyOne(e,n){const s=U(e),a=(s===void 0?e.sql:e.sql.slice(0,s)).trim();if(!z.test(n))throw new g("INTERNAL",`migration "${e.name}" produced a non-hex hash; refusing to inline into SQL`);const h=`INSERT INTO ${d} (hash, created_at, version) VALUES ('${n}', ${String(Date.now())}, ${String(e.version)})`,f=[this.client.drizzle.run(w.raw(a)),this.client.drizzle.run(w.raw(h))];try{await this.client.batch(f)}catch(t){if(C.test(t instanceof Error?t.message:String(t)))return!1;throw t}return!0}assertUniqueVersions(){const e=new Set;for(const n of this.migrations){if(!Number.isSafeInteger(n.version))throw new g("INTERNAL",`Migration "${n.name}" has version ${String(n.version)}; a version must be an integer`);if(e.has(n.version))throw new g("INTERNAL",`Duplicate migration version ${String(n.version)}`);e.add(n.version)}}assertUniqueSql(){const e=new Map;for(const n of this.migrations){const s=N(n.sql),a=e.get(s);if(a!==void 0)throw new g("INTERNAL",`Migrations ${String(a)} and ${String(n.version)} have identical SQL — bump the content, not just the version.`);e.set(s,n.version)}}}export{q as MigrationRunner,d as TRACKING_TABLE_NAME};