@lunora/testing 1.0.0-alpha.340 → 1.0.0-alpha.342
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
|
@@ -345,6 +345,8 @@ declare const createFakeSecretValues: () => FakeSecretValues;
|
|
|
345
345
|
interface FakeScheduledJob extends ScheduledJob {
|
|
346
346
|
/** The args the job was scheduled with. */
|
|
347
347
|
args: Record<string, unknown>;
|
|
348
|
+
/** The caller's `RunOptions.dedupKey`, when it fixed one. */
|
|
349
|
+
dedupKey?: string;
|
|
348
350
|
}
|
|
349
351
|
/**
|
|
350
352
|
* A single scheduled-job failure that exhausted its retry budget, captured
|
package/dist/index.d.ts
CHANGED
|
@@ -345,6 +345,8 @@ declare const createFakeSecretValues: () => FakeSecretValues;
|
|
|
345
345
|
interface FakeScheduledJob extends ScheduledJob {
|
|
346
346
|
/** The args the job was scheduled with. */
|
|
347
347
|
args: Record<string, unknown>;
|
|
348
|
+
/** The caller's `RunOptions.dedupKey`, when it fixed one. */
|
|
349
|
+
dedupKey?: string;
|
|
348
350
|
}
|
|
349
351
|
/**
|
|
350
352
|
* A single scheduled-job failure that exhausted its retry budget, captured
|
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 p}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-
|
|
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 p}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-CxviUcTV.mjs";import{createStreamGate as u,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-D8-EWo1j.mjs";import{absentScorer as T,containsScorer as b,evaluate as w,exactMatchScorer as C,keywordScorer as h,llmScorer as y,regexScorer as E,scoreSample as G}from"./packem_shared/absentScorer-tcGbGxnq.mjs";import{extractLink as L,listCapturedMail as V,waitForMail as j}from"@lunora/mail/testing";export{T as absentScorer,o as agentHarness,b as containsScorer,m as createArtifactsFake,p as createFakeSecretValues,u as createStreamGate,w as evaluate,l as evaluationAttributes,C as exactMatchScorer,L as extractLink,t as finalTurn,g as groundednessScorer,h as keywordScorer,V as listCapturedMail,y as llmScorer,f as lunoraTest,k as mrrScorer,M as ndcgAtK,v as precisionAtK,F as recallAtK,n as recordEvaluation,d as recordedModel,E as regexScorer,G as scoreSample,a as toolCallTurn,j as waitForMail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as se}from"node:async_hooks";import{LunoraError as A}from"@lunora/errors";import{withDeferredSchedules as be}from"@lunora/server";import{createInProcessRuntime as Se,resolveInProcessIdentity as Ee,runRegisteredFunction as K,registeredFunctionKind as V}from"@lunora/server/in-process";import{encodeWire as ce,decodeWire as ie}from"@lunora/wire";import{evaluationAttributes as Ae}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as Ne,createNotify as Re}from"@lunora/notify";import{createNotification as Te}from"@visulima/notification";import{serialize as _e,deserialize as Pe}from"node:v8";import{createQueues as Ie,createTopicContext as Oe}from"@lunora/queue";import{assertScheduleDelay as xe,TERMINAL_RETENTION_MS as $e,assertDedupKey as ke,MAX_RETRY_ATTEMPTS as qe,RETRY_BASE_DELAY_MS as De}from"@lunora/scheduler";import{DatabaseSync as Ce}from"node:sqlite";const O=(t,e)=>{throw new A("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} })`)},Me=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),Le=t=>new Proxy({...t},{get(e,r){if(!(Me.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 A("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),b=(t,e)=>new Proxy((...r)=>O(t,e),{apply:()=>O(t,e),get:()=>O(t,e)}),ae={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Fe={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>ae},Ke=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,i)=>{t.events.push({...i===void 0?{}:{attributes:{...i}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,Ae(r))},recordException:r=>{const i={"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&&(i["exception.stacktrace"]=r.stack),e.addEvent("exception",i)},setAttribute:(r,i)=>{t.attributes[r]=i},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>ae};return{handle:e,recorded:t}},Y=async(t,e)=>await e(Y,Fe),G={count:()=>{},gauge:()=>{},record:()=>{}},z={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>z},W="notify",Be=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},U=(t,e)=>typeof t=="function"?t(e):t,Ue=(t,e)=>{const r=[],i=(h,y)=>(r.push({channel:h,payload:structuredClone(y)}),{data:{messageId:`${h}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=h=>({channel:h,id:`lunora-testing-${h}`,initialize:()=>{},isAvailable:()=>!0,send:y=>i(h,y)}),c=U(t.webPush,e)!==void 0,w=U(t.fcm,e)!==void 0,f={...g("push"),send:h=>{const y=Array.isArray(h.to)?h.to:[h.to];if(y.length===0)throw new A("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const $ of y){const T=Be($)!==void 0;if(T?!c:!w)throw new Error(T?"@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 i("push",h)}},p={...c||w?{push:f}:{},...U(t.chat,e)===void 0?{}:{chat:g("chat")},...U(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...U(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},l=Ne(),{notify:v,push:S}=Re({...t,store:()=>l},e,{engine:Te(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:h=>h===void 0?[...r]:r.filter(y=>y.channel===h)},surfaces:{notify:v,push:S}}},je=(t,e)=>t!==void 0?Ue(t,e):{controls:{clear:()=>O("notify",W),sent:()=>O("notify",W)},surfaces:{notify:b("notify",W),push:b("push",W)}},Z="queues: [...]",re=128*1024,ne=256*1024,Je="json",oe=new TextEncoder,Qe=(t,e)=>{if(e==="v8"){const i=_e(t);return{body:Pe(i),bytes:i.byteLength}}if(e==="text"){if(typeof t!="string")throw new A("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof t}`);return{body:t,bytes:oe.encode(t).byteLength}}if(e==="bytes"){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new A("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 A("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof t}`);return{body:JSON.parse(r),bytes:oe.encode(r).byteLength}},ue=t=>{const e=new Set(t),r=[],i=(c,w,f)=>{const p=f?.contentType??Je,l=Qe(w,p);if(l.bytes>re)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} message is ${String(l.bytes)} bytes, over the Cloudflare Queues limit of ${String(re)} (128 KB)`);return{bytes:l.bytes,message:{body:l.body,contentType:p,...f?.delaySeconds===void 0?{}:{delaySeconds:f.delaySeconds},destination:c}}},g=c=>({send:(w,f)=>(r.push(i(c,w,f).message),Promise.resolve()),sendBatch:(w,f)=>{const p=[...w].map(v=>i(c,v.body,{contentType:v.contentType,delaySeconds:v.delaySeconds??f?.delaySeconds})),l=p.reduce((v,S)=>v+S.bytes,0);if(l>ne)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} batch is ${String(l)} bytes, over the Cloudflare Queues limit of ${String(ne)} (256 KB)`);return r.push(...p.map(v=>v.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(c=>[c,g(c)])),clear:()=>{r.length=0},read:(c,w,f)=>{if(c===void 0)return[...r];if(!e.has(c))throw new A("INTERNAL",`${w}("${c}"): no such ${f} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===c)}}},We=t=>{const e=ue(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:i,...g})=>({...g,queue:i}))},surfaces:{queues:Ie({bindings:e.bindings})}}},Ve=t=>t!==void 0?We(t):{controls:{clear:()=>O("queues",Z),sent:()=>O("queues",Z)},surfaces:{queues:b("queues",Z)}},Ye=864e5,ze=(t,e,r,i,g)=>{let c=g,w=1;const f=new Map,p=new Map,l=new Map,v=[],S=new Map,h=(o,n,s={},u,a)=>{ke(a);const E=ce(s);JSON.stringify(E);const P=ie(E),N=u??`fake-job-${String(w)}`;return w+=1,l.delete(N),f.set(N,{args:P,...a===void 0?{}:{dedupKey:a},enqueuedAt:c,functionPath:n,id:N,scheduledFor:o}),N},y=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",$={cancel:o=>{const n=f.get(o),s=n!==void 0;return n!==void 0&&l.set(o,{...n,completedAt:c,state:"canceled"}),f.delete(o),Promise.resolve({cancelled:s})},get:o=>{const n=f.get(o),s=p.get(o);let u=l.get(o);return u?.completedAt!==void 0&&u.completedAt<=c-$e&&(u=void 0),n!==void 0?u={...n,state:"pending"}:s!==void 0&&(u={...s,state:"running"}),Promise.resolve(u??null)},list:()=>Promise.resolve([...f.values()]),runAfter:(o,n,s,u)=>{xe(o,"ctx.scheduler.runAfter");const a=h(c+o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(a)},runAt:(o,n,s,u)=>{const a=h(o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(a)}},T=async o=>{f.delete(o.id);const n=i(),s=o.functionPath===void 0?void 0:n.get(o.functionPath);if(s===void 0)throw new A("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(s.kind!=="mutation"&&s.kind!=="action")throw new A("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${s.kind} — only mutations and actions can be scheduled`,{status:404});const u=o.dedupKey===void 0?void 0:S.get(o.dedupKey);if(u!==void 0&&c-u<Ye)return;const a=t(),E=s.kind==="action"?r():e();await a(s.kind,s,E,o.args,c),o.dedupKey!==void 0&&S.set(o.dedupKey,c)},_=async o=>{const n=[...f.values()].filter(a=>a.scheduledFor<=o).toSorted((a,E)=>a.scheduledFor-E.scheduledFor),s=[];let u=0;for(const a of n)if(f.has(a.id)){u+=1;try{p.set(a.id,a),await T(a),l.set(a.id,{...a,completedAt:c,state:"succeeded"})}catch(E){const P=(a.attempts??0)+1;if(P>qe){const N={args:a.args,error:E,functionPath:a.functionPath??"",id:a.id};s.push(N),v.push(N),l.set(a.id,{...a,attempts:P,completedAt:c,error:`dead-lettered after ${String(P)} attempts`,state:"failed"})}else{const N=De*2**(P-1);f.set(a.id,{...a,attempts:P,scheduledFor:c+N})}}finally{p.delete(a.id)}}return{executed:u,failed:s}},k=async(o,n)=>{const{executed:s,failed:u}=await _(o);if(u.length>0&&(n?.throwOnError??!0)){const[a]=u;throw u.length===1&&a!==void 0?a.error:new AggregateError(u.map(E=>E.error),`${String(u.length)} scheduled jobs failed: ${u.map(E=>E.functionPath).join(", ")}`)}return s};return{controls:{advance:(o,n)=>(c+=o,k(c,n)),failures:()=>[...v],list:()=>[...f.values()],runPending:o=>k(Number.POSITIVE_INFINITY,o)},scheduler:$}},ee="topics: [...]",Xe=t=>{if(t===void 0)return{controls:{clear:()=>O("topics",ee),published:()=>O("topics",ee)},surfaces:{topics:b("topics",ee)}};const e=ue(t),r=Oe(e.bindings,t.map(i=>({exportName:i,subscriptions:[{binding:i,exportName:i}]})));return{controls:{clear:e.clear,published:i=>e.read(i,"harness.topics.published","topic").map(({destination:g,...c})=>({...c,topic:g}))},surfaces:{topics:r}}},He=()=>{const t=new Ce(":memory:"),e=i=>({one(){if(i.length!==1)throw new A("INTERNAL",`expected exactly one row, received ${String(i.length)}`);const[g]=i;return g},[Symbol.iterator](){return i[Symbol.iterator]()},toArray(){return i}});return{close:()=>{t.close()},sql:{exec:(i,...g)=>{const w=t.prepare(i).all(...g);return e(w)}}}},B=new se,j=t=>{try{const e=JSON.stringify({result:ce(t)}),r=JSON.parse(e);return ie(r.result)}catch(e){throw new A("WIRE_ENCODE_FAILED",e instanceof Error?e.message:String(e),{cause:e})}},Ge=new se,Ze=(t,e,r,i)=>(c,w)=>{let f=!1;const p=[];let l,v,S=0,h=0;const y=()=>B.run(i(),()=>V(c)?t("query",c,e,w,!1):Promise.resolve(c(e))),$=(n,s)=>{if(n<h)return;h=n;const u={done:!1,value:s};if(p.length===0)l=u,v=void 0;else{l=void 0,v=void 0;for(const a of p.splice(0))a.resolve(u)}},T=(n,s)=>{if(!(n<h))if(h=n,p.length===0)v={error:s},l=void 0;else{l=void 0,v=void 0;for(const u of p.splice(0))u.reject(s)}},_=n=>s=>{$(n,s)},k=n=>s=>{T(n,s)},D=()=>{if(f)return;S+=1;const n=S;y().then(_(n)).catch(k(n))};r.add(D);const o={[Symbol.asyncIterator](){return o},next:()=>{if(f)return Promise.resolve({done:!0,value:void 0});if(h===S){if(v!==void 0){const{error:n}=v;return v=void 0,Promise.reject(n)}if(l!==void 0){const n=l;return l=void 0,Promise.resolve(n)}}return h<S?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(v!==void 0){const{error:s}=v;throw v=void 0,s}if(l!==void 0){const s=l;return l=void 0,s}return{done:!1,value:n}})},return:()=>{f=!0,r.delete(D);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return y().then(_(0)).catch(k(0)),o},ht=(t,e)=>{const{close:r,sql:i}=He();let g=!1;const c=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,I])=>[R,I])),f=new Set,p=()=>{for(const R of f)R()},l=R=>(p(),R);let v,S,h;const y=()=>e?.now??Date.now(),$=y(),T=R=>((...I)=>B.run(y(),()=>R(...I))),_=Ke(),{controls:k,surfaces:D}=Ve(e?.queues),{controls:o,surfaces:n}=Xe(e?.topics),{controls:s,surfaces:u}=je(e?.notify,e?.env??{}),a=(R,I)=>{if(R===void 0)throw new A("INTERNAL",`[fake-scheduler] ${I} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:E,scheduler:P}=ze(()=>a(v,"dispatch"),()=>a(S,"mutationContext"),()=>a(h,"actionContext"),()=>w,$),N=be(P),{createWriters:de,runInTransaction:J,runWithBudget:C}=Se(t,{enforceRls:e?.enforceRls,headroomScope:Ge,scheduler:N,sql:i}),te=R=>{const I=Ee(R),X={getIdentity:()=>Promise.resolve(I.claims),userId:I.userId},{database:H,rawDatabase:le}=de(I),M={...u,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runQuery:((d,m)=>q("query",d,M,m)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},L={...u,...D,...n,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runMutation:((d,m)=>q("mutation",d,L,m)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};S??=L;const fe=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(L),db:{enumerable:!0,value:le}}),Q={...u,...D,...n,auth:X,db:H,env:e?.env,fetch:e?.fetch??b("fetch"),log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runAction:((d,m)=>q("action",d,Q,m)),runMutation:((d,m)=>J(()=>q("mutation",d,L,m)).then(l)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),services:Le(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};h??=Q;const q=(d,m,x,F)=>K(d,m,x,F,!0),he=(d,m,x,F)=>d==="mutation"?J(()=>K("mutation",m,x,F,!0).then(j)).then(l):C(()=>q("action",m,x,F));v??=(d,m,x,F,we)=>B.run(we,()=>he(d,m,x,F));const ve=((d,m)=>V(d)?C(()=>K("query",d,M,m,!1).then(j)):C(()=>Promise.resolve(d(M)))),me=((d,m)=>{const x=V(d)?()=>K("mutation",d,L,m,!1).then(j):()=>d(L);return J(x).then(l)}),pe=((d,m)=>V(d)?C(()=>K("action",d,Q,m,!1).then(j)):C(()=>Promise.resolve(d(Q)))),ye=Ze((...d)=>C(()=>K(...d).then(j)),M,f,()=>e?.now??Date.now()),ge=d=>J(()=>d(fe)).then(l);return{action:T(pe),close:c,mutation:T(me),notify:s,query:T(ve),queues:k,run:T(ge),scheduler:E,subscribe:ye,topics:o,wideEvent:()=>_.recorded,withIdentity:d=>te(d)}};return te(null)};export{ht as lunoraTest};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/testing",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.342",
|
|
4
4
|
"description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -57,8 +57,8 @@
|
|
|
57
57
|
"@lunora/notify": "^1.0.0-alpha.111",
|
|
58
58
|
"@lunora/platform": "^1.0.0-alpha.81",
|
|
59
59
|
"@lunora/queue": "^1.0.0-alpha.146",
|
|
60
|
-
"@lunora/scheduler": "^1.0.0-alpha.
|
|
61
|
-
"@lunora/server": "^1.0.0-alpha.
|
|
60
|
+
"@lunora/scheduler": "^1.0.0-alpha.173",
|
|
61
|
+
"@lunora/server": "^1.0.0-alpha.279",
|
|
62
62
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
63
63
|
"@visulima/notification": "2.0.2",
|
|
64
64
|
"ai": "7.0.127"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as se}from"node:async_hooks";import{LunoraError as A}from"@lunora/errors";import{withDeferredSchedules as be}from"@lunora/server";import{createInProcessRuntime as Se,resolveInProcessIdentity as Ee,runRegisteredFunction as M,registeredFunctionKind as W}from"@lunora/server/in-process";import{encodeWire as ce,decodeWire as ie}from"@lunora/wire";import{evaluationAttributes as Ae}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as Ne,createNotify as Re}from"@lunora/notify";import{createNotification as Te}from"@visulima/notification";import{serialize as Pe,deserialize as _e}from"node:v8";import{createQueues as Ie,createTopicContext as Oe}from"@lunora/queue";import{assertScheduleDelay as xe,TERMINAL_RETENTION_MS as $e,MAX_RETRY_ATTEMPTS as ke,RETRY_BASE_DELAY_MS as qe}from"@lunora/scheduler";import{DatabaseSync as De}from"node:sqlite";const I=(t,e)=>{throw new A("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} })`)},Ce=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),Le=t=>new Proxy({...t},{get(e,r){if(!(Ce.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 A("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),b=(t,e)=>new Proxy((...r)=>I(t,e),{apply:()=>I(t,e),get:()=>I(t,e)}),ae={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Me={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>ae},Fe=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,i)=>{t.events.push({...i===void 0?{}:{attributes:{...i}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,Ae(r))},recordException:r=>{const i={"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&&(i["exception.stacktrace"]=r.stack),e.addEvent("exception",i)},setAttribute:(r,i)=>{t.attributes[r]=i},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>ae};return{handle:e,recorded:t}},V=async(t,e)=>await e(V,Me),G={count:()=>{},gauge:()=>{},record:()=>{}},Y={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>Y},Q="notify",je=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},B=(t,e)=>typeof t=="function"?t(e):t,Be=(t,e)=>{const r=[],i=(f,y)=>(r.push({channel:f,payload:structuredClone(y)}),{data:{messageId:`${f}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=f=>({channel:f,id:`lunora-testing-${f}`,initialize:()=>{},isAvailable:()=>!0,send:y=>i(f,y)}),a=B(t.webPush,e)!==void 0,w=B(t.fcm,e)!==void 0,l={...g("push"),send:f=>{const y=Array.isArray(f.to)?f.to:[f.to];if(y.length===0)throw new A("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const x of y){const T=je(x)!==void 0;if(T?!a:!w)throw new Error(T?"@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 i("push",f)}},p={...a||w?{push:l}:{},...B(t.chat,e)===void 0?{}:{chat:g("chat")},...B(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...B(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},d=Ne(),{notify:h,push:E}=Re({...t,store:()=>d},e,{engine:Te(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:f=>f===void 0?[...r]:r.filter(y=>y.channel===f)},surfaces:{notify:h,push:E}}},Ue=(t,e)=>t!==void 0?Be(t,e):{controls:{clear:()=>I("notify",Q),sent:()=>I("notify",Q)},surfaces:{notify:b("notify",Q),push:b("push",Q)}},Z="queues: [...]",re=128*1024,ne=256*1024,Je="json",oe=new TextEncoder,Ke=(t,e)=>{if(e==="v8"){const i=Pe(t);return{body:_e(i),bytes:i.byteLength}}if(e==="text"){if(typeof t!="string")throw new A("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof t}`);return{body:t,bytes:oe.encode(t).byteLength}}if(e==="bytes"){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new A("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 A("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof t}`);return{body:JSON.parse(r),bytes:oe.encode(r).byteLength}},ue=t=>{const e=new Set(t),r=[],i=(a,w,l)=>{const p=l?.contentType??Je,d=Ke(w,p);if(d.bytes>re)throw new A("VALIDATION_ERROR",`@lunora/queue: ${a} message is ${String(d.bytes)} bytes, over the Cloudflare Queues limit of ${String(re)} (128 KB)`);return{bytes:d.bytes,message:{body:d.body,contentType:p,...l?.delaySeconds===void 0?{}:{delaySeconds:l.delaySeconds},destination:a}}},g=a=>({send:(w,l)=>(r.push(i(a,w,l).message),Promise.resolve()),sendBatch:(w,l)=>{const p=[...w].map(h=>i(a,h.body,{contentType:h.contentType,delaySeconds:h.delaySeconds??l?.delaySeconds})),d=p.reduce((h,E)=>h+E.bytes,0);if(d>ne)throw new A("VALIDATION_ERROR",`@lunora/queue: ${a} batch is ${String(d)} bytes, over the Cloudflare Queues limit of ${String(ne)} (256 KB)`);return r.push(...p.map(h=>h.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(a=>[a,g(a)])),clear:()=>{r.length=0},read:(a,w,l)=>{if(a===void 0)return[...r];if(!e.has(a))throw new A("INTERNAL",`${w}("${a}"): no such ${l} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===a)}}},Qe=t=>{const e=ue(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:i,...g})=>({...g,queue:i}))},surfaces:{queues:Ie({bindings:e.bindings})}}},We=t=>t!==void 0?Qe(t):{controls:{clear:()=>I("queues",Z),sent:()=>I("queues",Z)},surfaces:{queues:b("queues",Z)}},Ve=(t,e,r,i,g)=>{let a=g,w=1;const l=new Map,p=new Map,d=new Map,h=[],E=(o,m,n={},s)=>{const c=ce(n);JSON.stringify(c);const S=ie(c),N=s??`fake-job-${String(w)}`;return w+=1,d.delete(N),l.set(N,{args:S,enqueuedAt:a,functionPath:m,id:N,scheduledFor:o}),N},f=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",y={cancel:o=>{const m=l.get(o),n=m!==void 0;return m!==void 0&&d.set(o,{...m,completedAt:a,state:"canceled"}),l.delete(o),Promise.resolve({cancelled:n})},get:o=>{const m=l.get(o),n=p.get(o);let s=d.get(o);return s?.completedAt!==void 0&&s.completedAt<=a-$e&&(s=void 0),m!==void 0?s={...m,state:"pending"}:n!==void 0&&(s={...n,state:"running"}),Promise.resolve(s??null)},list:()=>Promise.resolve([...l.values()]),runAfter:(o,m,n,s)=>{xe(o,"ctx.scheduler.runAfter");const c=E(a+o,f(m),n,s?.id);return Promise.resolve(c)},runAt:(o,m,n,s)=>{const c=E(o,f(m),n,s?.id);return Promise.resolve(c)}},x=async o=>{l.delete(o.id);const m=i(),n=o.functionPath===void 0?void 0:m.get(o.functionPath);if(n===void 0)throw new A("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(n.kind!=="mutation"&&n.kind!=="action")throw new A("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${n.kind} — only mutations and actions can be scheduled`,{status:404});const s=t(),c=n.kind==="action"?r():e();await s(n.kind,n,c,o.args,a)},T=async o=>{const m=[...l.values()].filter(c=>c.scheduledFor<=o).toSorted((c,S)=>c.scheduledFor-S.scheduledFor),n=[];let s=0;for(const c of m)if(l.has(c.id)){s+=1;try{p.set(c.id,c),await x(c),d.set(c.id,{...c,completedAt:a,state:"succeeded"})}catch(S){const N=(c.attempts??0)+1;if(N>ke){const k={args:c.args,error:S,functionPath:c.functionPath??"",id:c.id};n.push(k),h.push(k),d.set(c.id,{...c,attempts:N,completedAt:a,error:`dead-lettered after ${String(N)} attempts`,state:"failed"})}else{const k=qe*2**(N-1);l.set(c.id,{...c,attempts:N,scheduledFor:a+k})}}finally{p.delete(c.id)}}return{executed:s,failed:n}},P=async(o,m)=>{const{executed:n,failed:s}=await T(o);if(s.length>0&&(m?.throwOnError??!0)){const[c]=s;throw s.length===1&&c!==void 0?c.error:new AggregateError(s.map(S=>S.error),`${String(s.length)} scheduled jobs failed: ${s.map(S=>S.functionPath).join(", ")}`)}return n};return{controls:{advance:(o,m)=>(a+=o,P(a,m)),failures:()=>[...h],list:()=>[...l.values()],runPending:o=>P(Number.POSITIVE_INFINITY,o)},scheduler:y}},ee="topics: [...]",Ye=t=>{if(t===void 0)return{controls:{clear:()=>I("topics",ee),published:()=>I("topics",ee)},surfaces:{topics:b("topics",ee)}};const e=ue(t),r=Oe(e.bindings,t.map(i=>({exportName:i,subscriptions:[{binding:i,exportName:i}]})));return{controls:{clear:e.clear,published:i=>e.read(i,"harness.topics.published","topic").map(({destination:g,...a})=>({...a,topic:g}))},surfaces:{topics:r}}},ze=()=>{const t=new De(":memory:"),e=i=>({one(){if(i.length!==1)throw new A("INTERNAL",`expected exactly one row, received ${String(i.length)}`);const[g]=i;return g},[Symbol.iterator](){return i[Symbol.iterator]()},toArray(){return i}});return{close:()=>{t.close()},sql:{exec:(i,...g)=>{const w=t.prepare(i).all(...g);return e(w)}}}},F=new se,U=t=>{try{const e=JSON.stringify({result:ce(t)}),r=JSON.parse(e);return ie(r.result)}catch(e){throw new A("WIRE_ENCODE_FAILED",e instanceof Error?e.message:String(e),{cause:e})}},Xe=new se,He=(t,e,r,i)=>(a,w)=>{let l=!1;const p=[];let d,h,E=0,f=0;const y=()=>F.run(i(),()=>W(a)?t("query",a,e,w,!1):Promise.resolve(a(e))),x=(n,s)=>{if(n<f)return;f=n;const c={done:!1,value:s};if(p.length===0)d=c,h=void 0;else{d=void 0,h=void 0;for(const S of p.splice(0))S.resolve(c)}},T=(n,s)=>{if(!(n<f))if(f=n,p.length===0)h={error:s},d=void 0;else{d=void 0,h=void 0;for(const c of p.splice(0))c.reject(s)}},P=n=>s=>{x(n,s)},j=n=>s=>{T(n,s)},o=()=>{if(l)return;E+=1;const n=E;y().then(P(n)).catch(j(n))};r.add(o);const m={[Symbol.asyncIterator](){return m},next:()=>{if(l)return Promise.resolve({done:!0,value:void 0});if(f===E){if(h!==void 0){const{error:n}=h;return h=void 0,Promise.reject(n)}if(d!==void 0){const n=d;return d=void 0,Promise.resolve(n)}}return f<E?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(h!==void 0){const{error:s}=h;throw h=void 0,s}if(d!==void 0){const s=d;return d=void 0,s}return{done:!1,value:n}})},return:()=>{l=!0,r.delete(o);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return y().then(P(0)).catch(j(0)),m},lt=(t,e)=>{const{close:r,sql:i}=ze();let g=!1;const a=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,_])=>[R,_])),l=new Set,p=()=>{for(const R of l)R()},d=R=>(p(),R);let h,E,f;const y=()=>e?.now??Date.now(),x=y(),T=R=>((..._)=>F.run(y(),()=>R(..._))),P=Fe(),{controls:j,surfaces:o}=We(e?.queues),{controls:m,surfaces:n}=Ye(e?.topics),{controls:s,surfaces:c}=Ue(e?.notify,e?.env??{}),S=(R,_)=>{if(R===void 0)throw new A("INTERNAL",`[fake-scheduler] ${_} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:N,scheduler:k}=Ve(()=>S(h,"dispatch"),()=>S(E,"mutationContext"),()=>S(f,"actionContext"),()=>w,x),z=be(k),{createWriters:de,runInTransaction:J,runWithBudget:q}=Se(t,{enforceRls:e?.enforceRls,headroomScope:Xe,scheduler:z,sql:i}),te=R=>{const _=Ee(R),X={getIdentity:()=>Promise.resolve(_.claims),userId:_.userId},{database:H,rawDatabase:le}=de(_),D={...c,auth:X,db:H,env:e?.env,log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runQuery:((u,v)=>$("query",u,D,v)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},C={...c,...o,...n,auth:X,db:H,env:e?.env,log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runMutation:((u,v)=>$("mutation",u,C,v)),runQuery:((u,v)=>$("query",u,D,v)),scheduler:z,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};E??=C;const fe=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(C),db:{enumerable:!0,value:le}}),K={...c,...o,...n,auth:X,db:H,env:e?.env,fetch:e?.fetch??b("fetch"),log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runAction:((u,v)=>$("action",u,K,v)),runMutation:((u,v)=>J(()=>$("mutation",u,C,v)).then(d)),runQuery:((u,v)=>$("query",u,D,v)),scheduler:z,secrets:b("secrets"),services:Le(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};f??=K;const $=(u,v,O,L)=>M(u,v,O,L,!0),he=(u,v,O,L)=>u==="mutation"?J(()=>M("mutation",v,O,L,!0).then(U)).then(d):q(()=>$("action",v,O,L));h??=(u,v,O,L,we)=>F.run(we,()=>he(u,v,O,L));const me=((u,v)=>W(u)?q(()=>M("query",u,D,v,!1).then(U)):q(()=>Promise.resolve(u(D)))),ve=((u,v)=>{const O=W(u)?()=>M("mutation",u,C,v,!1).then(U):()=>u(C);return J(O).then(d)}),pe=((u,v)=>W(u)?q(()=>M("action",u,K,v,!1).then(U)):q(()=>Promise.resolve(u(K)))),ge=He((...u)=>q(()=>M(...u).then(U)),D,l,()=>e?.now??Date.now()),ye=u=>J(()=>u(fe)).then(d);return{action:T(pe),close:a,mutation:T(ve),notify:s,query:T(me),queues:j,run:T(ye),scheduler:N,subscribe:ge,topics:m,wideEvent:()=>P.recorded,withIdentity:u=>te(u)}};return te(null)};export{lt as lunoraTest};
|