@lunora/server 1.0.0-alpha.284 → 1.0.0-alpha.286
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/in-process.mjs +1 -1
- package/dist/index.d.mts +11 -2
- package/dist/index.d.ts +11 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-C09SMvM4.mjs → assertShapesDeclareReadPolicies-CVZ3SP5D.mjs} +1 -1
- package/dist/packem_shared/bindOrm-B0BYm2iu.mjs +1 -0
- package/dist/packem_shared/{defineLiveStream-q9yO3wl6.mjs → defineLiveStream-D3xRvNDy.mjs} +1 -1
- package/dist/packem_shared/{defineShape-H-0IbZlb.mjs → defineShape-Kr_MEOEl.mjs} +1 -1
- package/dist/packem_shared/httpAction-DD8h1jcf.mjs +1 -0
- package/dist/packem_shared/mask-Bh3f0uJN.mjs +1 -0
- package/dist/packem_shared/middleware-vDNQHKyX.mjs +1 -0
- package/dist/packem_shared/rls-OyCwu5L5.mjs +1 -0
- package/dist/packem_shared/storageRules-CeEfxxVa.mjs +1 -0
- package/dist/rls/testing.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/bindOrm-D5mVDvbi.mjs +0 -1
- package/dist/packem_shared/httpAction-Bfw3qwLG.mjs +0 -1
- package/dist/packem_shared/mask-ocdNb1L3.mjs +0 -1
- package/dist/packem_shared/middleware-CHYtnvZP.mjs +0 -1
- package/dist/packem_shared/rls-CvWnjgtq.mjs +0 -1
- package/dist/packem_shared/storageRules-BVIXkoRg.mjs +0 -1
package/dist/in-process.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{TransactionHeadroomTracker as l,runShardMigrations as p,createShardCtxDb as w,RLS_UNWRAP_SYMBOL as T}from"@lunora/shard-engine";import{beginDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{bindTableFacade as S}from"./packem_shared/bindOrm-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{TransactionHeadroomTracker as l,runShardMigrations as p,createShardCtxDb as w,RLS_UNWRAP_SYMBOL as T}from"@lunora/shard-engine";import{beginDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{bindTableFacade as S}from"./packem_shared/bindOrm-B0BYm2iu.mjs";class y extends l{fallback=new l;scope;constructor(r){super(),this.scope=r}run(r){return this.scope===void 0?(this.fallback=new l,r()):this.scope.run(new l,r)}headroom(){return this.current().headroom()}recordRead(r){this.current().recordRead(r)}recordReadBytes(r){this.current().recordReadBytes(r)}recordDocumentRead(r,n){this.current().recordDocumentRead(r,n)}recordWrite(r){this.current().recordWrite(r)}current(){return this.scope?.getStore()??this.fallback}}const C=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...n}=e;return{claims:Object.keys(n).length>0?n:null,userId:r}},O=(e,r)=>{const{scheduler:n,sql:a}=r,i=e;p(a,i);const c=new y(r.headroomScope),m=t=>{const o=t;for(const s of Object.keys(i.tables))o[s]=S(t,s);return t};let u=!1;const I=t=>{const o=w({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),s=o[T]??o;return{database:m(o),rawDatabase:m(s)}},d=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:I,runWithBudget:t=>c.run(t),runInTransaction:t=>{const o=async()=>{const b=g({scheduler:n});d("BEGIN"),u=!0;try{const h=await t();return d("COMMIT"),u=!1,await b(!0),h}catch(h){u=!1;try{d("ROLLBACK")}catch{}throw await b(!1),h}},s=f.then(()=>c.run(o));return f=s.then(()=>{},()=>{}),s}}},k=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},P=(e,r,n,a,i)=>{const c=k(r);if(c!==e)throw new R("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new R("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(n,a??{}))};export{O as createInProcessRuntime,k as registeredFunctionKind,C as resolveInProcessIdentity,P as runRegisteredFunction};
|
package/dist/index.d.mts
CHANGED
|
@@ -1921,7 +1921,7 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
|
1921
1921
|
*/
|
|
1922
1922
|
declare const isSafeHeaderValue: (value: string) => boolean;
|
|
1923
1923
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1924
|
-
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1924
|
+
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "QUERY";
|
|
1925
1925
|
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1926
1926
|
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1927
1927
|
/**
|
|
@@ -2214,6 +2214,7 @@ interface HttpRoute {
|
|
|
2214
2214
|
patch: HttpRouteFactory;
|
|
2215
2215
|
post: HttpRouteFactory;
|
|
2216
2216
|
put: HttpRouteFactory;
|
|
2217
|
+
query: HttpRouteFactory;
|
|
2217
2218
|
}
|
|
2218
2219
|
/**
|
|
2219
2220
|
* Read the SSE resume position off a request: the `Last-Event-ID` header a
|
|
@@ -2283,9 +2284,17 @@ declare const sseEvent: <R>(frame: {
|
|
|
2283
2284
|
* .params({ id: v.string() })
|
|
2284
2285
|
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
2285
2286
|
*
|
|
2287
|
+
* // QUERY (RFC 10008) is a safe, idempotent read whose filter travels as a typed
|
|
2288
|
+
* // JSON body instead of strings in the URL. Hono has no `app.query`, so mount it with `on`.
|
|
2289
|
+
* export const searchTodos = httpRoute
|
|
2290
|
+
* .query("/api/todos/search")
|
|
2291
|
+
* .body({ done: v.boolean(), limit: v.number() })
|
|
2292
|
+
* .handler(async ({ ctx, body }) => ctx.runQuery(api.todos.search, body));
|
|
2293
|
+
*
|
|
2286
2294
|
* const app = httpRouter();
|
|
2287
2295
|
* app.get("/api/todos", listTodos);
|
|
2288
2296
|
* app.get("/api/todos/:id", getTodo);
|
|
2297
|
+
* app.on("QUERY", "/api/todos/search", searchTodos);
|
|
2289
2298
|
* ```
|
|
2290
2299
|
*/
|
|
2291
2300
|
declare const httpRoute: HttpRoute;
|
|
@@ -3085,7 +3094,7 @@ interface DatabaseWriterLike {
|
|
|
3085
3094
|
*/
|
|
3086
3095
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
|
|
3087
3096
|
/**
|
|
3088
|
-
* Relation-graph traversal. Declared so the
|
|
3097
|
+
* Relation-graph traversal. Declared so the copied `base` entries' shape is
|
|
3089
3098
|
* typed, but never CALLED by the wrapper: the walk it performs is bound to
|
|
3090
3099
|
* whatever writer this closure came from, and the wrapper has to route each
|
|
3091
3100
|
* hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
|
package/dist/index.d.ts
CHANGED
|
@@ -1921,7 +1921,7 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
|
1921
1921
|
*/
|
|
1922
1922
|
declare const isSafeHeaderValue: (value: string) => boolean;
|
|
1923
1923
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1924
|
-
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1924
|
+
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "QUERY";
|
|
1925
1925
|
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1926
1926
|
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1927
1927
|
/**
|
|
@@ -2214,6 +2214,7 @@ interface HttpRoute {
|
|
|
2214
2214
|
patch: HttpRouteFactory;
|
|
2215
2215
|
post: HttpRouteFactory;
|
|
2216
2216
|
put: HttpRouteFactory;
|
|
2217
|
+
query: HttpRouteFactory;
|
|
2217
2218
|
}
|
|
2218
2219
|
/**
|
|
2219
2220
|
* Read the SSE resume position off a request: the `Last-Event-ID` header a
|
|
@@ -2283,9 +2284,17 @@ declare const sseEvent: <R>(frame: {
|
|
|
2283
2284
|
* .params({ id: v.string() })
|
|
2284
2285
|
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
2285
2286
|
*
|
|
2287
|
+
* // QUERY (RFC 10008) is a safe, idempotent read whose filter travels as a typed
|
|
2288
|
+
* // JSON body instead of strings in the URL. Hono has no `app.query`, so mount it with `on`.
|
|
2289
|
+
* export const searchTodos = httpRoute
|
|
2290
|
+
* .query("/api/todos/search")
|
|
2291
|
+
* .body({ done: v.boolean(), limit: v.number() })
|
|
2292
|
+
* .handler(async ({ ctx, body }) => ctx.runQuery(api.todos.search, body));
|
|
2293
|
+
*
|
|
2286
2294
|
* const app = httpRouter();
|
|
2287
2295
|
* app.get("/api/todos", listTodos);
|
|
2288
2296
|
* app.get("/api/todos/:id", getTodo);
|
|
2297
|
+
* app.on("QUERY", "/api/todos/search", searchTodos);
|
|
2289
2298
|
* ```
|
|
2290
2299
|
*/
|
|
2291
2300
|
declare const httpRoute: HttpRoute;
|
|
@@ -3085,7 +3094,7 @@ interface DatabaseWriterLike {
|
|
|
3085
3094
|
*/
|
|
3086
3095
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
|
|
3087
3096
|
/**
|
|
3088
|
-
* Relation-graph traversal. Declared so the
|
|
3097
|
+
* Relation-graph traversal. Declared so the copied `base` entries' shape is
|
|
3089
3098
|
* typed, but never CALLED by the wrapper: the walk it performs is bound to
|
|
3090
3099
|
* whatever writer this closure came from, and the wrapper has to route each
|
|
3091
3100
|
* hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
|
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-Dv4DKrj0.mjs";import{authorize as s}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as D,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as _,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as b,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as N}from"./packem_shared/bindOrm-
|
|
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-Dv4DKrj0.mjs";import{authorize as s}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as D,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as _,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as b,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as N}from"./packem_shared/bindOrm-B0BYm2iu.mjs";import{httpAction as H,httpRoute as k,httpRouter as w,lastEventId as B,sseEvent as V}from"./packem_shared/httpAction-DD8h1jcf.mjs";import{serveStorageObject as j}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as $,DEFAULT_MAX_LIMIT as ee,clampLimit as re,defineListArgs as oe}from"./packem_shared/DEFAULT_LIMIT-z7HB19s7.mjs";import{defineLiveStream as ie,liveStreamRouter as ne}from"./packem_shared/defineLiveStream-D3xRvNDy.mjs";import{defineMigration as ae}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as pe}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as ce}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as Ee,d as ue,a as Se,b as he,e as De,f as Te,g as Re,h as Ae,i as ge,j as Le,k as _e,m as Ie}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Me,PRESENCE_TABLE as Pe,definePresence as be,presenceExtension as ye}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs";import{PROCEDURE_META as Fe,UNLOADED_META as ve,procedureMeta as Ne}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as He}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as we}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ve}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as je}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-Kr_MEOEl.mjs";import{defineWebSocket as Je}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Qe}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as qe}from"@lunora/errors";import{cronJobs as $e}from"@lunora/scheduler";import{ValidationError as rr,v as or}from"@lunora/values";import{allowAll as ir,deny as nr,isDeny as fr,toWhereInput as ar}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as sr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as pr,buildRlsReadRegistry as xr,composeShapeReadWhere as cr}from"./packem_shared/assertShapesDeclareReadPolicies-CVZ3SP5D.mjs";import{buildMaskRegistry as Er}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Sr,definePermission as hr,definePolicies as Dr,definePolicy as Tr,defineRole as Rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as gr,defineStorageRules as Lr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Ir}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Mr}from"./packem_shared/mask-Bh3f0uJN.mjs";import{r as br}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as Or}from"./packem_shared/middleware-vDNQHKyX.mjs";import{storageRules as vr}from"./packem_shared/storageRules-CeEfxxVa.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,$ as DEFAULT_LIMIT,ee as DEFAULT_MAX_LIMIT,_ as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,b as LunoraEnvError,qe as LunoraError,Me as PRESENCE_DEFAULT_TTL_MS,Pe as PRESENCE_TABLE,Fe as PROCEDURE_META,ve as UNLOADED_META,e as VERSION,rr as ValidationError,n as actionCacheExtension,ir as allowAll,sr as asBucketStorage,pr as assertShapesDeclareReadPolicies,s as authorize,h as beginDeferredDeletes,A as beginDeferredSchedules,F as bindOrm,v as bindTableFacade,Er as buildMaskRegistry,xr as buildRlsReadRegistry,f as cacheKeyFor,re as clampLimit,Ee as composePluginMiddleware,cr as composeShapeReadWhere,Sr as createPolicyDsl,u as createSecrets,je as createServices,$e as cronJobs,a as defineActionCache,ue as defineAggregateIndex,Se as defineComponent,C as defineDocumentHistory,y as defineEnv,Y as defineIdentity,J as defineIdentityGuard,N as defineLazyFacade,oe as defineListArgs,ie as defineLiveStream,ae as defineMigration,se as defineModule,pe as defineMutator,hr as definePermission,he as definePlugin,Dr as definePolicies,Tr as definePolicy,be as definePresence,De as defineRankIndex,Rr as defineRole,Ve as defineRoom,Te as defineSchema,Re as defineSchemaExtension,Ye as defineShape,gr as defineStorageRule,Lr as defineStorageRules,Ae as defineTable,ge as defineVectorIndex,Je as defineWebSocket,nr as deny,M as documentHistoryExtension,D as flushDeferredDeletes,H as httpAction,k as httpRoute,w as httpRouter,Le as indexFieldsFromSchema,p as initLunora,_e as installPlugins,fr as isDeny,c as isPerDispatchMiddleware,Ir as isSafeHeaderValue,B as lastEventId,ne as liveStreamRouter,Mr as mask,Ie as mergeSchemaExtension,Q as onConnect,X as onDisconnect,we as onQueryChange,q as onShardInit,Qe as onWhisper,ce as platformAdmin,ye as presenceExtension,Ne as procedureMeta,He as protectPublic,br as redactSecrets,Or as rls,j as serveStorageObject,V as sseEvent,vr as storageRules,l as tagPerDispatchMiddleware,ar as toWhereInput,or as v,T as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,e as b,f as y}from"./middleware-vDNQHKyX.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]},A=(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})},S=(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=A(n,e);if(s!==void 0){if(d(s))return h;o.push(s)}}if(o.length!==0)return o.length===1?o[0]:{AND:o}},W=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}},$=(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: []\`.`)},B=(t,e)=>T(S(t,e),e.shapeWhere);export{$ as assertShapesDeclareReadPolicies,W as buildRlsReadRegistry,B as composeShapeReadWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{isPlainObject as k}from"@lunora/wire";const P=new Set(["connect","disconnect","set"]),p=500,E=(t,n,o)=>t!==void 0&&Object.hasOwn(t,n)&&k(o),b=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new y(t,n)},R=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const o=[...new Set(t)];return o.length>p&&u("VALIDATION_ERROR",`${n} names ${String(o.length)} rows; at most ${String(p)} per list`),o},T=(t,n,o)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${o}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},W=(t,n,o)=>{const{connect:e,disconnect:s,set:c}=o;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&s!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(s!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),T(t,n,"disconnect"),{info:n,name:t})},I=(t,n,o)=>{n.through===void 0&&T(t,n,o)},F=(t,n,o)=>{const{connect:e,disconnect:s,set:c}=o;if(c!==void 0)return(e!==void 0||s!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),I(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:R(c,`${t}.set`)};s!==void 0&&I(t,n,"disconnect");const a=e===void 0?[]:R(e,`${t}.connect`),r=s===void 0?[]:R(s,`${t}.disconnect`),i=a.find(d=>r.includes(d));return i!==void 0&&u("VALIDATION_ERROR",`${t}: "${i}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},U=(t,n,o,e)=>{const s=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(s).find(r=>!P.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(s).length===0)return;const a=o.refusal??o.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),o.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${o.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),o.kind==="one"?W(n,o,s):F(n,o,s)},V=t=>t.info.kind==="one",L=(t,n,o)=>{if(n===void 0)return{columns:o,manys:[],ones:[]};const e={},s=[],c=[];for(const[a,r]of Object.entries(o)){if(!E(n,a,r)){e[a]=r;continue}const i=U(t,a,n[a],r);i!==void 0&&(V(i)?c.push(i):s.push(i))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:s,ones:c}},w=(t,n,o,e)=>{const s=Object.entries(o).find(([c,a])=>E(n,c,a))?.[0];s!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${s}" is a relation write, which ${e} does not support; use insert or patch`)},O=async(t,n,o,e,s)=>{const c=await t.get(e,s);return c===null&&u("NOT_FOUND",`${n}.${o}: no "${e}" row with id "${s}"`),c},_=async(t,n)=>{const o={...n.columns};for(const{connect:e,info:s,name:c}of n.ones){let a=null;e!==void 0&&(a=(await O(t,c,"connect",s.table,e))[s.references]),o[s.field]=a}return o},C=async(t,{info:n,name:o},e,s)=>{(await O(t,o,"connect",n.table,e))[n.field]!==s&&await t.patch(n.table,e,{[n.field]:s})},q=async(t,{info:n},o,e)=>{o[n.field]===e&&await t.patch(n.table,String(o._id),{[n.field]:null})},m=async(t,{info:n,name:o},e)=>{const{page:s}=await t.findMany(n.table,{limit:p+1,where:{[n.field]:e}});return s.length>p&&u("VALIDATION_ERROR",`${o}.set: the relation already holds more than ${String(p)} rows; disconnect in batches first`),s},S=(t,n)=>{const o=new Set(t),e=new Set(n);return{attach:n.filter(s=>!o.has(s)),release:new Set(t.filter(s=>!e.has(s)))}},$=async(t,{name:n},{from:o,table:e,to:s},c,a)=>{const r=a===void 0?{[o]:c}:{[o]:c,[s]:{in:a}},{page:i}=await t.findMany(e,{limit:p+1,where:r});return i.length>p&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(p)} rows; disconnect in batches first`),i},B=async(t,n,o)=>{if(o.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:o.length,where:{_id:{in:o}}});return new Set(e.map(s=>String(s._id)))},z=async(t,n,o)=>{const{info:e,name:s}=n,{from:c,table:a,to:r}=e.through;let i,d;if(n.replace===void 0){await Promise.all(n.release.map(h=>O(t,s,"disconnect",e.table,h))),d=n.release.length===0?[]:await $(t,n,e.through,o,n.release);const l=n.attach.length===0?[]:await $(t,n,e.through,o,n.attach),f=new Set(l.map(h=>String(h[r])));i=n.attach.filter(h=>!f.has(h))}else{const l=await $(t,n,e.through,o,void 0),f=S(l.map(g=>String(g[r])),n.replace),h=await B(t,e.table,[...f.release]);({attach:i}=f),d=l.filter(g=>f.release.has(String(g[r]))&&h.has(String(g[r])))}await Promise.all(i.map(l=>O(t,s,"connect",e.table,l)));for(const l of d)await t.delete(a,String(l._id));for(const l of i)try{await t.insert(a,{[c]:o,[r]:l})}catch(f){if(!b(f)||!e.pairIsOnlyUnique)throw f}},G=async(t,n,o)=>{let{attach:e}=n,s;if(n.replace===void 0)s=await Promise.all(n.release.map(c=>O(t,n.name,"disconnect",n.info.table,c)));else{const c=await m(t,n,o),a=S(c.map(r=>String(r._id)),n.replace);({attach:e}=a),s=c.filter(r=>a.release.has(String(r._id)))}for(const c of s)await q(t,n,c,o);for(const c of e)await C(t,n,c,o)},x=async(t,n,o,e)=>{for(const s of o.manys){const{info:c}=s,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${s.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await z(t,{...s,info:c},r);continue}await G(t,{...s,info:c},r)}},M=(t,n,o,e)=>async s=>s==="_id"?o:Object.hasOwn(e,s)?e[s]:(await t.get(n,o))?.[s],K=async(t,n,o,e,s)=>{const c=L(n,o,e);if(c.ones.length===0&&c.manys.length===0)return s(c.columns);const a=await _(t,c),r=await s(a);return r!==null&&await x(t,n,c,M(t,n,r,a)),r},Q=async(t,n,o,e,s)=>{const c=L(n,o,s);if(c.ones.length===0&&c.manys.length===0){await t.patch(n,e,c.columns);return}const a=await _(t,c);if(Object.keys(a).length>0)await t.patch(n,e,a);else{if(await t.get(n,e)===null)throw new y("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(n,e)}await x(t,n,c,M(t,n,e,a))},X=(t,n,o,e)=>{const s=typeof n=="string"?[n]:n;if(s.length===0)throw new y("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of s){if(!(a in o)){const r=Object.entries(e??{}).find(([i,d])=>d.kind==="one"&&d.field===a&&i in o)?.[0];throw r!==void 0?new y("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new y("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=o[a]}return c},A=t=>({configurable:!0,enumerable:!0,value:t,writable:!0}),D=new WeakSet,j=(t,n,o)=>{const e=()=>{const s=o();return Object.defineProperty(t,n,A(s)),s};D.add(e),Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get:e,set(s){Object.defineProperty(this,n,A(s))}})},H=(t,n)=>{const o=async(i,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,i);try{return await t.insert(n,i)}catch(l){if(b(l))return null;throw l}},e=t.relationWrites?.[n],s=(i,d)=>K(t,n,e,i,l=>o(l,d)),c=(i,d)=>Q(t,n,e,i,d),a=async i=>{const d=i??{},l=await t.findMany(n,{...d,limit:2});if(l.page.length>1)throw new y("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return l.page[0]??null},r=async({create:i,target:d,update:l})=>{const f=X(n,d,i,e),h=await t.findFirst(n,{where:f});return h&&typeof h._id=="string"?(await c(h._id,l??i),{created:!1,id:h._id}):{created:!0,id:await s(i)}};return{aggregate:i=>t.aggregate(n,i),count:i=>t.count(n,i),delete:i=>t.delete(n,i),deleteMany:(i,d)=>{if(Array.isArray(i)){if(t.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(n,i,d)}if(t.deleteWhere===void 0)throw new y("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const l=i;return t.deleteWhere(n,l.where,{limit:l.limit})},exists:async i=>await t.findFirst(n,i===void 0?void 0:{where:i})!==null,explain:i=>t.explain(n,i),findFirst:i=>t.findFirst(n,i),findFirstOrThrow:i=>t.findFirstOrThrow(n,i),findMany:i=>t.findMany(n,i),findUnique:a,get:i=>t.get(n,i),groupBy:i=>t.groupBy(n,i),hardDelete:i=>t.delete(n,i,{hard:!0}),insert:s,insertMany:(i,d)=>{for(const l of i)w(n,e,l,"insertMany");if(t.insertMany===void 0)throw new y("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,i,d)},patch:c,patchMany:(i,d)=>{const l=Array.isArray(i)?i.map(h=>h.values):[i.values];for(const h of l)w(n,e,h,"patchMany");if(Array.isArray(i)){if(t.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(n,i.map(h=>({id:h.id,patch:h.values})),d)}if(t.patchWhere===void 0)throw new y("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=i;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(i,d)=>t.rank(n,i,d),rankPage:(i,d)=>t.rankPage(n,i,d),replace:(i,d)=>(w(n,e,d,"replace"),t.replace(n,i,d)),restore:async i=>{if(!t.restore)throw new y("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(n,i)},upsert:r,upsertMany:async({rows:i,target:d})=>{const l=[];for(const f of i)l.push(await r({create:f.create,target:d,update:f.update}));return l},withGeoIndex:(i,d)=>t.query(n).withGeoIndex(i,d),withSearchIndex:(i,d)=>t.query(n).withSearchIndex(i,d)}},v=(t,n)=>{j(t,n,()=>H(t,n))},J=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const n=t;return typeof n.findMany=="function"&&typeof n.withSearchIndex=="function"},N=(t,n,o)=>{const e=n;for(const s of Reflect.ownKeys(n)){const c=Object.getOwnPropertyDescriptor(n,s);if(c?.enumerable!==!0)continue;const a=Object.hasOwn(t,s);if(typeof s=="string"&&typeof c.get=="function"&&D.has(c.get)){o?v(t,s):a||j(t,s,()=>e[s]);continue}const r=e[s];o&&typeof s=="string"&&J(r)?v(t,s):a||Object.defineProperty(t,s,A(r))}},nn=t=>{const n=o=>{const e=t[o];if(!e)throw new y("INTERNAL",`unknown table: ${o}`);return e};return{delete:(o,e)=>n(o).delete(e),insert:o=>({values:e=>n(o).insert(e)}),query:t,replace:(o,e)=>({with:s=>n(o).replace(e,s)}),update:(o,e)=>({set:s=>n(o).patch(e,s)})}};export{nn as bindOrm,H as bindTableFacade,N as copyDatabaseEntries,v as defineLazyFacade,J as isFacadeEntry};
|
|
@@ -1 +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-
|
|
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-DD8h1jcf.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-
|
|
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-CVZ3SP5D.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 f,isLunoraError as F,toErrorBody as N}from"@lunora/errors";import{ValidationError as M,parseValidatorMap as v}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as C}from"hono";import{SSE_HEADERS as A,sseFrame as R,isSafeHeaderValue as $}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as b}from"./apply-output-C5wZ5EAL.mjs";import{isDevEnvironment as B}from"@lunora/shard-engine";const j=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],W=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,O=e=>W.test(e),V=(e,t,r=[])=>t?.access!==void 0||j.some(n=>e.has(n))||r.some(n=>!O(n)||e.has(n)),Q=e=>{const t=[];let r="",n=!1,o=!1;for(const s of e){if(o)o=!1;else if(n&&s==="\\")o=!0;else if(s==='"')n=!n;else if(s===","&&!n){t.push(r.trim()),r="";continue}r+=s}return t.push(r.trim()),t.filter(s=>s!=="")},J=new Set(["proxy-revalidate","public","s-maxage"]),Y=e=>{const t=Q(e),r=t.map(o=>o.toLowerCase());return r.includes("private")||r.includes("no-store")?e:["private",...t.filter((o,s)=>{const a=(r[s]?.split("=",1)[0]??"").trim();return!J.has(a)&&a!=="private"})].join(", ")},_=new WeakSet,z=e=>{try{return e.executionCtx}catch{return}},G=(e,t)=>[...j,...t].find(r=>e.has(r))??"cloudflare access",K=(e,t,r)=>{const{headers:n}=r.req.raw,o=e.credentialHeaders??[];if(!V(n,z(r),o))return t;const s=Y(t);return s!==t&&!_.has(e)&&B(r.env)&&(_.add(e),console.warn(`[lunora] httpRoute ${e.method} ${e.path}: sent Cache-Control "${s}" instead of the declared "${t}" because the request carries a credential (${G(n,o)}). A shared cache must not store a per-caller response. Further downgrades on this route are not reported.`)),s},g=e=>{if(e instanceof M)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(F(e)){const{body:t,redacted:r,status:n}=N(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message,...t.why===void 0?{}:{why:t.why}},{status:n})}throw e},Ee=e=>async t=>{try{return await e(t.get("lunora"),t.req.raw)}catch(r){return g(r)}},T=new WeakSet,H=new WeakSet,Re=e=>H.has(e),k=new WeakSet,Z=new Set(["*","/*"]),X="__COMPOSED_HANDLER",ee=e=>e[X]??e,te=e=>{let t,r=-1;return async n=>{if(t===void 0||r!==e.routes.length){const s=new C;for(const a of e.routes)k.has(ee(a.handler))||s.on(a.method,a.path,()=>new Response(null,{status:204}));t=s,r=e.routes.length}return(await t.fetch(new Request(n.url,{method:n.method}))).status===204}},be=()=>{const e=new C,t=te(e),r=e.use.bind(e);H.add(e),e.use=((...o)=>{const[s]=o;if(typeof s!="string"||Z.has(s))for(const a of o)typeof a=="function"&&k.add(a);return r(...o)}),e.use("*",async(o,s)=>{const a=o.env.__lunoraCtx;if(!a)throw new f("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",a);const{__lunoraShellFirst:i,__lunoraUnrouted:u}=o.env;if(i===!0&&!await t(o.req.raw))return u?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(T.add(o),c()),await s()});const n=e.notFound;return e.notFound=o=>n(s=>{const{__lunoraUnrouted:a}=s.env;return T.has(s)||a?.(),o(s)}),e.notFound(o=>o.text("404 Not Found",404)),e},P=e=>e.kind==="optional"?e._meta?.inner??e:e,w=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},re=(e,t,r)=>{const n=P(e);if(n.kind==="array"){const s=t.req.queries(r);if(s===void 0)return;const a=n._meta?.inner;return s.map(i=>w(a?.kind??"string",i))}const o=t.req.query(r);return o===void 0?void 0:w(n.kind,o)},D=(e,t)=>{const r={};for(const n of Object.keys(e)){const o=e[n];o&&(r[n]=re(o,t,n))}return v(e,r,"searchParams")},q=(e,t)=>{const r=t.req.param(),n={};for(const o of Object.keys(e)){const s=e[o];if(!s)continue;const a=r[o];n[o]=a===void 0?void 0:w(P(s).kind,a)}return v(e,n,"params")},oe=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new f("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new f("BAD_REQUEST","Expected a JSON object body");return v(e,r,"body")},L=(e,t)=>{const{method:r}=t.req;if(!(r===e.method||e.method==="GET"&&r==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${r} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},ne=e=>{const t=e.split(";",1)[0]?.trim().toLowerCase()??"";return t==="application/json"||t.startsWith("application/")&&t.endsWith("+json")},x=(e,t)=>{if(e.method!=="QUERY"||Object.keys(e.body).length===0)return;const r=t.req.header("content-type");if(r===void 0||r.trim()==="")return Response.json({code:"BAD_REQUEST",error:"A QUERY request must declare its Content-Type"},{status:400});if(!ne(r))return Response.json({code:"UNSUPPORTED_MEDIA_TYPE",error:`${r} is not supported on this route; send application/json`},{headers:{"accept-query":"application/json"},status:415})},se=(e,t)=>async r=>{const n=L(e,r)??x(e,r);if(n)return n;try{const o=r.get("lunora"),s=Object.keys(e.searchParams).length>0?D(e.searchParams,r):{},a=Object.keys(e.params).length>0?q(e.params,r):{},i=Object.keys(e.body).length>0?await oe(e.body,r):{},u=await t({body:i,ctx:o,params:a,searchParams:s}),c=e.output?b(e.output,u):u,d={};e.cacheControl&&(d["cache-control"]=K(e,e.cacheControl,r)),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const y=Object.keys(d).length>0;return c===void 0?new Response(null,{headers:y?d:void 0,status:204}):Response.json(c,{headers:y?d:void 0})}catch(o){return g(o)}},we=e=>{const t=e.headers.get("last-event-id");if(t!==null)return t===""?void 0:t;const r=new URL(e.url).searchParams.get("lastEventId");return r===null||r===""?void 0:r},I=Symbol.for("@lunora/server/sse-event"),ve=e=>({[I]:!0,data:e.data,id:e.id}),ae=e=>typeof e=="object"&&e!==null&&e[I]===!0,ce=(e,t)=>{if(ae(t)){if(!$(t.id))throw new f("INTERNAL","sseEvent id must not contain CR, LF or NUL");const r=e?b(e,t.data):t.data;return R(S(r),void 0,t.id)}return R(S(e?b(e,t):t))},ie=(e,t)=>(async r=>{const n=L(e,r)??x(e,r);if(n)return n;let o,s;try{o=Object.keys(e.searchParams).length>0?D(e.searchParams,r):{},s=Object.keys(e.params).length>0?q(e.params,r):{}}catch(p){return g(p)}const a=r.get("lunora"),i=r.req.raw,u=new TextEncoder,c=new AbortController;if(i.signal.aborted)return c.abort(),new Response("",{headers:A});const d=()=>{c.abort()};i.signal.addEventListener("abort",d,{once:!0});const y=new ReadableStream({cancel(){i.signal.removeEventListener("abort",d),c.abort()},async start(p){try{const E=t({ctx:a,params:s,request:i,searchParams:o,signal:c.signal});for await(const m of E){if(c.signal.aborted)break;p.enqueue(u.encode(ce(e.output,m)))}c.signal.aborted||p.enqueue(u.encode(R({},"complete")))}catch(E){const{body:m,redacted:U}=N(E,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});U&&console.error("[lunora] unhandled stream handler error:",E),c.signal.aborted||p.enqueue(u.encode(R({code:m.code,hint:m.hint,message:m.message,why:m.why},"error")))}finally{i.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(y,{headers:A})}),de=e=>{const t=e?.find(r=>!O(r));if(t!==void 0)throw new f("INTERNAL",`httpRoute .cacheControl(): credentialHeaders entry ${JSON.stringify(t)} is not a header name`);return e},h=e=>({body:t=>h({...e,body:{...e.body,...t}}),cacheControl:(t,r)=>h({...e,cacheControl:t,credentialHeaders:de(r?.credentialHeaders)}),cacheTag:t=>h({...e,cacheTag:t}),handler:t=>se(e,t),output:t=>h({...e,output:t}),params:t=>h({...e,params:{...e.params,...t}}),searchParams:t=>h({...e,searchParams:{...e.searchParams,...t}}),stream:t=>ie(e,t),vary:t=>h({...e,vary:t})}),l=e=>t=>h({body:{},method:e,params:{},path:t,searchParams:{}}),ge={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),query:l("QUERY")};export{Ee as httpAction,ge as httpRoute,be as httpRouter,Re as isHttpRouter,$ as isSafeHeaderValue,we as lastEventId,ve as sseEvent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as F}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as x,b as H,c as C}from"./middleware-vDNQHKyX.mjs";import{copyDatabaseEntries as J,bindOrm as X}from"./bindOrm-B0BYm2iu.mjs";import{tagMaskMiddleware as Y}from"./buildMaskRegistry-DpWMtalG.mjs";const L=Symbol.for("lunora.ctxdb.rls-relation-gate"),Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?F(i.toString()):F(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},d=(s,i,c)=>{const w={...s};for(const[y,p]of Object.entries(i))y in w&&(w[y]=Q(p,s[y],{...c,column:y,row:s}));return w},v=(s,i,c)=>({...s,page:s.page.map(w=>d(w,i,c))}),P=(s,i)=>{const c=H(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},K=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,p=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&y.add(f),p())});s(p());for(const f of y)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${f}" is not supported`)},G=64,V=(s,i,c,w)=>{const y=s.rankBefore,p=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>d(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},h=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const u=a.find(I=>P(e,I));if(u!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${u}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,t,c)},collect:async()=>(await r.collect()).map(e=>d(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=d(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(d(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?d(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>v(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>d(a,t,c)),unique:async()=>{const o=await r.unique();return o?d(o,t,c):null},withIndex:(o,e)=>(h(n,o,"withIndex","index"),K(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(K(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(h(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o,e=0)=>{if(!(!r||typeof r!="object")){if(e>=G)throw new S("MASK_UNSUPPORTED",`${o}() filtering "${n}" with a where nested deeper than ${String(G)} levels is not supported`);if(Array.isArray(r)){for(const a of r)A(a,t,n,o,e+1);return}for(const[a,u]of Object.entries(r))T(a,u,t,n,o,e+1)}},T=(r,t,n,o,e,a)=>{if(r==="AND"||r==="OR"||r==="NOT"){A(t,n,o,e,a);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 u of Object.values(t))A(u,l,`${o}.${r}`,e,a)}},B=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},g=(r,t,n)=>{l.size===0||t===void 0||A(t,B(r),r,n)},_=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.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 a=e,u=`${r}.${o}`;A(a.where,l,u,n),_(u,a.orderBy,l,n),j(u,a.with,n)}},$=(r,t,n)=>{g(r,t?.where,n),g(r,t?.baseWhere,n),_(r,t?.orderBy,B(r),n),j(r,t?.with,n)},U=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=U(t);g(r,o?.where,n),g(r,o?.baseWhere,n),j(r,o?.with,n)},W=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,E={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[a,u]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?W(e.through.table,e.through.from)??W(e.through.table,e.through.to):W(a,e.field)??W(u,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(g(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(g(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:d(o.doc,e,c)}:o},async patchWhere(r,t,n){if(g(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"),g(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=U(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return g(r,o,"count"),n&&g(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?d(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?d(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?v(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:d(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?d(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),g(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),h(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),h(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?v(o,e,c):o},...x("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),h(t,n,"rankBefore","rank"),r(t,n,o))),...x("rankPageRows",p,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),h(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(u=>({...u,doc:d(u.doc,a,c)}))}:e})};J(E,s,l.size>0);const D=s[L];return D!==void 0&&Object.defineProperty(E,L,{configurable:!0,enumerable:!1,value:D,writable:!1}),E},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=q(i.roles),y=async({ctx:f,next:k})=>{const h=f,O={auth:await z(h.auth??{},w),ctx:h};if(i.bypass?.(O)===!0)return k();const R=V(h.db,c,O,i.indexFields),l={db:R},{orm:A}=h;return A!==null&&typeof A=="object"&&(l.orm=X(R)),k({ctx:l})},p=new Map;for(const[f,k]of c)p.set(f,new Set(Object.keys(k)));return Y(y,{columns:p})};export{nr as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{copyDatabaseEntries as Te,bindOrm as Ae}from"./bindOrm-B0BYm2iu.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class P extends Error{}const N=e=>e.includes("."),vt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new P(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new P(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},Pe=(e,t)=>{const r=Object.keys(e).filter(a=>N(a));if(r.length===0)return e;for(const a of r){const f=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(f!==void 0)throw new P(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},me=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,Q=(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??ue},z=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={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 B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},Ce=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},je=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,Ce({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return Pe(i,t)}catch(a){if(a instanceof P)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,T=0,E=1,m=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===T?T:m(e===S),se=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},A=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`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?me(f)===void 0:!se(f))i=w(i,S);else if(A(t))i=w(i,T);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,m(y&&g(t,f)))}}return i},ie=(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},ae=(e,t)=>t.length===0?S:A(e)?T:t.includes(e)?E:t.some(r=>A(r))?T:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=A(t)?w(i,T):w(i,m(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,m(r.isNull===!0===A(t)))),i},G=(e,t,r)=>t===null?m(r===A(e)):A(e)?T:m(r===(e===t)),He=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},Ke=(e,t,r)=>w(He(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Qe=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",ze=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Qe(e,i,a,ge));continue}const f=_e(e,i);if(ze(a)){r=w(r,Ke(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{z(e,Q(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),K=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))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||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),K.set(b,u);const v=n=>{const o=typeof n=="function"?K.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),K.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},H=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:a.has(l.tableName)?l.tableName:void 0}}const o=[...a.keys()],c=(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 c?{row:c.row,tableName:c.tableName}:{row:null,tableName:void 0}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},C=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...je(s,l)})),j=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=Q(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return z(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await H(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>C(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>C(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await C(n,o,s.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,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.get(n,o).then(d=>d!==null,d=>{if(Be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?c:{applied:c.applied,doc:null}},async patchMany(n,o,s){U(o.length,s?.limit,"patchMany");for(const c of o)await C(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=Q(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return z(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return j(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return j(n,"rankPage"),y(n).rankPage(n,o,s)},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})},...oe("rankBefore",We,n=>(o,s,c)=>(j(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(j(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};return Te(I,e,a.size>0),Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,lt=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},ft=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},dt=["roles","role"],ut=e=>{for(const t of dt){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},ht=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ut(r),...e.roles??[]])];return{can:ft(i,t),identity:r,roles:i,userId:e.userId??null}},Wt=(e,t={})=>{const r=e,i=Ve(r),a=lt(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await ht(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,H=v?.raw??b[Xe]??b,M=ct($,H,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Ae(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{ht as a,vt as b,Fe as c,ut as d,et as e,ft as f,rt as g,lt as i,Y as m,oe as o,Wt as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as t,g as i,i as m,m as l,d,f as p,a as h,r as n}from"./middleware-vDNQHKyX.mjs";import"./bindOrm-B0BYm2iu.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as matchesWhere,d as readIdentityRoles,p as resolveCan,h as resolvePolicyAuth,n as rls};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{copyDatabaseEntries as A}from"./bindOrm-B0BYm2iu.mjs";import{i as D,a as E}from"./middleware-vDNQHKyX.mjs";const N=(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},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},M=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},$=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",M],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],P=[["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.']],B=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},L=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&B(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 })\`.`)},x=(e,t={})=>{const o=D(t.roles);return async({ctx:i,next:c})=>{const g=await E(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=>S(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 $){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 P)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();L(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;if(y!==void 0&&m!==void 0&&typeof m=="object"){const s={system:N(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})};A(s,y,!1),p.db=s}return c({ctx:p})}};export{x as storageRules};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,
|
|
1
|
+
import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-vDNQHKyX.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 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{isPlainObject as x}from"@lunora/wire";const M=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&x(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},R=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},j=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:R(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:R(e,`${t}.connect`),r=i===void 0?[]:R(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},k=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!M.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):j(n,s,i)},P=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=k(t,a,n[a],r);o!==void 0&&(P(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},w=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},O=async(t,n,s,e,i)=>{const c=await t.get(e,i);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},b=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await O(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},W=async(t,{info:n,name:s},e,i)=>{(await O(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(n.table,e,{[n.field]:i})},F=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(n.table,String(s._id),{[n.field]:null})},U=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},$=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},V=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},C=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>O(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await $(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await $(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await $(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await V(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>O(t,i,"connect",e.table,h)));for(const h of d)await t.delete(a,String(h._id));for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>O(t,n.name,"disconnect",n.info.table,c)));else{const c=await U(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await F(t,n,c,s);for(const c of e)await W(t,n,c,s)},_=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await C(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},S=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(n,s))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await b(t,c),r=await i(a);return r!==null&&await _(t,n,c,S(t,n,r,a)),r},G=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(n,e,c.columns);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(n,e,a);else{if(await t.get(n,e)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(n,e)}await _(t,n,c,S(t,n,e,a))},m=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},z=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>G(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=m(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(n,o),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(n,o,d)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(n,o),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(n,o,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)w(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)w(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(n,o.map(l=>({id:l.id,patch:l.values})),d)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>(w(n,e,d,"replace"),t.replace(n,o,d)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(n,o)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{const s=e=>({configurable:!0,enumerable:!0,value:e,writable:!0});Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,s(e)),e},set(e){Object.defineProperty(this,n,s(e))}})},H=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{H as bindOrm,z as bindTableFacade,X as defineLazyFacade};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f,isLunoraError as I,toErrorBody as C}from"@lunora/errors";import{ValidationError as M,parseValidatorMap as v}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as H}from"hono";import{SSE_HEADERS as A,sseFrame as w,isSafeHeaderValue as U}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";import{isDevEnvironment as $}from"@lunora/shard-engine";const O=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,T=e=>B.test(e),V=(e,r,t=[])=>r?.access!==void 0||O.some(n=>e.has(n))||t.some(n=>!T(n)||e.has(n)),W=e=>{const r=[];let t="",n=!1,o=!1;for(const a of e){if(o)o=!1;else if(n&&a==="\\")o=!0;else if(a==='"')n=!n;else if(a===","&&!n){r.push(t.trim()),t="";continue}t+=a}return r.push(t.trim()),r.filter(a=>a!=="")},J=new Set(["proxy-revalidate","public","s-maxage"]),Q=e=>{const r=W(e),t=r.map(o=>o.toLowerCase());return t.includes("private")||t.includes("no-store")?e:["private",...r.filter((o,a)=>{const s=(t[a]?.split("=",1)[0]??"").trim();return!J.has(s)&&s!=="private"})].join(", ")},N=new WeakSet,z=e=>{try{return e.executionCtx}catch{return}},G=(e,r)=>[...O,...r].find(t=>e.has(t))??"cloudflare access",K=(e,r,t)=>{const{headers:n}=t.req.raw,o=e.credentialHeaders??[];if(!V(n,z(t),o))return r;const a=Q(r);return a!==r&&!N.has(e)&&$(t.env)&&(N.add(e),console.warn(`[lunora] httpRoute ${e.method} ${e.path}: sent Cache-Control "${a}" instead of the declared "${r}" because the request carries a credential (${G(n,o)}). A shared cache must not store a per-caller response. Further downgrades on this route are not reported.`)),a},g=e=>{if(e instanceof M)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(I(e)){const{body:r,redacted:t,status:n}=C(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return t&&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},fe=e=>async r=>{try{return await e(r.get("lunora"),r.req.raw)}catch(t){return g(t)}},_=new WeakSet,k=new WeakSet,ye=e=>k.has(e),L=new WeakSet,Z=new Set(["*","/*"]),X="__COMPOSED_HANDLER",Y=e=>e[X]??e,ee=e=>{let r,t=-1;return async n=>{if(r===void 0||t!==e.routes.length){const a=new H;for(const s of e.routes)L.has(Y(s.handler))||a.on(s.method,s.path,()=>new Response(null,{status:204}));r=a,t=e.routes.length}return(await r.fetch(new Request(n.url,{method:n.method}))).status===204}},Ee=()=>{const e=new H,r=ee(e),t=e.use.bind(e);k.add(e),e.use=((...o)=>{const[a]=o;if(typeof a!="string"||Z.has(a))for(const s of o)typeof s=="function"&&L.add(s);return t(...o)}),e.use("*",async(o,a)=>{const s=o.env.__lunoraCtx;if(!s)throw new f("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",s);const{__lunoraShellFirst:i,__lunoraUnrouted:u}=o.env;if(i===!0&&!await r(o.req.raw))return u?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(_.add(o),c()),await a()});const n=e.notFound;return e.notFound=o=>n(a=>{const{__lunoraUnrouted:s}=a.env;return _.has(a)||s?.(),o(a)}),e.notFound(o=>o.text("404 Not Found",404)),e},P=e=>e.kind==="optional"?e._meta?.inner??e:e,b=(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}},re=(e,r,t)=>{const n=P(e);if(n.kind==="array"){const a=r.req.queries(t);if(a===void 0)return;const s=n._meta?.inner;return a.map(i=>b(s?.kind??"string",i))}const o=r.req.query(t);return o===void 0?void 0:b(n.kind,o)},j=(e,r)=>{const t={};for(const n of Object.keys(e)){const o=e[n];o&&(t[n]=re(o,r,n))}return v(e,t,"searchParams")},D=(e,r)=>{const t=r.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=t[o];n[o]=s===void 0?void 0:b(P(a).kind,s)}return v(e,n,"params")},te=async(e,r)=>{let t;try{t=await r.req.json()}catch{throw new f("BAD_REQUEST","Invalid JSON body")}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("BAD_REQUEST","Expected a JSON object body");return v(e,t,"body")},x=(e,r)=>{const{method:t}=r.req;if(!(t===e.method||e.method==="GET"&&t==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${t} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},oe=(e,r)=>async t=>{const n=x(e,t);if(n)return n;try{const o=t.get("lunora"),a=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},s=Object.keys(e.params).length>0?D(e.params,t):{},i=Object.keys(e.body).length>0?await te(e.body,t):{},u=await r({body:i,ctx:o,params:s,searchParams:a}),c=e.output?R(e.output,u):u,d={};e.cacheControl&&(d["cache-control"]=K(e,e.cacheControl,t)),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const y=Object.keys(d).length>0;return c===void 0?new Response(null,{headers:y?d:void 0,status:204}):Response.json(c,{headers:y?d:void 0})}catch(o){return g(o)}},we=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const t=new URL(e.url).searchParams.get("lastEventId");return t===null||t===""?void 0:t},q=Symbol.for("@lunora/server/sse-event"),Re=e=>({[q]:!0,data:e.data,id:e.id}),ne=e=>typeof e=="object"&&e!==null&&e[q]===!0,ae=(e,r)=>{if(ne(r)){if(!U(r.id))throw new f("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=e?R(e,r.data):r.data;return w(S(t),void 0,r.id)}return w(S(e?R(e,r):r))},se=(e,r)=>(async t=>{const n=x(e,t);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},a=Object.keys(e.params).length>0?D(e.params,t):{}}catch(p){return g(p)}const s=t.get("lunora"),i=t.req.raw,u=new TextEncoder,c=new AbortController;if(i.signal.aborted)return c.abort(),new Response("",{headers:A});const d=()=>{c.abort()};i.signal.addEventListener("abort",d,{once:!0});const y=new ReadableStream({cancel(){i.signal.removeEventListener("abort",d),c.abort()},async start(p){try{const E=r({ctx:s,params:a,request:i,searchParams:o,signal:c.signal});for await(const m of E){if(c.signal.aborted)break;p.enqueue(u.encode(ae(e.output,m)))}c.signal.aborted||p.enqueue(u.encode(w({},"complete")))}catch(E){const{body:m,redacted:F}=C(E,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});F&&console.error("[lunora] unhandled stream handler error:",E),c.signal.aborted||p.enqueue(u.encode(w({code:m.code,hint:m.hint,message:m.message,why:m.why},"error")))}finally{i.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(y,{headers:A})}),ce=e=>{const r=e?.find(t=>!T(t));if(r!==void 0)throw new f("INTERNAL",`httpRoute .cacheControl(): credentialHeaders entry ${JSON.stringify(r)} is not a header name`);return e},l=e=>({body:r=>l({...e,body:{...e.body,...r}}),cacheControl:(r,t)=>l({...e,cacheControl:r,credentialHeaders:ce(t?.credentialHeaders)}),cacheTag:r=>l({...e,cacheTag:r}),handler:r=>oe(e,r),output:r=>l({...e,output:r}),params:r=>l({...e,params:{...e.params,...r}}),searchParams:r=>l({...e,searchParams:{...e.searchParams,...r}}),stream:r=>se(e,r),vary:r=>l({...e,vary:r})}),h=e=>r=>l({body:{},method:e,params:{},path:r,searchParams:{}}),be={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")};export{fe as httpAction,be as httpRoute,Ee as httpRouter,ye as isHttpRouter,U as isSafeHeaderValue,we as lastEventId,Re as sseEvent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as L,b as H,c as C,d as J}from"./middleware-CHYtnvZP.mjs";import{defineLazyFacade as X,bindOrm as Y}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const x=Symbol.for("lunora.ctxdb.rls-relation-gate"),V=(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}},f=(s,i,c)=>{const w={...s};for(const[y,p]of Object.entries(i))y in w&&(w[y]=V(p,s[y],{...c,column:y,row:s}));return w},v=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),P=(s,i)=>{const c=C(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},K=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,p=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),p())});s(p());for(const u of y)if(P(i,u))throw new S("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},G=64,Z=(s,i,c,w)=>{const y=s.rankBefore,p=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},h=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(I=>P(e,I));if(d!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>v(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(h(n,o,"withIndex","index"),K(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(K(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(h(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o,e=0)=>{if(!(!r||typeof r!="object")){if(e>=G)throw new S("MASK_UNSUPPORTED",`${o}() filtering "${n}" with a where nested deeper than ${String(G)} levels is not supported`);if(Array.isArray(r)){for(const a of r)A(a,t,n,o,e+1);return}for(const[a,d]of Object.entries(r))T(a,d,t,n,o,e+1)}},T=(r,t,n,o,e,a)=>{if(r==="AND"||r==="OR"||r==="NOT"){A(t,n,o,e,a);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(J(t))for(const d of Object.values(t))A(d,l,`${o}.${r}`,e,a)}},B=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},g=(r,t,n)=>{l.size===0||t===void 0||A(t,B(r),r,n)},_=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.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 a=e,d=`${r}.${o}`;A(a.where,l,d,n),_(d,a.orderBy,l,n),j(d,a.with,n)}},$=(r,t,n)=>{g(r,t?.where,n),g(r,t?.baseWhere,n),_(r,t?.orderBy,B(r),n),j(r,t?.with,n)},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=F(t);g(r,o?.where,n),g(r,o?.baseWhere,n),j(r,o?.with,n)},W=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,E={...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[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?W(e.through.table,e.through.from)??W(e.through.table,e.through.to):W(a,e.field)??W(d,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(g(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(g(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:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(g(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"),g(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=F(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return g(r,o,"count"),n&&g(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?v(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:f(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?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),g(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),h(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),h(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?v(o,e,c):o},...L("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),h(t,n,"rankBefore","rank"),r(t,n,o))),...L("rankPageRows",p,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),h(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})};if(l.size>0)for(const[r,t]of Object.entries(s))H(t)&&X(E,r);const U=s[x];return U!==void 0&&Object.defineProperty(E,x,{configurable:!0,enumerable:!1,value:U,writable:!1}),E},or=(s,i={})=>{const c=new Map(Object.entries(s)),w=q(i.roles),y=async({ctx:u,next:k})=>{const h=u,O={auth:await z(h.auth??{},w),ctx:h};if(i.bypass?.(O)===!0)return k();const R=Z(h.db,c,O,i.indexFields),l={db:R},{orm:A}=h;return A!==null&&typeof A=="object"&&(l.orm=Y(R)),k({ctx:l})},p=new Map;for(const[u,k]of c)p.set(u,new Set(Object.keys(k)));return Q(y,{columns:p})};export{or as mask};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Ae,bindOrm as Te}from"./bindOrm-D5mVDvbi.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class m extends Error{}const N=e=>e.includes("."),Wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new m(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new m(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},me=(e,t)=>{const r=Object.keys(e).filter(a=>N(a));if(r.length===0)return e;for(const a of r){const f=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(f!==void 0)throw new m(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new m(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},Pe=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,K=(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??ue},Q=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={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 B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},je=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},Ce=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,je({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return me(i,t)}catch(a){if(a instanceof m)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,A=0,E=1,P=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===A?A:P(e===S),se=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`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?Pe(f)===void 0:!se(f))i=w(i,S);else if(T(t))i=w(i,A);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,P(y&&g(t,f)))}}return i},ie=(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},ae=(e,t)=>t.length===0?S:T(e)?A:t.includes(e)?E:t.some(r=>T(r))?A:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=T(t)?w(i,A):w(i,P(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,P(r.isNull===!0===T(t)))),i},G=(e,t,r)=>t===null?P(r===T(e)):T(e)?A:P(r===(e===t)),ze=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},He=(e,t,r)=>w(ze(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Ke=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",Qe=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Ke(e,i,a,ge));continue}const f=_e(e,i);if(Qe(a)){r=w(r,He(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{Q(e,K(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),H=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))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||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},lt=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),H.set(b,u);const v=n=>{const o=typeof n=="function"?H.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),H.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},z=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:a.has(l.tableName)?l.tableName:void 0}}const o=[...a.keys()],c=(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 c?{row:c.row,tableName:c.tableName}:{row:null,tableName:void 0}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},j=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Ce(s,l)})),C=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={...e,async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return Q(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await z(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>j(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await j(n,o,s.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,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.get(n,o).then(d=>d!==null,d=>{if(Be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?c:{applied:c.applied,doc:null}},async patchMany(n,o,s){U(o.length,s?.limit,"patchMany");for(const c of o)await j(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return Q(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return C(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return C(n,"rankPage"),y(n).rankPage(n,o,s)},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})},...oe("rankBefore",We,n=>(o,s,c)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))ct(o)&&Ae(I,n);return Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,ft=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},dt=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},ut=["roles","role"],ht=e=>{for(const t of ut){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},yt=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ht(r),...e.roles??[]])];return{can:dt(i,t),identity:r,roles:i,userId:e.userId??null}},Rt=(e,t={})=>{const r=e,i=Ve(r),a=ft(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await yt(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,z=v?.raw??b[Xe]??b,M=lt($,z,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Te(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{yt as a,ct as b,Wt as c,Fe as d,ht as e,et as f,dt as g,rt as h,ft as i,Y as m,oe as o,Rt as r};
|
|
@@ -1 +0,0 @@
|
|
|
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-CHYtnvZP.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 +0,0 @@
|
|
|
1
|
-
import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-CHYtnvZP.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};
|