@lunora/server 1.0.0-alpha.57 → 1.0.0-alpha.59

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.mjs CHANGED
@@ -1 +1 @@
1
- import{initLunora as t}from"./packem_shared/initLunora-DXCOVntr.mjs";import{createSecrets as i}from"./packem_shared/createSecrets-CgVPiW2C.mjs";import{LunoraEnvError as f,defineEnv as s,redactSecrets as m}from"./packem_shared/LunoraEnvError-CgpI2Mm_.mjs";import{LunoraError as p}from"./packem_shared/LunoraError-LVhdU0Lo.mjs";import{bindOrm as c,bindTableFacade as l}from"./packem_shared/bindOrm-Bp9hsM2q.mjs";import{httpAction as u,httpRoute as S,httpRouter as g,isSafeHeaderValue as R,serveStorageObject as L}from"./packem_shared/httpAction-C14NuF3V.mjs";import{defineIdentity as P}from"./packem_shared/defineIdentity-B7gfAgxx.mjs";import{onConnect as A,onDisconnect as I}from"./packem_shared/onConnect-CEtRmUpJ.mjs";import{DEFAULT_LIMIT as y,DEFAULT_MAX_LIMIT as M,clampLimit as _,defineListArgs as D}from"./packem_shared/DEFAULT_LIMIT-yHJ5O96W.mjs";import{defineMigration as k}from"./packem_shared/defineMigration-Bfpwxv2f.mjs";import{defineMutator as C}from"./packem_shared/defineMutator-BgpQ-xUo.mjs";import{c as N,H as O,d as U,a as W,X as w,Z as B,b as H,q as X,K as j,W as q,i as J,m as K}from"./packem_shared/plugin-B5pDeN17.mjs";import{PRESENCE_DEFAULT_TTL_MS as z,PRESENCE_TABLE as G,definePresence as Q,presenceExtension as Y}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DO2-TdzC.mjs";import{protectPublic as ee}from"./packem_shared/protectPublic-BhKewPqm.mjs";import{defineShape as oe}from"./packem_shared/defineShape-Ds8uNqzX.mjs";import{anyApi as ne}from"./types.mjs";import{cronJobs as ae}from"@lunora/scheduler";import{ValidationError as se,v as me}from"@lunora/values";import{allowAll as pe,deny as xe,isDeny as ce,toWhereInput as le}from"./packem_shared/allowAll-BnyNbJZT.mjs";import{asBucketStorage as ue}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as ge}from"./packem_shared/buildMaskRegistry-BCIzKxdK.mjs";import{buildRlsReadRegistry as Le,composeShapeReadWhere as he}from"./packem_shared/buildRlsReadRegistry-CA-aUi7I.mjs";import{createPolicyDsl as be,definePermission as Ae,definePolicies as Ie,definePolicy as Te,defineRole as ye}from"./packem_shared/createPolicyDsl-sV1swpkD.mjs";import{defineStorageRule as _e,defineStorageRules as De}from"./packem_shared/defineStorageRule-BDu01PUn.mjs";import{mask as ke}from"./packem_shared/mask-DF7mtxQe.mjs";import{rls as Ce}from"./packem_shared/rls-tRDkICWZ.mjs";import{storageRules as Ne}from"./packem_shared/storageRules-BptPZbi8.mjs";const e="0.0.0";export{y as DEFAULT_LIMIT,M as DEFAULT_MAX_LIMIT,f as LunoraEnvError,p as LunoraError,z as PRESENCE_DEFAULT_TTL_MS,G as PRESENCE_TABLE,e as VERSION,se as ValidationError,pe as allowAll,ne as anyApi,ue as asBucketStorage,c as bindOrm,l as bindTableFacade,ge as buildMaskRegistry,Le as buildRlsReadRegistry,_ as clampLimit,N as composePluginMiddleware,he as composeShapeReadWhere,be as createPolicyDsl,i as createSecrets,ae as cronJobs,O as defineAggregateIndex,U as defineComponent,s as defineEnv,P as defineIdentity,D as defineListArgs,k as defineMigration,C as defineMutator,Ae as definePermission,W as definePlugin,Ie as definePolicies,Te as definePolicy,Q as definePresence,w as defineRankIndex,ye as defineRole,B as defineSchema,H as defineSchemaExtension,oe as defineShape,_e as defineStorageRule,De as defineStorageRules,X as defineTable,j as defineVectorIndex,xe as deny,u as httpAction,S as httpRoute,g as httpRouter,q as indexFieldsFromSchema,t as initLunora,J as installPlugins,ce as isDeny,R as isSafeHeaderValue,ke as mask,K as mergeSchemaExtension,A as onConnect,I as onDisconnect,Y as presenceExtension,ee as protectPublic,m as redactSecrets,Ce as rls,L as serveStorageObject,Ne as storageRules,le as toWhereInput,me as v};
1
+ import{initLunora as t}from"./packem_shared/initLunora-DXCOVntr.mjs";import{createSecrets as i}from"./packem_shared/createSecrets-CgVPiW2C.mjs";import{LunoraEnvError as f,defineEnv as s,redactSecrets as m}from"./packem_shared/LunoraEnvError-CgpI2Mm_.mjs";import{LunoraError as p}from"./packem_shared/LunoraError-LVhdU0Lo.mjs";import{bindOrm as c,bindTableFacade as l}from"./packem_shared/bindOrm-Bp9hsM2q.mjs";import{httpAction as u,httpRoute as S,httpRouter as g,isSafeHeaderValue as R,serveStorageObject as L}from"./packem_shared/httpAction-C14NuF3V.mjs";import{defineIdentity as P}from"./packem_shared/defineIdentity-B7gfAgxx.mjs";import{onConnect as A,onDisconnect as I}from"./packem_shared/onConnect-CEtRmUpJ.mjs";import{DEFAULT_LIMIT as y,DEFAULT_MAX_LIMIT as M,clampLimit as _,defineListArgs as D}from"./packem_shared/DEFAULT_LIMIT-yHJ5O96W.mjs";import{defineMigration as k}from"./packem_shared/defineMigration-Bfpwxv2f.mjs";import{defineMutator as C}from"./packem_shared/defineMutator-BgpQ-xUo.mjs";import{c as N,K as O,d as U,a as W,H as j,W as w,b as B,j as H,q,Q as J,i as K,m as Q}from"./packem_shared/plugin-CDBMGCeQ.mjs";import{PRESENCE_DEFAULT_TTL_MS as z,PRESENCE_TABLE as G,definePresence as Y,presenceExtension as Z}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DmnVChTY.mjs";import{protectPublic as ee}from"./packem_shared/protectPublic-BhKewPqm.mjs";import{defineShape as oe}from"./packem_shared/defineShape-Ds8uNqzX.mjs";import{anyApi as ne}from"./types.mjs";import{cronJobs as ae}from"@lunora/scheduler";import{ValidationError as se,v as me}from"@lunora/values";import{allowAll as pe,deny as xe,isDeny as ce,toWhereInput as le}from"./packem_shared/allowAll-BnyNbJZT.mjs";import{asBucketStorage as ue}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as ge}from"./packem_shared/buildMaskRegistry-BCIzKxdK.mjs";import{buildRlsReadRegistry as Le,composeShapeReadWhere as he}from"./packem_shared/buildRlsReadRegistry-CA-aUi7I.mjs";import{createPolicyDsl as be,definePermission as Ae,definePolicies as Ie,definePolicy as Te,defineRole as ye}from"./packem_shared/createPolicyDsl-sV1swpkD.mjs";import{defineStorageRule as _e,defineStorageRules as De}from"./packem_shared/defineStorageRule-BDu01PUn.mjs";import{mask as ke}from"./packem_shared/mask-DF7mtxQe.mjs";import{rls as Ce}from"./packem_shared/rls-tRDkICWZ.mjs";import{storageRules as Ne}from"./packem_shared/storageRules-BptPZbi8.mjs";const e="0.0.0";export{y as DEFAULT_LIMIT,M as DEFAULT_MAX_LIMIT,f as LunoraEnvError,p as LunoraError,z as PRESENCE_DEFAULT_TTL_MS,G as PRESENCE_TABLE,e as VERSION,se as ValidationError,pe as allowAll,ne as anyApi,ue as asBucketStorage,c as bindOrm,l as bindTableFacade,ge as buildMaskRegistry,Le as buildRlsReadRegistry,_ as clampLimit,N as composePluginMiddleware,he as composeShapeReadWhere,be as createPolicyDsl,i as createSecrets,ae as cronJobs,O as defineAggregateIndex,U as defineComponent,s as defineEnv,P as defineIdentity,D as defineListArgs,k as defineMigration,C as defineMutator,Ae as definePermission,W as definePlugin,Ie as definePolicies,Te as definePolicy,Y as definePresence,j as defineRankIndex,ye as defineRole,w as defineSchema,B as defineSchemaExtension,oe as defineShape,_e as defineStorageRule,De as defineStorageRules,H as defineTable,q as defineVectorIndex,xe as deny,u as httpAction,S as httpRoute,g as httpRouter,J as indexFieldsFromSchema,t as initLunora,K as installPlugins,ce as isDeny,R as isSafeHeaderValue,ke as mask,Q as mergeSchemaExtension,A as onConnect,I as onDisconnect,Z as presenceExtension,ee as protectPublic,m as redactSecrets,Ce as rls,L as serveStorageObject,Ne as storageRules,le as toWhereInput,me as v};
@@ -1 +1 @@
1
- import{v as t}from"@lunora/values";import{initLunora as E}from"./initLunora-DXCOVntr.mjs";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{onDisconnect as q}from"./onConnect-CEtRmUpJ.mjs";import{b as v,q as R,d as _}from"./plugin-B5pDeN17.mjs";const D=3e4,y=4096,u="presence",h="present",c=`${u}_${h}`,M=v(u,{tables:{[h]:R({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"])}}),{mutation:b,query:L}=E.dataModel().create(),B=(l={})=>{const m=l.ttlMs??D,f=Math.max(0,Math.min(l.disconnectGraceMs??0,m)),w=b.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(),i=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>y)throw new p("BAD_REQUEST",`presence data exceeds the ${String(y)}-byte limit`);const e=await s.db.query(c).withIndex("byRoomSession",n=>n.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==i)throw new p("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},...i===void 0?{}:{userId:i}};return await(e?s.db.patch(e._id,a):s.db.insert(c,a)),{lastSeen:r}}),S=L.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,i=(await s.db.query(c).withIndex("byRoom",n=>n.eq("roomId",o.roomId)).collect()).filter(n=>n.lastSeen>r).toSorted((n,d)=>d.lastSeen-n.lastSeen),e=new Set,a=[];for(const n of i){const d=n.userId;if(d!==void 0){if(e.has(d))continue;e.add(d)}const I={lastSeen:n.lastSeen,roomId:n.roomId};d!==void 0&&(I.userId=d),n.data!==void 0&&(I.data=n.data),a.push(I)}return a}),g={...b.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,i=await s.db.query(c).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(i.map(e=>s.db.delete(e._id))),{deleted:i.length}}),visibility:"internal"},x=q(async(o,s)=>{const r=s.context?.roomId,i=s.context?.sessionId;if(typeof r!="string"||typeof i!="string")return;const e=await o.db.query(c).withIndex("byRoomSession",d=>d.eq("roomId",r).eq("sessionId",i)).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 n=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:n})});return _(u,{extension:M,functions:{disconnect:x,heartbeat:w,listPresent:S,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,c as PRESENCE_TABLE,B as definePresence,M as presenceExtension};
1
+ import{v as t}from"@lunora/values";import{initLunora as E}from"./initLunora-DXCOVntr.mjs";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{onDisconnect as q}from"./onConnect-CEtRmUpJ.mjs";import{b as v,j as R,d as _}from"./plugin-CDBMGCeQ.mjs";const D=3e4,y=4096,u="presence",h="present",c=`${u}_${h}`,M=v(u,{tables:{[h]:R({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"])}}),{mutation:b,query:L}=E.dataModel().create(),B=(l={})=>{const m=l.ttlMs??D,f=Math.max(0,Math.min(l.disconnectGraceMs??0,m)),w=b.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(),i=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>y)throw new p("BAD_REQUEST",`presence data exceeds the ${String(y)}-byte limit`);const e=await s.db.query(c).withIndex("byRoomSession",n=>n.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==i)throw new p("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},...i===void 0?{}:{userId:i}};return await(e?s.db.patch(e._id,a):s.db.insert(c,a)),{lastSeen:r}}),S=L.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,i=(await s.db.query(c).withIndex("byRoom",n=>n.eq("roomId",o.roomId)).collect()).filter(n=>n.lastSeen>r).toSorted((n,d)=>d.lastSeen-n.lastSeen),e=new Set,a=[];for(const n of i){const d=n.userId;if(d!==void 0){if(e.has(d))continue;e.add(d)}const I={lastSeen:n.lastSeen,roomId:n.roomId};d!==void 0&&(I.userId=d),n.data!==void 0&&(I.data=n.data),a.push(I)}return a}),g={...b.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,i=await s.db.query(c).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(i.map(e=>s.db.delete(e._id))),{deleted:i.length}}),visibility:"internal"},x=q(async(o,s)=>{const r=s.context?.roomId,i=s.context?.sessionId;if(typeof r!="string"||typeof i!="string")return;const e=await o.db.query(c).withIndex("byRoomSession",d=>d.eq("roomId",r).eq("sessionId",i)).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 n=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:n})});return _(u,{extension:M,functions:{disconnect:x,heartbeat:w,listPresent:S,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,c as PRESENCE_TABLE,B as definePresence,M as presenceExtension};
@@ -1 +1 @@
1
- import"@lunora/errors";import"./run-middleware-BeEEqmdE.mjs";import{c as s,d as o,a as m,b as t,i as d,m as l}from"./plugin-B5pDeN17.mjs";export{s as composePluginMiddleware,o as defineComponent,m as definePlugin,t as defineSchemaExtension,d as installPlugins,l as mergeSchemaExtension};
1
+ import"@lunora/errors";import"./run-middleware-BeEEqmdE.mjs";import{c as s,d as o,a as m,b as t,i as d,m as l}from"./plugin-CDBMGCeQ.mjs";export{s as composePluginMiddleware,o as defineComponent,m as definePlugin,t as defineSchemaExtension,d as installPlugins,l as mergeSchemaExtension};
@@ -1 +1 @@
1
- import"@lunora/errors";import{H as n,X as s,Z as r,q as f,K as m,W as o,N as t}from"./plugin-B5pDeN17.mjs";import"@lunora/values";export{n as defineAggregateIndex,s as defineRankIndex,r as defineSchema,f as defineTable,m as defineVectorIndex,o as indexFieldsFromSchema,t as validateIndexFields};
1
+ import"@lunora/errors";import{K as n,H as s,W as r,j as f,q as m,Q as o,N as t}from"./plugin-CDBMGCeQ.mjs";import"@lunora/values";export{n as defineAggregateIndex,s as defineRankIndex,r as defineSchema,f as defineTable,m as defineVectorIndex,o as indexFieldsFromSchema,t as validateIndexFields};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{l as z}from"./run-middleware-BeEEqmdE.mjs";import{v as B}from"@lunora/values";const T=["de","en","es","fr","it","nl","none","pt"],O=["native","portable"],F=e=>O.includes(e),C=e=>T.includes(e),P="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",_="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",H="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",K="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Q="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",U="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",J="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",W=/[\u0300-\u036F]/gu,G=e=>e.normalize("NFD").replaceAll(W,"").normalize("NFC").toLowerCase(),g=e=>new Set(G(e).split(" "));g(_),g(P),g(H),g(K),g(Q),g(U),g(J);const R=16,X={many:(e,n)=>({field:n.field,kind:"many",references:n.references??"_id",table:e}),one:(e,n)=>({field:n.field,kind:"one",onDelete:n.onDelete,references:n.references??"_id",table:e})},w=(e,n,t)=>({handler:t,op:n,timing:e}),Y=()=>({afterDelete:e=>w("after","delete",e),afterInsert:e=>w("after","insert",e),afterUpdate:e=>w("after","update",e),beforeDelete:e=>w("before","delete",e),beforeInsert:e=>w("before","insert",e),beforeUpdate:e=>w("before","update",e)}),ce=e=>{const n={...e},t=[],r=[],s=[],l=[],c={},d=[],m={},f=Y(),p=[];let $={kind:"root"},N=!1,j=!1,A,L,S,q;const u={aggregateIndex(a,o){const h=o?.op??"count";if(h!=="count"&&!o?.field)throw new i("INTERNAL",`aggregateIndex "${a}": op "${h}" requires a "field"`);return t.push({by:o?.by,field:o?.field,name:a,on:"",op:h,where:o?.where}),u},get aggregateIndexes(){return t},get externalSource(){return q},externallyManaged(){return N=!0,u},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),u},get geoIndexes(){return r},global(a){return $={backend:a?.backend??"d1",kind:"global"},u},get isExternallyManaged(){return N},get isPublic(){return j},index(a,o,h){return s.push({fields:o,name:a,unique:h?.unique??!1}),u},get indexes(){return s},ownedBy(a){return A=a,u},get ownerField(){return A},public(){return j=!0,u},rankIndex(a,o){if(!o.sortBy||o.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${a}": "sortBy" is required and must list at least one key`);const h=o.sortBy.map(b=>({direction:b.direction??"asc",field:b.field}));return l.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:h,where:o.where}),u},get rankIndexes(){return l},get relationMap(){return c},relations(a){return Object.assign(c,a(X)),u},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>R)throw new i("INTERNAL",`searchIndex "${a}": at most ${String(R)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:h}=o;if(h!==void 0&&!C(h))throw new i("INTERNAL",`searchIndex "${a}": unknown language "${h}" (supported: ${T.join(", ")})`);const{strategy:b}=o;if(b!==void 0&&!F(b))throw new i("INTERNAL",`searchIndex "${a}": unknown strategy "${b}" (supported: ${O.join(", ")})`);return d.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return d},shape:n,shardBy(a){return $={field:a,kind:"shardBy"},u},get shardMode(){return $},get softDeleteMode(){return L},source(a){if(!a.binding)throw new i("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new i("INTERNAL","source: `query` is required (the tenant-membership SQL)");return q=a,N=!0,u},softDelete(a){const o=a?.field??"deletedAt";return L={field:o},o in n||(n[o]=B.optional(B.number().nullable())),u},get triggerMap(){return m},triggers(a){return Object.assign(m,a(f)),u},ttl(a,o){return S={after:o?.after,field:a},u},get ttlPolicy(){return S},get vectorIndexes(){return p},vectorize(a,o){return p.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),u}};return u},me=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,n)=>{const t=n.op??"count";if(t!=="count"&&!n.field)throw new i("INTERNAL",`aggregateIndex "${e}": op "${t}" requires a "field"`);return{by:n.by,field:n.field,name:e,on:n.on,op:t,where:n.where}},he=(e,n)=>{if(!n.sortBy||n.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);const t=n.sortBy.map(r=>({direction:r.direction??"asc",field:r.field}));return{name:e,on:n.table,partitionBy:n.partitionBy,sortBy:t,where:n.where}},y=e=>({...e,extend(n){return y(D(e,n))},jurisdiction(n){return y(e)},rls(n){return y({...e,rlsMode:n})}}),V=e=>{for(const[n,t]of Object.entries(e)){for(const r of t.aggregateIndexes)r.on===""&&(r.on=n);for(const r of t.rankIndexes)r.on===""&&(r.on=n)}},Z=(e,n,t)=>{for(const r of Object.values(n)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);s.aggregateIndexes.push(r)}for(const r of Object.values(t)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);s.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},ne=(e,n)=>{const t=n.mode==="incremental";if(n.mode!==void 0&&n.mode!=="full-pull"&&!t)throw new i("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(n.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!t){const r=ee(n);if(r)throw new i("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(!n.cursor?.column||!n.cursor.query)throw new i("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(n.reconcileEveryMs===void 0&&n.softDeleteColumn===void 0)throw new i("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).`)},te=e=>{for(const[n,t]of Object.entries(e)){const r=t.externalSource;if(r){if(t.shardMode.kind==="global")throw new i("INTERNAL",`defineSchema: table "${n}" 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(t.shardMode.kind==="shardBy"&&!r.tenantBy)throw new i("INTERNAL",`defineSchema: sourced + .shardBy() table "${n}" 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.`);ne(n,r)}}},re=["_creationTime","_id"],oe=new Set(re),x=(e,n,t,r)=>{if(!(oe.has(t)||t in r.shape))throw new i("INTERNAL",`defineSchema: table "${e}" index "${n}" names column "${t}" which is not in the table's shape`)},k=(e,n,t,r)=>{const s=new Set;for(const l of t){if(s.has(l.name))throw new i("INTERNAL",`defineSchema: table "${e}" declares ${n} "${l.name}" more than once`);s.add(l.name),r(l)}},M=e=>{for(const[n,t]of Object.entries(e))k(n,"index",t.indexes,r=>{for(const s of r.fields)x(n,r.name,s,t)}),k(n,"rank index",t.rankIndexes,r=>{for(const s of r.sortBy)x(n,r.name,s.field,t);for(const s of r.partitionBy??[])x(n,r.name,s,t)}),k(n,"geo index",t.geoIndexes,r=>{x(n,r.name,r.field,t)})},v=(e,n,t)=>{if(e.length===0)return;const r={};for(const s of e)r[n(s)]=t(s);return r},ae=e=>{const n=new Set(e.sortBy.map(t=>t.field));for(const t of e.partitionBy??[])n.add(t);return[...n]},ge=e=>{const n={};for(const[t,r]of Object.entries(e.tables)){const s=v(r.geoIndexes,d=>d.name,d=>[d.field]),l=v(r.indexes,d=>d.name,d=>d.fields),c=v(r.rankIndexes,d=>d.name,ae);(s||l||c)&&(n[t]={...s?{geo:s}:{},...l?{index:l}:{},...c?{rank:c}:{}})}return n},be=(e,n={},t={},r={})=>(V(e),Z(e,t,r),te(e),M(e),y({tables:e,vectorIndexes:n})),I=(e,n)=>`${e}_${n}`,E=(e,n,t)=>t.has(e)?I(n,e):e,se=(e,n,t,r)=>{const s=I(n,r),l=f=>f===""?s:E(f,n,t),c={};for(const[f,p]of Object.entries(e.relationMap))c[f]={...p,table:E(p.table,n,t)};const d=e.aggregateIndexes.map(f=>({...f,on:l(f.on)})),m=e.rankIndexes.map(f=>({...f,on:l(f.on)}));return{...e,aggregateIndexes:d,rankIndexes:m,relationMap:c}},we=(e,n)=>{if(!e)throw new i("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:n.tables,...n.vectorIndexes?{vectorIndexes:n.vectorIndexes}:{}}},ie=((e,n)=>{if(!e)throw new i("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(n.extension&&n.extension.key!==e)throw new i("INTERNAL",`definePlugin("${e}"): extension key "${n.extension.key}" does not match plugin key`);return{key:e,...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}}),pe=(e,n)=>({...ie(e,{...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}),functions:n.functions??{}}),D=(e,n)=>{const{key:t}=n,r=new Set(Object.keys(n.tables)),s={...e.tables};for(const[c,d]of Object.entries(n.tables)){const m=I(t,c);if(Object.hasOwn(s,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): table "${m}" already exists in the base schema — another extension with the same key already contributed it`);s[m]=se(d,t,r,c)}const l={...e.vectorIndexes};if(n.vectorIndexes)for(const[c,d]of Object.entries(n.vectorIndexes)){const m=I(t,c);if(Object.hasOwn(l,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): vector index "${m}" already exists in the base schema — another extension with the same key already contributed it`);l[m]={...d,table:E(d.table,t,r)}}return M(s),{rlsMode:e.rlsMode,tables:s,vectorIndexes:l}},xe=(e,n)=>{let t=e;for(const r of n)r.extension&&(t=D(t,r.extension));return t},ye=e=>{const n=e.map(t=>t.middleware).filter(t=>t!==void 0);return(async({ctx:t,next:r})=>z(n,t,s=>r({ctx:s})))};export{he as H,fe as K,M as N,ge as Q,be as W,ie as a,we as b,ye as c,pe as d,xe as i,ce as j,D as m,me as q};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.57",
3
+ "version": "1.0.0-alpha.59",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -67,8 +67,8 @@
67
67
  },
68
68
  "dependencies": {
69
69
  "@lunora/errors": "1.0.0-alpha.12",
70
- "@lunora/scheduler": "1.0.0-alpha.18",
71
- "@lunora/values": "1.0.0-alpha.15",
70
+ "@lunora/scheduler": "1.0.0-alpha.19",
71
+ "@lunora/values": "1.0.0-alpha.16",
72
72
  "drizzle-orm": "^0.45.2",
73
73
  "hono": "^4.12.32"
74
74
  },
@@ -1 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{l as z}from"./run-middleware-BeEEqmdE.mjs";import{isOrWrapsFromValidator as F,v as S}from"@lunora/values";const B=["de","en","es","fr","it","nl","none","pt"],O=["native","portable"],C=e=>O.includes(e),P=e=>B.includes(e),_="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",H="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",K="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",Q="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",U="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",W="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",J="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",G=/[\u0300-\u036F]/gu,V=e=>e.normalize("NFD").replaceAll(G,"").normalize("NFC").toLowerCase(),g=e=>new Set(V(e).split(" "));g(H),g(_),g(K),g(Q),g(U),g(W),g(J);const q=16,X={many:(e,n)=>({field:n.field,kind:"many",references:n.references??"_id",table:e}),one:(e,n)=>({field:n.field,kind:"one",onDelete:n.onDelete,references:n.references??"_id",table:e})},w=(e,n,t)=>({handler:t,op:n,timing:e}),Y=()=>({afterDelete:e=>w("after","delete",e),afterInsert:e=>w("after","insert",e),afterUpdate:e=>w("after","update",e),beforeDelete:e=>w("before","delete",e),beforeInsert:e=>w("before","insert",e),beforeUpdate:e=>w("before","update",e)}),me=e=>{const n={...e};for(const[a,o]of Object.entries(n))if(F(o))throw new i("INTERNAL",`defineTable: column "${a}" uses v.from() which is args-only — table columns need a concrete v.* type`);const t=[],r=[],s=[],l=[],c={},d=[],m={},f=Y(),p=[];let $={kind:"root"},N=!1,j=!1,A,L,T,R;const u={aggregateIndex(a,o){const h=o?.op??"count";if(h!=="count"&&!o?.field)throw new i("INTERNAL",`aggregateIndex "${a}": op "${h}" requires a "field"`);return t.push({by:o?.by,field:o?.field,name:a,on:"",op:h,where:o?.where}),u},get aggregateIndexes(){return t},get externalSource(){return R},externallyManaged(){return N=!0,u},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),u},get geoIndexes(){return r},global(a){return $={backend:a?.backend??"d1",kind:"global"},u},get isExternallyManaged(){return N},get isPublic(){return j},index(a,o,h){return s.push({fields:o,name:a,unique:h?.unique??!1}),u},get indexes(){return s},ownedBy(a){return A=a,u},get ownerField(){return A},public(){return j=!0,u},rankIndex(a,o){if(!o.sortBy||o.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${a}": "sortBy" is required and must list at least one key`);const h=o.sortBy.map(b=>({direction:b.direction??"asc",field:b.field}));return l.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:h,where:o.where}),u},get rankIndexes(){return l},get relationMap(){return c},relations(a){return Object.assign(c,a(X)),u},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>q)throw new i("INTERNAL",`searchIndex "${a}": at most ${String(q)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:h}=o;if(h!==void 0&&!P(h))throw new i("INTERNAL",`searchIndex "${a}": unknown language "${h}" (supported: ${B.join(", ")})`);const{strategy:b}=o;if(b!==void 0&&!C(b))throw new i("INTERNAL",`searchIndex "${a}": unknown strategy "${b}" (supported: ${O.join(", ")})`);return d.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return d},shape:n,shardBy(a){return $={field:a,kind:"shardBy"},u},get shardMode(){return $},get softDeleteMode(){return L},source(a){if(!a.binding)throw new i("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new i("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=a,N=!0,u},softDelete(a){const o=a?.field??"deletedAt";return L={field:o},o in n||(n[o]=S.optional(S.number().nullable())),u},get triggerMap(){return m},triggers(a){return Object.assign(m,a(f)),u},ttl(a,o){return T={after:o?.after,field:a},u},get ttlPolicy(){return T},get vectorIndexes(){return p},vectorize(a,o){return p.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),u}};return u},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,n)=>{const t=n.op??"count";if(t!=="count"&&!n.field)throw new i("INTERNAL",`aggregateIndex "${e}": op "${t}" requires a "field"`);return{by:n.by,field:n.field,name:e,on:n.on,op:t,where:n.where}},ge=(e,n)=>{if(!n.sortBy||n.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);const t=n.sortBy.map(r=>({direction:r.direction??"asc",field:r.field}));return{name:e,on:n.table,partitionBy:n.partitionBy,sortBy:t,where:n.where}},y=e=>({...e,extend(n){return y(D(e,n))},jurisdiction(n){return y(e)},rls(n){return y({...e,rlsMode:n})}}),Z=e=>{for(const[n,t]of Object.entries(e)){for(const r of t.aggregateIndexes)r.on===""&&(r.on=n);for(const r of t.rankIndexes)r.on===""&&(r.on=n)}},ee=(e,n,t)=>{for(const r of Object.values(n)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);s.aggregateIndexes.push(r)}for(const r of Object.values(t)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);s.rankIndexes.push(r)}},ne=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,n)=>{const t=n.mode==="incremental";if(n.mode!==void 0&&n.mode!=="full-pull"&&!t)throw new i("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(n.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!t){const r=ne(n);if(r)throw new i("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(!n.cursor?.column||!n.cursor.query)throw new i("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(n.reconcileEveryMs===void 0&&n.softDeleteColumn===void 0)throw new i("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).`)},re=e=>{for(const[n,t]of Object.entries(e)){const r=t.externalSource;if(r){if(t.shardMode.kind==="global")throw new i("INTERNAL",`defineSchema: table "${n}" 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(t.shardMode.kind==="shardBy"&&!r.tenantBy)throw new i("INTERNAL",`defineSchema: sourced + .shardBy() table "${n}" 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.`);te(n,r)}}},oe=["_creationTime","_id"],ae=new Set(oe),x=(e,n,t,r)=>{if(!(ae.has(t)||t in r.shape))throw new i("INTERNAL",`defineSchema: table "${e}" index "${n}" names column "${t}" which is not in the table's shape`)},v=(e,n,t,r)=>{const s=new Set;for(const l of t){if(s.has(l.name))throw new i("INTERNAL",`defineSchema: table "${e}" declares ${n} "${l.name}" more than once`);s.add(l.name),r(l)}},M=e=>{for(const[n,t]of Object.entries(e))v(n,"index",t.indexes,r=>{for(const s of r.fields)x(n,r.name,s,t)}),v(n,"rank index",t.rankIndexes,r=>{for(const s of r.sortBy)x(n,r.name,s.field,t);for(const s of r.partitionBy??[])x(n,r.name,s,t)}),v(n,"geo index",t.geoIndexes,r=>{x(n,r.name,r.field,t)})},k=(e,n,t)=>{if(e.length===0)return;const r={};for(const s of e)r[n(s)]=t(s);return r},se=e=>{const n=new Set(e.sortBy.map(t=>t.field));for(const t of e.partitionBy??[])n.add(t);return[...n]},be=e=>{const n={};for(const[t,r]of Object.entries(e.tables)){const s=k(r.geoIndexes,d=>d.name,d=>[d.field]),l=k(r.indexes,d=>d.name,d=>d.fields),c=k(r.rankIndexes,d=>d.name,se);(s||l||c)&&(n[t]={...s?{geo:s}:{},...l?{index:l}:{},...c?{rank:c}:{}})}return n},we=(e,n={},t={},r={})=>(Z(e),ee(e,t,r),re(e),M(e),y({tables:e,vectorIndexes:n})),I=(e,n)=>`${e}_${n}`,E=(e,n,t)=>t.has(e)?I(n,e):e,ie=(e,n,t,r)=>{const s=I(n,r),l=f=>f===""?s:E(f,n,t),c={};for(const[f,p]of Object.entries(e.relationMap))c[f]={...p,table:E(p.table,n,t)};const d=e.aggregateIndexes.map(f=>({...f,on:l(f.on)})),m=e.rankIndexes.map(f=>({...f,on:l(f.on)}));return{...e,aggregateIndexes:d,rankIndexes:m,relationMap:c}},pe=(e,n)=>{if(!e)throw new i("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:n.tables,...n.vectorIndexes?{vectorIndexes:n.vectorIndexes}:{}}},de=((e,n)=>{if(!e)throw new i("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(n.extension&&n.extension.key!==e)throw new i("INTERNAL",`definePlugin("${e}"): extension key "${n.extension.key}" does not match plugin key`);return{key:e,...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}}),xe=(e,n)=>({...de(e,{...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}),functions:n.functions??{}}),D=(e,n)=>{const{key:t}=n,r=new Set(Object.keys(n.tables)),s={...e.tables};for(const[c,d]of Object.entries(n.tables)){const m=I(t,c);if(Object.hasOwn(s,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): table "${m}" already exists in the base schema — another extension with the same key already contributed it`);s[m]=ie(d,t,r,c)}const l={...e.vectorIndexes};if(n.vectorIndexes)for(const[c,d]of Object.entries(n.vectorIndexes)){const m=I(t,c);if(Object.hasOwn(l,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): vector index "${m}" already exists in the base schema — another extension with the same key already contributed it`);l[m]={...d,table:E(d.table,t,r)}}return M(s),{rlsMode:e.rlsMode,tables:s,vectorIndexes:l}},ye=(e,n)=>{let t=e;for(const r of n)r.extension&&(t=D(t,r.extension));return t},Ie=e=>{const n=e.map(t=>t.middleware).filter(t=>t!==void 0);return(async({ctx:t,next:r})=>z(n,t,s=>r({ctx:s})))};export{he as H,fe as K,M as N,be as W,ge as X,we as Z,de as a,pe as b,Ie as c,xe as d,ye as i,D as m,me as q};