@lunora/server 1.0.0-alpha.266 → 1.0.0-alpha.268

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2675,13 +2675,13 @@ type LiveRouterFallback = (LiveHostTriggers & LiveRouterApp) | ((request: Reques
2675
2675
  * Serve each declared stream's connect and control routes. Codegen emits this as the worker's `httpRouter`, or wraps
2676
2676
  * a framework host with it, so a stream needs no `app.get` / `app.post` of its own.
2677
2677
  *
2678
- * A Hono `fallback` (the app's `httpRouter()`) gets the stream routes registered on it, so its middleware runs for
2679
- * them, and it is returned as the router. Any other `fallback` is a framework host: the stream routes are matched
2678
+ * A `fallback` built by `httpRouter()` gets the stream routes registered on it, so its middleware runs for
2679
+ * them, and it is returned as the router. Any other `fallback`, a plain Hono app included, is a framework host: the stream routes are matched
2680
2680
  * first on a router of their own, and every other request goes to the host. With no `fallback`, the router is the
2681
2681
  * stream routes alone.
2682
2682
  *
2683
2683
  * Only the exact method and path of a stream's two routes are taken. Calling this again with the same Hono app adds
2684
- * nothing, so the same app can be passed on every build.
2684
+ * nothing for a stream it already carries, so the same app can be passed on every build.
2685
2685
  */
2686
2686
  declare const liveStreamRouter: (mounts: ReadonlyArray<LiveStreamMount>, fallback?: LiveRouterFallback) => LiveRouterApp;
2687
2687
  /**
package/dist/index.d.ts CHANGED
@@ -2675,13 +2675,13 @@ type LiveRouterFallback = (LiveHostTriggers & LiveRouterApp) | ((request: Reques
2675
2675
  * Serve each declared stream's connect and control routes. Codegen emits this as the worker's `httpRouter`, or wraps
2676
2676
  * a framework host with it, so a stream needs no `app.get` / `app.post` of its own.
2677
2677
  *
2678
- * A Hono `fallback` (the app's `httpRouter()`) gets the stream routes registered on it, so its middleware runs for
2679
- * them, and it is returned as the router. Any other `fallback` is a framework host: the stream routes are matched
2678
+ * A `fallback` built by `httpRouter()` gets the stream routes registered on it, so its middleware runs for
2679
+ * them, and it is returned as the router. Any other `fallback`, a plain Hono app included, is a framework host: the stream routes are matched
2680
2680
  * first on a router of their own, and every other request goes to the host. With no `fallback`, the router is the
2681
2681
  * stream routes alone.
2682
2682
  *
2683
2683
  * Only the exact method and path of a stream's two routes are taken. Calling this again with the same Hono app adds
2684
- * nothing, so the same app can be passed on every build.
2684
+ * nothing for a stream it already carries, so the same app can be passed on every build.
2685
2685
  */
2686
2686
  declare const liveStreamRouter: (mounts: ReadonlyArray<LiveStreamMount>, fallback?: LiveRouterFallback) => LiveRouterApp;
2687
2687
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as O,bindTableFacade as F,defineLazyFacade as v}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as U,httpRoute as H,httpRouter as k,lastEventId as w,sseEvent as B}from"./packem_shared/httpAction-DuAVtPa_.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as G}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as K,onDisconnect as Q,onShardInit as X}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-BmMpdotv.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as de}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as ue,b as Se,e as De,f as he,g as Te,h as Re,i as Ae,j as ge,k as Le,m as _e}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs";import{PROCEDURE_META as Oe,UNLOADED_META as Fe,procedureMeta as ve}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ue}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as ke}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Be}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as We}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-JcqUI9iZ.mjs";import{defineWebSocket as Ge}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ke}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Xe}from"@lunora/errors";import{cronJobs as Ze}from"@lunora/scheduler";import{ValidationError as er,v as rr}from"@lunora/values";import{allowAll as tr,deny as ir,isDeny as nr,toWhereInput as fr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as dr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as mr,buildRlsReadRegistry as pr,composeShapeReadWhere as xr}from"./packem_shared/assertShapesDeclareReadPolicies-BfxqaO3Z.mjs";import{buildMaskRegistry as lr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as ur,definePermission as Sr,definePolicies as Dr,definePolicy as hr,defineRole as Tr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ar,defineStorageRules as gr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as _r}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Cr}from"./packem_shared/mask-Wqcb6WNS.mjs";import{r as Pr}from"./packem_shared/middleware-D4Z_QWhU.mjs";import{storageRules as yr}from"./packem_shared/storageRules-DmYr_Gi9.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Xe as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,Oe as PROCEDURE_META,Fe as UNLOADED_META,e as VERSION,er as ValidationError,n as actionCacheExtension,tr as allowAll,dr as asBucketStorage,mr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,O as bindOrm,F as bindTableFacade,lr as buildMaskRegistry,pr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,xr as composeShapeReadWhere,ur as createPolicyDsl,l as createSecrets,We as createServices,Ze as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,ue as defineComponent,_ as defineDocumentHistory,P as defineEnv,Y as defineIdentity,G as defineIdentityGuard,v as defineLazyFacade,re as defineListArgs,te as defineLiveStream,fe as defineMigration,de as defineModule,me as defineMutator,Sr as definePermission,Se as definePlugin,Dr as definePolicies,hr as definePolicy,Pe as definePresence,De as defineRankIndex,Tr as defineRole,Be as defineRoom,he as defineSchema,Te as defineSchemaExtension,Ye as defineShape,Ar as defineStorageRule,gr as defineStorageRules,Re as defineTable,Ae as defineVectorIndex,Ge as defineWebSocket,ir as deny,I as documentHistoryExtension,S as flushDeferredDeletes,U as httpAction,H as httpRoute,k as httpRouter,ge as indexFieldsFromSchema,s as initLunora,Le as installPlugins,nr as isDeny,p as isPerDispatchMiddleware,_r as isSafeHeaderValue,w as lastEventId,ie as liveStreamRouter,Cr as mask,_e as mergeSchemaExtension,K as onConnect,Q as onDisconnect,ke as onQueryChange,X as onShardInit,Ke as onWhisper,xe as platformAdmin,be as presenceExtension,ve as procedureMeta,Ue as protectPublic,b as redactSecrets,Pr as rls,W as serveStorageObject,B as sseEvent,yr as storageRules,x as tagPerDispatchMiddleware,fr as toWhereInput,rr as v,D as withDeferredDeletes,R as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as O,bindTableFacade as F,defineLazyFacade as v}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as U,httpRoute as H,httpRouter as k,lastEventId as w,sseEvent as B}from"./packem_shared/httpAction-B9zD0ykG.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as G}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as K,onDisconnect as Q,onShardInit as X}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-Doz9iDSY.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as de}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as ue,b as Se,e as De,f as he,g as Te,h as Re,i as Ae,j as ge,k as Le,m as _e}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs";import{PROCEDURE_META as Oe,UNLOADED_META as Fe,procedureMeta as ve}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ue}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as ke}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Be}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as We}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-CAIsX21I.mjs";import{defineWebSocket as Ge}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ke}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Xe}from"@lunora/errors";import{cronJobs as Ze}from"@lunora/scheduler";import{ValidationError as er,v as rr}from"@lunora/values";import{allowAll as tr,deny as ir,isDeny as nr,toWhereInput as fr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as dr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as mr,buildRlsReadRegistry as pr,composeShapeReadWhere as xr}from"./packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs";import{buildMaskRegistry as lr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as ur,definePermission as Sr,definePolicies as Dr,definePolicy as hr,defineRole as Tr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ar,defineStorageRules as gr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as _r}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Cr}from"./packem_shared/mask--ZXtzCj7.mjs";import{r as Pr}from"./packem_shared/middleware-CdoC33P7.mjs";import{storageRules as yr}from"./packem_shared/storageRules-BZgB67oS.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Xe as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,Oe as PROCEDURE_META,Fe as UNLOADED_META,e as VERSION,er as ValidationError,n as actionCacheExtension,tr as allowAll,dr as asBucketStorage,mr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,O as bindOrm,F as bindTableFacade,lr as buildMaskRegistry,pr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,xr as composeShapeReadWhere,ur as createPolicyDsl,l as createSecrets,We as createServices,Ze as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,ue as defineComponent,_ as defineDocumentHistory,P as defineEnv,Y as defineIdentity,G as defineIdentityGuard,v as defineLazyFacade,re as defineListArgs,te as defineLiveStream,fe as defineMigration,de as defineModule,me as defineMutator,Sr as definePermission,Se as definePlugin,Dr as definePolicies,hr as definePolicy,Pe as definePresence,De as defineRankIndex,Tr as defineRole,Be as defineRoom,he as defineSchema,Te as defineSchemaExtension,Ye as defineShape,Ar as defineStorageRule,gr as defineStorageRules,Re as defineTable,Ae as defineVectorIndex,Ge as defineWebSocket,ir as deny,I as documentHistoryExtension,S as flushDeferredDeletes,U as httpAction,H as httpRoute,k as httpRouter,ge as indexFieldsFromSchema,s as initLunora,Le as installPlugins,nr as isDeny,p as isPerDispatchMiddleware,_r as isSafeHeaderValue,w as lastEventId,ie as liveStreamRouter,Cr as mask,_e as mergeSchemaExtension,K as onConnect,Q as onDisconnect,ke as onQueryChange,X as onShardInit,Ke as onWhisper,xe as platformAdmin,be as presenceExtension,ve as procedureMeta,Ue as protectPublic,b as redactSecrets,Pr as rls,W as serveStorageObject,B as sseEvent,yr as storageRules,x as tagPerDispatchMiddleware,fr as toWhereInput,rr as v,D as withDeferredDeletes,R as withDeferredSchedules};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-D4Z_QWhU.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-CdoC33P7.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
@@ -0,0 +1 @@
1
+ import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-B9zD0ykG.mjs";const A="/_lunora/live/connect",N="/_lunora/live/control",D="room:",B="__lunora_socket__:",K=256,m=e=>`/live/${e}/connect`,v=e=>`/live/${e}/control`,U=/^[A-Za-z]\w*$/u,T=e=>U.test(e),H=e=>`${e}:`.startsWith(D)||`${e}:`.startsWith(B),V=(e,t,o)=>[e,...t.map(d=>{const i=o[d];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${d}`);return encodeURIComponent(i)})].join(":"),k=(e,t)=>{if(e.length>K)return;const[o,...d]=e.split(":");if(o===void 0||!Object.hasOwn(t,o))return;const i=t[o];if(d.length!==i.length)return;const r={};try{for(const[c,u]of i.entries())r[u]=decodeURIComponent(d[c]);return V(o,i,r)===e?{key:r,name:o}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},S=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),M=(e,t)=>{for(const[o,d]of Object.entries(t)){if(!T(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(H(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" would encode into a reserved topic prefix`);for(const[i,r]of Object.entries(d.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a plain identifier`);if(!P(r))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new O("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),q=e=>{M(e.id,e.topics);const t=m(e.id),o=v(e.id),d=Object.fromEntries(Object.entries(e.topics).map(([s,a])=>[s,Object.keys(a.key??{})])),i=s=>{const a=k(s,d),n=a===void 0?void 0:e.topics[a.name];if(!(a===void 0||n===void 0))try{return{declaration:n,key:b(n.key??{},a.key,"key"),name:a.name}}catch{return}},r=(s,a)=>{const n=i(s);if(n===void 0)throw new O("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return b({payload:p.payload},{payload:a},"topic").payload}catch(f){throw z(s,f)}},c=async(s,a)=>{const n=i(a);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:a,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,a)=>{const n=new URL(a.url).searchParams.get("shard")??void 0;return s.fetchShard(n,A,{method:"GET"})}),R=E(async(s,a)=>{const n=await F(a);if(!n)return h("Expected a JSON object body");const{action:p}=n,f=typeof n.topic=="string"?n.topic:void 0;if(f===void 0||f.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const y=typeof n.shardKey=="string"?n.shardKey:void 0,L=y===void 0?s:{...s,...s.forShard(y)};if(p==="subscribe"&&!await c(L,f))return S(f);const w=s.fetchShard(y,N,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return w;try{return await w}catch(l){if(I(l)&&l.code==="FORBIDDEN_SHARD")return S(f);throw l}});return{connect:u,connectPath:t,control:R,controlPath:o,id:e.id,topics:e.topics,validatePublish:r}},G=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},_=new WeakMap,$=(e,t)=>{for(const o of t){let d;const i=()=>(d??=o.load().catch(r=>{throw d=void 0,r}),d);e.get(m(o.id),async r=>{const{connect:c}=await i();return c(r)}),e.post(v(o.id),async r=>{const{control:c}=await i();return c(r)})}},Y=(e,t)=>{if(t instanceof g&&j(t)){const r=_.get(t)??new Set,c=e.filter(u=>!r.has(u.id));$(t,c),_.set(t,r);for(const u of c)r.add(u.id);return t}const o=C();if($(o,e),t===void 0)return o;const d=new Set(e.flatMap(r=>[`GET ${m(r.id)}`,`POST ${v(r.id)}`])),i=(r,c,u)=>typeof t=="function"?t(r,c,u):t.fetch(r,c,u);return{...G(t),fetch:(r,c,u)=>d.has(`${r.method} ${new URL(r.url).pathname}`)?o.fetch(r,c,u):i(r,c,u)}};export{q as defineLiveStream,Y as liveStreamRouter};
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-BfxqaO3Z.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-CWrMYcqw.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
@@ -0,0 +1 @@
1
+ import{LunoraError as E,toErrorBody as T,isLunoraError as q}from"@lunora/errors";import{parseValidatorMap as w,ValidationError as C}from"@lunora/values";import{encodeWire as v}from"@lunora/wire";import{Hono as H}from"hono";import{SSE_HEADERS as S,sseFrame as b,isSafeHeaderValue as I}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const z=e=>async r=>e(r.get("lunora"),r.req.raw),O=new WeakSet,K=e=>O.has(e),X=()=>{const e=new H;return O.add(e),e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},A=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},D=(e,r,o)=>{const n=A(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=n._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},N=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=D(t,r,n))}return w(e,o,"searchParams")},j=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const i=o[t];n[t]=i===void 0?void 0:g(A(a).kind,i)}return w(e,n,"params")},x=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return w(e,o,"body")},P=e=>{if(e instanceof C)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(q(e)){const{body:r,redacted:o,status:n}=T(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},_=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},B=(e,r)=>async o=>{const n=_(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?N(e.searchParams,o):{},i=Object.keys(e.params).length>0?j(e.params,o):{},d=Object.keys(e.body).length>0?await x(e.body,o):{},h=await r({body:d,ctx:t,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const y=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:y?c:void 0,status:204}):Response.json(s,{headers:y?c:void 0})}catch(t){return P(t)}},Y=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},k=Symbol.for("@lunora/server/sse-event"),Z=e=>({[k]:!0,data:e.data,id:e.id}),V=e=>typeof e=="object"&&e!==null&&e[k]===!0,M=(e,r)=>{if(V(r)){if(!I(r.id))throw new E("INTERNAL","sseEvent id must not contain CR, LF or NUL");const o=e?R(e,r.data):r.data;return b(v(o),void 0,r.id)}return b(v(e?R(e,r):r))},U=(e,r)=>(async o=>{const n=_(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?N(e.searchParams,o):{},a=Object.keys(e.params).length>0?j(e.params,o):{}}catch(m){return P(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:S});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const y=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:t,signal:s.signal});for await(const p of f){if(s.signal.aborted)break;m.enqueue(h.encode(M(e.output,p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:p,redacted:L}=T(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});L&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(y,{headers:S})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>B(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>U(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),ee={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{z as httpAction,ee as httpRoute,X as httpRouter,K as isHttpRouter,I as isSafeHeaderValue,Y as lastEventId,Z as sseEvent};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as K,a as q,o as _,b as z,c as G,d as C}from"./middleware-D4Z_QWhU.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},a=(s,i,c)=>{const u={...s};for(const[w,l]of Object.entries(i))w in u&&(u[w]=Q(l,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>a(u,i,c))}),P=(s,i)=>{const c=G(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},x=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,l=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),l())});s(l());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,l=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>a(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[t];if(!d)return;const g=d.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,t,c)},collect:async()=>(await r.collect()).map(e=>a(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=a(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(a(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?a(o,t,c):null},order:o=>A(r.order(o),t,n),paginate:async o=>B(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(d=>a(d,t,c)),unique:async()=>{const o=await r.unique();return o?a(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),x(e,t,n,"withIndex"),A(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(x(e,t,n,"withSearchIndex"),A(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},p=new Set;for(const r of i.values())for(const t of Object.keys(r))p.add(t);const O=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))L(e,d,t,n,o)},L=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(t)?t:[])O(d,n,o,e);return}if(r==="NOT"){O(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(t))for(const d of Object.values(t))O(d,p,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{p.size===0||t===void 0||O(t,F(r),r,n)},E=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(n,d))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,t,n)=>{if(!(p.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,g=`${r}.${o}`;O(d.where,p,g,n),E(g,d.orderBy,p,n),j(g,d.with,n)}},W=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),E(r,t?.orderBy,F(r),n),j(r,t?.with,n)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,t,n)=>{const o=v(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},M=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[d,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:a(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=v(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){W(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?a(n,o,c):n},async findFirstOrThrow(r,t){W(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?a(n,o,c):n},async explain(r,t){return W(r,t,"explain"),s.explain(r,t)},async findMany(r,t){W(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?B(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:a(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?a(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?A(t,n,r):t},async rank(r,t,n){return $(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){$(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(t,n,o)=>($(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),..._("rankPageRows",l,r=>async(t,n,o)=>{$(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),d=i.get(t);return d?{...e,rows:e.rows.map(g=>({...g,doc:a(g.doc,d,c)}))}:e})};if(p.size>0)for(const[r,t]of Object.entries(s))z(t)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=K(i.roles),w=async({ctx:f,next:k})=>{const y=f,A={auth:await q(y.auth??{},u),ctx:y};if(i.bypass?.(A)===!0)return k();const R=V(y.db,c,A,i.indexFields),p={db:R},{orm:O}=y;return O!==null&&typeof O=="object"&&(p.orm=J(R)),k({ctx:p})},l=new Map;for(const[f,k]of c)l.set(f,new Set(Object.keys(k)));return T(w,{columns:l})};export{rr as mask};
1
+ import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as K,a as q,o as _,b as z,c as G,d as C}from"./middleware-CdoC33P7.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},a=(s,i,c)=>{const u={...s};for(const[w,l]of Object.entries(i))w in u&&(u[w]=Q(l,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>a(u,i,c))}),P=(s,i)=>{const c=G(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},x=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,l=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),l())});s(l());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,l=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>a(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[t];if(!d)return;const g=d.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,t,c)},collect:async()=>(await r.collect()).map(e=>a(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=a(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(a(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?a(o,t,c):null},order:o=>A(r.order(o),t,n),paginate:async o=>B(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(d=>a(d,t,c)),unique:async()=>{const o=await r.unique();return o?a(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),x(e,t,n,"withIndex"),A(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(x(e,t,n,"withSearchIndex"),A(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},p=new Set;for(const r of i.values())for(const t of Object.keys(r))p.add(t);const O=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))L(e,d,t,n,o)},L=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(t)?t:[])O(d,n,o,e);return}if(r==="NOT"){O(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(t))for(const d of Object.values(t))O(d,p,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{p.size===0||t===void 0||O(t,F(r),r,n)},E=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(n,d))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,t,n)=>{if(!(p.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,g=`${r}.${o}`;O(d.where,p,g,n),E(g,d.orderBy,p,n),j(g,d.with,n)}},W=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),E(r,t?.orderBy,F(r),n),j(r,t?.with,n)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,t,n)=>{const o=v(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},M=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[d,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:a(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=v(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){W(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?a(n,o,c):n},async findFirstOrThrow(r,t){W(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?a(n,o,c):n},async explain(r,t){return W(r,t,"explain"),s.explain(r,t)},async findMany(r,t){W(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?B(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:a(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?a(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?A(t,n,r):t},async rank(r,t,n){return $(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){$(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(t,n,o)=>($(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),..._("rankPageRows",l,r=>async(t,n,o)=>{$(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),d=i.get(t);return d?{...e,rows:e.rows.map(g=>({...g,doc:a(g.doc,d,c)}))}:e})};if(p.size>0)for(const[r,t]of Object.entries(s))z(t)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=K(i.roles),w=async({ctx:f,next:k})=>{const y=f,A={auth:await q(y.auth??{},u),ctx:y};if(i.bypass?.(A)===!0)return k();const R=V(y.db,c,A,i.indexFields),p={db:R},{orm:O}=y;return O!==null&&typeof O=="object"&&(p.orm=J(R)),k({ctx:p})},l=new Map;for(const[f,k]of c)l.set(f,new Set(Object.keys(k)));return T(w,{columns:l})};export{rr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as p,isLunoraError as Oe}from"@lunora/errors";import{findRelated as ve,whereFilter as We}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Re,bindOrm as Ee}from"./bindOrm-D5mVDvbi.mjs";import{t as Ae}from"./policy-tag-V0lqFzgS.mjs";import{deny as Be}from"./allowAll-DkRAgItV.mjs";const G=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},te=4;class P extends Error{}const x=e=>e.includes("."),gt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ce=e=>{const t=e.split(".");if(t.length>te||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(te)} non-empty segments`);return t},Se=(e,t)=>{if(!x(t))return e[t];let r=e;for(const s of ce(t)){if(!G(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ae=(e,t,r,s)=>{const[c,...f]=t;if(c===void 0)throw new P(`field path "${s}" is empty`);if(e!=null&&!G(e))throw new P(`cannot set "${s}": "${c}" sits inside a value that is not an object`);const u=e??{};return{...u,[c]:f.length===0?r:ae(u[c],f,r,s)}},Te=(e,t)=>{const r=Object.keys(e).filter(c=>x(c));if(r.length===0)return e;for(const c of r){const f=r.find(u=>u!==c&&u.startsWith(`${c}.`));if(f!==void 0)throw new P(`patch sets both "${c}" and "${f}", which overlap; set one or the other`)}const s={};for(const[c,f]of Object.entries(e))x(c)||(s[c]=f);for(const c of r){const[f="",...u]=ce(c);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${c}"; set one or the other`);s[f]=ae(Object.hasOwn(s,f)?s[f]:t[f],u,e[c],c)}return s},ke=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},Ie=["every","is","isNot","none","some"],Pe=new Set(Ie),me=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Pe.has(r))},ne=(e,t,r)=>t?{[e]:r(t)}:{},le=500,z=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??le},H=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},J={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const fe=e=>{if(!G(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(J,r)))return{operand:e[r],operator:r}},_e=e=>fe(e)!==void 0,$e=(e,t,r,s)=>{const c=J[t];if(c.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const f=c.apply(s,r);if(!Number.isFinite(f))throw new R(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},de=(e,t)=>{const r=new Set;for(const[s,c]of Object.entries(e))t(s)!==void 0&&_e(c)&&r.add(s);return r},De=(e,t,r)=>{let s;for(const c of de(e,r)){const{operand:f,operator:u}=fe(e[c]),g=r(c);if(J[u].kind!==g)throw new R(`patch: "${u}" does not apply to the ${String(g)} column "${c}".`);s??={...e},s[c]=$e(c,u,f,t[c])}return s??e},Fe=(e,t)=>{const r=c=>{const f=t[c];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},s={...e};for(const c of de(e,r))try{Object.assign(s,De({[c]:e[c]},t,r))}catch(f){if(!(f instanceof R))throw f}try{return Te(s,t)}catch(c){if(c instanceof P)return s;throw c}},Me=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,S=0,E=1,m=e=>e?E:B,w=(e,t)=>e<t?e:t,Le=(e,t)=>e>t?e:t,ue=e=>e===S?S:m(e===B),re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},je={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Ce=(e,t,r)=>{let s=E;for(const c of["gt","gte","lt","lte"]){if(!(c in r))continue;const f=r[c];F(e,c,f);const u=x(e);if(u?ke(f)===void 0:!re(f))s=w(s,B);else if(T(t))s=w(s,S);else{const g=je[c],y=u?typeof t==typeof f:re(t);s=w(s,m(y&&g(t,f)))}}return s},oe=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},se=(e,t)=>t.length===0?B:T(e)?S:t.includes(e)?E:t.some(r=>T(r))?S:B,Ue=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,se(t,oe(e,"in",r.in)))),"notIn"in r&&(s=w(s,ue(se(t,oe(e,"notIn",r.notIn))))),"contains"in r){const c=r.contains;F(e,"contains",c),s=T(t)?w(s,S):w(s,m(typeof t=="string"&&typeof c=="string"&&t.includes(c)))}return"isNull"in r&&(s=w(s,m(r.isNull===!0===T(t)))),s},K=(e,t,r)=>t===null?m(r===T(e)):T(e)?S:m(r===(e===t)),xe=(e,t,r)=>{let s=E;return"eq"in r&&(F(e,"eq",r.eq),s=w(s,K(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),s=w(s,K(t,r.ne,!1))),s},Ne=(e,t,r)=>w(xe(e,t,r),w(Ue(e,t,r),Ce(e,t,r))),qe=(e,t,r,s)=>{if(t==="NOT")return ue(s(e,r??{}));if(!Array.isArray(r))return B;let c=t==="AND"?E:B;for(const f of r){const u=s(e,f);c=t==="AND"?w(c,u):Le(c,u)}return c},he=e=>e==="AND"||e==="OR"||e==="NOT",Ye=e=>X(e)&&Object.keys(e).every(t=>Me.includes(t)),N=e=>Object.keys(e).some(t=>{const r=e[t];return he(t)?t==="NOT"?N(r??{}):Array.isArray(r)&&r.some(s=>N(s??{})):me(r)}),ye=(e,t)=>{let r=E;for(const s of Object.keys(t)){const c=t[s];if(he(s)){r=w(r,qe(e,s,c,ye));continue}const f=Se(e,s);if(Ye(c)){r=w(r,Ne(s,f,c));continue}F(s,"eq",c),r=w(r,K(f,c,!0))}return r},q=(e,t)=>ye(e,t)===E,ie=(e,t)=>e===void 0||t===void 0?e??t:(r,s)=>e(r,s)&&t(r,s),I=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{H(e,z(t,r,I),r,I)},ze=Be(),He=Symbol.for("lunora.ctxdb.rls-unwrap"),pe=Symbol.for("lunora.rls.wrapped-chain"),Ke=e=>e[pe],Qe=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Xe=(e,t)=>{const r=[];let s=!1;for(const c of e){if(c.on!=="read")continue;const f=c.when(t);if(f!==void 0){if(f===!0){s=!0;break}f!==!1&&r.push(f)}}if(!s)return r.length===0?ze:r.length===1?r[0]:{OR:r}},Ge=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Je=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Ge(e,t,r);if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Ze=(e,t,r,s)=>{let c=!1;for(const f of e)if(f.on===t&&(c=!0,!Je(f,r,s)))return!1;return c},Ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),et=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),tt=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ve.has(r)&&et(r,e[r]))},nt=e=>e===void 0?{}:X(e)&&tt(e)?e:{where:e},Q=e=>e!==void 0&&Object.keys(e).length>0,rt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>Q(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ot=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},st=(e,t,r)=>{const[s]=r,c=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const i=[];let a=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;a=!0;const O=Xe(h,d.context);O!==void 0&&i.push(O)}const l={baseWhere:rt(i),restricts:a};return f.set(n,l),l},g=(n,o,i,a)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!Ze(d,o,{...l.context,row:i},a))return!1}return!0},y=n=>u(n).restricts?t:e,b=n=>u(n).baseWhere,W=async(n,o)=>{const i=await t.get(n,o);return i?{row:i,tableName:c.has(n)?n:void 0}:{row:null,tableName:void 0}},_=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:c.has(l.tableName)?l.tableName:void 0}}const o=[...c.keys()],a=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return a?{row:a.row,tableName:a.tableName}:{row:null,tableName:void 0}},Y=async(n,o)=>{const i=await W(n,o);return i.row&&i.tableName!==void 0?{row:i.row,tableName:i.tableName}:void 0},A=async(n,o,i,a,l)=>{const d=await Y(n,o);if(!d)return a(e);const h=l?l(d.row):void 0;if(!g(d.tableName,i,d.row,h))throw new p("FORBIDDEN",`${i} denied by policy`);return a(t,d.tableName)},M=(n,o,i)=>{if(i?.hard===!0)return!1;const a=e.softDeleteFields?.get(n);return a!==void 0&&o[a]!==null&&o[a]!==void 0},L=async(n,o,i,a,l)=>{const d=i?t:e,h=await d.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...a?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:v(l,{_id:n})});if(!h||M(o,h,a))return!1;if(i&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,a),!0},$=async(n,o,i,a)=>{const l=c.has(n),d=l?t:e,h=i===void 0?void 0:{hard:i},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const V of o){const ee=String(V._id);if(O){await L(ee,n,l,h,a)&&(D+=1);continue}if(l&&!g(n,"delete",V))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ee,h),D+=1}return D},j=(n,o,i,a)=>A(n,o,"update",(l,d)=>a(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Fe(i,l)})),C=(n,o)=>{const{baseWhere:i}=u(n);if(Q(i))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},ge=e.rankBefore,be=e.rankPageRows,{relationEdges:Z}=e,k={...e,async count(n,o){const{baseWhere:i}=u(n),a=nt(o);return y(n).count(n,{...a,baseWhere:v(a.baseWhere,i),relationBaseWhere:b,restrictsCounts:(a.restrictsCounts??!1)||Q(i)})},delete:(n,o,i)=>A(n,o,"delete",a=>a.delete(n,o,i)),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??le),{baseWhere:a}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:a,limit:i,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await $(n,h,o?.hard),h.length<i))break}return{deleted:l}},async deleteMany(n,o,i){U(o.length,i?.limit,"deleteMany");for(const a of o)await A(n,a,"delete",l=>l.delete(n,a));return{deleted:o.length}},async deleteWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"deleteWhere",I),d=await y(n).findMany(n,{baseWhere:v(o,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return H(h.length,l,"deleteWhere",I),{deleted:await $(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async get(n,o){const i=await W(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:a,restricts:l}=u(i.tableName);if(!l)return e.get(n,o);if(!a)return i.row;const d=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const i=o===void 0?await _(n):await W(o,n);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:a}=u(i.tableName);if(!a)return{row:i.row,tableName:i.tableName};const l=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:i.tableName}:null},async insert(n,o,i){if(c.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(U(o.length,i?.limit,"insertMany"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(U(o.length,i?.limit,"insertManyUnsafe"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i,a)=>j(n,o,i,(l,d)=>l.patch(n,o,i,{...a,verify:ie(a?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,i){const a=await j(n,o,i.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...i,verify:ie(i.verify,h.verify)})});return a.doc===null||await k.get(n,o).then(d=>d!==null,d=>{if(Oe(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?a:{applied:a.applied,doc:null}},async patchMany(n,o,i){U(o.length,i?.limit,"patchMany");for(const a of o)await j(n,a.id,a.patch,(l,d)=>l.patch(n,a.id,a.patch,d));return{patched:o.length}},async patchWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"patchWhere",I),h=(await y(n).findMany(n,{baseWhere:v(o.where,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return H(h.length,l,"patchWhere",I),k.patchMany(n,h,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(We(o,a=>q(a,o))):i},related:Z===void 0?void 0:async(n,o)=>ve({findMany:async(i,a)=>k.findMany(i,a),lookupById:async i=>t.lookupById?.(i)},Z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,o,"update",async i=>{const a=i.restore??t.restore;if(!a)throw new p("BAD_REQUEST","restore is not supported by this writer");await a(n,o)}),replace:(n,o,i)=>A(n,o,"update",a=>a.replace(n,o,i),a=>({...i,_creationTime:i._creationTime??a._creationTime,_id:a._id})),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},rank(n,o,i){return C(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return C(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new p("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...ne("rankBefore",ge,n=>(o,i,a)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,i,a))),...ne("rankPageRows",be,n=>(o,i,a)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,a)))};if(c.size>0)for(const[n,o]of Object.entries(e))ot(o)&&Re(k,n);return Object.defineProperty(k,pe,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),k},we=e=>typeof e=="string"?e:e.name,it=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>we(s))));return t},ct=(e,t)=>{const r=new Set;for(const s of e)for(const c of t.get(s)??[])r.add(c);return s=>r.has(we(s))},at=["roles","role"],lt=e=>{for(const t of at){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(c=>typeof c=="string"&&c.length>0);if(s.length>0)return s}}return[]},ft=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...lt(r),...e.roles??[]])];return{can:ct(s,t),identity:r,roles:s,userId:e.userId??null}},bt=(e,t={})=>{const r=e,s=Qe(r),c=it(t.roles);return Ae(async({ctx:u,next:g})=>{const y=u,b={auth:await ft(y.auth??{},c),ctx:y},W=y.db,_=Ke(W),Y=_?.base??W,A=_?.raw??W[He]??W,M=st(Y,A,[..._?.steps??[],{context:b,perTable:s}]),L={db:M},{orm:$}=y;return $!==null&&typeof $=="object"&&(L.orm=Ee(M)),g({ctx:L})},[{policies:r,roles:t.roles??[]}])};export{ft as a,ot as b,gt as c,me as d,lt as e,Xe as f,ct as g,Ze as h,it as i,q as m,ne as o,bt as r};
@@ -1 +1 @@
1
- import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-D4Z_QWhU.mjs";import"./bindOrm-D5mVDvbi.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
1
+ import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-CdoC33P7.mjs";import"./bindOrm-D5mVDvbi.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-D4Z_QWhU.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-CdoC33P7.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1 +1 @@
1
- import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-D4Z_QWhU.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-CdoC33P7.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.266",
3
+ "version": "1.0.0-alpha.268",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -73,9 +73,9 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
76
- "@lunora/scheduler": "1.0.0-alpha.168",
77
- "@lunora/shard-engine": "1.0.0-alpha.185",
78
- "@lunora/values": "1.0.0-alpha.94",
76
+ "@lunora/scheduler": "^1.0.0-alpha.169",
77
+ "@lunora/shard-engine": "^1.0.0-alpha.187",
78
+ "@lunora/values": "^1.0.0-alpha.95",
79
79
  "@lunora/wire": "1.0.0-alpha.6",
80
80
  "drizzle-orm": "1.0.0-rc.5",
81
81
  "hono": "^4.13.13"
@@ -1 +0,0 @@
1
- import{LunoraError as S,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as w}from"@lunora/values";import{Hono as j}from"hono";import{httpRouter as A,httpAction as E}from"./httpAction-DuAVtPa_.mjs";const C="/_lunora/live/connect",g="/_lunora/live/control",N="room:",D="__lunora_socket__:",B=256,v=e=>`/live/${e}/connect`,m=e=>`/live/${e}/control`,K=/^[A-Za-z]\w*$/u,T=e=>K.test(e),U=e=>`${e}:`.startsWith(N)||`${e}:`.startsWith(D),k=(e,t,r)=>[e,...t.map(a=>{const i=r[a];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${a}`);return encodeURIComponent(i)})].join(":"),V=(e,t)=>{if(e.length>B)return;const[r,...a]=e.split(":");if(r===void 0||!Object.hasOwn(t,r))return;const i=t[r];if(a.length!==i.length)return;const o={};try{for(const[d,u]of i.entries())o[u]=decodeURIComponent(a[d]);return k(r,i,o)===e?{key:o,name:r}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},_=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),H=(e,t)=>{for(const[r,a]of Object.entries(t)){if(!T(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(U(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" would encode into a reserved topic prefix`);for(const[i,o]of Object.entries(a.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a plain identifier`);if(!P(o))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new S("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),X=e=>{H(e.id,e.topics);const t=v(e.id),r=m(e.id),a=Object.fromEntries(Object.entries(e.topics).map(([s,c])=>[s,Object.keys(c.key??{})])),i=s=>{const c=V(s,a),n=c===void 0?void 0:e.topics[c.name];if(!(c===void 0||n===void 0))try{return{declaration:n,key:w(n.key??{},c.key,"key"),name:c.name}}catch{return}},o=(s,c)=>{const n=i(s);if(n===void 0)throw new S("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return w({payload:p.payload},{payload:c},"topic").payload}catch(y){throw z(s,y)}},d=async(s,c)=>{const n=i(c);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:c,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,c)=>{const n=new URL(c.url).searchParams.get("shard")??void 0;return s.fetchShard(n,C,{method:"GET"})}),R=E(async(s,c)=>{const n=await F(c);if(!n)return h("Expected a JSON object body");const{action:p}=n,y=typeof n.topic=="string"?n.topic:void 0;if(y===void 0||y.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const l=typeof n.shardKey=="string"?n.shardKey:void 0,L=l===void 0?s:{...s,...s.forShard(l)};if(p==="subscribe"&&!await d(L,y))return _(y);const b=s.fetchShard(l,g,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return b;try{return await b}catch(f){if(I(f)&&f.code==="FORBIDDEN_SHARD")return _(y);throw f}});return{connect:u,connectPath:t,control:R,controlPath:r,id:e.id,topics:e.topics,validatePublish:o}},M=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},$=new WeakSet,O=(e,t)=>{for(const r of t){let a;const i=()=>(a??=r.load().catch(o=>{throw a=void 0,o}),a);e.get(v(r.id),async o=>{const{connect:d}=await i();return d(o)}),e.post(m(r.id),async o=>{const{control:d}=await i();return d(o)})}},q=(e,t)=>{if(t instanceof j)return $.has(t)||(O(t,e),$.add(t)),t;const r=A();if(O(r,e),t===void 0)return r;const a=new Set(e.flatMap(o=>[`GET ${v(o.id)}`,`POST ${m(o.id)}`])),i=(o,d,u)=>typeof t=="function"?t(o,d,u):t.fetch(o,d,u);return{...M(t),fetch:(o,d,u)=>a.has(`${o.method} ${new URL(o.url).pathname}`)?r.fetch(o,d,u):i(o,d,u)}};export{X as defineLiveStream,q as liveStreamRouter};
@@ -1 +0,0 @@
1
- import{LunoraError as E,toErrorBody as T,isLunoraError as L}from"@lunora/errors";import{parseValidatorMap as w,ValidationError as q}from"@lunora/values";import{encodeWire as v}from"@lunora/wire";import{Hono as C}from"hono";import{SSE_HEADERS as S,sseFrame as b,isSafeHeaderValue as H}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const $=e=>async r=>e(r.get("lunora"),r.req.raw),z=()=>{const e=new C;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},I=(e,r,o)=>{const n=O(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=n._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},A=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=I(t,r,n))}return w(e,o,"searchParams")},N=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const i=o[t];n[t]=i===void 0?void 0:g(O(a).kind,i)}return w(e,n,"params")},D=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return w(e,o,"body")},j=e=>{if(e instanceof q)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(L(e)){const{body:r,redacted:o,status:n}=T(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},P=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},x=(e,r)=>async o=>{const n=P(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?A(e.searchParams,o):{},i=Object.keys(e.params).length>0?N(e.params,o):{},d=Object.keys(e.body).length>0?await D(e.body,o):{},h=await r({body:d,ctx:t,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const y=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:y?c:void 0,status:204}):Response.json(s,{headers:y?c:void 0})}catch(t){return j(t)}},K=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},_=Symbol.for("@lunora/server/sse-event"),X=e=>({[_]:!0,data:e.data,id:e.id}),B=e=>typeof e=="object"&&e!==null&&e[_]===!0,V=(e,r)=>{if(B(r)){if(!H(r.id))throw new E("INTERNAL","sseEvent id must not contain CR, LF or NUL");const o=e?R(e,r.data):r.data;return b(v(o),void 0,r.id)}return b(v(e?R(e,r):r))},M=(e,r)=>(async o=>{const n=P(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?A(e.searchParams,o):{},a=Object.keys(e.params).length>0?N(e.params,o):{}}catch(m){return j(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:S});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const y=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:t,signal:s.signal});for await(const p of f){if(s.signal.aborted)break;m.enqueue(h.encode(V(e.output,p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:p,redacted:k}=T(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});k&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(y,{headers:S})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>x(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>M(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Y={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{$ as httpAction,Y as httpRoute,z as httpRouter,H as isSafeHeaderValue,K as lastEventId,X as sseEvent};
@@ -1 +0,0 @@
1
- import{LunoraError as p,isLunoraError as be}from"@lunora/errors";import{findRelated as Oe,whereFilter as ve}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as We,bindOrm as Re}from"./bindOrm-D5mVDvbi.mjs";import{t as Ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ae}from"./allowAll-DkRAgItV.mjs";const G=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},te=4;class P extends Error{}const x=e=>e.includes("."),wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ie=e=>{const t=e.split(".");if(t.length>te||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(te)} non-empty segments`);return t},Be=(e,t)=>{if(!x(t))return e[t];let r=e;for(const s of ie(t)){if(!G(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ce=(e,t,r,s)=>{const[c,...f]=t;if(c===void 0)throw new P(`field path "${s}" is empty`);if(e!=null&&!G(e))throw new P(`cannot set "${s}": "${c}" sits inside a value that is not an object`);const u=e??{};return{...u,[c]:f.length===0?r:ce(u[c],f,r,s)}},Se=(e,t)=>{const r=Object.keys(e).filter(c=>x(c));if(r.length===0)return e;for(const c of r){const f=r.find(u=>u!==c&&u.startsWith(`${c}.`));if(f!==void 0)throw new P(`patch sets both "${c}" and "${f}", which overlap; set one or the other`)}const s={};for(const[c,f]of Object.entries(e))x(c)||(s[c]=f);for(const c of r){const[f="",...u]=ie(c);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${c}"; set one or the other`);s[f]=ce(Object.hasOwn(s,f)?s[f]:t[f],u,e[c],c)}return s},Te=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ke=["every","is","isNot","none","some"],Ie=new Set(ke),Pe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Ie.has(r))},ne=(e,t,r)=>t?{[e]:r(t)}:{},ae=500,z=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ae},H=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},J={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const le=e=>{if(!G(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(J,r)))return{operand:e[r],operator:r}},me=e=>le(e)!==void 0,_e=(e,t,r,s)=>{const c=J[t];if(c.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const f=c.apply(s,r);if(!Number.isFinite(f))throw new R(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},fe=(e,t)=>{const r=new Set;for(const[s,c]of Object.entries(e))t(s)!==void 0&&me(c)&&r.add(s);return r},$e=(e,t,r)=>{let s;for(const c of fe(e,r)){const{operand:f,operator:u}=le(e[c]),g=r(c);if(J[u].kind!==g)throw new R(`patch: "${u}" does not apply to the ${String(g)} column "${c}".`);s??={...e},s[c]=_e(c,u,f,t[c])}return s??e},De=(e,t)=>{const r=c=>{const f=t[c];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},s={...e};for(const c of fe(e,r))try{Object.assign(s,$e({[c]:e[c]},t,r))}catch(f){if(!(f instanceof R))throw f}try{return Se(s,t)}catch(c){if(c instanceof P)return s;throw c}},Fe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,S=0,E=1,m=e=>e?E:B,w=(e,t)=>e<t?e:t,Me=(e,t)=>e>t?e:t,de=e=>e===S?S:m(e===B),re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Le={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},je=(e,t,r)=>{let s=E;for(const c of["gt","gte","lt","lte"]){if(!(c in r))continue;const f=r[c];F(e,c,f);const u=x(e);if(u?Te(f)===void 0:!re(f))s=w(s,B);else if(T(t))s=w(s,S);else{const g=Le[c],y=u?typeof t==typeof f:re(t);s=w(s,m(y&&g(t,f)))}}return s},oe=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},se=(e,t)=>t.length===0?B:T(e)?S:t.includes(e)?E:t.some(r=>T(r))?S:B,Ce=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,se(t,oe(e,"in",r.in)))),"notIn"in r&&(s=w(s,de(se(t,oe(e,"notIn",r.notIn))))),"contains"in r){const c=r.contains;F(e,"contains",c),s=T(t)?w(s,S):w(s,m(typeof t=="string"&&typeof c=="string"&&t.includes(c)))}return"isNull"in r&&(s=w(s,m(r.isNull===!0===T(t)))),s},K=(e,t,r)=>t===null?m(r===T(e)):T(e)?S:m(r===(e===t)),Ue=(e,t,r)=>{let s=E;return"eq"in r&&(F(e,"eq",r.eq),s=w(s,K(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),s=w(s,K(t,r.ne,!1))),s},xe=(e,t,r)=>w(Ue(e,t,r),w(Ce(e,t,r),je(e,t,r))),Ne=(e,t,r,s)=>{if(t==="NOT")return de(s(e,r??{}));if(!Array.isArray(r))return B;let c=t==="AND"?E:B;for(const f of r){const u=s(e,f);c=t==="AND"?w(c,u):Me(c,u)}return c},ue=e=>e==="AND"||e==="OR"||e==="NOT",qe=e=>X(e)&&Object.keys(e).every(t=>Fe.includes(t)),N=e=>Object.keys(e).some(t=>{const r=e[t];return ue(t)?t==="NOT"?N(r??{}):Array.isArray(r)&&r.some(s=>N(s??{})):Pe(r)}),he=(e,t)=>{let r=E;for(const s of Object.keys(t)){const c=t[s];if(ue(s)){r=w(r,Ne(e,s,c,he));continue}const f=Be(e,s);if(qe(c)){r=w(r,xe(s,f,c));continue}F(s,"eq",c),r=w(r,K(f,c,!0))}return r},q=(e,t)=>he(e,t)===E,I=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{H(e,z(t,r,I),r,I)},Ye=Ae(),ze=Symbol.for("lunora.ctxdb.rls-unwrap"),ye=Symbol.for("lunora.rls.wrapped-chain"),He=e=>e[ye],Ke=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Qe=(e,t)=>{const r=[];let s=!1;for(const c of e){if(c.on!=="read")continue;const f=c.when(t);if(f!==void 0){if(f===!0){s=!0;break}f!==!1&&r.push(f)}}if(!s)return r.length===0?Ye:r.length===1?r[0]:{OR:r}},Xe=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Ge=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Xe(e,t,r);if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Je=(e,t,r,s)=>{let c=!1;for(const f of e)if(f.on===t&&(c=!0,!Ge(f,r,s)))return!1;return c},Ze=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ve=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),et=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ze.has(r)&&Ve(r,e[r]))},tt=e=>e===void 0?{}:X(e)&&et(e)?e:{where:e},Q=e=>e!==void 0&&Object.keys(e).length>0,nt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>Q(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,rt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ot=(e,t,r)=>{const[s]=r,c=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const i=[];let a=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;a=!0;const O=Qe(h,d.context);O!==void 0&&i.push(O)}const l={baseWhere:nt(i),restricts:a};return f.set(n,l),l},g=(n,o,i,a)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!Je(d,o,{...l.context,row:i},a))return!1}return!0},y=n=>u(n).restricts?t:e,b=n=>u(n).baseWhere,W=async(n,o)=>{const i=await t.get(n,o);return i?{row:i,tableName:c.has(n)?n:void 0}:{row:null,tableName:void 0}},_=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:c.has(l.tableName)?l.tableName:void 0}}const o=[...c.keys()],a=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return a?{row:a.row,tableName:a.tableName}:{row:null,tableName:void 0}},Y=async(n,o)=>{const i=await W(n,o);return i.row&&i.tableName!==void 0?{row:i.row,tableName:i.tableName}:void 0},A=async(n,o,i,a,l)=>{const d=await Y(n,o);if(!d)return a(e);const h=l?l(d.row):void 0;if(!g(d.tableName,i,d.row,h))throw new p("FORBIDDEN",`${i} denied by policy`);return a(t,d.tableName)},M=(n,o,i)=>{if(i?.hard===!0)return!1;const a=e.softDeleteFields?.get(n);return a!==void 0&&o[a]!==null&&o[a]!==void 0},L=async(n,o,i,a,l)=>{const d=i?t:e,h=await d.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...a?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:v(l,{_id:n})});if(!h||M(o,h,a))return!1;if(i&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,a),!0},$=async(n,o,i,a)=>{const l=c.has(n),d=l?t:e,h=i===void 0?void 0:{hard:i},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const V of o){const ee=String(V._id);if(O){await L(ee,n,l,h,a)&&(D+=1);continue}if(l&&!g(n,"delete",V))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ee,h),D+=1}return D},j=(n,o,i,a)=>A(n,o,"update",(l,d)=>a(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...De(i,l)})),C=(n,o)=>{const{baseWhere:i}=u(n);if(Q(i))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},we=e.rankBefore,ge=e.rankPageRows,{relationEdges:Z}=e,k={...e,async count(n,o){const{baseWhere:i}=u(n),a=tt(o);return y(n).count(n,{...a,baseWhere:v(a.baseWhere,i),relationBaseWhere:b,restrictsCounts:(a.restrictsCounts??!1)||Q(i)})},delete:(n,o,i)=>A(n,o,"delete",a=>a.delete(n,o,i)),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??ae),{baseWhere:a}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:a,limit:i,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await $(n,h,o?.hard),h.length<i))break}return{deleted:l}},async deleteMany(n,o,i){U(o.length,i?.limit,"deleteMany");for(const a of o)await A(n,a,"delete",l=>l.delete(n,a));return{deleted:o.length}},async deleteWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"deleteWhere",I),d=await y(n).findMany(n,{baseWhere:v(o,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return H(h.length,l,"deleteWhere",I),{deleted:await $(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async get(n,o){const i=await W(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:a,restricts:l}=u(i.tableName);if(!l)return e.get(n,o);if(!a)return i.row;const d=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const i=o===void 0?await _(n):await W(o,n);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:a}=u(i.tableName);if(!a)return{row:i.row,tableName:i.tableName};const l=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:i.tableName}:null},async insert(n,o,i){if(c.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(U(o.length,i?.limit,"insertMany"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(U(o.length,i?.limit,"insertManyUnsafe"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i,a)=>j(n,o,i,(l,d)=>l.patch(n,o,i,{...a,...d})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,i){const a=await j(n,o,i.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...i,verify:h.verify})});return a.doc===null||await k.get(n,o).then(d=>d!==null,d=>{if(be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?a:{applied:a.applied,doc:null}},async patchMany(n,o,i){U(o.length,i?.limit,"patchMany");for(const a of o)await j(n,a.id,a.patch,(l,d)=>l.patch(n,a.id,a.patch,d));return{patched:o.length}},async patchWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"patchWhere",I),h=(await y(n).findMany(n,{baseWhere:v(o.where,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return H(h.length,l,"patchWhere",I),k.patchMany(n,h,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(ve(o,a=>q(a,o))):i},related:Z===void 0?void 0:async(n,o)=>Oe({findMany:async(i,a)=>k.findMany(i,a),lookupById:async i=>t.lookupById?.(i)},Z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,o,"update",async i=>{const a=i.restore??t.restore;if(!a)throw new p("BAD_REQUEST","restore is not supported by this writer");await a(n,o)}),replace:(n,o,i)=>A(n,o,"update",a=>a.replace(n,o,i),a=>({...i,_creationTime:i._creationTime??a._creationTime,_id:a._id})),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},rank(n,o,i){return C(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return C(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new p("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...ne("rankBefore",we,n=>(o,i,a)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,i,a))),...ne("rankPageRows",ge,n=>(o,i,a)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,a)))};if(c.size>0)for(const[n,o]of Object.entries(e))rt(o)&&We(k,n);return Object.defineProperty(k,ye,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),k},pe=e=>typeof e=="string"?e:e.name,st=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>pe(s))));return t},it=(e,t)=>{const r=new Set;for(const s of e)for(const c of t.get(s)??[])r.add(c);return s=>r.has(pe(s))},ct=["roles","role"],at=e=>{for(const t of ct){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(c=>typeof c=="string"&&c.length>0);if(s.length>0)return s}}return[]},lt=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...at(r),...e.roles??[]])];return{can:it(s,t),identity:r,roles:s,userId:e.userId??null}},gt=(e,t={})=>{const r=e,s=Ke(r),c=st(t.roles);return Ee(async({ctx:u,next:g})=>{const y=u,b={auth:await lt(y.auth??{},c),ctx:y},W=y.db,_=He(W),Y=_?.base??W,A=_?.raw??W[ze]??W,M=ot(Y,A,[..._?.steps??[],{context:b,perTable:s}]),L={db:M},{orm:$}=y;return $!==null&&typeof $=="object"&&(L.orm=Re(M)),g({ctx:L})},[{policies:r,roles:t.roles??[]}])};export{lt as a,rt as b,wt as c,Pe as d,at as e,Qe as f,it as g,Je as h,st as i,q as m,ne as o,gt as r};