@lunora/server 1.0.0-alpha.129 → 1.0.0-alpha.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +44 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-BUgVxqdd.mjs → ACTION_CACHE_DEFAULT_TTL_MS-BsqmelIH.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-CfwQ4VO8.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-BLwd8bNw.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-BT8zKkFZ.mjs → PRESENCE_DEFAULT_TTL_MS-Ds9uPwnE.mjs} +1 -1
- package/dist/packem_shared/{composePluginMiddleware-DOqAWbsS.mjs → composePluginMiddleware-B2us3uLo.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-DCd1HExR.mjs → defineAggregateIndex-EAcp6JIN.mjs} +1 -1
- package/dist/packem_shared/plugin-CeaKFo33.mjs +1 -0
- package/dist/types.d.mts +6 -0
- package/dist/types.d.ts +6 -0
- package/package.json +2 -2
- package/dist/packem_shared/plugin-UzUBbP3t.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -653,6 +653,50 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
653
653
|
* it advances the sequence and pages through like any other change.
|
|
654
654
|
*/
|
|
655
655
|
commitOrdered: () => TableBuilder<Shape>;
|
|
656
|
+
/**
|
|
657
|
+
* Drop a `patch` whose fields have MOVED since the caller last saw the row,
|
|
658
|
+
* instead of letting it clobber the newer value.
|
|
659
|
+
*
|
|
660
|
+
* The case this exists for is the one every offline-capable app hits. Two
|
|
661
|
+
* clients edit the same row; one is offline, so its write replays later and
|
|
662
|
+
* wins on arrival order rather than on authorship. The newer edit is gone with
|
|
663
|
+
* nothing to show it existed.
|
|
664
|
+
*
|
|
665
|
+
* With this flag the shard compares the fields a patch writes against the row
|
|
666
|
+
* as the caller last saw it — its CDC baseline, stamped by the client at call
|
|
667
|
+
* time and replayed verbatim from its offline queue. If any of those fields
|
|
668
|
+
* changed in between, the whole patch is dropped.
|
|
669
|
+
*
|
|
670
|
+
* ```ts
|
|
671
|
+
* documents: defineTable({ title: v.string(), body: v.string() }).dropStalePatches(),
|
|
672
|
+
* ```
|
|
673
|
+
*
|
|
674
|
+
* Two clients editing DIFFERENT fields of one row both win, which is the point.
|
|
675
|
+
* Two editing the SAME field means the later-composed write survives and the
|
|
676
|
+
* stale one is discarded.
|
|
677
|
+
*
|
|
678
|
+
* **The whole patch is dropped, never part of it.** Applying the fresh half and
|
|
679
|
+
* discarding the stale half would produce a row no mutation ever wrote —
|
|
680
|
+
* `status: "shipped"` landing while `shippedAt` is thrown away — and a
|
|
681
|
+
* handler's invariants live across the fields of one `patch` call.
|
|
682
|
+
*
|
|
683
|
+
* **A drop is silent to the caller.** No row change, no CDC entry, no
|
|
684
|
+
* broadcast, no triggers: indistinguishable from a patch that was never
|
|
685
|
+
* issued. The shard logs each one (table, row, fields) so it is traceable, but
|
|
686
|
+
* the mutation still resolves successfully. Do not use this where the caller
|
|
687
|
+
* must be told its write did not land — throw from the handler after comparing
|
|
688
|
+
* yourself instead.
|
|
689
|
+
*
|
|
690
|
+
* **Requires CDC** (the changelog is where the baseline comes from) and it
|
|
691
|
+
* fails OPEN: no baseline, no changelog entry at or below it (retention
|
|
692
|
+
* trimmed it, or the row is newer than the caller's cursor), or CDC off, and
|
|
693
|
+
* the write applies exactly as it would without this flag. Discarding writes
|
|
694
|
+
* because retention ran would trade a rare lost edit for a common one.
|
|
695
|
+
*
|
|
696
|
+
* Shard-local only — a `.global()` table has no per-shard changelog to
|
|
697
|
+
* establish a baseline from.
|
|
698
|
+
*/
|
|
699
|
+
dropStalePatches: () => TableBuilder<Shape>;
|
|
656
700
|
/**
|
|
657
701
|
* Mark this table as written outside Lunora's discoverable insert path —
|
|
658
702
|
* by an adapter, a migration, or framework middleware (e.g. `@lunora/auth`'s
|
package/dist/index.d.ts
CHANGED
|
@@ -653,6 +653,50 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
653
653
|
* it advances the sequence and pages through like any other change.
|
|
654
654
|
*/
|
|
655
655
|
commitOrdered: () => TableBuilder<Shape>;
|
|
656
|
+
/**
|
|
657
|
+
* Drop a `patch` whose fields have MOVED since the caller last saw the row,
|
|
658
|
+
* instead of letting it clobber the newer value.
|
|
659
|
+
*
|
|
660
|
+
* The case this exists for is the one every offline-capable app hits. Two
|
|
661
|
+
* clients edit the same row; one is offline, so its write replays later and
|
|
662
|
+
* wins on arrival order rather than on authorship. The newer edit is gone with
|
|
663
|
+
* nothing to show it existed.
|
|
664
|
+
*
|
|
665
|
+
* With this flag the shard compares the fields a patch writes against the row
|
|
666
|
+
* as the caller last saw it — its CDC baseline, stamped by the client at call
|
|
667
|
+
* time and replayed verbatim from its offline queue. If any of those fields
|
|
668
|
+
* changed in between, the whole patch is dropped.
|
|
669
|
+
*
|
|
670
|
+
* ```ts
|
|
671
|
+
* documents: defineTable({ title: v.string(), body: v.string() }).dropStalePatches(),
|
|
672
|
+
* ```
|
|
673
|
+
*
|
|
674
|
+
* Two clients editing DIFFERENT fields of one row both win, which is the point.
|
|
675
|
+
* Two editing the SAME field means the later-composed write survives and the
|
|
676
|
+
* stale one is discarded.
|
|
677
|
+
*
|
|
678
|
+
* **The whole patch is dropped, never part of it.** Applying the fresh half and
|
|
679
|
+
* discarding the stale half would produce a row no mutation ever wrote —
|
|
680
|
+
* `status: "shipped"` landing while `shippedAt` is thrown away — and a
|
|
681
|
+
* handler's invariants live across the fields of one `patch` call.
|
|
682
|
+
*
|
|
683
|
+
* **A drop is silent to the caller.** No row change, no CDC entry, no
|
|
684
|
+
* broadcast, no triggers: indistinguishable from a patch that was never
|
|
685
|
+
* issued. The shard logs each one (table, row, fields) so it is traceable, but
|
|
686
|
+
* the mutation still resolves successfully. Do not use this where the caller
|
|
687
|
+
* must be told its write did not land — throw from the handler after comparing
|
|
688
|
+
* yourself instead.
|
|
689
|
+
*
|
|
690
|
+
* **Requires CDC** (the changelog is where the baseline comes from) and it
|
|
691
|
+
* fails OPEN: no baseline, no changelog entry at or below it (retention
|
|
692
|
+
* trimmed it, or the row is newer than the caller's cursor), or CDC off, and
|
|
693
|
+
* the write applies exactly as it would without this flag. Discarding writes
|
|
694
|
+
* because retention ran would trade a rare lost edit for a common one.
|
|
695
|
+
*
|
|
696
|
+
* Shard-local only — a `.global()` table has no per-shard changelog to
|
|
697
|
+
* establish a baseline from.
|
|
698
|
+
*/
|
|
699
|
+
dropStalePatches: () => TableBuilder<Shape>;
|
|
656
700
|
/**
|
|
657
701
|
* Mark this table as written outside Lunora's discoverable insert path —
|
|
658
702
|
* by an adapter, a migration, or framework middleware (e.g. `@lunora/auth`'s
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BsqmelIH.mjs";import{initLunora as d}from"./packem_shared/initLunora-DAbEYdSo.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as c}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CIhFddA2.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BLwd8bNw.mjs";import{LunoraEnvError as P,defineEnv as M,redactSecrets as b}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-DFVhrm8u.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-9mdw0nyU.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as re}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as te,d as ne,a as ie,b as ae,e as fe,f as se,g as de,h as me,i as pe,j as ce,k as xe,m as le}from"./packem_shared/plugin-CeaKFo33.mjs";import{PRESENCE_DEFAULT_TTL_MS as he,PRESENCE_TABLE as Se,definePresence as ue,presenceExtension as De}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Ds9uPwnE.mjs";import{protectPublic as ge}from"./packem_shared/protectPublic-BUYCMZZB.mjs";import{onQueryChange as Re}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Le}from"./packem_shared/defineShape-Be5u-Whf.mjs";import{anyApi as Ie}from"./types.mjs";import{LunoraError as Me}from"@lunora/errors";import{cronJobs as ye}from"@lunora/scheduler";import{ValidationError as Oe,v as He}from"@lunora/values";import{allowAll as we,deny as Ue,isDeny as ke,toWhereInput as ve}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as We,buildRlsReadRegistry as Ye,composeShapeReadWhere as Je}from"./packem_shared/assertShapesDeclareReadPolicies-CjJWccLg.mjs";import{buildMaskRegistry as Qe}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as qe,definePermission as ze,definePolicies as Ge,definePolicy as Ze,defineRole as $e}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as rr,defineStorageRules as or}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as nr}from"./packem_shared/mask-DsL8pZvt.mjs";import{r as ar}from"./packem_shared/middleware-CgYaL-lL.mjs";import{storageRules as sr}from"./packem_shared/storageRules-DLH8uzGB.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,Me as LunoraError,he as PRESENCE_DEFAULT_TTL_MS,Se as PRESENCE_TABLE,e as VERSION,Oe as ValidationError,i as actionCacheExtension,we as allowAll,Ie as anyApi,Ve as asBucketStorage,We as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,Qe as buildMaskRegistry,Ye as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,te as composePluginMiddleware,Je as composeShapeReadWhere,qe as createPolicyDsl,l as createSecrets,ye as cronJobs,f as defineActionCache,ne as defineAggregateIndex,ie as defineComponent,L as defineDocumentHistory,M as defineEnv,j as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineMutator,ze as definePermission,ae as definePlugin,Ge as definePolicies,Ze as definePolicy,ue as definePresence,fe as defineRankIndex,$e as defineRole,se as defineSchema,de as defineSchemaExtension,Le as defineShape,rr as defineStorageRule,or as defineStorageRules,me as defineTable,pe as defineVectorIndex,Ue as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,ce as indexFieldsFromSchema,d as initLunora,xe as installPlugins,ke as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,nr as mask,le as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Re as onQueryChange,K as onShardInit,De as presenceExtension,ge as protectPublic,b as redactSecrets,ar as rls,B as serveStorageObject,sr as storageRules,c as tagPerDispatchMiddleware,ve as toWhereInput,He as v,u as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-CeaKFo33.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-CeaKFo33.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-CeaKFo33.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-
|
|
1
|
+
import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-CeaKFo33.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
|
package/dist/packem_shared/{defineAggregateIndex-DCd1HExR.mjs → defineAggregateIndex-EAcp6JIN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-
|
|
1
|
+
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-CeaKFo33.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-DNvrHMHx.mjs";import{v as D}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],Q=e=>F.includes(e),X=e=>q.includes(e),U=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},P=e=>{if(e.kind==="literal")return U(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?P(t):e.kind},j=16,V={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),Y=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),C=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},he=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},c=[],f={},h=Y(),b=[];let w={kind:"root"},k=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const B=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},l={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),l},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return k=!0,l},get commitOrderedMode(){return k},dropStalePatches(){return $=!0,l},get dropStalePatchesMode(){return $},externallyManaged(){return p=!0,l},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),l},get geoIndexes(){return r},global(a){return B({backend:a?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),l},get indexes(){return i},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(a){return L=a,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:C(a,o.sortBy),where:o.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(V)),l},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>j)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(j)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!X(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=o;if(N!==void 0&&!Q(N))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(a){return B({field:a,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=a,p=!0,l},softDelete(a){const o=a?.field??"deletedAt";return A={field:o},o in t||(t[o]=D.optional(D.number().nullable())),l},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),l},ttl(a,o){return O={after:o?.after,field:a},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),l}};return l},me=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),ge=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},be=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:C(e,t.sortBy),where:t.where}),y=e=>({...e,extend(t){return y(H(e,t))},jurisdiction(t){return y(e)},rls(t){return y({...e,rlsMode:t})}}),G=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},J=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},W=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},Z=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=W(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ee=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);Z(t,r)}}},te=["_commitSeq","_creationTime","_id"],_="_commitSeq",ne=new Set(te),x=(e,t,n,r)=>{if(!(ne.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},K=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},S=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},re=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},we=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=S(r.geoIndexes,c=>c.name,c=>[c.field]),d=S(r.indexes,c=>c.name,c=>c.fields),u=S(r.rankIndexes,c=>c.name,re);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ae=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},oe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(P(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},ie=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},se=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(_))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${_}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},xe=(e,t={},n={},r={})=>(G(e),J(e,n,r),ee(e),se(e),ie(e),oe(e),ae(e),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,E=(e,t,n)=>n.has(e)?I(t,e):e,de=(e,t,n,r)=>{const i=I(t,r),d=h=>h===""?i:E(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:E(b.table,t,n)};const c=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:c,rankIndexes:f,relationMap:u}},ye=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},le=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Ie=(e,t)=>({...le(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),H=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,c]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=de(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...c,table:E(c.table,n,r)}}return K(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},pe=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=H(n,r.extension));return n},Ne=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{Ie as a,le as b,Ne as c,ge as d,be as e,xe as f,ye as g,he as h,me as i,we as j,pe as k,H as m,K as v};
|
package/dist/types.d.mts
CHANGED
|
@@ -367,6 +367,12 @@ interface TableDefinition<Shape extends Record<string, Validator> = Record<strin
|
|
|
367
367
|
* ⇒ rows carry no `_commitSeq`, as before.
|
|
368
368
|
*/
|
|
369
369
|
commitOrderedMode?: boolean;
|
|
370
|
+
/**
|
|
371
|
+
* `.dropStalePatches()` — drop a `patch` whose fields moved since the caller's
|
|
372
|
+
* CDC baseline rather than clobbering the newer value. See the builder method
|
|
373
|
+
* for the rule, the whole-patch granularity, and why it fails open.
|
|
374
|
+
*/
|
|
375
|
+
dropStalePatchesMode?: boolean;
|
|
370
376
|
/**
|
|
371
377
|
* Set by `.source(...)` (named `externalSource`, not `source`, so the data
|
|
372
378
|
* field doesn't collide with the fluent `.source()` builder method — same
|
package/dist/types.d.ts
CHANGED
|
@@ -367,6 +367,12 @@ interface TableDefinition<Shape extends Record<string, Validator> = Record<strin
|
|
|
367
367
|
* ⇒ rows carry no `_commitSeq`, as before.
|
|
368
368
|
*/
|
|
369
369
|
commitOrderedMode?: boolean;
|
|
370
|
+
/**
|
|
371
|
+
* `.dropStalePatches()` — drop a `patch` whose fields moved since the caller's
|
|
372
|
+
* CDC baseline rather than clobbering the newer value. See the builder method
|
|
373
|
+
* for the rule, the whole-patch granularity, and why it fails open.
|
|
374
|
+
*/
|
|
375
|
+
dropStalePatchesMode?: boolean;
|
|
370
376
|
/**
|
|
371
377
|
* Set by `.source(...)` (named `externalSource`, not `source`, so the data
|
|
372
378
|
* field doesn't collide with the fluent `.source()` builder method — same
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.130",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@lunora/errors": "1.0.0-alpha.39",
|
|
70
70
|
"@lunora/scheduler": "1.0.0-alpha.76",
|
|
71
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
71
|
+
"@lunora/shard-engine": "1.0.0-alpha.73",
|
|
72
72
|
"@lunora/values": "1.0.0-alpha.49",
|
|
73
73
|
"drizzle-orm": "^0.45.2",
|
|
74
74
|
"hono": "^4.13.7"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const _=["de","en","es","fr","it","nl","none","pt"],q=["native","portable"],H=e=>q.includes(e),Q=e=>_.includes(e),X=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},F=e=>{if(e.kind==="literal")return X(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?F(t):e.kind},D=16,U={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),V=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),P=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ue=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},l=[],f={},h=V(),b=[];let w={kind:"root"},S=!1,N=!1,$=!1,T=!1,L,M,A,O;const R=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},c={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return S=!0,c},get commitOrderedMode(){return S},externallyManaged(){return N=!0,c},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),c},get geoIndexes(){return r},global(a){return R({backend:a?.backend??"d1",kind:"global"}),c},get isExternallyManaged(){return N},get isPublic(){return T},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),c},get indexes(){return i},memory(){return $=!0,c},get memoryMode(){return $},ownedBy(a){return L=a,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:P(a,o.sortBy),where:o.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(U)),c},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>D)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(D)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!Q(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${_.join(", ")})`);const{strategy:p}=o;if(p!==void 0&&!H(p))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${p}" (supported: ${q.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(a){return R({field:a,kind:"shardBy"}),c},get shardMode(){return w},get softDeleteMode(){return M},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=a,N=!0,c},softDelete(a){const o=a?.field??"deletedAt";return M={field:o},o in t||(t[o]=B.optional(B.number().nullable())),c},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),c},ttl(a,o){return A={after:o?.after,field:a},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),c}};return c},fe=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),he=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},me=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:P(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(K(e,t))},jurisdiction(t){return I(e)},rls(t){return I({...e,rlsMode:t})}}),Y=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},G=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},J=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},W=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=J(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},Z=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);W(t,r)}}},ee=["_commitSeq","_creationTime","_id"],j="_commitSeq",te=new Set(ee),x=(e,t,n,r)=>{if(!(te.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},C=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},ne=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ge=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,ne);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},re=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ae=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(F(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},oe=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(j))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${j}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},be=(e,t={},n={},r={})=>(Y(e),G(e,n,r),Z(e),oe(e),ae(e),re(e),C(e),I({tables:e,vectorIndexes:t})),y=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?y(t,e):e,ie=(e,t,n,r)=>{const i=y(t,r),d=h=>h===""?i:k(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:k(b.table,t,n)};const l=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},we=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},se=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),xe=(e,t)=>({...se(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),K=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=y(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=ie(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=y(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:k(l.table,n,r)}}return C(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},Ie=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=K(n,r.extension));return n},ye=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{xe as a,se as b,ye as c,he as d,me as e,be as f,we as g,ue as h,fe as i,ge as j,Ie as k,K as m,C as v};
|