@lunora/shard-engine 1.0.0-alpha.127 → 1.0.0-alpha.128
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/conformance/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-Bsvi2ytY.mjs → ADMIN_FUNCTIONS-DmacEYTh.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-D77Ynq1b.mjs → AGG_COUNT-DYFE3qB4.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CZNxCRLv.mjs → AUDIT_LOG_TABLE-CuIP7PJ0.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-BPEzVAil.mjs → CDC_LOG_TABLE-CvInVdXu.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs → CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-BY_vc9bw.mjs → COMMIT_SEQ_FIELD-BcUO15fR.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs → DATA_MIGRATION_STATE_TABLE-CGF7qQsu.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs → DEFAULT_MAX_RELATION_KEYS-COmk7y1x.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BqSpObEl.mjs → DEFAULT_MAX_RELAYS-DSIYUnPB.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-y2CRbfuZ.mjs → DurableStreamRunner-SCTUaMG0.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-AOJCuq5U.mjs → IDEMPOTENCY_TABLE-CymJf4r0.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-BxAGL3hK.mjs → MAIL_RETENTION-BP1GSXQ0.mjs} +1 -1
- package/dist/packem_shared/{NotUniqueError-BXDZxdAt.mjs → NotUniqueError-BavQAvdW.mjs} +1 -1
- package/dist/packem_shared/{QUEUE_TABLE-DKANxmEZ.mjs → QUEUE_TABLE-jEc6-2wm.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-B8IehLv8.mjs → REACTOR_STATE_TABLE-DHaBP_vb.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs → SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs → SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-wgl-SePe.mjs → SEARCH_STATE_TABLE-BThmEiED.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs → SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs → VECTOR_BACKFILL_MAX_PAGES-CIi7v65O.mjs} +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs +1 -0
- package/dist/packem_shared/{appendStreamChunk-7ZyAZGg_.mjs → appendStreamChunk-DF_Jrgpy.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-BON69Nug.mjs → archiveCdcSegment-CIiYU1FU.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-CJrtolQ9.mjs → backfillAggregateIndexes-DBrKU3Ya.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-CRS4SNgc.mjs → buildReprojectionMigration-D29YmeMF.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-C3hPtSKO.mjs → buildShapeDiff-CdT2gjFd.mjs} +1 -1
- package/dist/packem_shared/{clearCompanionSignatures-C2CSfkeQ.mjs → clearCompanionSignatures-Qf67j6dd.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-CogAvVHR.mjs → clearMemoryTables-Lu0S2GOb.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-BaMGeXXq.mjs → compileWhereSql-Dol9VRTW.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-CFeFkZ_k.mjs → computeRankPage-D9mACvr3.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-B7dV2y4L.mjs → createCompanionSync-C2cZNaCR.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-B9F5PAQ0.mjs → createReplicaLink-DjykIKTn.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-kGRKSxRs.mjs → ctx-db-relay-shapes-OAI2tSoy.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-DVCp4JQf.mjs → ctx-db-search-state-CrTLPmFN.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-dlOQgRU1.mjs → defineEngineContractSuite-DIOU6uW7.mjs} +1 -1
- package/dist/packem_shared/{do-sql-Cg3zXJpF.mjs → do-sql-CeuVvE0W.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-CTDgQEF8.mjs → exportShardRows-yxw7vFf9.mjs} +1 -1
- package/dist/packem_shared/{fts-companion-pUdD6kF-.mjs → fts-companion-DzfEHonU.mjs} +1 -1
- package/dist/packem_shared/{ftsCompanionDdl-Co6WSyCB.mjs → ftsCompanionDdl-Cka6_-Fm.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-BTGu2iBl.mjs → isSoftDeleted-CLY0FNLV.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-Cx6_A2W3.mjs → materializeExternalRows-UxGuXjjF.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-Du5HLitO.mjs → runDrizzle-B2GG3IJa.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-eqHNBW6S.mjs → runShardMigrations-B6FUu4iW.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-CilDdUr2.mjs → selectExpiredIds-CGR1ndMV.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-CU8Kl2Bq.mjs → selectShapeMembers-DS28-P_Z.mjs} +1 -1
- package/dist/packem_shared/{where-sql-Dn9trjRu.mjs → where-sql-CxnXsLbt.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-
|
|
1
|
+
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-B2GG3IJa.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
captured_at INTEGER NOT NULL,
|
|
4
4
|
message_id TEXT NOT NULL,
|
package/dist/packem_shared/{REACTOR_STATE_TABLE-B8IehLv8.mjs → REACTOR_STATE_TABLE-DHaBP_vb.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-B2GG3IJa.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
2
|
path TEXT PRIMARY KEY,
|
|
3
3
|
digest TEXT NOT NULL,
|
|
4
4
|
tables TEXT NOT NULL,
|
package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs → SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-B2GG3IJa.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
envelope_json TEXT NOT NULL,
|
|
4
4
|
attempts INTEGER NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-B2GG3IJa.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
2
|
hash TEXT PRIMARY KEY,
|
|
3
3
|
seq INTEGER NOT NULL,
|
|
4
4
|
snapshot_json TEXT NOT NULL,
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-wgl-SePe.mjs → SEARCH_STATE_TABLE-BThmEiED.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-
|
|
1
|
+
import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-CrTLPmFN.mjs";import"./runDrizzle-B2GG3IJa.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-B2GG3IJa.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CrTLPmFN.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{runDrizzle as p}from"./runDrizzle-B2GG3IJa.mjs";import{h}from"./do-sql-CeuVvE0W.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteSyncDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},y=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,N=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(e.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,y as renderSql,T as sqliteInList,N as unionAll};
|
package/dist/packem_shared/{appendStreamChunk-7ZyAZGg_.mjs → appendStreamChunk-DF_Jrgpy.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-B2GG3IJa.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
|
|
2
2
|
run_key TEXT PRIMARY KEY,
|
|
3
3
|
status TEXT NOT NULL,
|
|
4
4
|
last_seq INTEGER NOT NULL DEFAULT 0,
|
package/dist/packem_shared/{archiveCdcSegment-BON69Nug.mjs → archiveCdcSegment-CIiYU1FU.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-B2GG3IJa.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
seq INTEGER NOT NULL
|
|
4
4
|
)`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-
|
|
1
|
+
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CrTLPmFN.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-DzfEHonU.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-C2cZNaCR.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-B2GG3IJa.mjs";import{i as M,D as m,h as A}from"./do-sql-CeuVvE0W.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-B2GG3IJa.mjs";import{k as m,D as E}from"./do-sql-CeuVvE0W.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DS28-P_Z.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-Br3kxusw.mjs";import{projectColumns as g}from"./buildPokeFrames-CDOP-XYp.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-DbAttCNH.mjs";import{runDrizzle as r}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-DbAttCNH.mjs";import{runDrizzle as r}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as f}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const n="__lunora_companion_state",g=1,c=1,E=i=>i?T(Object.keys(i),i):"",$=(i,e)=>JSON.stringify([g,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),e??""]),d=(i,e)=>JSON.stringify([c,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),e??""]),s=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${t.identifier("companion")} TEXT PRIMARY KEY, ${t.identifier("signature")} TEXT NOT NULL)`)},u=(i,e)=>{s(i),r(i,e.length===0?t`DELETE FROM ${t.identifier(n)}`:t`DELETE FROM ${t.identifier(n)} WHERE ${f(t.raw('"companion"'),e,!0)}`)},R=(i,e)=>r(i,t`SELECT ${t.identifier("signature")} FROM ${t.identifier(n)} WHERE ${t.identifier("companion")} = ${e}`).toArray()[0]?.signature,A=(i,e,o)=>{r(i,t`INSERT INTO ${t.identifier(n)} (${t.identifier("companion")}, ${t.identifier("signature")}) VALUES (${e}, ${o}) ON CONFLICT (${t.identifier("companion")}) DO UPDATE SET ${t.identifier("signature")} = excluded.${t.identifier("signature")}`)},N=i=>{s(i),r(i,t`DELETE FROM ${t.identifier(n)}`)};export{$ as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,d as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
package/dist/packem_shared/{clearMemoryTables-CogAvVHR.mjs → clearMemoryTables-Lu0S2GOb.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-B2GG3IJa.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as p,s}from"./where-sql-CxnXsLbt.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-BKugKf70.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-B7dV2y4L.mjs → createCompanionSync-C2cZNaCR.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-
|
|
1
|
+
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-DzfEHonU.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-B2fjnGc3.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-DbAttCNH.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-Qf67j6dd.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-B2GG3IJa.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-CeuVvE0W.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-BKugKf70.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-BbZ5hKM7.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
package/dist/packem_shared/{createReplicaLink-B9F5PAQ0.mjs → createReplicaLink-DjykIKTn.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{verifySiblingBody as A,RELAY_SIGNATURE_HEADER as g,siblingStub as N,siblingSecretOf as E,signSiblingBody as T}from"./stubByName-C_P73AOx.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),I=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!I(r)))return{ownerKey:t,region:r}},b=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
package/dist/packem_shared/{ctx-db-relay-shapes-kGRKSxRs.mjs → ctx-db-relay-shapes-OAI2tSoy.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as a}from"./runDrizzle-B2GG3IJa.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
2
2
|
key TEXT PRIMARY KEY,
|
|
3
3
|
relay_idx INTEGER,
|
|
4
4
|
connection_id TEXT,
|
package/dist/packem_shared/{ctx-db-search-state-DVCp4JQf.mjs → ctx-db-search-state-CrTLPmFN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-
|
|
1
|
+
import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-B2GG3IJa.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-BavQAvdW.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DSIYUnPB.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-B6FUu4iW.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{e as T}from"./effective-kind-BmG_zCAy.mjs";import{S as h,i as A,s as $,F as O}from"./json-field-path-B2fjnGc3.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import{d as y,n as N,e as b}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as f}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{e as T}from"./effective-kind-BmG_zCAy.mjs";import{S as h,i as A,s as $,F as O}from"./json-field-path-B2fjnGc3.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import{d as y,n as N,e as b}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as f}from"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BbZ5hKM7.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return N(n)?JSON.stringify(b(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=e=>{const t=y(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return $(e)}catch(t){throw t instanceof O?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(A(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${h[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${g(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||T(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-
|
|
1
|
+
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-DzfEHonU.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-B2GG3IJa.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-UxGuXjjF.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DS28-P_Z.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
package/dist/packem_shared/{runShardMigrations-eqHNBW6S.mjs → runShardMigrations-B6FUu4iW.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-DzfEHonU.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as A}from"./aggregateTableName-DbAttCNH.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{migrateCdcLog as C,migrateCdcMeta as N}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{migrateClientWatermark as b}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as D}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as $}from"./clearCompanionSignatures-Qf67j6dd.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as M}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as G}from"./ctx-db-relay-shapes-OAI2tSoy.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as y}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as m,runAll as k}from"./runDrizzle-B2GG3IJa.mjs";import{D as P,d as E,e as u,t as Y,i as B,g as j,a as v,b as w,A as p}from"./do-sql-CeuVvE0W.mjs";import{renderSql as H}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as K}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as S,sortColumnName as W}from"./RANK_TIEBREAK-BKugKf70.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as z}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const l=r`_creationTime, id`,L=(e,n,o,i,t,a)=>{const s=r.join(t.map(d=>r`${d} IS NOT NULL`),r` AND `);if(m(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${s} GROUP BY ${i} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new h("INTERNAL",`unique index "${n}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},J=(e,n,o,i,t,a)=>{const c=m(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o}`).toArray()[0]?.sql;if(c==null)return;const d=_=>{const g=_.indexOf("(");return g===-1?void 0:_.slice(g,_.lastIndexOf(")")+1)},T=d(H("sqlite",E(n,o,i,t)).sql),f=d(c);T===void 0||f===void 0||T===f||(t&&L(e,n,o,i,a,"cannot be re-created with its new column list"),m(e,r`DROP INDEX IF EXISTS ${r.identifier(n)}`))},Q=(e,n,o)=>m(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,n,o,i,t,a)=>{t&&!Q(e,n,o)&&L(e,n,o,i,a,"cannot be created"),m(e,E(n,o,i,t))},Z=(e,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,a=i.unique??!1,s=i.fields.map(T=>u(T)),c=r.join(s,r`, `),d=a?c:r`${c}, ${l}`;J(e,t,n,d,a,s),I(e,t,n,d,a,s)}for(const[i,t]of Y(o)){if(!t.unique)continue;const a=u(i);I(e,`${n}_unique_${i}`,n,a,!0,[a])}},q=(e,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(e))){for(const i of o.searchIndexes)k(e,x(O(n,i.name)));R(e,n,o)}},ee=(e,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=j(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${i.name}__btree`;m(e,E(a,t,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},re=(e,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=A(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${v} TEXT PRIMARY KEY, ${w} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),m(e,r`PRAGMA table_info(${r.identifier(t)})`).toArray().some(s=>s.name==="__count__")||m(e,r`ALTER TABLE ${r.identifier(t)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},te=(e,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=S(n,i.name),a=i.sortBy.map((f,_)=>W(_)),s=a.map(f=>r`${r.identifier(f)} BLOB`),c=s.length>0?r`, ${r.join(s,r`, `)}`:r``;m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const g=i.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(g==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${n}__rank_${i.name}__btree`;m(e,E(T,t,r.join(d,r`, `),!1))}},Oe=(e,n,o={})=>{o.schemaSnapshot!==void 0&&z(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),y(e);const i=[];for(const[t,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"&&(m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(P)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B2GG3IJa.mjs";import{e}from"./do-sql-CeuVvE0W.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-CU8Kl2Bq.mjs → selectShapeMembers-DS28-P_Z.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B2GG3IJa.mjs";import{D as p,r as a,m as h}from"./do-sql-CeuVvE0W.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as $}from"./where-sql-CxnXsLbt.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,a as y}from"./json-field-path-B2fjnGc3.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,a as y}from"./json-field-path-B2fjnGc3.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{quoteIdentifier as w}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as b,SEEK_RANGE as j}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const U={binary:(t,n,s)=>c`${t} ${c.raw(n)} ${s}`,constant:t=>t?c`1 = 1`:c`0 = 1`,connect:(t,n,s)=>c`(${t}) ${c.raw(s)} (${n})`,contains:(t,n)=>c`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>x(t,n,s,o),negate:t=>c`NOT (${t})`,nullCheck:(t,n)=>n?c`${t} IS NOT NULL`:c`${t} IS NULL`,value:t=>c`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},E=t=>({params:[t],text:"?"}),A=t=>({params:[],text:t}),nt=t=>A(w(t)),st={binary:(t,n,s)=>h(t," ".concat(n," "),E(s)),constant:t=>A(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(l=>O(l)),r=n.length>o&&!e?C(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',E(r),"))");if(n.length>o&&!e)throw new S("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(E(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',E(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:E},v=L.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],M=new Set(I),R=new Set(["gt","gte","lt","lte"]),D={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>M.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},g=(t,n,s,o,i)=>{const e=y(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},k=(t,n,s,o,i,e,r,l)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!l&&R.has(s)&&T(t)?g(t,a,i,e,r):a},F=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new S("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const l=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):e.inList(n,l,a,v)},$=L.boundParams/2,G=6e4,B=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&O(o))s.numbers.push(o);else if(typeof o=="string"&&O(o))s.strings.push(o);else throw new S("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},q=(t,n,s)=>{const o=[],i=c.identifier("v"),e=c.identifier("__in__"),r=a=>c`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>c`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${c.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT ${r(s.strings)})`:c`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:c`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:c`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},ot=t=>(n,s,o,i=$)=>{const e=Math.floor(G*i/$);if(s.length<=e){const u=c.join(s.map(p=>c`${p}`),c`, `);return o?c`${n} NOT IN (${u})`:c`${n} IN (${u})`}const r=B(s,e);if(o&&r.hasNull)return c`1 = 0`;const l=q(t,n,r);if(l.length===0)return c`1 = 0`;const a=l.length===1?l[0]:c`(${c.join(l,c` OR `)})`;return o?c`NOT (${a})`:a},K=(t,n,s,o,i)=>{const e=s,r=[];for(const l of I){if(!(l in e))continue;const a=e[l],u=D[l];u?r.push(k(t,n,l,u,a,o,i,s[j]===!0)):l==="isNull"?r.push(i.nullCheck(n,!a)):l==="contains"?r.push(P(t,n,a,o,i)):r.push(F(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return r},z=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?K(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},J=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const l=f(r??{},s,o);if(l!==void 0)e.push(l);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:N(e,n,o)},Y=new Set(["AND","NOT","OR",b]),Q=(t,n,s,o)=>{if(t===b){if(!s.relationExists)throw new S("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=f(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return J(n,t,s,o)},f=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Y.has(i)){const r=Q(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...z(i,e,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const e=m(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),T(i)&&(s+=1+Object.keys(e).filter(r=>R.has(r)).length)):s+=T(i)?2:1;return{lists:n,scalars:s}},it=(t,n,s=U,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=m(t);if(i===0)return f(t,n,s);const r=Math.max(1,Math.floor(Math.min($,L.boundParams-e-o)/i)),l=n.inList??((a,u,p,_)=>s.inList(a,u,p,_??r));return f(t,{...n,inList:(a,u,p)=>l(a,u,p,r)},s)};export{it as c,nt as i,h as j,A as r,ot as s,st as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.128",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{MySqlDialect as u}from"drizzle-orm/mysql-core";import{PgDialect as S}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const d=new S,h=new u,m=new p,L={mysql:h,postgres:d,sqlite:m},i={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},E=i.boundParams/2,$=t=>t===null||typeof t=="boolean"?!0:typeof t=="number"?Number.isFinite(t):typeof t=="string"&&t.isWellFormed(),g=t=>{const n=[];for(const r of t){if(!(r instanceof Uint8Array))return;n.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(n)},D=(t,n)=>{const{params:r,sql:o}=L[t].sqlToQuery(n);return{params:r,sql:o}},y=t=>e`${t}`,w=t=>{if(t.length===0)throw new Error("unionAll: expected at least one branch");let n=[...t];for(;n.length>i.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=i.compoundSelect){const s=e.join(n.slice(o,o+i.compoundSelect),e` UNION ALL `);r.push(e`SELECT * FROM (${s}) ${e.identifier("__u__")}`)}n=r}return e.join(n,e` UNION ALL `)},O=(t,n,r,o=E)=>{const s=r?e` NOT IN `:e` IN `,a=n.every(l=>$(l)),c=n.length>o&&!a?g(n):void 0;if(c!==void 0)return e`${t}${s}(SELECT unhex(${e.identifier("value")}) FROM json_each(${c}))`;if(n.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?e`${t}${s}(${e.join(n.map(l=>y(l)),e`, `)})`:e`${t}${s}(SELECT ${e.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{i as WORKERD_SQLITE_LIMITS,g as bytesAsHexJson,$ as isJsonSafe,y as param,D as renderSql,O as sqliteInList,w as unionAll};
|