@lunora/server 1.0.0-alpha.270 → 1.0.0-alpha.271
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 +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{defineLiveStream-CmmPtMBt.mjs → defineLiveStream-B9_cpxrR.mjs} +1 -1
- package/dist/packem_shared/httpAction-DKWIT1bN.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/httpAction-CVo4_CSy.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -2029,8 +2029,16 @@ interface LivePublisher {
|
|
|
2029
2029
|
* `c.var.lunora` so handlers can read it as a typed variable.
|
|
2030
2030
|
*/
|
|
2031
2031
|
interface LunoraHttpEnv {
|
|
2032
|
+
/**
|
|
2033
|
+
* `__lunoraUnrouted` is how the runtime learns that no route matched (rather than a handler answering 404 on
|
|
2034
|
+
* purpose): only the router's own not-found handler calls it. `__lunoraShellFirst` marks a page navigation the
|
|
2035
|
+
* single-page app's assets binding answers with its shell (never a real file): when no route matches it, the
|
|
2036
|
+
* router says so before any app middleware runs, so a blanket auth gate cannot turn a deep link into its 401.
|
|
2037
|
+
*/
|
|
2032
2038
|
Bindings: Record<string, unknown> & {
|
|
2033
2039
|
__lunoraCtx?: HttpActionCtx;
|
|
2040
|
+
__lunoraShellFirst?: boolean;
|
|
2041
|
+
__lunoraUnrouted?: () => void;
|
|
2034
2042
|
};
|
|
2035
2043
|
Variables: {
|
|
2036
2044
|
lunora: HttpActionCtx;
|
|
@@ -2064,6 +2072,11 @@ declare const httpAction: (handler: HttpActionHandler) => LunoraRouteHandler;
|
|
|
2064
2072
|
* export default createWorker({ httpRouter: app, ... });
|
|
2065
2073
|
* ```
|
|
2066
2074
|
*
|
|
2075
|
+
* A request no route matched answers Hono's plain 404 and tells the runtime, which
|
|
2076
|
+
* may serve a single-page app's shell for it (`spaAssets` in `@lunora/runtime`).
|
|
2077
|
+
* That holds for a not-found handler the app sets with `app.notFound(…)` too. A
|
|
2078
|
+
* `c.notFound()` a handler or middleware returns stays a real 404.
|
|
2079
|
+
*
|
|
2067
2080
|
* The lifting middleware throws if the context is absent. `createWorker` injects
|
|
2068
2081
|
* it on every request the router sees, so this only trips when the app is run
|
|
2069
2082
|
* outside the runtime — a misconfiguration we surface loudly rather than let
|
|
@@ -2452,7 +2465,7 @@ declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHo
|
|
|
2452
2465
|
*
|
|
2453
2466
|
* export const warm = onShardInit(async (ctx, event) => {
|
|
2454
2467
|
* // Rebuild ephemeral state from the durable tables that outlived us.
|
|
2455
|
-
* for await (const member of ctx.db.roomMembers.
|
|
2468
|
+
* for await (const member of ctx.db.query("roomMembers").filter((m) => m.roomId === event.shardKey)) {
|
|
2456
2469
|
* await ctx.db.presence.insert({ userId: member.userId, status: "away" });
|
|
2457
2470
|
* }
|
|
2458
2471
|
* });
|
package/dist/index.d.ts
CHANGED
|
@@ -2029,8 +2029,16 @@ interface LivePublisher {
|
|
|
2029
2029
|
* `c.var.lunora` so handlers can read it as a typed variable.
|
|
2030
2030
|
*/
|
|
2031
2031
|
interface LunoraHttpEnv {
|
|
2032
|
+
/**
|
|
2033
|
+
* `__lunoraUnrouted` is how the runtime learns that no route matched (rather than a handler answering 404 on
|
|
2034
|
+
* purpose): only the router's own not-found handler calls it. `__lunoraShellFirst` marks a page navigation the
|
|
2035
|
+
* single-page app's assets binding answers with its shell (never a real file): when no route matches it, the
|
|
2036
|
+
* router says so before any app middleware runs, so a blanket auth gate cannot turn a deep link into its 401.
|
|
2037
|
+
*/
|
|
2032
2038
|
Bindings: Record<string, unknown> & {
|
|
2033
2039
|
__lunoraCtx?: HttpActionCtx;
|
|
2040
|
+
__lunoraShellFirst?: boolean;
|
|
2041
|
+
__lunoraUnrouted?: () => void;
|
|
2034
2042
|
};
|
|
2035
2043
|
Variables: {
|
|
2036
2044
|
lunora: HttpActionCtx;
|
|
@@ -2064,6 +2072,11 @@ declare const httpAction: (handler: HttpActionHandler) => LunoraRouteHandler;
|
|
|
2064
2072
|
* export default createWorker({ httpRouter: app, ... });
|
|
2065
2073
|
* ```
|
|
2066
2074
|
*
|
|
2075
|
+
* A request no route matched answers Hono's plain 404 and tells the runtime, which
|
|
2076
|
+
* may serve a single-page app's shell for it (`spaAssets` in `@lunora/runtime`).
|
|
2077
|
+
* That holds for a not-found handler the app sets with `app.notFound(…)` too. A
|
|
2078
|
+
* `c.notFound()` a handler or middleware returns stays a real 404.
|
|
2079
|
+
*
|
|
2067
2080
|
* The lifting middleware throws if the context is absent. `createWorker` injects
|
|
2068
2081
|
* it on every request the router sees, so this only trips when the app is run
|
|
2069
2082
|
* outside the runtime — a misconfiguration we surface loudly rather than let
|
|
@@ -2452,7 +2465,7 @@ declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHo
|
|
|
2452
2465
|
*
|
|
2453
2466
|
* export const warm = onShardInit(async (ctx, event) => {
|
|
2454
2467
|
* // Rebuild ephemeral state from the durable tables that outlived us.
|
|
2455
|
-
* for await (const member of ctx.db.roomMembers.
|
|
2468
|
+
* for await (const member of ctx.db.query("roomMembers").filter((m) => m.roomId === event.shardKey)) {
|
|
2456
2469
|
* await ctx.db.presence.insert({ userId: member.userId, status: "away" });
|
|
2457
2470
|
* }
|
|
2458
2471
|
* });
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as O,bindTableFacade as F,defineLazyFacade as v}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as U,httpRoute as H,httpRouter as k,lastEventId as w,sseEvent as B}from"./packem_shared/httpAction-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as O,bindTableFacade as F,defineLazyFacade as v}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as U,httpRoute as H,httpRouter as k,lastEventId as w,sseEvent as B}from"./packem_shared/httpAction-DKWIT1bN.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as G}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as K,onDisconnect as Q,onShardInit as X}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-B9_cpxrR.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as de}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as ue,b as Se,e as De,f as he,g as Te,h as Re,i as Ae,j as ge,k as Le,m as _e}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs";import{PROCEDURE_META as Oe,UNLOADED_META as Fe,procedureMeta as ve}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ue}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as ke}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Be}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as We}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-CAIsX21I.mjs";import{defineWebSocket as Ge}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ke}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Xe}from"@lunora/errors";import{cronJobs as Ze}from"@lunora/scheduler";import{ValidationError as er,v as rr}from"@lunora/values";import{allowAll as tr,deny as ir,isDeny as nr,toWhereInput as fr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as dr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as mr,buildRlsReadRegistry as pr,composeShapeReadWhere as xr}from"./packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs";import{buildMaskRegistry as lr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as ur,definePermission as Sr,definePolicies as Dr,definePolicy as hr,defineRole as Tr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ar,defineStorageRules as gr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as _r}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Cr}from"./packem_shared/mask--ZXtzCj7.mjs";import{r as Pr}from"./packem_shared/middleware-CdoC33P7.mjs";import{storageRules as yr}from"./packem_shared/storageRules-BZgB67oS.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Xe as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,Oe as PROCEDURE_META,Fe as UNLOADED_META,e as VERSION,er as ValidationError,n as actionCacheExtension,tr as allowAll,dr as asBucketStorage,mr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,O as bindOrm,F as bindTableFacade,lr as buildMaskRegistry,pr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,xr as composeShapeReadWhere,ur as createPolicyDsl,l as createSecrets,We as createServices,Ze as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,ue as defineComponent,_ as defineDocumentHistory,P as defineEnv,Y as defineIdentity,G as defineIdentityGuard,v as defineLazyFacade,re as defineListArgs,te as defineLiveStream,fe as defineMigration,de as defineModule,me as defineMutator,Sr as definePermission,Se as definePlugin,Dr as definePolicies,hr as definePolicy,Pe as definePresence,De as defineRankIndex,Tr as defineRole,Be as defineRoom,he as defineSchema,Te as defineSchemaExtension,Ye as defineShape,Ar as defineStorageRule,gr as defineStorageRules,Re as defineTable,Ae as defineVectorIndex,Ge as defineWebSocket,ir as deny,I as documentHistoryExtension,S as flushDeferredDeletes,U as httpAction,H as httpRoute,k as httpRouter,ge as indexFieldsFromSchema,s as initLunora,Le as installPlugins,nr as isDeny,p as isPerDispatchMiddleware,_r as isSafeHeaderValue,w as lastEventId,ie as liveStreamRouter,Cr as mask,_e as mergeSchemaExtension,K as onConnect,Q as onDisconnect,ke as onQueryChange,X as onShardInit,Ke as onWhisper,xe as platformAdmin,be as presenceExtension,ve as procedureMeta,Ue as protectPublic,b as redactSecrets,Pr as rls,W as serveStorageObject,B as sseEvent,yr as storageRules,x as tagPerDispatchMiddleware,fr as toWhereInput,rr as v,D as withDeferredDeletes,R as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-
|
|
1
|
+
import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-DKWIT1bN.mjs";const A="/_lunora/live/connect",N="/_lunora/live/control",D="room:",B="__lunora_socket__:",K=256,m=e=>`/live/${e}/connect`,v=e=>`/live/${e}/control`,U=/^[A-Za-z]\w*$/u,T=e=>U.test(e),H=e=>`${e}:`.startsWith(D)||`${e}:`.startsWith(B),V=(e,t,o)=>[e,...t.map(d=>{const i=o[d];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${d}`);return encodeURIComponent(i)})].join(":"),k=(e,t)=>{if(e.length>K)return;const[o,...d]=e.split(":");if(o===void 0||!Object.hasOwn(t,o))return;const i=t[o];if(d.length!==i.length)return;const r={};try{for(const[c,u]of i.entries())r[u]=decodeURIComponent(d[c]);return V(o,i,r)===e?{key:r,name:o}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},S=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),M=(e,t)=>{for(const[o,d]of Object.entries(t)){if(!T(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(H(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" would encode into a reserved topic prefix`);for(const[i,r]of Object.entries(d.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a plain identifier`);if(!P(r))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new O("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),q=e=>{M(e.id,e.topics);const t=m(e.id),o=v(e.id),d=Object.fromEntries(Object.entries(e.topics).map(([s,a])=>[s,Object.keys(a.key??{})])),i=s=>{const a=k(s,d),n=a===void 0?void 0:e.topics[a.name];if(!(a===void 0||n===void 0))try{return{declaration:n,key:b(n.key??{},a.key,"key"),name:a.name}}catch{return}},r=(s,a)=>{const n=i(s);if(n===void 0)throw new O("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return b({payload:p.payload},{payload:a},"topic").payload}catch(f){throw z(s,f)}},c=async(s,a)=>{const n=i(a);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:a,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,a)=>{const n=new URL(a.url).searchParams.get("shard")??void 0;return s.fetchShard(n,A,{method:"GET"})}),R=E(async(s,a)=>{const n=await F(a);if(!n)return h("Expected a JSON object body");const{action:p}=n,f=typeof n.topic=="string"?n.topic:void 0;if(f===void 0||f.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const y=typeof n.shardKey=="string"?n.shardKey:void 0,L=y===void 0?s:{...s,...s.forShard(y)};if(p==="subscribe"&&!await c(L,f))return S(f);const w=s.fetchShard(y,N,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return w;try{return await w}catch(l){if(I(l)&&l.code==="FORBIDDEN_SHARD")return S(f);throw l}});return{connect:u,connectPath:t,control:R,controlPath:o,id:e.id,topics:e.topics,validatePublish:r}},G=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},_=new WeakMap,$=(e,t)=>{for(const o of t){let d;const i=()=>(d??=o.load().catch(r=>{throw d=void 0,r}),d);e.get(m(o.id),async r=>{const{connect:c}=await i();return c(r)}),e.post(v(o.id),async r=>{const{control:c}=await i();return c(r)})}},Y=(e,t)=>{if(t instanceof g&&j(t)){const r=_.get(t)??new Set,c=e.filter(u=>!r.has(u.id));$(t,c),_.set(t,r);for(const u of c)r.add(u.id);return t}const o=C();if($(o,e),t===void 0)return o;const d=new Set(e.flatMap(r=>[`GET ${m(r.id)}`,`POST ${v(r.id)}`])),i=(r,c,u)=>typeof t=="function"?t(r,c,u):t.fetch(r,c,u);return{...G(t),fetch:(r,c,u)=>d.has(`${r.method} ${new URL(r.url).pathname}`)?o.fetch(r,c,u):i(r,c,u)}};export{q as defineLiveStream,Y as liveStreamRouter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E,isLunoraError as D,toErrorBody as O}from"@lunora/errors";import{ValidationError as F,parseValidatorMap as g}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as A}from"hono";import{SSE_HEADERS as N,sseFrame as b,isSafeHeaderValue as x}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const v=e=>{if(e instanceof F)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(D(e)){const{body:r,redacted:t,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return t&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},re=e=>async r=>{try{return await e(r.get("lunora"),r.req.raw)}catch(t){return v(t)}},_=new WeakSet,T=new WeakSet,te=e=>T.has(e),P=new WeakSet,I=new Set(["*","/*"]),U="__COMPOSED_HANDLER",B=e=>e[U]??e,M=e=>{let r,t=-1;return async n=>{if(r===void 0||t!==e.routes.length){const a=new A;for(const s of e.routes)P.has(B(s.handler))||a.on(s.method,s.path,()=>new Response(null,{status:204}));r=a,t=e.routes.length}return(await r.fetch(new Request(n.url,{method:n.method}))).status===204}},oe=()=>{const e=new A,r=M(e),t=e.use.bind(e);T.add(e),e.use=((...o)=>{const[a]=o;if(typeof a!="string"||I.has(a))for(const s of o)typeof s=="function"&&P.add(s);return t(...o)}),e.use("*",async(o,a)=>{const s=o.env.__lunoraCtx;if(!s)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",s);const{__lunoraShellFirst:d,__lunoraUnrouted:i}=o.env;if(d===!0&&!await r(o.req.raw))return i?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(_.add(o),c()),await a()});const n=e.notFound;return e.notFound=o=>n(a=>{const{__lunoraUnrouted:s}=a.env;return _.has(a)||s?.(),o(a)}),e.notFound(o=>o.text("404 Not Found",404)),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,w=(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}},V=(e,r,t)=>{const n=k(e);if(n.kind==="array"){const a=r.req.queries(t);if(a===void 0)return;const s=n._meta?.inner;return a.map(d=>w(s?.kind??"string",d))}const o=r.req.query(t);return o===void 0?void 0:w(n.kind,o)},j=(e,r)=>{const t={};for(const n of Object.keys(e)){const o=e[n];o&&(t[n]=V(o,r,n))}return g(e,t,"searchParams")},L=(e,r)=>{const t=r.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=t[o];n[o]=s===void 0?void 0:w(k(a).kind,s)}return g(e,n,"params")},W=async(e,r)=>{let t;try{t=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof t!="object"||t===null||Array.isArray(t))throw new E("BAD_REQUEST","Expected a JSON object body");return g(e,t,"body")},H=(e,r)=>{const{method:t}=r.req;if(!(t===e.method||e.method==="GET"&&t==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${t} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},Q=(e,r)=>async t=>{const n=H(e,t);if(n)return n;try{const o=t.get("lunora"),a=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},s=Object.keys(e.params).length>0?L(e.params,t):{},d=Object.keys(e.body).length>0?await W(e.body,t):{},i=await r({body:d,ctx:o,params:s,searchParams:a}),c=e.output?R(e.output,i):i,u={};e.cacheControl&&(u["cache-control"]=e.cacheControl),e.cacheTag&&(u["cache-tag"]=e.cacheTag),e.vary&&(u.vary=e.vary);const f=Object.keys(u).length>0;return c===void 0?new Response(null,{headers:f?u:void 0,status:204}):Response.json(c,{headers:f?u:void 0})}catch(o){return v(o)}},ne=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const t=new URL(e.url).searchParams.get("lastEventId");return t===null||t===""?void 0:t},q=Symbol.for("@lunora/server/sse-event"),ae=e=>({[q]:!0,data:e.data,id:e.id}),G=e=>typeof e=="object"&&e!==null&&e[q]===!0,J=(e,r)=>{if(G(r)){if(!x(r.id))throw new E("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=e?R(e,r.data):r.data;return b(S(t),void 0,r.id)}return b(S(e?R(e,r):r))},$=(e,r)=>(async t=>{const n=H(e,t);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},a=Object.keys(e.params).length>0?L(e.params,t):{}}catch(m){return v(m)}const s=t.get("lunora"),d=t.req.raw,i=new TextEncoder,c=new AbortController;if(d.signal.aborted)return c.abort(),new Response("",{headers:N});const u=()=>{c.abort()};d.signal.addEventListener("abort",u,{once:!0});const f=new ReadableStream({cancel(){d.signal.removeEventListener("abort",u),c.abort()},async start(m){try{const y=r({ctx:s,params:a,request:d,searchParams:o,signal:c.signal});for await(const p of y){if(c.signal.aborted)break;m.enqueue(i.encode(J(e.output,p)))}c.signal.aborted||m.enqueue(i.encode(b({},"complete")))}catch(y){const{body:p,redacted:C}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});C&&console.error("[lunora] unhandled stream handler error:",y),c.signal.aborted||m.enqueue(i.encode(b({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",u);try{m.close()}catch{}}}});return new Response(f,{headers:N})}),l=e=>({body:r=>l({...e,body:{...e.body,...r}}),cacheControl:r=>l({...e,cacheControl:r}),cacheTag:r=>l({...e,cacheTag:r}),handler:r=>Q(e,r),output:r=>l({...e,output:r}),params:r=>l({...e,params:{...e.params,...r}}),searchParams:r=>l({...e,searchParams:{...e.searchParams,...r}}),stream:r=>$(e,r),vary:r=>l({...e,vary:r})}),h=e=>r=>l({body:{},method:e,params:{},path:r,searchParams:{}}),se={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")};export{re as httpAction,se as httpRoute,oe as httpRouter,te as isHttpRouter,x as isSafeHeaderValue,ne as lastEventId,ae as sseEvent};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.271",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"dependencies": {
|
|
75
75
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
76
76
|
"@lunora/scheduler": "^1.0.0-alpha.169",
|
|
77
|
-
"@lunora/shard-engine": "^1.0.0-alpha.
|
|
77
|
+
"@lunora/shard-engine": "^1.0.0-alpha.191",
|
|
78
78
|
"@lunora/values": "^1.0.0-alpha.95",
|
|
79
79
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
80
80
|
"drizzle-orm": "1.0.0-rc.5",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E,isLunoraError as q,toErrorBody as O}from"@lunora/errors";import{ValidationError as C,parseValidatorMap as w}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as H}from"hono";import{SSE_HEADERS as T,sseFrame as b,isSafeHeaderValue as I}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const v=e=>{if(e instanceof C)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(q(e)){const{body:r,redacted:o,status:t}=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,...r.why===void 0?{}:{why:r.why}},{status:t})}throw e},z=e=>async r=>{try{return await e(r.get("lunora"),r.req.raw)}catch(o){return v(o)}},A=new WeakSet,K=e=>A.has(e),X=()=>{const e=new H;return A.add(e),e.use("*",async(r,o)=>{const t=r.env.__lunoraCtx;if(!t)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",t),await o()}),e},N=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},D=(e,r,o)=>{const t=N(e);if(t.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=t._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const n=r.req.query(o);return n===void 0?void 0:g(t.kind,n)},j=(e,r)=>{const o={};for(const t of Object.keys(e)){const n=e[t];n&&(o[t]=D(n,r,t))}return w(e,o,"searchParams")},P=(e,r)=>{const o=r.req.param(),t={};for(const n of Object.keys(e)){const a=e[n];if(!a)continue;const i=o[n];t[n]=i===void 0?void 0:g(N(a).kind,i)}return w(e,t,"params")},x=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return w(e,o,"body")},_=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},B=(e,r)=>async o=>{const t=_(e,o);if(t)return t;try{const n=o.get("lunora"),a=Object.keys(e.searchParams).length>0?j(e.searchParams,o):{},i=Object.keys(e.params).length>0?P(e.params,o):{},d=Object.keys(e.body).length>0?await x(e.body,o):{},h=await r({body:d,ctx:n,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const y=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:y?c:void 0,status:204}):Response.json(s,{headers:y?c:void 0})}catch(n){return v(n)}},Y=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},k=Symbol.for("@lunora/server/sse-event"),Z=e=>({[k]:!0,data:e.data,id:e.id}),V=e=>typeof e=="object"&&e!==null&&e[k]===!0,M=(e,r)=>{if(V(r)){if(!I(r.id))throw new E("INTERNAL","sseEvent id must not contain CR, LF or NUL");const o=e?R(e,r.data):r.data;return b(S(o),void 0,r.id)}return b(S(e?R(e,r):r))},U=(e,r)=>(async o=>{const t=_(e,o);if(t)return t;let n,a;try{n=Object.keys(e.searchParams).length>0?j(e.searchParams,o):{},a=Object.keys(e.params).length>0?P(e.params,o):{}}catch(m){return v(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:T});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const y=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:n,signal:s.signal});for await(const p of f){if(s.signal.aborted)break;m.enqueue(h.encode(M(e.output,p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:p,redacted:L}=O(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});L&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(y,{headers:T})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>B(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>U(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),ee={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{z as httpAction,ee as httpRoute,X as httpRouter,K as isHttpRouter,I as isSafeHeaderValue,Y as lastEventId,Z as sseEvent};
|