@lunora/d1 1.0.0-alpha.77 → 1.0.0-alpha.78

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/dialect.mjs CHANGED
@@ -1 +1 @@
1
- import{quoteIdentifier as i}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";const t=e=>{switch(e){case"boolean":return"INTEGER";case"bytes":return"BLOB";case"date":case"number":case"timestamp":return"REAL";default:return"TEXT"}},a=100,o=()=>[`${i("id")} TEXT PRIMARY KEY`,`${i("_creationTime")} REAL NOT NULL`],c=e=>e==="_id"||e==="id"?i("id"):e==="_creationTime"?i("_creationTime"):i(e),m=(e,r)=>i(`${e}_${r}`);export{a as MAX_D1_TABLE_COLUMNS,c as columnRef,o as frameworkColumnDdl,m as physicalIndexName,i as quoteIdentifier,t as sqlAffinityForKind};
1
+ import{quoteIdentifier as t}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";const i=e=>{switch(e){case"boolean":return"INTEGER";case"bytes":return"BLOB";case"date":case"number":case"timestamp":return"REAL";default:return"TEXT"}},o=100,c=()=>[`${t("id")} TEXT PRIMARY KEY`,`${t("_creationTime")} REAL NOT NULL`],a=e=>e==="_id"||e==="id"?t("id"):e==="_creationTime"?t("_creationTime"):t(e),s=(e,r)=>t(`${e}_${r}`);export{o as MAX_D1_TABLE_COLUMNS,a as columnRef,c as frameworkColumnDdl,s as physicalIndexName,t as quoteIdentifier,i as sqlAffinityForKind};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportGlobalRows as a,importGlobalRows as o,selectGlobalTables as l}from"./packem_shared/exportGlobalRows-_yXk_oxX.mjs";import{D1Client as i,D1Session as n}from"./packem_shared/D1Client-DeccGO7F.mjs";import{backfillD1SearchIndexes as b,createD1CtxDb as D,readD1CdcChanges as g,runD1AggregateMigrations as c,runD1CdcMigration as x,runD1GlobalTableMigrations as f,runD1RankMigrations as m,runD1SearchMigrations as p,trimD1CdcChanges as C}from"./packem_shared/backfillD1SearchIndexes-KCnA1HXB.mjs";import{facetGlobalColumn as d,listGlobalTables as G,readGlobalTablePage as M}from"./packem_shared/facetGlobalColumn-CVjP-5p6.mjs";import{MigrationRunner as R}from"./packem_shared/MigrationRunner-CNH8wlIl.mjs";import{default as T}from"./packem_shared/sqliteDialect-BKmeSU04.mjs";import{createSqlCtxDb as q}from"@lunora/sql-store";export{i as D1Client,n as D1Session,R as MigrationRunner,b as backfillD1SearchIndexes,D as createD1CtxDb,q as createSqlCtxDb,a as exportGlobalRows,d as facetGlobalColumn,o as importGlobalRows,G as listGlobalTables,g as readD1CdcChanges,M as readGlobalTablePage,c as runD1AggregateMigrations,x as runD1CdcMigration,f as runD1GlobalTableMigrations,m as runD1RankMigrations,p as runD1SearchMigrations,l as selectGlobalTables,T as sqliteDialect,C as trimD1CdcChanges};
1
+ import{exportGlobalRows as a,importGlobalRows as o,selectGlobalTables as l}from"./packem_shared/exportGlobalRows-Cc8cXltm.mjs";import{D1Client as i,D1Session as n}from"./packem_shared/D1Client-IzEOlt9I.mjs";import{backfillD1SearchIndexes as b,createD1CtxDb as D,readD1CdcChanges as g,runD1AggregateMigrations as c,runD1CdcMigration as x,runD1GlobalTableMigrations as f,runD1RankMigrations as m,runD1SearchMigrations as p,trimD1CdcChanges as C}from"./packem_shared/backfillD1SearchIndexes-By6bbCLe.mjs";import{facetGlobalColumn as d,listGlobalTables as G,readGlobalTablePage as M}from"./packem_shared/facetGlobalColumn-D1npxpva.mjs";import{MigrationRunner as R}from"./packem_shared/MigrationRunner-IF213ALw.mjs";import{default as T}from"./packem_shared/sqliteDialect-DZoYJOa-.mjs";import{createSqlCtxDb as q}from"@lunora/sql-store";export{i as D1Client,n as D1Session,R as MigrationRunner,b as backfillD1SearchIndexes,D as createD1CtxDb,q as createSqlCtxDb,a as exportGlobalRows,d as facetGlobalColumn,o as importGlobalRows,G as listGlobalTables,g as readD1CdcChanges,M as readGlobalTablePage,c as runD1AggregateMigrations,x as runD1CdcMigration,f as runD1GlobalTableMigrations,m as runD1RankMigrations,p as runD1SearchMigrations,l as selectGlobalTables,T as sqliteDialect,C as trimD1CdcChanges};
@@ -0,0 +1 @@
1
+ import{drizzle as i}from"drizzle-orm/d1";const a=(s,e)=>{if(s.size<e)return;const t=s.keys().next().value;t!==void 0&&s.delete(t)},h=256,d=(s,e,t)=>{const r=s.get(t);if(r)return s.delete(t),s.set(t,r),r;const n=e(t);return a(s,h),s.set(t,n),n},o="first-unconstrained";class l{session;stmtCache=new Map;constructor(e){this.session=e}prepare(e){return d(this.stmtCache,t=>this.session.prepare(t),e)}async run(e,...t){return this.prepare(e).bind(...t).run()}async all(e,...t){return this.prepare(e).bind(...t).all()}async first(e,...t){return this.prepare(e).bind(...t).first()}getBookmark(){return this.session.getBookmark()??void 0}}class u{db;stmtCache=new Map;drizzleHandle;constructor(e){this.db=e}withSession(e){const t=this.db.withSession(e??o);return new l(t)}prepare(e){return d(this.stmtCache,t=>this.db.prepare(t),e)}get drizzle(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=i(this.db,{logger:!1}),this.drizzleHandle)}drizzleSession(e){const t=this.db.withSession(e??o);return i(t,{logger:!1})}async batch(e){return this.drizzle.batch(e)}get raw(){return this.db}}export{u as D1Client,l as D1Session};
@@ -0,0 +1,2 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{sql as h}from"drizzle-orm";import{D1Client as m}from"./D1Client-IzEOlt9I.mjs";const u="__drizzle_migrations",p=`CREATE TABLE IF NOT EXISTS ${u} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC)`,d=/\s/u,E=/^[0-9a-f]{64}$/u,S=new RegExp(String.raw`UNIQUE constraint failed:\s*${u}\.hash`,"iu"),w=c=>{const n=c.sql;let e=!1,i=!1,o=!1,a=!1,r;for(let t=0;t<n.length;t+=1){const s=n[t],l=n[t+1];if(o){s===`
2
+ `&&(o=!1);continue}if(a){s==="*"&&l==="/"&&(a=!1,t+=1);continue}if(e){s==="'"&&(l==="'"?t+=1:e=!1);continue}if(i){s==='"'&&(l==='"'?t+=1:i=!1);continue}if(s==="-"&&l==="-"){o=!0,t+=1;continue}if(s==="/"&&l==="*"){a=!0,t+=1;continue}if(r!==void 0){if(s!==void 0&&!d.test(s))throw new f("INTERNAL",`Migration "${c.name}" (v${String(c.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);continue}if(s==="'"){e=!0;continue}if(s==='"'){i=!0;continue}s===";"&&(r=t)}return r},g=async c=>{const n=new TextEncoder().encode(c),e=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(e)].map(i=>i.toString(16).padStart(2,"0")).join("")};class A{client;migrations;constructor(n,e){this.client=n instanceof m?n:new m(n),this.migrations=[...e].toSorted((i,o)=>i.version-o.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.client.drizzle.run(h.raw(p));const n=await this.client.drizzle.all(h.raw(`SELECT hash FROM ${u}`)),e=new Set(n.map(r=>r.hash)),i=[],o=[],a=await Promise.all(this.migrations.map(async r=>g(r.sql)));for(const[r,t]of this.migrations.entries()){const s=a[r];if(e.has(s)){o.push({name:t.name,version:t.version});continue}await this.applyOne(t,s)?i.push({name:t.name,version:t.version}):o.push({name:t.name,version:t.version})}return{applied:i,skipped:o}}async applyOne(n,e){const i=w(n),o=(i===void 0?n.sql:n.sql.slice(0,i)).trim();if(!E.test(e))throw new f("INTERNAL",`migration "${n.name}" produced a non-hex hash; refusing to inline into SQL`);const a=`INSERT INTO ${u} (hash, created_at) VALUES ('${e}', ${String(Date.now())})`,r=[this.client.drizzle.run(h.raw(o)),this.client.drizzle.run(h.raw(a))];try{await this.client.batch(r)}catch(t){if(S.test(t instanceof Error?t.message:String(t)))return!1;throw t}return!0}assertUniqueVersions(){const n=new Set;for(const e of this.migrations){if(n.has(e.version))throw new f("INTERNAL",`Duplicate migration version ${String(e.version)}`);n.add(e.version)}}assertUniqueSql(){const n=new Map;for(const e of this.migrations){const i=n.get(e.sql);if(i!==void 0)throw new f("INTERNAL",`Migrations ${String(i)} and ${String(e.version)} have identical SQL — bump the content, not just the version.`);n.set(e.sql,e.version)}}}export{A as MigrationRunner};
@@ -0,0 +1 @@
1
+ import{backfillSqlSearchIndexes as n,createSqlCtxDb as e,readSqlCdcChanges as o,runSqlAggregateMigrations as i,runSqlCdcMigration as c,runSqlGlobalTableMigrations as s,runSqlRankMigrations as l,runSqlSearchMigrations as g,trimSqlCdcChanges as D}from"@lunora/sql-store";import{createSqlCtxDb as G,decodeGlobalRow as R}from"@lunora/sql-store";import t from"./sqliteDialect-DZoYJOa-.mjs";const d=a=>e({...a,dialect:t}),b=(a,r)=>s(a,r,t),q=(a,r)=>i(a,r,t),u=(a,r)=>l(a,r,t),M=(a,r)=>g(a,r,t),h=(a,r)=>n(a,r,t),x=a=>c(a,t),m=(a,r={})=>o(a,r,t),f=(a,r)=>D(a,r,t);export{h as backfillD1SearchIndexes,d as createD1CtxDb,G as createSqlCtxDb,R as decodeGlobalRow,m as readD1CdcChanges,q as runD1AggregateMigrations,x as runD1CdcMigration,b as runD1GlobalTableMigrations,u as runD1RankMigrations,M as runD1SearchMigrations,f as trimD1CdcChanges};
@@ -0,0 +1 @@
1
+ import{toErrorBody as u}from"@lunora/errors";import{runD1GlobalTableMigrations as p}from"./backfillD1SearchIndexes-By6bbCLe.mjs";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{decodeGlobalRow as w}from"@lunora/sql-store";const E=200,R=(i,o)=>{const e=t=>i.tables[t]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(t=>e(t)):Object.keys(i.tables).filter(t=>e(t))},m=(i,o,e)=>{const t=i.tables[o];return t?w(t,e):{_creationTime:e._creationTime,_id:e.id}},O=async function*(i,o,e){const t=R(o,e.tables),s=e.batchSize??E;await p(i,o);for(const r of t){const n=f(r);let c,l=!0;for(;l;){const a=c===void 0?await i.all(`SELECT * FROM ${n} ORDER BY "id" LIMIT ?`,[s]):await i.all(`SELECT * FROM ${n} WHERE "id" > ? ORDER BY "id" LIMIT ?`,[c,s]);for(const b of a)yield{doc:m(o,r,b),table:r};const d=a.at(-1);d!==void 0&&(c=String(d.id)),l=a.length===s}}},k=(i,o,e)=>{const t=i.tables[o];if(!t)return`unknown table: ${o}`;for(const[s,r]of Object.entries(t.shape)){const n=e[s],c=r.kind==="optional";if(n===void 0&&c)continue;const l=r.parse;if(typeof l=="function")try{l(n)}catch(a){const d=a instanceof Error?a.message:String(a);return`field "${s}": ${d}`}}},g=async(i,o,e,t)=>{try{return o?(await o.all(`SELECT 1 AS hit FROM ${f(e)} WHERE "id" = ? LIMIT 1`,[t])).length>0:await i.get(t)!==null}catch{return!1}},y=async(i,o,e,t,s)=>{const{doc:r,table:n}=t;if(o.tables[n]?.shardMode?.kind!=="global")return{kind:"skip"};if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:s,message:"row is missing or malformed `doc`",table:n},kind:"error"};const c=k(o,n,r);if(c!==void 0)return{error:{code:"VALIDATION_ERROR",line:s,message:c,table:n},kind:"error"};const l=typeof r._id=="string"?r._id:void 0;if(l!==void 0&&await g(i,e.exec,n,l))return{kind:"conflict"};try{return await i.insert(n,r,{allowExplicitId:!0}),{inserted:n,kind:"inserted"}}catch(a){const{body:d}=u(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:s,message:d.message,table:n},kind:"error"}}},v=async(i,o,e)=>{const t=[],s={};let r=0,n=(e.startLine??1)-1;for(const c of e.rows){n+=1;const l=c.line??n,a=await y(i,o,e,c,l);switch(a.kind){case"conflict":{r+=1;break}case"error":{t.push(a.error);break}case"inserted":{s[a.inserted]=(s[a.inserted]??0)+1;break}}}return{conflicts:r,errors:t,inserted:s}};export{O as exportGlobalRows,v as importGlobalRows,R as selectGlobalTables};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{runD1GlobalTableMigrations as T}from"./backfillD1SearchIndexes-By6bbCLe.mjs";import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{decodeGlobalRow as O}from"@lunora/sql-store";const R=50,p=500,I=30,$=200,M=(t,a,n)=>Math.min(Math.max(t,a),n),C=/^sqlite_|^_cf_|^d1_|^__cdc|__agg_|__rank_|__fts_/u,y=t=>C.test(t),b=/password|secret|token|hash|salt|credential/iu,v=async t=>(await t.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",[])).map(n=>String(n.name)).filter(n=>!y(n)),S=async(t,a,n)=>{if(await T(t,a),!(await v(t)).includes(n))throw new E("UNKNOWN_TABLE",`unknown table: ${n}`,{status:404})},N=async(t,a,n="",o=[])=>{const s=await t.all(`SELECT COUNT(*) AS c FROM ${a}${n}`,o);return Number(s[0]?.c??0)},h=(t,a,n)=>t.tables[a]!==void 0&&n==="_id"?"id":n,A=(t,a,n,o)=>{const s=[],r=[];for(const e of o??[]){if(!n.includes(e.column))throw new E("UNKNOWN_COLUMN",`unknown column: ${e.column}`,{status:404});if(t.tables[a]===void 0&&b.test(e.column))throw new E("FORBIDDEN",`cannot filter on a redacted column: ${e.column}`,{status:403});const l=i(h(t,a,e.column));e.value===null||e.value===void 0?s.push(`${l} IS NULL`):(s.push(`${l} = ?`),r.push(e.value))}return{params:r,where:s.length>0?` WHERE ${s.join(" AND ")}`:""}},g=(t,a,n)=>{const o=t.tables[a];if(o)return O(o,n);const s={};for(const[r,e]of Object.entries(n))s[r]=e!=null&&b.test(r)?"•••":e;return s},L=async(t,a,n)=>{const o=a.tables[n];return o?["_id","_creationTime",...Object.keys(o.shape)]:(await t.all(`PRAGMA table_info(${i(n)})`,[])).map(r=>String(r.name))},U=async(t,a,n)=>{if(a.tables[n])return;const o=await t.all(`PRAGMA foreign_key_list(${i(n)})`,[]);if(o.length===0)return;const s={};for(const r of o){const e=String(r.from),l=String(r.table);s[e]??=l}return s},q=async(t,a)=>{await T(t,a);const n=await v(t);return Promise.all(n.map(async o=>({name:o,rowCount:await N(t,i(o))})))},D=async(t,a,n)=>{const{table:o}=n;await S(t,a,o);const s=M(Math.trunc(n.limit??R),1,p),r=Math.max(0,Math.trunc(n.offset??0)),e=i(o),l=await L(t,a,o),{params:w,where:u}=A(a,o,l,n.filters),f=await N(t,e,u,w),m=(await t.all(`SELECT * FROM ${e}${u} LIMIT ? OFFSET ?`,[...w,s,r])).map(c=>g(a,o,c)),_=await U(t,a,o);return _===void 0?{columns:l,rows:m,total:f}:{columns:l,refs:_,rows:m,total:f}},B=async(t,a,n)=>{const{column:o,table:s}=n;await S(t,a,s);const r=await L(t,a,s);if(!r.includes(o))throw new E("UNKNOWN_COLUMN",`unknown column: ${o}`,{status:404});const e=i(s),{params:l,where:w}=A(a,s,r,n.filters);if(a.tables[s]===void 0&&b.test(o)){const c=await N(t,e,w,l);return{truncated:!1,values:c===0?[]:[{count:c,value:"•••"}]}}const u=M(Math.trunc(n.limit??I),1,$),f=i(h(a,s,o)),d=await t.all(`SELECT ${f} AS value, COUNT(*) AS count FROM ${e}${w} GROUP BY ${f} ORDER BY count DESC LIMIT ?`,[...l,u+1]),m=d.length>u,_=m?d.slice(0,u):d;return{truncated:m,values:_.map(c=>({count:Number(c.count),value:c.value}))}};export{B as facetGlobalColumn,q as listGlobalTables,D as readGlobalTablePage};
@@ -1 +1 @@
1
- import{sqliteEncode as t,sqliteDecode as i}from"@lunora/sql-store";import{sql as n}from"drizzle-orm";import{MAX_D1_TABLE_COLUMNS as o,sqlAffinityForKind as r}from"../dialect.mjs";const s=/unique constraint failed/iu,T={companionTypes:{autoincrementPrimaryKey:"INTEGER PRIMARY KEY AUTOINCREMENT",integer:"INTEGER",key:"TEXT",real:"REAL",text:"TEXT"},columnType:r,decode:i,encode:t,frameworkColumns:()=>[{name:"id",type:"TEXT PRIMARY KEY"},{name:"_creationTime",type:"REAL NOT NULL"}],isUniqueViolation:e=>e instanceof Error&&s.test(e.message),maxTableColumns:o,name:"sqlite",supportsFts5:!0,supportsReturning:!0,tableExists:e=>n`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${e}`};export{T as default};
1
+ import{sqliteEncode as t,sqliteDecode as i}from"@lunora/sql-store";import{sql as n}from"drizzle-orm";import{MAX_D1_TABLE_COLUMNS as o,sqlAffinityForKind as s}from"../dialect.mjs";const a=/unique constraint failed/iu,l={companionTypes:{autoincrementPrimaryKey:"INTEGER PRIMARY KEY AUTOINCREMENT",integer:"INTEGER",key:"TEXT",real:"REAL",text:"TEXT"},columnType:s,decode:i,encode:t,frameworkColumns:()=>[{name:"id",type:"TEXT PRIMARY KEY"},{name:"_creationTime",type:"REAL NOT NULL"}],isUniqueViolation:e=>e instanceof Error&&a.test(e.message),maxTableColumns:o,name:"sqlite",supportsFts5:!0,supportsReturning:!0,tableExists:e=>n`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${e}`};export{l as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/d1",
3
- "version": "1.0.0-alpha.77",
3
+ "version": "1.0.0-alpha.78",
4
4
  "description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,10 +50,10 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/errors": "1.0.0-alpha.21",
54
- "@lunora/platform": "1.0.0-alpha.10",
55
- "@lunora/shard-engine": "1.0.0-alpha.27",
56
- "@lunora/sql-store": "1.0.0-alpha.79",
53
+ "@lunora/errors": "1.0.0-alpha.22",
54
+ "@lunora/platform": "1.0.0-alpha.11",
55
+ "@lunora/shard-engine": "1.0.0-alpha.28",
56
+ "@lunora/sql-store": "1.0.0-alpha.80",
57
57
  "drizzle-orm": "^0.45.2"
58
58
  },
59
59
  "engines": {
@@ -1 +0,0 @@
1
- import{drizzle as n}from"drizzle-orm/d1";import"@lunora/platform";const d=(t,e)=>{if(t.size<e)return;const s=t.keys().next().value;s!==void 0&&t.delete(s)},l=256,o=(t,e,s)=>{const r=t.get(s);if(r)return t.delete(s),t.set(s,r),r;const i=e(s);return d(t,l),t.set(s,i),i},a="first-unconstrained";class h{session;stmtCache=new Map;constructor(e){this.session=e}prepare(e){return o(this.stmtCache,s=>this.session.prepare(s),e)}async run(e,...s){return this.prepare(e).bind(...s).run()}async all(e,...s){return this.prepare(e).bind(...s).all()}async first(e,...s){return this.prepare(e).bind(...s).first()}getBookmark(){return this.session.getBookmark()??void 0}}class p{db;stmtCache=new Map;drizzleHandle;constructor(e){this.db=e}withSession(e){const s=this.db.withSession(e??a);return new h(s)}prepare(e){return o(this.stmtCache,s=>this.db.prepare(s),e)}get drizzle(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=n(this.db,{logger:!1}),this.drizzleHandle)}drizzleSession(e){const s=this.db.withSession(e??a);return n(s,{logger:!1})}async batch(e){return this.drizzle.batch(e)}get raw(){return this.db}}export{p as D1Client,h as D1Session};
@@ -1,2 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{sql as h}from"drizzle-orm";import{D1Client as m}from"./D1Client-DeccGO7F.mjs";const f="__drizzle_migrations",w=`CREATE TABLE IF NOT EXISTS ${f} (id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, created_at NUMERIC)`,g=/\s/u,p=/^[0-9a-f]{64}$/u,d=new RegExp(String.raw`UNIQUE constraint failed:\s*${f}\.hash`,"iu"),E=c=>{const n=c.sql;let i=!1,e=!1,r=!1,o=!1,a;for(let t=0;t<n.length;t+=1){const s=n[t],l=n[t+1];if(r){s===`
2
- `&&(r=!1);continue}if(o){s==="*"&&l==="/"&&(o=!1,t+=1);continue}if(i){s==="'"&&(l==="'"?t+=1:i=!1);continue}if(e){s==='"'&&(l==='"'?t+=1:e=!1);continue}if(s==="-"&&l==="-"){r=!0,t+=1;continue}if(s==="/"&&l==="*"){o=!0,t+=1;continue}if(a!==void 0){if(s!==void 0&&!g.test(s))throw new u("INTERNAL",`Migration "${c.name}" (v${String(c.version)}) contains more than one SQL statement. Split it into separate migrations — batch() runs them atomically.`);continue}if(s==="'"){i=!0;continue}if(s==='"'){e=!0;continue}s===";"&&(a=t)}return a},S=async c=>{const n=new TextEncoder().encode(c),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,"0")).join("")};class I{client;migrations;constructor(n,i){this.client=n instanceof m?n:new m(n),this.migrations=[...i].toSorted((e,r)=>e.version-r.version),this.assertUniqueVersions(),this.assertUniqueSql()}async run(){await this.client.drizzle.run(h.raw(w));const n=await this.client.drizzle.all(h.raw(`SELECT hash FROM ${f}`)),i=new Set(n.map(a=>a.hash)),e=[],r=[],o=await Promise.all(this.migrations.map(async a=>S(a.sql)));for(const[a,t]of this.migrations.entries()){const s=o[a];if(i.has(s)){r.push({name:t.name,version:t.version});continue}await this.applyOne(t,s)?e.push({name:t.name,version:t.version}):r.push({name:t.name,version:t.version})}return{applied:e,skipped:r}}async applyOne(n,i){const e=E(n),r=(e===void 0?n.sql:n.sql.slice(0,e)).trim();if(!p.test(i))throw new u("INTERNAL",`migration "${n.name}" produced a non-hex hash; refusing to inline into SQL`);const o=`INSERT INTO ${f} (hash, created_at) VALUES ('${i}', ${String(Date.now())})`,a=[this.client.drizzle.run(h.raw(r)),this.client.drizzle.run(h.raw(o))];try{await this.client.batch(a)}catch(t){if(d.test(t instanceof Error?t.message:String(t)))return!1;throw t}return!0}assertUniqueVersions(){const n=new Set;for(const i of this.migrations){if(n.has(i.version))throw new u("INTERNAL",`Duplicate migration version ${String(i.version)}`);n.add(i.version)}}assertUniqueSql(){const n=new Map;for(const i of this.migrations){const e=n.get(i.sql);if(e!==void 0)throw new u("INTERNAL",`Migrations ${String(e)} and ${String(i.version)} have identical SQL — bump the content, not just the version.`);n.set(i.sql,i.version)}}}export{I as MigrationRunner};
@@ -1 +0,0 @@
1
- import{backfillSqlSearchIndexes as n,createSqlCtxDb as i,readSqlCdcChanges as t,runSqlAggregateMigrations as s,runSqlCdcMigration as l,runSqlGlobalTableMigrations as o,runSqlRankMigrations as g,runSqlSearchMigrations as c,trimSqlCdcChanges as d}from"@lunora/sql-store";import{createSqlCtxDb as G,decodeGlobalRow as R}from"@lunora/sql-store";import e from"./sqliteDialect-BKmeSU04.mjs";const D=a=>i({...a,dialect:e}),b=(a,r)=>o(a,r,e),q=(a,r)=>s(a,r,e),u=(a,r)=>g(a,r,e),M=(a,r)=>c(a,r,e),h=(a,r)=>n(a,r,e),m=a=>l(a,e),x=(a,r={})=>t(a,r,e),f=(a,r)=>d(a,r,e);export{h as backfillD1SearchIndexes,D as createD1CtxDb,G as createSqlCtxDb,R as decodeGlobalRow,x as readD1CdcChanges,q as runD1AggregateMigrations,m as runD1CdcMigration,b as runD1GlobalTableMigrations,u as runD1RankMigrations,M as runD1SearchMigrations,f as trimD1CdcChanges};
@@ -1 +0,0 @@
1
- import{toErrorBody as u}from"@lunora/errors";import{runD1GlobalTableMigrations as m}from"./backfillD1SearchIndexes-KCnA1HXB.mjs";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{decodeGlobalRow as E}from"@lunora/sql-store";const k=200,R=(o,t)=>{const r=e=>o.tables[e]?.shardMode?.kind==="global";return t&&t.length>0?t.filter(e=>r(e)):Object.keys(o.tables).filter(e=>r(e))},w=(o,t,r)=>{const e=o.tables[t];return e?E(e,r):{_creationTime:r._creationTime,_id:r.id}},O=async function*(o,t,r){const e=R(t,r.tables),a=r.batchSize??k;await m(o,t);for(const i of e){const n=f(i);let c,l=!0;for(;l;){const s=c===void 0?await o.all(`SELECT * FROM ${n} ORDER BY "id" LIMIT ?`,[a]):await o.all(`SELECT * FROM ${n} WHERE "id" > ? ORDER BY "id" LIMIT ?`,[c,a]);for(const b of s)yield{doc:w(t,i,b),table:i};const d=s.at(-1);d!==void 0&&(c=String(d.id)),l=s.length===a}}},y=(o,t,r)=>{const e=o.tables[t];if(!e)return`unknown table: ${t}`;for(const[a,i]of Object.entries(e.shape)){const n=r[a],c=i.kind==="optional";if(n===void 0&&c)continue;const l=i.parse;if(typeof l=="function")try{l(n)}catch(s){const d=s instanceof Error?s.message:String(s);return`field "${a}": ${d}`}}},g=async(o,t,r,e)=>{try{return t?(await t.all(`SELECT 1 AS hit FROM ${f(r)} WHERE "id" = ? LIMIT 1`,[e])).length>0:await o.get(e)!==null}catch{return!1}},p=async(o,t,r,e,a)=>{const{doc:i,table:n}=e;if(t.tables[n]?.shardMode?.kind!=="global")return{kind:"skip"};if(!i||typeof i!="object"||Array.isArray(i))return{error:{code:"BAD_ROW",line:a,message:"row is missing or malformed `doc`",table:n},kind:"error"};const c=y(t,n,i);if(c!==void 0)return{error:{code:"VALIDATION_ERROR",line:a,message:c,table:n},kind:"error"};const l=typeof i._id=="string"?i._id:void 0;if(l!==void 0&&await g(o,r.exec,n,l))return{kind:"conflict"};try{return await o.insert(n,i,{allowExplicitId:!0}),{inserted:n,kind:"inserted"}}catch(s){const{body:d}=u(s,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:a,message:d.message,table:n},kind:"error"}}},M=async(o,t,r)=>{const e=[],a={};let i=0,n=(r.startLine??1)-1;for(const c of r.rows){n+=1;const l=c.line??n,s=await p(o,t,r,c,l);switch(s.kind){case"conflict":{i+=1;break}case"error":{e.push(s.error);break}case"inserted":{a[s.inserted]=(a[s.inserted]??0)+1;break}}}return{conflicts:i,errors:e,inserted:a}};export{O as exportGlobalRows,M as importGlobalRows,R as selectGlobalTables};
@@ -1 +0,0 @@
1
- import{LunoraError as _}from"@lunora/errors";import{runD1GlobalTableMigrations as E}from"./backfillD1SearchIndexes-KCnA1HXB.mjs";import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{decodeGlobalRow as T}from"@lunora/sql-store";const v=50,y=500,L=30,g=200,N=(a,t,n)=>Math.min(Math.max(a,t),n),C=/^sqlite_|^_cf_|^d1_|^__cdc|__agg_|__rank_|__fts_/u,A=a=>C.test(a),h=/password|secret|token|hash|salt|credential/iu,O=async a=>(await a.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",[])).map(t=>String(t.name)).filter(t=>!A(t)),M=async(a,t,n)=>{if(await E(a,t),!(await O(a)).includes(n))throw new _("UNKNOWN_TABLE",`unknown table: ${n}`,{status:404})},p=async(a,t,n="",o=[])=>{const s=await a.all(`SELECT COUNT(*) AS c FROM ${t}${n}`,o);return Number(s[0]?.c??0)},$=(a,t,n)=>a.tables[t]!==void 0&&n==="_id"?"id":n,R=(a,t,n,o)=>{const s=[],l=[];for(const e of o??[]){if(!n.includes(e.column))throw new _("UNKNOWN_COLUMN",`unknown column: ${e.column}`,{status:404});if(a.tables[t]===void 0&&h.test(e.column))throw new _("FORBIDDEN",`cannot filter on a redacted column: ${e.column}`,{status:403});const r=i($(a,t,e.column));e.value===null||e.value===void 0?s.push(`${r} IS NULL`):(s.push(`${r} = ?`),l.push(e.value))}return{params:l,where:s.length>0?` WHERE ${s.join(" AND ")}`:""}},G=(a,t,n)=>{const o=a.tables[t];if(o)return T(o,n);const s={};for(const[l,e]of Object.entries(n))s[l]=e!=null&&h.test(l)?"•••":e;return s},S=async(a,t,n)=>{const o=t.tables[n];return o?["_id","_creationTime",...Object.keys(o.shape)]:(await a.all(`PRAGMA table_info(${i(n)})`,[])).map(s=>String(s.name))},U=async(a,t,n)=>{if(t.tables[n])return;const o=await a.all(`PRAGMA foreign_key_list(${i(n)})`,[]);if(o.length===0)return;const s={};for(const l of o){const e=String(l.from),r=String(l.table);s[e]??=r}return s},P=async(a,t)=>{await E(a,t);const n=await O(a);return Promise.all(n.map(async o=>({name:o,rowCount:await p(a,i(o))})))},B=async(a,t,n)=>{const{table:o}=n;await M(a,t,o);const s=N(Math.trunc(n.limit??v),1,y),l=Math.max(0,Math.trunc(n.offset??0)),e=i(o),r=await S(a,t,o),{params:m,where:c}=R(t,o,r,n.filters),w=await p(a,e,c,m),u=(await a.all(`SELECT * FROM ${e}${c} LIMIT ? OFFSET ?`,[...m,s,l])).map(d=>G(t,o,d)),f=await U(a,t,o);return f===void 0?{columns:r,rows:u,total:w}:{columns:r,refs:f,rows:u,total:w}},W=async(a,t,n)=>{const{column:o,table:s}=n;await M(a,t,s);const l=await S(a,t,s);if(!l.includes(o))throw new _("UNKNOWN_COLUMN",`unknown column: ${o}`,{status:404});const e=i(s),{params:r,where:m}=R(t,s,l,n.filters);if(t.tables[s]===void 0&&h.test(o)){const b=await p(a,e,m,r);return{truncated:!1,values:b===0?[]:[{count:b,value:"•••"}]}}const c=N(Math.trunc(n.limit??L),1,g),w=i($(t,s,o)),u=await a.all(`SELECT ${w} AS value, COUNT(*) AS count FROM ${e}${m} GROUP BY ${w} ORDER BY count DESC LIMIT ?`,[...r,c+1]),f=u.length>c,d=f?u.slice(0,c):u;return{truncated:f,values:d.map(b=>({count:Number(b.count),value:b.value}))}};export{W as facetGlobalColumn,P as listGlobalTables,B as readGlobalTablePage};