@lunora/server 1.0.0-alpha.101 → 1.0.0-alpha.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1730,7 +1730,8 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
1730
1730
  * builder, `.output(validator)` defaults to the `undefined` sentinel — while
1731
1731
  * unset the handler is generic over its own return; once set the handler must
1732
1732
  * return that type and the result is parsed through the validator before
1733
- * serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
1733
+ * serialization. It binds `.stream()` the same way, per yielded chunk.
1734
+ * `[Output] extends [undefined]` is tuple-wrapped so a union
1734
1735
  * `Output` doesn't distribute and the test is for the exact sentinel.
1735
1736
  *
1736
1737
  * The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
@@ -1759,10 +1760,12 @@ interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends Args
1759
1760
  * iterator completion the route writes a final `event: complete` frame; on
1760
1761
  * throw, an `event: error` frame is written with `{code, message}` before
1761
1762
  * the stream closes. The chunks are JSON-encoded; `R` is inferred from the
1762
- * handler's yielded type.
1763
+ * handler's yielded type — unless `.output()` was declared, in which case each
1764
+ * chunk must be that type and is parsed through the validator before the frame
1765
+ * is written (a violation ends the stream with an `event: error` frame).
1763
1766
  * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
1764
1767
  */
1765
- stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
1768
+ stream: [Output] extends [undefined] ? <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler : (handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<Output, void, void> | AsyncIterable<Output>) => LunoraRouteHandler;
1766
1769
  /**
1767
1770
  * Attach a `Vary` header to the response so Cloudflare stores separate
1768
1771
  * cached variants per distinct value of the listed request headers.
@@ -2492,10 +2495,13 @@ type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
2492
2495
  * - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
2493
2496
  * inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
2494
2497
  * not listed grants no permissions (fails closed for unknown roles).
2495
- * - `bypass` is a procedure-wide escape hatch: when it returns `true` the whole
2496
- * mask is skipped (the caller sees raw values). Use it for a privileged
2498
+ * - `bypass` is a procedure-wide escape hatch: when it returns exactly `true` the
2499
+ * whole mask is skipped (the caller sees raw values). Use it for a privileged
2497
2500
  * viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
2498
2501
  * branching every column when an entire class of caller should see clear data.
2502
+ * The verdict is compared to `true`, never evaluated for truthiness: returning
2503
+ * a claim (`auth.identity?.role`) rather than a decision is a DENIAL here, not
2504
+ * an unmasked read.
2499
2505
  * - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
2500
2506
  * the `mask/middleware` module docblock's "Residual read-position oracles" section).
2501
2507
  */
@@ -3207,10 +3213,17 @@ interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = Qu
3207
3213
  /** Declare a replication shape. See the module docs for runtime semantics. */
3208
3214
  declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
3209
3215
  /**
3210
- * Operations a storage rule can gate. `read` covers `download` / `getMetadata`
3211
- * / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
3212
- * `delete` is `delete`; `list` is a prefix listing (governed via the file
3213
- * browser / admin path, not `ctx.storage` which has no `list`).
3216
+ * Operations a storage rule can gate. `read` covers `download` / `getMetadata` /
3217
+ * `head` / `getSignedUrl` / `getUrl`; `write` covers `store` /
3218
+ * `generateUploadUrl`; `delete` covers `delete` and the `deleteAfterCommit`
3219
+ * enqueue; `list` is a prefix listing.
3220
+ *
3221
+ * `list` governs `ctx.db.system.query("_storage")` — the object enumeration
3222
+ * reachable from a handler — plus the file browser / admin path. It governs
3223
+ * nothing on `ctx.storage`, which exposes no `list` (and `storageRules` drops
3224
+ * any). Note the enumeration is additionally narrowed by the bucket's `read`
3225
+ * rules, so a `read` prefix rule scopes what a handler can enumerate even with
3226
+ * no `list` rule declared.
3214
3227
  */
3215
3228
  type StorageOperation = "delete" | "list" | "read" | "write";
