@lunora/server 1.0.0-alpha.121 → 1.0.0-alpha.122

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/README.md CHANGED
@@ -91,7 +91,7 @@ export const send = mutation
91
91
 
92
92
  The builder chain is `<builder>.input(validators).<kind>(handler)`, plus `.use(middleware)` and `.output(validator)`. `internalQuery` / `internalMutation` / `internalAction` are the same builders but kept off the public `api`. Run `lunora codegen` (or the Vite plugin) to (re)generate `_generated/` after a schema change.
93
93
 
94
- > **Determinism:** `query` and `mutation` handlers must be deterministic — they may be re-run on OCC retry or subscription re-evaluation. Read the current time from **`ctx.now`** (epoch ms, captured once per execution — also on `ActionCtx`) instead of `Date.now()`; compute randomness and network results in an `action` (`crypto.randomUUID()`, `fetch`) and pass them into the mutation as arguments. The `nondeterministic_query_mutation` advisor flags `Date.now()`/`Math.random()`/`fetch` in query/mutation handlers.
94
+ > **Determinism:** `query` and `mutation` handlers must be deterministic — they may be re-run on subscription re-evaluation (an OCC conflict surfaces as a `409` to the caller, not an internal retry). Read the current time from **`ctx.now`** (epoch ms, captured once per execution — also on `ActionCtx`) instead of `Date.now()`; compute randomness and network results in an `action` (`crypto.randomUUID()`, `fetch`) and pass them into the mutation as arguments. The `nondeterministic_query_mutation` advisor flags `Date.now()`/`Math.random()`/`fetch` in query/mutation handlers.
95
95
 
96
96
  ### Local-first sync engine
97
97
 
@@ -128,22 +128,28 @@ export const getProduct = httpRoute
128
128
  });
129
129
  ```
130
130
 
131
- **Purge cache by tag** from an action handler:
131
+ **Purge cache by tag** from an HTTP action handler:
132
132
 
133
133
  ```ts
134
- import { action } from "./_generated/server";
134
+ import { httpAction, httpRouter } from "@lunora/server";
135
135
 
