@lunora/testing 1.0.0-alpha.315 → 1.0.0-alpha.317

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -693,6 +693,17 @@ interface LunoraTestOptions {
693
693
  * ```
694
694
  */
695
695
  services?: Record<string, object>;
696
+ /**
697
+ * The shard every context reports as `ctx.shardKey`. The harness runs one
698
+ * in-process database, so this only sets what a handler that checks its
699
+ * shard sees; it does not partition rows.
700
+ * @default "__root__"
701
+ * @example
702
+ * ```ts
703
+ * const t = lunoraTest(schema, { shardKey: "org_1" });
704
+ * ```
705
+ */
706
+ shardKey?: string;
696
707
  /**
697
708
  * The export names of the topics in `lunora/queues.ts` (the keys of
698
709
  * `ctx.topics`). Each gets a recording publisher on mutation and action
package/dist/index.d.ts CHANGED
@@ -693,6 +693,17 @@ interface LunoraTestOptions {
693
693
  * ```
694
694
  */
695
695
  services?: Record<string, object>;
696
+ /**
697
+ * The shard every context reports as `ctx.shardKey`. The harness runs one
698
+ * in-process database, so this only sets what a handler that checks its
699
+ * shard sees; it does not partition rows.
700
+ * @default "__root__"
701
+ * @example
702
+ * ```ts
703
+ * const t = lunoraTest(schema, { shardKey: "org_1" });
704
+ * ```
705
+ */
706
+ shardKey?: string;
696
707
  /**
697
708
  * The export names of the topics in `lunora/queues.ts` (the keys of
698
709
  * `ctx.topics`). Each gets a recording publisher on mutation and action
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{agentHarness as o,finalTurn as t,toolCallTurn as a}from"./packem_shared/agentHarness-BM24QFnh.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{createArtifactsFake as m}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{createFakeSecretValues as s}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-jk0t_K-w.mjs";import{createStreamGate as S,recordedModel as d}from"./packem_shared/createStreamGate-Geg-yvx6.mjs";import{groundednessScorer as g,mrrScorer as k,ndcgAtK as M,precisionAtK as v,recallAtK as F}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as T,evaluate as w,exactMatchScorer as C,keywordScorer as b,llmScorer as h,regexScorer as y,scoreSample as E}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as H,listCapturedMail as L,waitForMail as V}from"@lunora/mail/testing";export{o as agentHarness,T as containsScorer,m as createArtifactsFake,s as createFakeSecretValues,S as createStreamGate,w as evaluate,l as evaluationAttributes,C as exactMatchScorer,H as extractLink,t as finalTurn,g as groundednessScorer,b as keywordScorer,L as listCapturedMail,h as llmScorer,f as lunoraTest,k as mrrScorer,M as ndcgAtK,v as precisionAtK,F as recallAtK,n as recordEvaluation,d as recordedModel,y as regexScorer,E as scoreSample,a as toolCallTurn,V as waitForMail};
1
+ import{agentHarness as o,finalTurn as t,toolCallTurn as a}from"./packem_shared/agentHarness-BM24QFnh.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{createArtifactsFake as m}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{createFakeSecretValues as s}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-KJJjjDCt.mjs";import{createStreamGate as S,recordedModel as d}from"./packem_shared/createStreamGate-Geg-yvx6.mjs";import{groundednessScorer as g,mrrScorer as k,ndcgAtK as M,precisionAtK as v,recallAtK as F}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as T,evaluate as w,exactMatchScorer as C,keywordScorer as b,llmScorer as h,regexScorer as y,scoreSample as E}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as H,listCapturedMail as L,waitForMail as V}from"@lunora/mail/testing";export{o as agentHarness,T as containsScorer,m as createArtifactsFake,s as createFakeSecretValues,S as createStreamGate,w as evaluate,l as evaluationAttributes,C as exactMatchScorer,H as extractLink,t as finalTurn,g as groundednessScorer,b as keywordScorer,L as listCapturedMail,h as llmScorer,f as lunoraTest,k as mrrScorer,M as ndcgAtK,v as precisionAtK,F as recallAtK,n as recordEvaluation,d as recordedModel,y as regexScorer,E as scoreSample,a as toolCallTurn,V as waitForMail};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as me}from"node:async_hooks";import{LunoraError as N}from"@lunora/errors";import{withDeferredSchedules as ve}from"@lunora/server";import{createInProcessRuntime as pe,resolveInProcessIdentity as ye,runRegisteredFunction as C,registeredFunctionKind as K}from"@lunora/server/in-process";import{evaluationAttributes as ge}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as we,createNotify as be}from"@lunora/notify";import{createNotification as Se}from"@visulima/notification";import{serialize as Ae,deserialize as Ee}from"node:v8";import{createQueues as Ne,createTopicContext as Pe}from"@lunora/queue";import{assertScheduleDelay as Re,MAX_RETRY_ATTEMPTS as Te,RETRY_BASE_DELAY_MS as _e}from"@lunora/scheduler";import{encodeWire as Ie,decodeWire as xe}from"@lunora/wire";import{DatabaseSync as Oe}from"node:sqlite";const I=(t,e)=>{throw new N("INTERNAL",e===void 0?`ctx.${t} is not available in the in-memory @lunora/testing harness (v1)`:`ctx.${t} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${e} })`)},ke=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),qe=t=>new Proxy({...t},{get(e,r){if(!(ke.has(r)&&!Object.hasOwn(e,r))){if(typeof r=="symbol"||Object.hasOwn(e,r)||r in Object.prototype)return Reflect.get(e,r);throw new N("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),A=(t,e)=>new Proxy((...r)=>I(t,e),{apply:()=>I(t,e),get:()=>I(t,e)}),re={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},$e={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>re},Ce=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,s)=>{t.events.push({...s===void 0?{}:{attributes:{...s}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,ge(r))},recordException:r=>{const s={"exception.message":r instanceof Error?r.message:String(r),"exception.type":r instanceof Error?r.constructor.name:"Error"};r instanceof Error&&r.stack!==void 0&&(s["exception.stacktrace"]=r.stack),e.addEvent("exception",s)},setAttribute:(r,s)=>{t.attributes[r]=s},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>re};return{handle:e,recorded:t}},Q=async(t,e)=>await e(Q,$e),z={count:()=>{},gauge:()=>{},record:()=>{}},V={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>V},U="notify",De=t=>{let e=t;if(typeof t=="string"){if(!t.startsWith("{"))return;try{e=JSON.parse(t)}catch{return}}const r=e?.endpoint;return typeof r=="string"?r:void 0},D=(t,e)=>typeof t=="function"?t(e):t,Le=(t,e)=>{const r=[],s=(l,g)=>(r.push({channel:l,payload:structuredClone(g)}),{data:{messageId:`${l}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),y=l=>({channel:l,id:`lunora-testing-${l}`,initialize:()=>{},isAvailable:()=>!0,send:g=>s(l,g)}),c=D(t.webPush,e)!==void 0,b=D(t.fcm,e)!==void 0,a={...y("push"),send:l=>{const g=Array.isArray(l.to)?l.to:[l.to];if(g.length===0)throw new N("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const x of g){const R=De(x)!==void 0;if(R?!c:!b)throw new Error(R?"@lunora/notify: received a web-push target but no `webPush` channel is configured":"@lunora/notify: received an FCM token target but no `fcm` channel is configured")}return s("push",l)}},p={...c||b?{push:a}:{},...D(t.chat,e)===void 0?{}:{chat:y("chat")},...D(t.inApp,e)===void 0?{}:{inapp:y("inapp")},...D(t.webhook,e)===void 0?{}:{webhook:y("webhook")}},u=we(),{notify:d,push:E}=be({...t,store:()=>u},e,{engine:Se(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:l=>l===void 0?[...r]:r.filter(g=>g.channel===l)},surfaces:{notify:d,push:E}}},Fe=(t,e)=>t!==void 0?Le(t,e):{controls:{clear:()=>I("notify",U),sent:()=>I("notify",U)},surfaces:{notify:A("notify",U),push:A("push",U)}},H="queues: [...]",Z=128*1024,ee=256*1024,Me="json",te=new TextEncoder,je=(t,e)=>{if(e==="v8"){const s=Ae(t);return{body:Ee(s),bytes:s.byteLength}}if(e==="text"){if(typeof t!="string")throw new N("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof t}`);return{body:t,bytes:te.encode(t).byteLength}}if(e==="bytes"){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new N("VALIDATION_ERROR",'@lunora/queue: a "bytes" message body must be an ArrayBuffer or an ArrayBufferView');return{body:t,bytes:t.byteLength}}const r=JSON.stringify(t);if(typeof r!="string")throw new N("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof t}`);return{body:JSON.parse(r),bytes:te.encode(r).byteLength}},ne=t=>{const e=new Set(t),r=[],s=(c,b,a)=>{const p=a?.contentType??Me,u=je(b,p);if(u.bytes>Z)throw new N("VALIDATION_ERROR",`@lunora/queue: ${c} message is ${String(u.bytes)} bytes, over the Cloudflare Queues limit of ${String(Z)} (128 KB)`);return{bytes:u.bytes,message:{body:u.body,contentType:p,...a?.delaySeconds===void 0?{}:{delaySeconds:a.delaySeconds},destination:c}}},y=c=>({send:(b,a)=>(r.push(s(c,b,a).message),Promise.resolve()),sendBatch:(b,a)=>{const p=[...b].map(d=>s(c,d.body,{contentType:d.contentType,delaySeconds:d.delaySeconds??a?.delaySeconds})),u=p.reduce((d,E)=>d+E.bytes,0);if(u>ee)throw new N("VALIDATION_ERROR",`@lunora/queue: ${c} batch is ${String(u)} bytes, over the Cloudflare Queues limit of ${String(ee)} (256 KB)`);return r.push(...p.map(d=>d.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(c=>[c,y(c)])),clear:()=>{r.length=0},read:(c,b,a)=>{if(c===void 0)return[...r];if(!e.has(c))throw new N("INTERNAL",`${b}("${c}"): no such ${a} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===c)}}},Be=t=>{const e=ne(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:s,...y})=>({...y,queue:s}))},surfaces:{queues:Ne({bindings:e.bindings})}}},Ue=t=>t!==void 0?Be(t):{controls:{clear:()=>I("queues",H),sent:()=>I("queues",H)},surfaces:{queues:A("queues",H)}},Ke=(t,e,r,s,y)=>{let c=y,b=1;const a=new Map,p=[],u=(o,w,h={},m)=>{const n=Ie(h);JSON.stringify(n);const f=xe(n),S=m??`fake-job-${String(b)}`;return b+=1,a.set(S,{args:f,enqueuedAt:c,functionPath:w,id:S,scheduledFor:o}),S},d=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",E={cancel:o=>{const w=a.has(o);return a.delete(o),Promise.resolve({cancelled:w})},get:o=>Promise.resolve(a.get(o)??null),list:()=>Promise.resolve([...a.values()]),runAfter:(o,w,h,m)=>{Re(o,"ctx.scheduler.runAfter");const n=u(c+o,d(w),h,m?.id);return Promise.resolve(n)},runAt:(o,w,h,m)=>{const n=u(o,d(w),h,m?.id);return Promise.resolve(n)}},l=async o=>{a.delete(o.id);const w=s(),h=o.functionPath===void 0?void 0:w.get(o.functionPath);if(h===void 0)throw new N("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(h.kind!=="mutation"&&h.kind!=="action")throw new N("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${h.kind} — only mutations and actions can be scheduled`,{status:404});const m=t(),n=h.kind==="action"?r():e();await m(h.kind,h,{...n,now:c},o.args)},g=async o=>{const w=[...a.values()].filter(n=>n.scheduledFor<=o).toSorted((n,f)=>n.scheduledFor-f.scheduledFor),h=[];let m=0;for(const n of w)if(a.has(n.id)){m+=1;try{await l(n)}catch(f){const S=(n.attempts??0)+1;if(S>Te){const T={args:n.args,error:f,functionPath:n.functionPath??"",id:n.id};h.push(T),p.push(T)}else{const T=_e*2**(S-1);a.set(n.id,{...n,attempts:S,scheduledFor:c+T})}}}return{executed:m,failed:h}},x=async(o,w)=>{const{executed:h,failed:m}=await g(o);if(m.length>0&&(w?.throwOnError??!0)){const[n]=m;throw m.length===1&&n!==void 0?n.error:new AggregateError(m.map(f=>f.error),`${String(m.length)} scheduled jobs failed: ${m.map(f=>f.functionPath).join(", ")}`)}return h};return{controls:{advance:(o,w)=>(c+=o,x(c,w)),failures:()=>[...p],list:()=>[...a.values()],runPending:o=>x(Number.POSITIVE_INFINITY,o)},scheduler:E}},X="topics: [...]",Qe=t=>{if(t===void 0)return{controls:{clear:()=>I("topics",X),published:()=>I("topics",X)},surfaces:{topics:A("topics",X)}};const e=ne(t),r=Pe(e.bindings,t.map(s=>({exportName:s,subscriptions:[{binding:s,exportName:s}]})));return{controls:{clear:e.clear,published:s=>e.read(s,"harness.topics.published","topic").map(({destination:y,...c})=>({...c,topic:y}))},surfaces:{topics:r}}},Ve=()=>{const t=new Oe(":memory:"),e=s=>({one(){if(s.length!==1)throw new N("INTERNAL",`expected exactly one row, received ${String(s.length)}`);const[y]=s;return y},[Symbol.iterator](){return s[Symbol.iterator]()},toArray(){return s}});return{close:()=>{t.close()},sql:{exec:(s,...y)=>{const b=t.prepare(s).all(...y);return e(b)}}}},L=new me,Ye=(t,e,r,s)=>(c,b)=>{let a=!1;const p=[];let u,d,E=0,l=0;const g=()=>L.run(s(),()=>K(c)?t("query",c,e,b,!1):Promise.resolve(c(e))),x=(n,f)=>{if(n<l)return;l=n;const S={done:!1,value:f};if(p.length===0)u=S,d=void 0;else{u=void 0,d=void 0;for(const T of p.splice(0))T.resolve(S)}},R=(n,f)=>{if(!(n<l))if(l=n,p.length===0)d={error:f},u=void 0;else{u=void 0,d=void 0;for(const S of p.splice(0))S.reject(f)}},o=n=>f=>{x(n,f)},w=n=>f=>{R(n,f)},h=()=>{if(a)return;E+=1;const n=E;g().then(o(n)).catch(w(n))};r.add(h);const m={[Symbol.asyncIterator](){return m},next:()=>{if(a)return Promise.resolve({done:!0,value:void 0});if(l===E){if(d!==void 0){const{error:n}=d;return d=void 0,Promise.reject(n)}if(u!==void 0){const n=u;return u=void 0,Promise.resolve(n)}}return l<E?new Promise((n,f)=>{p.push({reject:f,resolve:n})}):g().then(n=>{if(d!==void 0){const{error:f}=d;throw d=void 0,f}if(u!==void 0){const f=u;return u=void 0,f}return{done:!1,value:n}})},return:()=>{a=!0,r.delete(h);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return g().then(o(0)).catch(w(0)),m},ct=(t,e)=>{const{close:r,sql:s}=Ve();let y=!1;const c=()=>{y||(y=!0,r())},b=new Map(Object.entries(e?.functions??{}).map(([P,_])=>[P,_])),a=new Set,p=()=>{for(const P of a)P()},u=P=>(p(),P);let d,E,l;const g=()=>e?.now??Date.now(),x=g(),R=P=>((..._)=>L.run(g(),()=>P(..._))),o=Ce(),{controls:w,surfaces:h}=Ue(e?.queues),{controls:m,surfaces:n}=Qe(e?.topics),{controls:f,surfaces:S}=Fe(e?.notify,e?.env??{}),T=(P,_)=>{if(P===void 0)throw new N("INTERNAL",`[fake-scheduler] ${_} not yet available — scheduler.advance called before harness construction completed`);return P},{controls:oe,scheduler:se}=Ke(()=>T(d,"dispatch"),()=>T(E,"mutationContext"),()=>T(l,"actionContext"),()=>b,x),Y=ve(se),{createWriters:ce,resetHeadroom:F,runInTransaction:M}=pe(t,{enforceRls:e?.enforceRls,scheduler:Y,sql:s}),G=P=>{const _=ye(P),J={getIdentity:()=>Promise.resolve(_.claims),userId:_.userId},{database:W,rawDatabase:ie}=ce(_),k={...S,auth:J,db:W,env:e?.env,log:V,metrics:z,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:o.handle,trace:Q,runQuery:((i,v)=>O("query",i,k,v)),secrets:A("secrets"),storage:A("storage"),vectors:A("vectors")},q={...S,...h,...n,auth:J,db:W,env:e?.env,log:V,metrics:z,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:o.handle,trace:Q,runMutation:((i,v)=>O("mutation",i,q,v)),runQuery:((i,v)=>O("query",i,k,v)),scheduler:Y,secrets:A("secrets"),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};E??=q;const ae=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(q),db:{enumerable:!0,value:ie}}),j={...S,...h,...n,auth:J,db:W,env:e?.env,fetch:e?.fetch??A("fetch"),log:V,metrics:z,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:o.handle,trace:Q,runAction:((i,v)=>O("action",i,j,v)),runMutation:((i,v)=>M(()=>O("mutation",i,q,v)).then(u)),runQuery:((i,v)=>O("query",i,k,v)),scheduler:Y,secrets:A("secrets"),services:qe(e?.services),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};l??=j;const O=(i,v,$,B)=>C(i,v,$,B,!0);d??=(i,v,$,B)=>i==="mutation"?M(()=>C("mutation",v,$,B,!0)).then(u):(F(),O("action",v,$,B));const ue=((i,v)=>(F(),K(i)?C("query",i,k,v,!1):Promise.resolve(i(k)))),de=((i,v)=>{const $=K(i)?()=>C("mutation",i,q,v,!1):()=>i(q);return M($).then(u)}),le=((i,v)=>(F(),K(i)?C("action",i,j,v,!1):Promise.resolve(i(j)))),fe=Ye((...i)=>(F(),C(...i)),k,a,()=>e?.now??Date.now()),he=i=>M(()=>i(ae)).then(u);return{action:R(le),close:c,mutation:R(de),notify:f,query:R(ue),queues:w,run:R(he),scheduler:oe,subscribe:fe,topics:m,wideEvent:()=>o.recorded,withIdentity:i=>G(i)}};return G(null)};export{ct as lunoraTest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/testing",
3
- "version": "1.0.0-alpha.315",
3
+ "version": "1.0.0-alpha.317",
4
4
  "description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,15 +50,15 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/agent": "1.0.0-alpha.260",
54
- "@lunora/bindings": "1.0.0-alpha.140",
53
+ "@lunora/agent": "1.0.0-alpha.262",
54
+ "@lunora/bindings": "1.0.0-alpha.141",
55
55
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
56
56
  "@lunora/mail": "1.0.0-alpha.129",
57
57
  "@lunora/notify": "1.0.0-alpha.101",
58
- "@lunora/platform": "1.0.0-alpha.75",
59
- "@lunora/queue": "1.0.0-alpha.131",
60
- "@lunora/scheduler": "1.0.0-alpha.155",
61
- "@lunora/server": "1.0.0-alpha.250",
58
+ "@lunora/platform": "1.0.0-alpha.76",
59
+ "@lunora/queue": "1.0.0-alpha.132",
60
+ "@lunora/scheduler": "1.0.0-alpha.157",
61
+ "@lunora/server": "1.0.0-alpha.252",
62
62
  "@lunora/wire": "1.0.0-alpha.3",
63
63
  "@visulima/notification": "2.0.2",
64
64
  "ai": "7.0.127"
@@ -1 +0,0 @@
1
- import{AsyncLocalStorage as me}from"node:async_hooks";import{LunoraError as N}from"@lunora/errors";import{withDeferredSchedules as ve}from"@lunora/server";import{createInProcessRuntime as pe,resolveInProcessIdentity as ye,runRegisteredFunction as C,registeredFunctionKind as Q}from"@lunora/server/in-process";import{evaluationAttributes as ge}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as we,createNotify as be}from"@lunora/notify";import{createNotification as Se}from"@visulima/notification";import{serialize as Ae,deserialize as Ee}from"node:v8";import{createQueues as Ne,createTopicContext as Pe}from"@lunora/queue";import{assertScheduleDelay as Re,MAX_RETRY_ATTEMPTS as Te,RETRY_BASE_DELAY_MS as Ie}from"@lunora/scheduler";import{encodeWire as xe,decodeWire as Oe}from"@lunora/wire";import{DatabaseSync as ke}from"node:sqlite";const x=(e,t)=>{throw new N("INTERNAL",t===void 0?`ctx.${e} is not available in the in-memory @lunora/testing harness (v1)`:`ctx.${e} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${t} })`)},qe=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),$e=e=>new Proxy({...e},{get(t,r){if(!(qe.has(r)&&!Object.hasOwn(t,r))){if(typeof r=="symbol"||Object.hasOwn(t,r)||r in Object.prototype)return Reflect.get(t,r);throw new N("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),A=(e,t)=>new Proxy((...r)=>x(e,t),{apply:()=>x(e,t),get:()=>x(e,t)}),re={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},_e={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>re},Ce=()=>{const e={attributes:{},events:[],links:[]},t={addEvent:(r,s)=>{e.events.push({...s===void 0?{}:{attributes:{...s}},name:r})},addLink:r=>{e.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(e.attributes,ge(r))},recordException:r=>{const s={"exception.message":r instanceof Error?r.message:String(r),"exception.type":r instanceof Error?r.constructor.name:"Error"};r instanceof Error&&r.stack!==void 0&&(s["exception.stacktrace"]=r.stack),t.addEvent("exception",s)},setAttribute:(r,s)=>{e.attributes[r]=s},setAttributes:r=>{Object.assign(e.attributes,r)},spanContext:()=>re};return{handle:t,recorded:e}},V=async(e,t)=>await t(V,_e),H={count:()=>{},gauge:()=>{},record:()=>{}},Y={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>Y},U="notify",De=e=>{let t=e;if(typeof e=="string"){if(!e.startsWith("{"))return;try{t=JSON.parse(e)}catch{return}}const r=t?.endpoint;return typeof r=="string"?r:void 0},D=(e,t)=>typeof e=="function"?e(t):e,Le=(e,t)=>{const r=[],s=(l,g)=>(r.push({channel:l,payload:structuredClone(g)}),{data:{messageId:`${l}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),y=l=>({channel:l,id:`lunora-testing-${l}`,initialize:()=>{},isAvailable:()=>!0,send:g=>s(l,g)}),c=D(e.webPush,t)!==void 0,b=D(e.fcm,t)!==void 0,a={...y("push"),send:l=>{const g=Array.isArray(l.to)?l.to:[l.to];if(g.length===0)throw new N("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const O of g){const R=De(O)!==void 0;if(R?!c:!b)throw new Error(R?"@lunora/notify: received a web-push target but no `webPush` channel is configured":"@lunora/notify: received an FCM token target but no `fcm` channel is configured")}return s("push",l)}},p={...c||b?{push:a}:{},...D(e.chat,t)===void 0?{}:{chat:y("chat")},...D(e.inApp,t)===void 0?{}:{inapp:y("inapp")},...D(e.webhook,t)===void 0?{}:{webhook:y("webhook")}},u=we(),{notify:d,push:E}=be({...e,store:()=>u},t,{engine:Se(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:l=>l===void 0?[...r]:r.filter(g=>g.channel===l)},surfaces:{notify:d,push:E}}},Fe=(e,t)=>e!==void 0?Le(e,t):{controls:{clear:()=>x("notify",U),sent:()=>x("notify",U)},surfaces:{notify:A("notify",U),push:A("push",U)}},K="queues: [...]",Z=128*1024,ee=256*1024,Me="json",te=new TextEncoder,je=(e,t)=>{if(t==="v8"){const s=Ae(e);return{body:Ee(s),bytes:s.byteLength}}if(t==="text"){if(typeof e!="string")throw new N("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof e}`);return{body:e,bytes:te.encode(e).byteLength}}if(t==="bytes"){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw new N("VALIDATION_ERROR",'@lunora/queue: a "bytes" message body must be an ArrayBuffer or an ArrayBufferView');return{body:e,bytes:e.byteLength}}const r=JSON.stringify(e);if(typeof r!="string")throw new N("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof e}`);return{body:JSON.parse(r),bytes:te.encode(r).byteLength}},ne=e=>{const t=new Set(e),r=[],s=(c,b,a)=>{const p=a?.contentType??Me,u=je(b,p);if(u.bytes>Z)throw new N("VALIDATION_ERROR",`@lunora/queue: ${c} message is ${String(u.bytes)} bytes, over the Cloudflare Queues limit of ${String(Z)} (128 KB)`);return{bytes:u.bytes,message:{body:u.body,contentType:p,...a?.delaySeconds===void 0?{}:{delaySeconds:a.delaySeconds},destination:c}}},y=c=>({send:(b,a)=>(r.push(s(c,b,a).message),Promise.resolve()),sendBatch:(b,a)=>{const p=[...b].map(d=>s(c,d.body,{contentType:d.contentType,delaySeconds:d.delaySeconds??a?.delaySeconds})),u=p.reduce((d,E)=>d+E.bytes,0);if(u>ee)throw new N("VALIDATION_ERROR",`@lunora/queue: ${c} batch is ${String(u)} bytes, over the Cloudflare Queues limit of ${String(ee)} (256 KB)`);return r.push(...p.map(d=>d.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...t].map(c=>[c,y(c)])),clear:()=>{r.length=0},read:(c,b,a)=>{if(c===void 0)return[...r];if(!t.has(c))throw new N("INTERNAL",`${b}("${c}"): no such ${a} — declared: ${[...t].join(", ")||"(none)"}`);return r.filter(p=>p.destination===c)}}},Be=e=>{const t=ne(e);return{controls:{clear:t.clear,sent:r=>t.read(r,"harness.queues.sent","queue").map(({destination:s,...y})=>({...y,queue:s}))},surfaces:{queues:Ne({bindings:t.bindings})}}},Ue=e=>e!==void 0?Be(e):{controls:{clear:()=>x("queues",K),sent:()=>x("queues",K)},surfaces:{queues:A("queues",K)}},Qe=(e,t,r,s,y)=>{let c=y,b=1;const a=new Map,p=[],u=(o,w,h={},m)=>{const n=xe(h);JSON.stringify(n);const f=Oe(n),S=m??`fake-job-${String(b)}`;return b+=1,a.set(S,{args:f,enqueuedAt:c,functionPath:w,id:S,scheduledFor:o}),S},d=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",E={cancel:o=>{const w=a.has(o);return a.delete(o),Promise.resolve({cancelled:w})},get:o=>Promise.resolve(a.get(o)??null),list:()=>Promise.resolve([...a.values()]),runAfter:(o,w,h,m)=>{Re(o,"ctx.scheduler.runAfter");const n=u(c+o,d(w),h,m?.id);return Promise.resolve(n)},runAt:(o,w,h,m)=>{const n=u(o,d(w),h,m?.id);return Promise.resolve(n)}},l=async o=>{a.delete(o.id);const w=s(),h=o.functionPath===void 0?void 0:w.get(o.functionPath);if(h===void 0)throw new N("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(h.kind!=="mutation"&&h.kind!=="action")throw new N("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${h.kind} — only mutations and actions can be scheduled`,{status:404});const m=e(),n=h.kind==="action"?r():t();await m(h.kind,h,{...n,now:c},o.args)},g=async o=>{const w=[...a.values()].filter(n=>n.scheduledFor<=o).toSorted((n,f)=>n.scheduledFor-f.scheduledFor),h=[];let m=0;for(const n of w)if(a.has(n.id)){m+=1;try{await l(n)}catch(f){const S=(n.attempts??0)+1;if(S>Te){const T={args:n.args,error:f,functionPath:n.functionPath??"",id:n.id};h.push(T),p.push(T)}else{const T=Ie*2**(S-1);a.set(n.id,{...n,attempts:S,scheduledFor:c+T})}}}return{executed:m,failed:h}},O=async(o,w)=>{const{executed:h,failed:m}=await g(o);if(m.length>0&&(w?.throwOnError??!0)){const[n]=m;throw m.length===1&&n!==void 0?n.error:new AggregateError(m.map(f=>f.error),`${String(m.length)} scheduled jobs failed: ${m.map(f=>f.functionPath).join(", ")}`)}return h};return{controls:{advance:(o,w)=>(c+=o,O(c,w)),failures:()=>[...p],list:()=>[...a.values()],runPending:o=>O(Number.POSITIVE_INFINITY,o)},scheduler:E}},X="topics: [...]",Ve=e=>{if(e===void 0)return{controls:{clear:()=>x("topics",X),published:()=>x("topics",X)},surfaces:{topics:A("topics",X)}};const t=ne(e),r=Pe(t.bindings,e.map(s=>({exportName:s,subscriptions:[{binding:s,exportName:s}]})));return{controls:{clear:t.clear,published:s=>t.read(s,"harness.topics.published","topic").map(({destination:y,...c})=>({...c,topic:y}))},surfaces:{topics:r}}},Ye=()=>{const e=new ke(":memory:"),t=s=>({one(){if(s.length!==1)throw new N("INTERNAL",`expected exactly one row, received ${String(s.length)}`);const[y]=s;return y},[Symbol.iterator](){return s[Symbol.iterator]()},toArray(){return s}});return{close:()=>{e.close()},sql:{exec:(s,...y)=>{const b=e.prepare(s).all(...y);return t(b)}}}},L=new me,Je=(e,t,r,s)=>(c,b)=>{let a=!1;const p=[];let u,d,E=0,l=0;const g=()=>L.run(s(),()=>Q(c)?e("query",c,t,b,!1):Promise.resolve(c(t))),O=(n,f)=>{if(n<l)return;l=n;const S={done:!1,value:f};if(p.length===0)u=S,d=void 0;else{u=void 0,d=void 0;for(const T of p.splice(0))T.resolve(S)}},R=(n,f)=>{if(!(n<l))if(l=n,p.length===0)d={error:f},u=void 0;else{u=void 0,d=void 0;for(const S of p.splice(0))S.reject(f)}},o=n=>f=>{O(n,f)},w=n=>f=>{R(n,f)},h=()=>{if(a)return;E+=1;const n=E;g().then(o(n)).catch(w(n))};r.add(h);const m={[Symbol.asyncIterator](){return m},next:()=>{if(a)return Promise.resolve({done:!0,value:void 0});if(l===E){if(d!==void 0){const{error:n}=d;return d=void 0,Promise.reject(n)}if(u!==void 0){const n=u;return u=void 0,Promise.resolve(n)}}return l<E?new Promise((n,f)=>{p.push({reject:f,resolve:n})}):g().then(n=>{if(d!==void 0){const{error:f}=d;throw d=void 0,f}if(u!==void 0){const f=u;return u=void 0,f}return{done:!1,value:n}})},return:()=>{a=!0,r.delete(h);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return g().then(o(0)).catch(w(0)),m},ct=(e,t)=>{const{close:r,sql:s}=Ye();let y=!1;const c=()=>{y||(y=!0,r())},b=new Map(Object.entries(t?.functions??{}).map(([P,I])=>[P,I])),a=new Set,p=()=>{for(const P of a)P()},u=P=>(p(),P);let d,E,l;const g=()=>t?.now??Date.now(),O=g(),R=P=>((...I)=>L.run(g(),()=>P(...I))),o=Ce(),{controls:w,surfaces:h}=Ue(t?.queues),{controls:m,surfaces:n}=Ve(t?.topics),{controls:f,surfaces:S}=Fe(t?.notify,t?.env??{}),T=(P,I)=>{if(P===void 0)throw new N("INTERNAL",`[fake-scheduler] ${I} not yet available — scheduler.advance called before harness construction completed`);return P},{controls:oe,scheduler:se}=Qe(()=>T(d,"dispatch"),()=>T(E,"mutationContext"),()=>T(l,"actionContext"),()=>b,O),J=ve(se),{createWriters:ce,resetHeadroom:F,runInTransaction:M}=pe(e,{enforceRls:t?.enforceRls,scheduler:J,sql:s}),G=P=>{const I=ye(P),W={getIdentity:()=>Promise.resolve(I.claims),userId:I.userId},{database:z,rawDatabase:ie}=ce(I),q={...S,auth:W,db:z,env:t?.env,log:Y,metrics:H,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),span:o.handle,trace:V,runQuery:((i,v)=>k("query",i,q,v)),secrets:A("secrets"),storage:A("storage"),vectors:A("vectors")},$={...S,...h,...n,auth:W,db:z,env:t?.env,log:Y,metrics:H,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),span:o.handle,trace:V,runMutation:((i,v)=>k("mutation",i,$,v)),runQuery:((i,v)=>k("query",i,q,v)),scheduler:J,secrets:A("secrets"),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};E??=$;const ae=Object.defineProperties({},{...Object.getOwnPropertyDescriptors($),db:{enumerable:!0,value:ie}}),j={...S,...h,...n,auth:W,db:z,env:t?.env,fetch:t?.fetch??A("fetch"),log:Y,metrics:H,get now(){return L.getStore()??g()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),span:o.handle,trace:V,runAction:((i,v)=>k("action",i,j,v)),runMutation:((i,v)=>M(()=>k("mutation",i,$,v)).then(u)),runQuery:((i,v)=>k("query",i,q,v)),scheduler:J,secrets:A("secrets"),services:$e(t?.services),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};l??=j;const k=(i,v,_,B)=>C(i,v,_,B,!0);d??=(i,v,_,B)=>i==="mutation"?M(()=>C("mutation",v,_,B,!0)).then(u):(F(),k("action",v,_,B));const ue=((i,v)=>(F(),Q(i)?C("query",i,q,v,!1):Promise.resolve(i(q)))),de=((i,v)=>{const _=Q(i)?()=>C("mutation",i,$,v,!1):()=>i($);return M(_).then(u)}),le=((i,v)=>(F(),Q(i)?C("action",i,j,v,!1):Promise.resolve(i(j)))),fe=Je((...i)=>(F(),C(...i)),q,a,()=>t?.now??Date.now()),he=i=>M(()=>i(ae)).then(u);return{action:R(le),close:c,mutation:R(de),notify:f,query:R(ue),queues:w,run:R(he),scheduler:oe,subscribe:fe,topics:m,wideEvent:()=>o.recorded,withIdentity:i=>G(i)}};return G(null)};export{ct as lunoraTest};