3216
3229
  /** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
@@ -3295,6 +3308,7 @@ declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInp
3295
3308
  declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
3296
3309
  interface StorageContextIn {
3297
3310
  auth?: AuthLike;
3311
+ db?: unknown;
3298
3312
  storage?: unknown;
3299
3313
  }
3300
3314
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
package/dist/index.d.ts CHANGED
@@ -1730,7 +1730,8 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
1730
1730
  * builder, `.output(validator)` defaults to the `undefined` sentinel — while
1731
1731
  * unset the handler is generic over its own return; once set the handler must
1732
1732
  * return that type and the result is parsed through the validator before
1733
- * serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
1733
+ * serialization. It binds `.stream()` the same way, per yielded chunk.
1734
+ * `[Output] extends [undefined]` is tuple-wrapped so a union
1734
1735
  * `Output` doesn't distribute and the test is for the exact sentinel.
1735
1736
  *
1736
1737
  * The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
@@ -1759,10 +1760,12 @@ interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends Args
1759
1760
  * iterator completion the route writes a final `event: complete` frame; on
1760
1761
  * throw, an `event: error` frame is written with `{code, message}` before
1761
1762
  * the stream closes. The chunks are JSON-encoded; `R` is inferred from the
1762
- * handler's yielded type.
1763
+ * handler's yielded type — unless `.output()` was declared, in which case each
1764
+ * chunk must be that type and is parsed through the validator before the frame
1765
+ * is written (a violation ends the stream with an `event: error` frame).
1763
1766
  * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
1764
1767
  */
1765
- stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
1768
+ stream: [Output] extends [undefined] ? <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler : (handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<Output, void, void> | AsyncIterable<Output>) => LunoraRouteHandler;
1766
1769
  /**
1767
1770
  * Attach a `Vary` header to the response so Cloudflare stores separate
1768
1771
  * cached variants per distinct value of the listed request headers.
@@ -2492,10 +2495,13 @@ type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
2492
2495
  * - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
2493
2496
  * inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
2494
2497
  * not listed grants no permissions (fails closed for unknown roles).
2495
- * - `bypass` is a procedure-wide escape hatch: when it returns `true` the whole
2496
- * mask is skipped (the caller sees raw values). Use it for a privileged
2498
+ * - `bypass` is a procedure-wide escape hatch: when it returns exactly `true` the
2499
+ * whole mask is skipped (the caller sees raw values). Use it for a privileged
2497
2500
  * viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
2498
2501
  * branching every column when an entire class of caller should see clear data.
2502
+ * The verdict is compared to `true`, never evaluated for truthiness: returning
2503
+ * a claim (`auth.identity?.role`) rather than a decision is a DENIAL here, not
2504
+ * an unmasked read.
2499
2505
  * - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
2500
2506
  * the `mask/middleware` module docblock's "Residual read-position oracles" section).
2501
2507
  */
@@ -3207,10 +3213,17 @@ interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = Qu
3207
3213
  /** Declare a replication shape. See the module docs for runtime semantics. */
3208
3214
  declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
3209
3215
  /**
3210
- * Operations a storage rule can gate. `read` covers `download` / `getMetadata`
3211
- * / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
3212
- * `delete` is `delete`; `list` is a prefix listing (governed via the file
3213
- * browser / admin path, not `ctx.storage` which has no `list`).
3216
+ * Operations a storage rule can gate. `read` covers `download` / `getMetadata` /
3217
+ * `head` / `getSignedUrl` / `getUrl`; `write` covers `store` /
3218
+ * `generateUploadUrl`; `delete` covers `delete` and the `deleteAfterCommit`
3219
+ * enqueue; `list` is a prefix listing.
3220
+ *
3221
+ * `list` governs `ctx.db.system.query("_storage")` — the object enumeration
3222
+ * reachable from a handler — plus the file browser / admin path. It governs
3223
+ * nothing on `ctx.storage`, which exposes no `list` (and `storageRules` drops
3224
+ * any). Note the enumeration is additionally narrowed by the bucket's `read`
3225
+ * rules, so a `read` prefix rule scopes what a handler can enumerate even with
3226
+ * no `list` rule declared.
3214
3227
  */
3215
3228
  type StorageOperation = "delete" | "list" | "read" | "write";