136
- export const refreshProducts = action.action(async ({ ctx }) => {
137
- if (!ctx.cache) {
138
- throw new Error("Workers Cache is not enabled in wrangler.jsonc");
139
- }
136
+ export const app = httpRouter();
140
137
 
141
- await ctx.cache.purge({ tags: ["products"] });
142
- return { ok: true };
143
- });
138
+ app.post(
139
+ "/admin/refresh-products",
140
+ httpAction(async (ctx) => {
141
+ if (!ctx.cache) {
142
+ return new Response("Workers Cache is not enabled in wrangler.jsonc", { status: 501 });
143
+ }
144
+
145
+ await ctx.cache.purge({ tags: ["products"] });
146
+
147
+ return Response.json({ ok: true });
148
+ }),
149
+ );
144
150
  ```
145
151
 
146
- The `ctx.cache.purge` API accepts `{ tags?: string[]; purgeEverything?: boolean }`. Only action handlers expose `ctx.cache`; queries and mutations run inside the Durable Object and do not have access to the Worker-level cache binding.
152
+ The `ctx.cache.purge` API accepts `{ tags?: string[]; purgeEverything?: boolean }`. Only **HTTP action** handlers expose `ctx.cache`: the Worker holds the cache binding and builds `HttpActionCtx`. Queries, mutations, and actions reached over RPC all run inside the Durable Object, where `ctx.cache` is `undefined`.
147
153
 
148
154
  ## Related
149
155
 
package/dist/index.d.mts CHANGED
@@ -3069,6 +3069,19 @@ type PresenceComponent = Component<{
3069
3069
  declare const presenceExtension: SchemaExtension<{
3070
3070
  [PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
3071
3071
  }>;
3072
+ /**
3073
+ * Build a presence {@link Component} — schema extension + heartbeat / listPresent
3074
+ * / sweep functions — wired to a single TTL. Re-export `component.functions`
3075
+ * from your `lunora/` module so codegen exposes them, and `.extend(component.
3076
+ * extension)` to merge the table.
3077
+ *
3078
+ * Deviations from the brief: `sweep` is shipped as an **internal** mutation
3079
+ * (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
3080
+ * client triggered. `listPresent` stays a plain public query so the client can
3081
+ * subscribe to it.
3082
+ * @param options presence configuration (TTL).
3083
+ * @returns a component bundling the extension and the presence functions.
3084
+ */
3072
3085
  declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
3073
3086
  /**
3074
3087
  * The middlewares `protectPublic` chains, in the order they run. Every field is
package/dist/index.d.ts CHANGED
@@ -3069,6 +3069,19 @@ type PresenceComponent = Component<{
3069
3069
  declare const presenceExtension: SchemaExtension<{
3070
3070
  [PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
3071
3071
  }>;
3072
+ /**
3073
+ * Build a presence {@link Component} — schema extension + heartbeat / listPresent
3074
+ * / sweep functions — wired to a single TTL. Re-export `component.functions`
3075
+ * from your `lunora/` module so codegen exposes them, and `.extend(component.
3076
+ * extension)` to merge the table.
3077
+ *
3078
+ * Deviations from the brief: `sweep` is shipped as an **internal** mutation
3079
+ * (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
3080
+ * client triggered. `listPresent` stays a plain public query so the client can
3081
+ * subscribe to it.
3082
+ * @param options presence configuration (TTL).
3083
+ * @returns a component bundling the extension and the presence functions.
3084
+ */
3072
3085
  declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
3073
3086
  /**
3074
3087
  * The middlewares `protectPublic` chains, in the order they run. Every field is
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as c,flushDeferredDeletes as l,withDeferredDeletes as E}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as h}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as R}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs";import{LunoraEnvError as L,defineEnv as C,redactSecrets as I}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as F,httpRoute as O,httpRouter as H,isSafeHeaderValue as N}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as k}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as w}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as V,onDisconnect as j,onShardInit as W}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as J,DEFAULT_MAX_LIMIT as K,clampLimit as Q,defineListArgs as X}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as z}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Z}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as ee,d as re,a as oe,b as te,e as ne,f as ie,g as ae,h as fe,i as se,j as de,k as me,m as pe}from"./packem_shared/plugin-DY0N7ZWx.mjs";import{PRESENCE_DEFAULT_TTL_MS as ce,PRESENCE_TABLE as le,definePresence as Ee,presenceExtension as Se}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DheiApL3.mjs";import{protectPublic as he}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-DtBuu6Yh.mjs";import{anyApi as _e}from"./types.mjs";import{LunoraError as Ce}from"@lunora/errors";import{cronJobs as be}from"@lunora/scheduler";import{ValidationError as Pe,v as Me}from"@lunora/values";import{allowAll as Oe,deny as He,isDeny as Ne,toWhereInput as Ue}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Be,buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/assertShapesDeclareReadPolicies-DHLO-AVP.mjs";import{buildMaskRegistry as Ye}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ke,definePermission as Qe,definePolicies as Xe,definePolicy as qe,defineRole as ze}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ze,defineStorageRules as $e}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as rr}from"./packem_shared/mask-rh0M0XlH.mjs";import{r as tr}from"./packem_shared/middleware-DciZ1Q3A.mjs";import{storageRules as ir}from"./packem_shared/storageRules-DvM18uSL.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,J as DEFAULT_LIMIT,K as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,L as LunoraEnvError,Ce as LunoraError,ce as PRESENCE_DEFAULT_TTL_MS,le as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Oe as allowAll,_e as anyApi,ve as asBucketStorage,Be as assertShapesDeclareReadPolicies,c as beginDeferredDeletes,u as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,Ye as buildMaskRegistry,Ve as buildRlsReadRegistry,a as cacheKeyFor,Q as clampLimit,ee as composePluginMiddleware,je as composeShapeReadWhere,Ke as createPolicyDsl,p as createSecrets,be as cronJobs,f as defineActionCache,re as defineAggregateIndex,oe as defineComponent,A as defineDocumentHistory,C as defineEnv,w as defineIdentity,X as defineListArgs,z as defineMigration,Z as defineMutator,Qe as definePermission,te as definePlugin,Xe as definePolicies,qe as definePolicy,Ee as definePresence,ne as defineRankIndex,ze as defineRole,ie as defineSchema,ae as defineSchemaExtension,Ae as defineShape,Ze as defineStorageRule,$e as defineStorageRules,fe as defineTable,se as defineVectorIndex,He as deny,R as documentHistoryExtension,l as flushDeferredDeletes,F as httpAction,O as httpRoute,H as httpRouter,de as indexFieldsFromSchema,d as initLunora,me as installPlugins,Ne as isDeny,N as isSafeHeaderValue,rr as mask,pe as mergeSchemaExtension,V as onConnect,j as onDisconnect,Te as onQueryChange,W as onShardInit,Se as presenceExtension,he as protectPublic,I as redactSecrets,tr as rls,k as serveStorageObject,ir as storageRules,Ue as toWhereInput,Me as v,E as withDeferredDeletes,h as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-COBng51i.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as c,flushDeferredDeletes as l,withDeferredDeletes as E}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as h}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as R}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-C8sDYzqZ.mjs";import{LunoraEnvError as L,defineEnv as C,redactSecrets as I}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as F,httpRoute as O,httpRouter as H,isSafeHeaderValue as N}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as k}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as w}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as V,onDisconnect as j,onShardInit as W}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as J,DEFAULT_MAX_LIMIT as K,clampLimit as Q,defineListArgs as X}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as z}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Z}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as ee,d as re,a as oe,b as te,e as ne,f as ie,g as ae,h as fe,i as se,j as de,k as me,m as pe}from"./packem_shared/plugin-CqXQ2s-i.mjs";import{PRESENCE_DEFAULT_TTL_MS as ce,PRESENCE_TABLE as le,definePresence as Ee,presenceExtension as Se}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-BzZ7xnmQ.mjs";import{protectPublic as he}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-DtBuu6Yh.mjs";import{anyApi as _e}from"./types.mjs";import{LunoraError as Ce}from"@lunora/errors";import{cronJobs as be}from"@lunora/scheduler";import{ValidationError as Pe,v as Me}from"@lunora/values";import{allowAll as Oe,deny as He,isDeny as Ne,toWhereInput as Ue}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Be,buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/assertShapesDeclareReadPolicies-DHLO-AVP.mjs";import{buildMaskRegistry as Ye}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ke,definePermission as Qe,definePolicies as Xe,definePolicy as qe,defineRole as ze}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ze,defineStorageRules as $e}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as rr}from"./packem_shared/mask-rh0M0XlH.mjs";import{r as tr}from"./packem_shared/middleware-DciZ1Q3A.mjs";import{storageRules as ir}from"./packem_shared/storageRules-DvM18uSL.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,J as DEFAULT_LIMIT,K as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,L as LunoraEnvError,Ce as LunoraError,ce as PRESENCE_DEFAULT_TTL_MS,le as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Oe as allowAll,_e as anyApi,ve as asBucketStorage,Be as assertShapesDeclareReadPolicies,c as beginDeferredDeletes,u as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,Ye as buildMaskRegistry,Ve as buildRlsReadRegistry,a as cacheKeyFor,Q as clampLimit,ee as composePluginMiddleware,je as composeShapeReadWhere,Ke as createPolicyDsl,p as createSecrets,be as cronJobs,f as defineActionCache,re as defineAggregateIndex,oe as defineComponent,A as defineDocumentHistory,C as defineEnv,w as defineIdentity,X as defineListArgs,z as defineMigration,Z as defineMutator,Qe as definePermission,te as definePlugin,Xe as definePolicies,qe as definePolicy,Ee as definePresence,ne as defineRankIndex,ze as defineRole,ie as defineSchema,ae as defineSchemaExtension,Ae as defineShape,Ze as defineStorageRule,$e as defineStorageRules,fe as defineTable,se as defineVectorIndex,He as deny,R as documentHistoryExtension,l as flushDeferredDeletes,F as httpAction,O as httpRoute,H as httpRouter,de as indexFieldsFromSchema,d as initLunora,me as installPlugins,Ne as isDeny,N as isSafeHeaderValue,rr as mask,pe as mergeSchemaExtension,V as onConnect,j as onDisconnect,Te as onQueryChange,W as onShardInit,Se as presenceExtension,he as protectPublic,I as redactSecrets,tr as rls,k as serveStorageObject,ir as storageRules,Ue as toWhereInput,Me as v,E as withDeferredDeletes,h as withDeferredSchedules};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CH4vwdFT.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-BzC2zEfH.mjs";import{g as k,h as q,a as B}from"./plugin-DY0N7ZWx.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
1
+ import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CH4vwdFT.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-BzC2zEfH.mjs";import{g as k,h as q,a as B}from"./plugin-CqXQ2s-i.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CH4vwdFT.mjs";import{initLunora as x}from"./initLunora-BzC2zEfH.mjs";import{g as v,h as R,a as U}from"./plugin-DY0N7ZWx.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CH4vwdFT.mjs";import{initLunora as x}from"./initLunora-BzC2zEfH.mjs";import{g as v,h as R,a as U}from"./plugin-CqXQ2s-i.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BzC2zEfH.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-DY0N7ZWx.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BzC2zEfH.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-CqXQ2s-i.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +1 @@
1
- import"./compose-middleware-MCpZZKh7.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-DY0N7ZWx.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
1
+ import"./compose-middleware-MCpZZKh7.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-CqXQ2s-i.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -1 +1 @@
1
- import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-DY0N7ZWx.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
1
+ import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-CqXQ2s-i.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-MCpZZKh7.mjs";import{v as B}from"@lunora/values";const _=["de","en","es","fr","it","nl","none","pt"],q=["native","portable"],H=e=>q.includes(e),Q=e=>_.includes(e),F=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?F(t):e.kind},D=16,X={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),U=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),P=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ce=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},l=[],f={},h=U(),b=[];let w={kind:"root"},S=!1,N=!1,$=!1,T=!1,L,M,A,O;const R=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},c={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return S=!0,c},get commitOrderedMode(){return S},externallyManaged(){return N=!0,c},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),c},get geoIndexes(){return r},global(a){return R({backend:a?.backend??"d1",kind:"global"}),c},get isExternallyManaged(){return N},get isPublic(){return T},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),c},get indexes(){return i},memory(){return $=!0,c},get memoryMode(){return $},ownedBy(a){return L=a,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:P(a,o.sortBy),where:o.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(X)),c},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>D)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(D)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!Q(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${_.join(", ")})`);const{strategy:p}=o;if(p!==void 0&&!H(p))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${p}" (supported: ${q.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(a){return R({field:a,kind:"shardBy"}),c},get shardMode(){return w},get softDeleteMode(){return M},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=a,N=!0,c},softDelete(a){const o=a?.field??"deletedAt";return M={field:o},o in t||(t[o]=B.optional(B.number().nullable())),c},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),c},ttl(a,o){return A={after:o?.after,field:a},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),c}};return c},ue=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},he=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:P(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(K(e,t))},jurisdiction(t){return I(e)},rls(t){return I({...e,rlsMode:t})}}),V=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Y=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},G=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},J=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=G(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},W=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);J(t,r)}}},Z=["_commitSeq","_creationTime","_id"],j="_commitSeq",ee=new Set(Z),x=(e,t,n,r)=>{if(!(ee.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},C=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},te=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,te);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ne=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},re=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(F(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},ae=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(j))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${j}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},ge=(e,t={},n={},r={})=>(V(e),Y(e,n,r),W(e),ae(e),re(e),ne(e),C(e),I({tables:e,vectorIndexes:t})),y=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?y(t,e):e,oe=(e,t,n,r)=>{const i=y(t,r),d=h=>h===""?i:k(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:k(b.table,t,n)};const l=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},be=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ie=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),we=(e,t)=>({...ie(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),K=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=y(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=oe(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=y(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:k(l.table,n,r)}}return C(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},xe=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=K(n,r.extension));return n},Ie=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{we as a,ie as b,Ie as c,fe as d,he as e,ge as f,be as g,ce as h,ue as i,me as j,xe as k,K as m,C as v};
package/dist/types.d.mts CHANGED
@@ -2210,7 +2210,7 @@ interface SpanOptions {
2210
2210
  * @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
2211
2211
  * and put the varying part in `attributes` — a name built from an id makes every
2212
2212
  * span its own group in a collector.
2213
- * @param fn The body to time, receiving a tracer bound to this span for any
2213
+ * @param function_ The body to time, receiving a tracer bound to this span for any
2214
2214
  * nested spans and the enclosing span's {@link SpanHandle} for post-hoc
2215
2215
  * attributes. May be sync or async; the result is awaited.
2216
2216
  * @param attributes Either a plain attribute bag to stamp on the span at start
@@ -2368,7 +2368,8 @@ interface QueryCtx {
2368
2368
  /**
2369
2369
  * Wall-clock time (epoch ms) the function began, captured once so the whole
2370
2370
  * handler sees a single stable value. Query/mutation handlers must be
2371
- * deterministic — they may be re-run on OCC retry / subscription re-eval — so
2371
+ * deterministic — they may be re-run on subscription re-evaluation (an OCC
2372
+ * conflict surfaces as a `409` to the caller, not an internal retry) — so
2372
2373
  * read time through `ctx.now` instead of `Date.now()` (the latter is flagged
2373
2374
  * by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2374
2375
  */
@@ -2423,9 +2424,10 @@ interface MutationCtx {
2423
2424
  /**
2424
2425
  * Wall-clock time (epoch ms) the function began, captured once so the whole
2425
2426
  * handler sees a single stable value. Mutation handlers must be deterministic
2426
- * — they may be re-run on OCC retry — so read time through `ctx.now` instead
2427
- * of `Date.now()` (the latter is flagged by the `nondeterministic_query_mutation`
2428
- * advisor). Actions may use `Date.now()`.
2427
+ * — an OCC conflict surfaces as a `409` to the caller rather than an internal
2428
+ * retry, but a caller's own retry is a fresh dispatch — so read time through
2429
+ * `ctx.now` instead of `Date.now()` (the latter is flagged by the
2430
+ * `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2429
2431
  */
2430
2432
  readonly now: number;
2431
2433
  /**
package/dist/types.d.ts CHANGED
@@ -2210,7 +2210,7 @@ interface SpanOptions {
2210
2210
  * @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
2211
2211
  * and put the varying part in `attributes` — a name built from an id makes every
2212
2212
  * span its own group in a collector.
2213
- * @param fn The body to time, receiving a tracer bound to this span for any
2213
+ * @param function_ The body to time, receiving a tracer bound to this span for any
2214
2214
  * nested spans and the enclosing span's {@link SpanHandle} for post-hoc
2215
2215
  * attributes. May be sync or async; the result is awaited.
2216
2216
  * @param attributes Either a plain attribute bag to stamp on the span at start
@@ -2368,7 +2368,8 @@ interface QueryCtx {
2368
2368
  /**
2369
2369
  * Wall-clock time (epoch ms) the function began, captured once so the whole
2370
2370
  * handler sees a single stable value. Query/mutation handlers must be
2371
- * deterministic — they may be re-run on OCC retry / subscription re-eval — so
2371
+ * deterministic — they may be re-run on subscription re-evaluation (an OCC
2372
+ * conflict surfaces as a `409` to the caller, not an internal retry) — so
2372
2373
  * read time through `ctx.now` instead of `Date.now()` (the latter is flagged
2373
2374
  * by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2374
2375
  */
@@ -2423,9 +2424,10 @@ interface MutationCtx {
2423
2424
  /**
2424
2425
  * Wall-clock time (epoch ms) the function began, captured once so the whole
2425
2426
  * handler sees a single stable value. Mutation handlers must be deterministic
2426
- * — they may be re-run on OCC retry — so read time through `ctx.now` instead
2427
- * of `Date.now()` (the latter is flagged by the `nondeterministic_query_mutation`
2428
- * advisor). Actions may use `Date.now()`.
2427
+ * — an OCC conflict surfaces as a `409` to the caller rather than an internal
2428
+ * retry, but a caller's own retry is a fresh dispatch — so read time through
2429
+ * `ctx.now` instead of `Date.now()` (the latter is flagged by the
2430
+ * `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2429
2431
  */
2430
2432
  readonly now: number;
2431
2433
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.121",
3
+ "version": "1.0.0-alpha.122",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -69,7 +69,7 @@
69
69
  "@lunora/errors": "1.0.0-alpha.36",
70
70
  "@lunora/scheduler": "1.0.0-alpha.71",
71
71
  "@lunora/shard-engine": "1.0.0-alpha.64",
72
- "@lunora/values": "1.0.0-alpha.45",
72
+ "@lunora/values": "1.0.0-alpha.46",
73
73
  "drizzle-orm": "^0.45.2",
74
74
  "hono": "^4.13.7"
75
75
  },
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{c as K}from"./compose-middleware-MCpZZKh7.mjs";import{v as R}from"@lunora/values";const j=["de","en","es","fr","it","nl","none","pt"],_=["native","portable"],z=e=>_.includes(e),H=e=>j.includes(e),q=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?q(t):e.kind},B=16,Q={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),X=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),F=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},le=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},l=[],f={},m=X(),b=[];let y={kind:"root"},$=!1,N=!1,k=!1,T=!1,L,M,A,O;const c={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return $=!0,c},get commitOrderedMode(){return $},externallyManaged(){return N=!0,c},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),c},get geoIndexes(){return r},global(i){return y={backend:i?.backend??"d1",kind:"global"},c},get isExternallyManaged(){return N},get isPublic(){return T},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),c},get indexes(){return o},memory(){return k=!0,c},get memoryMode(){return k},ownedBy(i){return L=i,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:F(i,a.sortBy),where:a.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Q)),c},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>B)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(B)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!H(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${j.join(", ")})`);const{strategy:v}=a;if(v!==void 0&&!z(v))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${v}" (supported: ${_.join(", ")})`);return l.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(i){return y={field:i,kind:"shardBy"},c},get shardMode(){return y},get softDeleteMode(){return M},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=i,N=!0,c},softDelete(i){const a=i?.field??"deletedAt";return M={field:a},a in t||(t[a]=R.optional(R.number().nullable())),c},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),c},ttl(i,a){return A={after:a?.after,field:i},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(i,a){return b.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,name:a.index}),c}};return c},ce=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),ue=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},fe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:F(e,t.sortBy),where:t.where}),x=e=>({...e,extend(t){return x(C(e,t))},jurisdiction(t){return x(e)},rls(t){return x({...e,rlsMode:t})}}),U=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},V=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},Y=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},G=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=Y(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},J=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);G(t,r)}}},W=["_commitSeq","_creationTime","_id"],D="_commitSeq",Z=new Set(W),w=(e,t,n,r)=>{if(!(Z.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},p=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},P=e=>{for(const[t,n]of Object.entries(e))p(t,"index",n.indexes,r=>{for(const o of r.fields)w(t,r.name,o,n)}),p(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)w(t,r.name,o.field,n);for(const o of r.partitionBy??[])w(t,r.name,o,n)}),p(t,"geo index",n.geoIndexes,r=>{w(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},ee=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,ee);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},te=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ne=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(q(o)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},re=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(D))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${D}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},he=(e,t={},n={},r={})=>(U(e),V(e,n,r),J(e),re(e),ne(e),te(e),P(e),x({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,S=(e,t,n)=>n.has(e)?I(t,e):e,ae=(e,t,n,r)=>{const o=I(t,r),d=m=>m===""?o:S(m,t,n),u={};for(const[m,b]of Object.entries(e.relationMap))u[m]={...b,table:S(b.table,t,n)};const l=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},ge=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},oe=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),be=(e,t)=>({...oe(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),C=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=ae(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:S(l.table,n,r)}}return P(o),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},we=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=C(n,r.extension));return n},xe=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return K(t)};export{be as a,oe as b,xe as c,ue as d,fe as e,he as f,ge as g,le as h,ce as i,me as j,we as k,C as m,P as v};