3216
3229
  /** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
@@ -3295,6 +3308,7 @@ declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInp
3295
3308
  declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
3296
3309
  interface StorageContextIn {
3297
3310
  auth?: AuthLike;
3311
+ db?: unknown;
3298
3312
  storage?: unknown;
3299
3313
  }
3300
3314
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-TegvdZ1v.mjs";import{initLunora as d}from"./packem_shared/initLunora-D5TSiy5j.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as S}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as D}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-Bs1tdJu1.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as b}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as P,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-CF2zTm9X.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-Cof46mpm.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as fe,i as ae,j as se,k as de,m as me}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs";import{protectPublic as Se}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as be,v as Me}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{buildMaskRegistry as we}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/buildRlsReadRegistry-BMJeR-II.mjs";import{createPolicyDsl as Ye,definePermission as Je,definePolicies as Ke,definePolicy as Qe,defineRole as Xe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ze,defineStorageRules as Ge}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as $e}from"./packem_shared/mask-DiBA2jnw.mjs";import{r as rr}from"./packem_shared/middleware-BU9adRMp.mjs";import{storageRules as tr}from"./packem_shared/storageRules-ClZXWHBt.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,be as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,u as beginDeferredSchedules,y as bindOrm,b as bindTableFacade,we as buildMaskRegistry,Ve as buildRlsReadRegistry,f as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,je as composeShapeReadWhere,Ye as createPolicyDsl,p as createSecrets,Ie as cronJobs,a as defineActionCache,ee as defineAggregateIndex,re as defineComponent,A as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Je as definePermission,oe as definePlugin,Ke as definePolicies,Qe as definePolicy,le as definePresence,te as defineRankIndex,Xe as defineRole,ne as defineSchema,ie as defineSchemaExtension,Ae as defineShape,ze as defineStorageRule,Ge as defineStorageRules,fe as defineTable,ae as defineVectorIndex,Oe as deny,D as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,$e as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,Se as protectPublic,C as redactSecrets,rr as rls,U as serveStorageObject,tr as storageRules,Ne as toWhereInput,Me as v,l as withDeferredDeletes,S as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-TegvdZ1v.mjs";import{initLunora as d}from"./packem_shared/initLunora-D5TSiy5j.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as S}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as D}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-C0v7Jhq9.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as b}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as P,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-YRpmc049.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-te5TWJIE.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as fe,i as ae,j as se,k as de,m as me}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs";import{protectPublic as Se}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as be,v as Me}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{buildMaskRegistry as we}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/buildRlsReadRegistry-BMJeR-II.mjs";import{createPolicyDsl as Ye,definePermission as Je,definePolicies as Ke,definePolicy as Qe,defineRole as Xe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ze,defineStorageRules as Ge}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as $e}from"./packem_shared/mask-BNp49Xvt.mjs";import{r as rr}from"./packem_shared/middleware-BU9adRMp.mjs";import{storageRules as tr}from"./packem_shared/storageRules-DxnY-DLK.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,be as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,u as beginDeferredSchedules,y as bindOrm,b as bindTableFacade,we as buildMaskRegistry,Ve as buildRlsReadRegistry,f as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,je as composeShapeReadWhere,Ye as createPolicyDsl,p as createSecrets,Ie as cronJobs,a as defineActionCache,ee as defineAggregateIndex,re as defineComponent,A as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Je as definePermission,oe as definePlugin,Ke as definePolicies,Qe as definePolicy,le as definePresence,te as defineRankIndex,Xe as defineRole,ne as defineSchema,ie as defineSchemaExtension,Ae as defineShape,ze as defineStorageRule,Ge as defineStorageRules,fe as defineTable,ae as defineVectorIndex,Oe as deny,D as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,$e as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,Se as protectPublic,C as redactSecrets,rr as rls,U as serveStorageObject,tr as storageRules,Ne as toWhereInput,Me as v,l as withDeferredDeletes,S as withDeferredSchedules};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{v as o,optionalInner as b}from"@lunora/values";const A=25,S=100,w=100,L=8,O=new Set(["id","storage","string"]),u=t=>{const n=b(t)??t;if(O.has(n.kind))return!0;const r=n._meta;if(n.kind==="literal")return typeof r?.value=="string";if(n.kind!=="union"||r?.members===void 0)return!1;const{members:s}=r;return s.some(e=>u(e))&&s.every(e=>e.kind==="null"||u(e))},_=(t,n)=>{const r=s=>o.optional(o.array(s).check(e=>e.length<=n,{message:`at most ${String(n)} values`}));return o.object({...u(t)?{contains:o.optional(o.string())}:{},eq:o.optional(t),gt:o.optional(t),gte:o.optional(t),in:r(t),isNull:o.optional(o.boolean()),lt:o.optional(t),lte:o.optional(t),ne:o.optional(t),notIn:r(t)})},B=(t,n,r)=>t===void 0||!Number.isFinite(t)?Math.min(n,r):Math.min(Math.max(1,Math.floor(t)),r),p=(t,n)=>t===void 0||!Number.isFinite(t)?n:Math.max(1,Math.floor(t)),E=new Set(["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"]),M=(t,n,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const s=t,e={};let l=0;for(const a of E){if(!Object.hasOwn(s,a)||(l+=1,a==="contains"&&!r))continue;const c=s[a];if(Array.isArray(c)&&c.length>n)throw new y("BAD_REQUEST",`list filter: \`${a}\` accepts at most ${String(n)} values (got ${String(c.length)})`);e[a]=c}return l===0?void 0:e},I=(t,n,r,s)=>{const e={};for(const l of n){if(!Object.hasOwn(t,l))continue;const a=t[l],c=M(a,s,r.has(l));c!==void 0&&Object.keys(c).length===0||(e[l]=c??a)}return e},F=()=>t=>{const n=p(t.defaultLimit,A),r=p(t.maxLimit,S),s=p(t.maxInValues,w),e=p(t.maxOrderBy,L),l=new Set(Object.keys(t.filter)),a=new Set,c={};for(const[i,d]of Object.entries(t.filter))u(d)&&a.add(i),c[i]=o.optional(o.union(d,_(d,s)));const h=new Set(t.orderBy),g=t.orderBy.length===0?o.string().check(()=>!1,{message:"no sortable columns are declared for this endpoint"}):o.union(...t.orderBy.map(i=>o.literal(i)));return{args:{cursor:o.optional(o.union(o.string(),o.number(),o.null())),limit:o.optional(o.number()),orderBy:o.optional(o.array(o.object({direction:o.optional(o.union(o.literal("asc"),o.literal("desc"))),field:g}))),where:o.optional(o.object(c))},toQueryArgs:i=>{const d=i.orderBy?.filter(m=>h.has(m.field)).slice(0,e).map(m=>({[m.field]:m.direction??"asc"})),f=i.where===void 0?void 0:I(i.where,l,a,s);return{...i.cursor===void 0?{}:{cursor:typeof i.cursor=="number"?String(i.cursor):i.cursor},limit:B(i.limit,n,r),...d===void 0||d.length===0?{}:{orderBy:d},...f===void 0?{}:{where:f}}}}};export{A as DEFAULT_LIMIT,w as DEFAULT_MAX_IN_VALUES,S as DEFAULT_MAX_LIMIT,L as DEFAULT_MAX_ORDER_BY,B as clampLimit,F as defineListArgs,p as normalizeBound,I as sanitizeWhere};
@@ -0,0 +1 @@
1
+ import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-BOMWQpoF.mjs";import{initLunora as x}from"./initLunora-D5TSiy5j.mjs";import{g as v,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const V=e=>async r=>e(r.get("lunora"),r.req.raw),$=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},x=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},C=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},H=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await C(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(e);return`${r?`event: ${r}
2
+ `:""}data: ${o}
3
+
4
+ `},L=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(p){return j(p)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(p){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const m of y){if(s.signal.aborted)break;p.enqueue(h.encode(b(e.output?k(e.output,m):m)))}s.signal.aborted||p.enqueue(h.encode(b({},"complete")))}catch(y){const{body:m,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||p.enqueue(h.encode(b({code:m.code,message:m.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{p.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>H(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>L(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},J=e=>!(e.includes("\r")||e.includes(`
5
+ `)||e.includes("\0"));export{V as httpAction,U as httpRoute,$ as httpRouter,J as isSafeHeaderValue};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-BU9adRMp.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},u=(e,i,a)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...a,column:y,row:e}));return d},j=(e,i,a)=>({...e,page:e.page.map(d=>u(d,i,a))}),D=(e,i,a,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,a)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,a)},collect:async()=>(await r.collect()).map(s=>u(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,a):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>u(c,n,a)),unique:async()=>{const o=await r.unique();return o?u(o,n,a):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);return f?{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,a)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:u(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k))return l();const p=X(w.db,a,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of a)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
1
+ import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-BU9adRMp.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},u=(e,i,a)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...a,column:y,row:e}));return d},j=(e,i,a)=>({...e,page:e.page.map(d=>u(d,i,a))}),D=(e,i,a,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,a)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,a)},collect:async()=>(await r.collect()).map(s=>u(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,a):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>u(c,n,a)),unique:async()=>{const o=await r.unique();return o?u(o,n,a):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);return f?{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,a)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:u(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,a,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of a)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
@@ -1 +1 @@
1
- import{isSafeHeaderValue as l}from"./httpAction-CF2zTm9X.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
1
+ import{isSafeHeaderValue as l}from"./httpAction-YRpmc049.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
@@ -0,0 +1 @@
1
+ import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-BU9adRMp.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},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}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" 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 })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.101",
3
+ "version": "1.0.0-alpha.102",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -66,9 +66,9 @@
66
66
  "access": "public"
67
67
  },
68
68
  "dependencies": {
69
- "@lunora/errors": "1.0.0-alpha.30",
70
- "@lunora/scheduler": "1.0.0-alpha.50",
71
- "@lunora/values": "1.0.0-alpha.38",
69
+ "@lunora/errors": "1.0.0-alpha.31",
70
+ "@lunora/scheduler": "1.0.0-alpha.51",
71
+ "@lunora/values": "1.0.0-alpha.39",
72
72
  "drizzle-orm": "^0.45.2",
73
73
  "hono": "^4.13.1"
74
74
  },
@@ -1 +0,0 @@
1
- import{v as o,optionalInner as b}from"@lunora/values";const g=25,A=100,O=100,S=8,w=new Set(["id","storage","string"]),p=t=>{const n=b(t)??t;if(w.has(n.kind))return!0;const r=n._meta;if(n.kind==="literal")return typeof r?.value=="string";if(n.kind!=="union"||r?.members===void 0)return!1;const{members:s}=r;return s.some(e=>p(e))&&s.every(e=>e.kind==="null"||p(e))},L=(t,n)=>{const r=s=>o.optional(o.array(s).check(e=>e.length<=n,{message:`at most ${String(n)} values`}));return o.object({...p(t)?{contains:o.optional(o.string())}:{},eq:o.optional(t),gt:o.optional(t),gte:o.optional(t),in:r(t),isNull:o.optional(o.boolean()),lt:o.optional(t),lte:o.optional(t),ne:o.optional(t),notIn:r(t)})},_=(t,n,r)=>t===void 0||!Number.isFinite(t)?Math.min(n,r):Math.min(Math.max(1,Math.floor(t)),r),u=(t,n)=>t===void 0||!Number.isFinite(t)?n:Math.max(1,Math.floor(t)),I=new Set(["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"]),M=(t,n,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const s=t,e={};let l=0;for(const a of I){if(!Object.hasOwn(s,a)||(l+=1,a==="contains"&&!r))continue;const c=s[a];e[a]=Array.isArray(c)?c.slice(0,n):c}return l===0?void 0:e},B=(t,n,r,s)=>{const e={};for(const l of n){if(!Object.hasOwn(t,l))continue;const a=t[l],c=M(a,s,r.has(l));c!==void 0&&Object.keys(c).length===0||(e[l]=c??a)}return e},T=()=>t=>{const n=u(t.defaultLimit,g),r=u(t.maxLimit,A),s=u(t.maxInValues,O),e=u(t.maxOrderBy,S),l=new Set(Object.keys(t.filter)),a=new Set,c={};for(const[i,d]of Object.entries(t.filter))p(d)&&a.add(i),c[i]=o.optional(o.union(d,L(d,s)));const h=new Set(t.orderBy),y=t.orderBy.length===0?o.string().check(()=>!1,{message:"no sortable columns are declared for this endpoint"}):o.union(...t.orderBy.map(i=>o.literal(i)));return{args:{cursor:o.optional(o.union(o.string(),o.number(),o.null())),limit:o.optional(o.number()),orderBy:o.optional(o.array(o.object({direction:o.optional(o.union(o.literal("asc"),o.literal("desc"))),field:y}))),where:o.optional(o.object(c))},toQueryArgs:i=>{const d=i.orderBy?.filter(m=>h.has(m.field)).slice(0,e).map(m=>({[m.field]:m.direction??"asc"})),f=i.where===void 0?void 0:B(i.where,l,a,s);return{...i.cursor===void 0?{}:{cursor:typeof i.cursor=="number"?String(i.cursor):i.cursor},limit:_(i.limit,n,r),...d===void 0||d.length===0?{}:{orderBy:d},...f===void 0?{}:{where:f}}}}};export{g as DEFAULT_LIMIT,O as DEFAULT_MAX_IN_VALUES,A as DEFAULT_MAX_LIMIT,S as DEFAULT_MAX_ORDER_BY,_ as clampLimit,T as defineListArgs,u as normalizeBound,B as sanitizeWhere};
@@ -1 +0,0 @@
1
- import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-BOMWQpoF.mjs";import{initLunora as v}from"./initLunora-D5TSiy5j.mjs";import{g as x,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:j}=v.dataModel().create(),X=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):E,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,a)=>{for(const c of L){const s=(a[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
@@ -1,5 +0,0 @@
1
- import{LunoraError as E,toErrorBody as O,isLunoraError as P}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as N}from"@lunora/values";import{Hono as _}from"hono";import{a as q}from"./apply-output-C5wZ5EAL.mjs";const V=e=>async r=>e(r.get("lunora"),r.req.raw),$=()=>{const e=new _;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},x=(e,r,o)=>{const n=k(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},v=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return R(e,o,"searchParams")},S=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(k(a).kind,d)}return R(e,n,"params")},C=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},T=e=>{if(e instanceof N)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(P(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},j=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},H=(e,r)=>async o=>{const n=j(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},d=Object.keys(e.params).length>0?S(e.params,o):{},i=Object.keys(e.body).length>0?await C(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?q(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const p=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:p?c:void 0,status:204}):Response.json(s,{headers:p?c:void 0})}catch(t){return T(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(e);return`${r?`event: ${r}
2
- `:""}data: ${o}
3
-
4
- `},L=(e,r)=>(async o=>{const n=j(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},a=Object.keys(e.params).length>0?S(e.params,o):{}}catch(m){return T(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const p=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const y of f){if(s.signal.aborted)break;m.enqueue(h.encode(b(y)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:y,redacted:A}=O(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});A&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:y.code,message:y.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(p,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>H(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>L(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},J=e=>!(e.includes("\r")||e.includes(`
5
- `)||e.includes("\0"));export{V as httpAction,U as httpRoute,$ as httpRouter,J as isSafeHeaderValue};
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{i as y,a as R}from"./middleware-BU9adRMp.mjs";const U=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},v=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},N=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",v],["getUrl","read"],["head","read"],["store","write"]],$=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},A=(e,t)=>{const o=e.bucketName??"default",{bucket:c}=e;for(const s of new Set(t))if(!(s===o||typeof c=="function"&&$(c,s)))throw new b("INTERNAL",`storageRules: rule for bucket "${s}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${s}" 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 })\`.`)},S=(e,t={})=>{const o=y(t.roles);return async({ctx:c,next:s})=>{const g=await R(c.auth??{},o),w=(n,a,i)=>{const d=e.filter(r=>r.on===n&&r.bucket===i);if(d.length===0)return;const u={auth:g,ctx:c,key:a};if(!d.some(r=>U(r.prefix,a)&&r.when(u)===!0))throw new b("FORBIDDEN",`storage ${n} on "${a}" in bucket "${i}" denied by access rule`)},p=n=>{const a=n.bucketName??"default",i={bucketName:a};for(const[u,l]of N){const r=n[u];typeof r=="function"&&(i[u]=(...f)=>{const k=typeof f[0]=="string"?f[0]:"",m=typeof l=="function"?l(f):l;return w(m,k,a),r(...f)})}const{bucket:d}=n;return typeof d=="function"&&(i.bucket=u=>p(d(u))),i},h=c.storage;return h===void 0?s():(A(h,e.map(n=>n.bucket)),s({ctx:{storage:p(h)}}))}};export{S as storageRules};