@econ-v1/app-sdk 7.7.50 → 7.7.51

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/app-log.d.ts CHANGED
@@ -1,8 +1,21 @@
1
1
  export declare const ERROR_REPORT_INTERVAL_MS = 60000;
2
2
  export declare const APP_LOG_MAX_BYTES: number;
3
3
  export declare const APP_LOG_TAIL_BYTES: number;
4
+ /** Text that may wait for a write in flight; past it the new lines are dropped and counted. */
5
+ export declare const APP_LOG_WAITING_MAX_CHARS: number;
4
6
  export interface AppLogWriter {
5
7
  write(level: string, message: string): void;
8
+ /** Lines go to the file in the background from here on: the host has the app's name, so its folder stays. */
9
+ inBackground(): void;
10
+ /** Writes the waiting lines now, for an app about to exit. */
11
+ flush(): void;
12
+ /** Waits for the write in flight and what waits behind it, at most `ms`, then flushes. */
13
+ drain(ms: number): Promise<void>;
14
+ }
15
+ /** The two ways a line reaches the file by its path. `later` is absent on runtimes without async file calls. */
16
+ export interface AppLogAppender {
17
+ now(path: string, text: string): void;
18
+ later?(path: string, text: string): Promise<void>;
6
19
  }
7
20
  export interface AppLogWriterOptions {
8
21
  /** Where a failed write is reported. Defaults to `console.error`. */
@@ -13,5 +26,7 @@ export interface AppLogWriterOptions {
13
26
  maxBytes?: number;
14
27
  /** Newest bytes retained when the bound is crossed. */
15
28
  tailBytes?: number;
29
+ /** Append by path with these instead of through a held descriptor. Tests. */
30
+ byPath?: AppLogAppender;
16
31
  }
17
32
  export declare function createAppLogWriter(logDir: string | undefined, options?: AppLogWriterOptions): AppLogWriter;
@@ -1,2 +1,3 @@
1
- var me=Object.defineProperty;var ye=(e)=>e;function ge(e,t){this[e]=ye.bind(null,t)}var _e=(e,t)=>{for(var o in t)me(e,o,{get:t[o],enumerable:!0,configurable:!0,set:ge.bind(t,o)})};import{Database as Pe}from"burger:sqlite";var N={};_e(N,{incrementCounter:()=>q,initAppTelemetry:()=>M,injectTraceContext:()=>be,telemetryActive:()=>L,traceIncomingCapability:()=>he});async function M(e){}function L(){return!1}function q(e,t=1,o){}function be(e){return e}async function he(e,t,o){return o()}import{connect as xe,dataDir as Ce,exit as Z,logDir as Ie,memoryUsage as Se}from"burger:host";var G=null,Ge=import("burger:async_hooks").then((e)=>(G=e.AsyncLocalStorage,!0),()=>!1);function Y(){return G}function Q(e){let t=ve(),o=null,n=()=>{if(o)return o;let i=e();if(!i)return t;return o=new i,o};return{run(i,r){return n().run(i,r)},getStore(){return n().getStore()}}}function ve(){let e;return{run(t,o){let n=e;e=t;try{return o()}finally{e=n}},getStore(){return e}}}var H=!0,X=256;function F(){return{socket:void 0,logDir:Ie,dataDir:Ce}}var B=F();function J(){return B.socket}function ee(e,t,o=Z){o(e)}function b(e){Z(e)}function te(){}var Re=/the app channel is (not open|closed)/;function ne(e){let t=xe(),o=!0,n=!1;function i(r){if(n)return;try{t.send(r)}catch(a){if(a instanceof Error&&Re.test(a.message)){n=!0;return}throw a}}return t.onFrame((r)=>{if(!o)return;e.onFrame(r).catch((a)=>e.onFrameError(a))}),t.onClose((r)=>{if(n=!0,r)e.onError(r);else e.onClose()}),queueMicrotask(()=>e.onConnected("burger:host")),{send(r){i(r)},sendAndFlush(r){return i(r),Promise.resolve()},stopAccepting(){o=!1},end(){n=!0,t.close()}}}function oe(){return Q(Y)}function re(){let e=Se();return{heap_used_kb:Math.round(e.heap_used_kb),heap_total_kb:Math.round(e.heap_total_kb),external_kb:Math.round(e.external_kb),heap_capacity_kb:Math.round(e.heap_capacity_kb)}}function V(){throw Error("heap snapshots are not available in the Burger runtime")}async function ie(e,t=V,o=V){let n=t();return{size_bytes:await o(e,n)}}import*as s from"burger:fs";import{join as we}from"burger:path";var Ee=60000,ke=52428800,Te=10485760;function se(e,t={}){if(!e)return{write:()=>{}};let o=we(e,"app.log"),n=t.reportError??((l)=>console.error(l)),i=t.now??Date.now,r=t.maxBytes??ke,a=Math.min(t.tailBytes??Te,r),p=typeof s.openSync==="function"&&typeof s.writeSync==="function"&&typeof s.closeSync==="function"&&typeof s.fstatSync==="function"&&typeof s.readSync==="function"&&typeof s.ftruncateSync==="function",c=null,U=!1,T=null,C=0;function W(){if(U)return;s.mkdirSync(e,{recursive:!0}),U=!0}function fe(l){let I=i();if(T!==null&&I-T<Ee){C+=1;return}let S=l instanceof Error?l.message:String(l),d=C>0?`; ${C} earlier failure(s) not reported`:"";n(`[node-app-sdk] app.log write failed (${o}): ${S}${d}`),T=I,C=0}return{write(l,I){let S=`${new Date().toISOString()} [${l.toUpperCase().padEnd(5)}] ${I}
2
- `;try{if(!p){W(),s.appendFileSync(o,S);return}if(c===null)W(),c=s.openSync(o,"a+");let d=s.fstatSync(c).size;if(d>r){let P=Math.min(d,a),K=Buffer.alloc(P);s.readSync(c,K,0,P,d-P),s.ftruncateSync(c,0),s.writeSync(c,K)}s.writeSync(c,S)}catch(d){if(c!==null){try{s.closeSync(c)}catch{}c=null}fe(d)}}}}var{injectTraceContext:Me,traceIncomingCapability:Le}=N,qe=M,tt=L,nt=q,Ne=X;function ot(e,t={}){let o=t.cacheSizeKb??Ne;if(!Number.isInteger(o)||o<=0)throw RangeError("cacheSizeKb must be a positive integer");let n=new Pe(e);try{return n.exec(`PRAGMA cache_size = -${o}`),n}catch(i){throw n.close(),i}}var rt=F,it=J,st=ee,He=se(B.logDir),u=null,pe=oe(),v=new Map,f={trace:(e)=>h("trace",e),debug:(e)=>h("debug",e),info:(e)=>h("info",e),warn:(e)=>h("warn",e),error:(e)=>h("error",e),holdLease:()=>{let e=!1;return R(),()=>{if(e)return;e=!0,A()}}};function h(e,t){if(He.write(e,t),u)u({type:"log",level:e,message:t});else console[e==="trace"?"debug":e](t)}function at(e,t){if(!u)return Promise.reject(Error("Not connected to host"));let o=t??30000,n=e.timeout_ms===void 0?{...e,timeout_ms:o}:e,i={...n,trace_context:Me({...n.trace_context??{}})},r=pe.getStore();if(r?.active&&r.id!==void 0)i.invocation_context_id=r.id;return new Promise((a,p)=>{v.set(e.id,{resolve:a,reject:p}),u({type:"invoke_capability",id:e.id,request:i}),setTimeout(()=>{if(v.has(e.id))v.delete(e.id),p(Error(`Capability invocation timed out after ${o}ms: ${e.capability}`))},o)})}function pt(e,t){if(!u)throw Error("Not connected to host");u({type:"publish_event",event_name:e,data:t})}var m=0,_,y=null,x=!1,E,ce=()=>b(0),z=ce,D,ue=(e)=>(u?.(e),Promise.resolve()),O=ue;function j(e){if(_=e,e===void 0)k()}function k(){if(y)clearTimeout(y),y=null}function le(){if(x)return;if(_===void 0)return;if(m!==0)return;k();let e=Math.max(0,_*1000),t=setTimeout(()=>{y=null,Fe()},e);t.unref?.(),y=t}function R(){m++,k()}function A(){if(m=Math.max(0,m-1),m===0)le()}async function Fe(){if(x)return;if(x=!0,D?.(),E)await E.shutdown();await O({type:"lease_exit"}),z()}function ct(){k(),m=0,_=void 0,x=!1,E=void 0,z=ce,D=void 0,O=ue}function ut(e){z=e}function lt(){return{inFlight:m,rememberedSecs:_,timerArmed:y!==null,draining:x}}var $e=30000;function Be(){let e=process.env.NODE_APP_MEMORY_SAMPLE_INTERVAL_MS,t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>=1000?t:$e}var g=null,je=re;function ae(e){e({type:"app_memory",...je()})}function ze(e){if(g)return;ae(e),g=setInterval(()=>ae(e),Be()),g.unref?.()}function w(){if(g)clearInterval(g),g=null}var De=ie;async function Oe(e,t,o=De){try{let n=await o(e.path);t({type:"heap_snapshot_response",id:e.id,success:!0,size_bytes:n.size_bytes})}catch{t({type:"heap_snapshot_response",id:e.id,success:!1,error:"heap_snapshot_failed"})}}function Ue(e,t){let o=t.indexOf("?"),n=o>=0?t.slice(0,o):t,i=e.split("/"),r=n.split("/"),a=0,p=0;while(a<i.length){if(i[a]==="**")return!0;if(p>=r.length)return!1;if(i[a]!=="*"&&i[a]!==r[p])return!1;a++,p++}return p===r.length}class We{_routes=[];route(e,t,o,n){this._routes.push({method:e,path:t,policy:o,handler:n})}async init(e){}async shutdown(){}async handleRequest(e){if(this._routes.length>0)return this._dispatchRoute(e);return{status:501,headers:{},body:{error:"Not implemented"}}}async _dispatchRoute(e){let t=e.method.toUpperCase(),o=e.path;for(let n of this._routes){if(!(n.method==="*"||n.method.toUpperCase()===t))continue;if(!Ue(n.path,o))continue;let r=n.policy.requiredPermissions??[],a=e.caller?.granted_permissions??[],p=r.filter((c)=>!a.includes(c));if(p.length>0)return f.warn(`SDK scope denied: [${p.join(", ")}] missing for ${t} ${o}`),{status:403,headers:{},body:{error:`Missing permissions: ${p.join(", ")}`}};return n.handler(e)}return this.notFound()}async handleEvent(e){}providedCapabilities(){return[]}async handleCapability(e){return{id:e.id,success:!1,payload:{error:"Capability handling not implemented"}}}json(e,t=200){return{status:t,headers:{"Content-Type":"application/json"},body:e}}error(e,t=500){return{status:t,headers:{"Content-Type":"application/json"},body:{error:e}}}notFound(){return this.error("Not found",404)}}function dt(e){te(),qe(e.metadata?.name??"node-app");let t=ne({onConnected:(n)=>{f.debug(`Connected to host via ${n}`)},onFrame:(n)=>de(e,n,o),onFrameError:(n)=>{f.error(`Failed to parse IPC message: ${n}`)},onError:(n)=>{console.error(`[node-app-sdk] Socket error: ${n.message}`),b(1)},onClose:()=>{w(),b(0),f.debug("Socket closed, shutting down")}});function o(n){t.send(n)}u=o,D=()=>{t.stopAccepting()},O=(n)=>t.sendAndFlush(n),process.on("SIGTERM",async()=>{if(!H)return;w(),await e.shutdown(),t.end(),process.exit(0)}),process.on("SIGINT",async()=>{if(!H)return;w(),await e.shutdown(),t.end(),process.exit(0)})}async function de(e,t,o){switch(E=e,t.type){case"ping":{o({type:"pong",id:t.id});break}case"init":{let n=t.config;await e.init(n),o({type:"ready",protocol_features:["ipc_ping_v1"],metadata:e.metadata}),ze(o);break}case"lease_update":{let n=t.lease_secs;if(n!==_)j(n),le();break}case"request":{let{id:n,request:i}=t;R();try{let r=await e.handleRequest(i);o({type:"response",id:n,response:r})}catch(r){o({type:"response",id:n,response:{status:500,headers:{},body:{error:`Internal app error: ${r}`}}})}finally{A()}break}case"event":{let{event:n,lease_secs:i}=t;j(i),R();try{await e.handleEvent(n)}catch(r){f.error(`Event handler error: ${r}`)}finally{A()}break}case"capability_request":{let{id:n,request:i}=t;j(i.lease_secs),R();let r={id:i.invocation_context_id,active:!0};try{let a=await pe.run(r,async()=>{try{return await Le(i.capability,i.trace_context,()=>e.handleCapability(i))}finally{r.active=!1}});o({type:"capability_response",id:n,response:a})}catch(a){o({type:"capability_response",id:n,response:{id:i.id,success:!1,payload:{error:`Capability handler error: ${a}`}}})}finally{A()}break}case"invoke_capability_result":{let{id:n,response:i}=t,r=v.get(n);if(r)v.delete(n),r.resolve(i);break}case"shutdown":{f.info("Received shutdown signal from host"),w(),await e.shutdown(),b(0);break}case"heap_snapshot_request":{await Oe(t,o);break}default:f.warn(`Unknown IPC message type: ${t.type}`)}}async function ft(e,t,o){u=o,await de(e,t,u)}export{We as NodeApp,De as _captureHeapSnapshotTo,Oe as _handleHeapSnapshotRequest,rt as _resolveCtx,je as _sampleMemory,st as _testExitWorker,ft as _testHandleMessage,lt as _testLeaseState,ct as _testResetLeaseState,it as _testRunNodeAppPath,ut as _testSetLeaseExitFn,f as host,nt as incrementCounter,qe as initAppTelemetry,at as invokeCapability,ot as openDatabase,pt as publishEvent,dt as runNodeApp,tt as telemetryActive};
1
+ var ke=Object.defineProperty;var Ee=(e)=>e;function Te(e,t){this[e]=Ee.bind(null,t)}var Me=(e,t)=>{for(var n in t)ke(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Te.bind(t,n)})};import{Database as Ye}from"burger:sqlite";var z={};Me(z,{incrementCounter:()=>j,initAppTelemetry:()=>O,injectTraceContext:()=>Le,telemetryActive:()=>W,traceIncomingCapability:()=>Ne});async function O(e){}function W(){return!1}function j(e,t=1,n){}function Le(e){return e}async function Ne(e,t,n){return n()}import{connect as He,dataDir as Fe,exit as ce,logDir as Be,memoryUsage as $e}from"burger:host";var ie=null,ct=import("burger:async_hooks").then((e)=>(ie=e.AsyncLocalStorage,!0),()=>!1);function se(){return ie}function ae(e){let t=qe(),n=null,o=()=>{if(n)return n;let i=e();if(!i)return t;return n=new i,n};return{run(i,r){return o().run(i,r)},getStore(){return o().getStore()}}}function qe(){let e;return{run(t,n){let o=e;e=t;try{return n()}finally{e=o}},getStore(){return e}}}var U=!0,ue=256;function G(){return{socket:void 0,logDir:Be,dataDir:Fe}}var K=G();function le(){return K.socket}function de(e,t,n=ce){n(e)}function fe(e){ce(e)}function me(){}var De=/the app channel is (not open|closed)/;function ye(e){let t=He(),n=!0,o=!1;function i(r){if(o)return;try{t.send(r)}catch(a){if(a instanceof Error&&De.test(a.message)){o=!0;return}throw a}}return t.onFrame((r)=>{if(!n)return;e.onFrame(r).catch((a)=>e.onFrameError(a))}),t.onClose((r)=>{if(o=!0,r)e.onError(r);else e.onClose()}),queueMicrotask(()=>e.onConnected("burger:host")),{send(r){i(r)},sendAndFlush(r){return i(r),Promise.resolve()},stopAccepting(){n=!1},end(){o=!0,t.close()}}}function ge(){return ae(se)}function be(){let e=$e();return{heap_used_kb:Math.round(e.heap_used_kb),heap_total_kb:Math.round(e.heap_total_kb),external_kb:Math.round(e.external_kb),heap_capacity_kb:Math.round(e.heap_capacity_kb)}}function pe(){throw Error("heap snapshots are not available in the Burger runtime")}async function _e(e,t=pe,n=pe){let o=t();return{size_bytes:await n(e,o)}}import*as s from"burger:fs";import{join as We}from"burger:path";var je=60000,ze=52428800,Ue=10485760,Ge=262144;function Ke(){let e=s.promises?.appendFile;return{now:(t,n)=>s.appendFileSync(t,n),...typeof e==="function"?{later:(t,n)=>e(t,n)}:{}}}function he(e,t={}){if(!e)return{write:()=>{},inBackground:()=>{},flush:()=>{},drain:async()=>{}};let n=We(e,"app.log"),o=t.reportError??((p)=>console.error(p)),i=t.now??Date.now,r=t.maxBytes??ze,a=Math.min(t.tailBytes??Ue,r),c=t.byPath===void 0&&typeof s.openSync==="function"&&typeof s.writeSync==="function"&&typeof s.closeSync==="function"&&typeof s.fstatSync==="function"&&typeof s.readSync==="function"&&typeof s.ftruncateSync==="function",x=t.byPath??Ke(),l=null,b=[],R=0,w=0,X=!1,P=!1,J=Promise.resolve(),ee=!1,H=null,k=0;function F(){if(ee)return;s.mkdirSync(e,{recursive:!0}),ee=!0}function B(p){let u=i();if(H!==null&&u-H<je){k+=1;return}let f=p instanceof Error?p.message:String(p),m=k>0?`; ${k} earlier failure(s) not reported`:"";o(`[node-app-sdk] app.log write failed (${n}): ${f}${m}`),H=u,k=0}function te(){if(w>0)b.push(`${new Date().toISOString()} [WARN ] [node-app-sdk] ${w} line(s) not logged: the writes fell behind
2
+ `),w=0;let p=b.join("");return b=[],R=0,p}function ne(p){try{F(),x.now(n,p)}catch(u){B(u)}}async function we(p){try{while(b.length>0){let u=te();try{F(),await p(n,u)}catch(f){B(f)}}}finally{P=!1}}function Pe(p,u){if(R>0&&R+p.length>Ge){w+=1;return}if(b.push(p),R+=p.length,P)return;P=!0,J=we(u).catch(()=>{})}function oe(){if(b.length>0)ne(te())}return{inBackground(){X=!0},flush:oe,async drain(p){if(P){let u;await Promise.race([J,new Promise((f)=>u=setTimeout(f,p))]),clearTimeout(u)}oe()},write(p,u){let f=`${new Date().toISOString()} [${p.toUpperCase().padEnd(5)}] ${u}
3
+ `;if(!c){if(X&&x.later)Pe(f,x.later);else ne(f);return}try{if(l===null)F(),l=s.openSync(n,"a+");let m=s.fstatSync(l).size;if(m>r){let D=Math.min(m,a),re=Buffer.alloc(D);s.readSync(l,re,0,D,m-D),s.ftruncateSync(l,0),s.writeSync(l,re)}s.writeSync(l,f)}catch(m){if(l!==null){try{s.closeSync(l)}catch{}l=null}B(m)}}}}var{injectTraceContext:Qe,traceIncomingCapability:Ve}=z,Ze=O,bt=W,_t=j,Xe=ue;function ht(e,t={}){let n=t.cacheSizeKb??Xe;if(!Number.isInteger(n)||n<=0)throw RangeError("cacheSizeKb must be a positive integer");let o=new Ye(e);try{return o.exec(`PRAGMA cache_size = -${n}`),o}catch(i){throw o.close(),i}}var vt=G,xt=le,It=de,A=he(K.logDir),xe=500;function L(e){A.flush(),fe(e)}var d=null,Ie=ge(),C=new Map,y={trace:(e)=>I("trace",e),debug:(e)=>I("debug",e),info:(e)=>I("info",e),warn:(e)=>I("warn",e),error:(e)=>I("error",e),holdLease:()=>{let e=!1;return E(),()=>{if(e)return;e=!0,T()}}};function I(e,t){if(A.write(e,t),d)d({type:"log",level:e,message:t});else console[e==="trace"?"debug":e](t)}function Ct(e,t){if(!d)return Promise.reject(Error("Not connected to host"));let n=t??30000,o=e.timeout_ms===void 0?{...e,timeout_ms:n}:e,i={...o,trace_context:Qe({...o.trace_context??{}})},r=Ie.getStore();if(r?.active&&r.id!==void 0)i.invocation_context_id=r.id;return new Promise((a,c)=>{C.set(e.id,{resolve:a,reject:c}),d({type:"invoke_capability",id:e.id,request:i}),setTimeout(()=>{if(C.has(e.id))C.delete(e.id),c(Error(`Capability invocation timed out after ${n}ms: ${e.capability}`))},n)})}function At(e,t){if(!d)throw Error("Not connected to host");d({type:"publish_event",event_name:e,data:t})}var g=0,v,_=null,S=!1,N,Ce=()=>L(0),Q=Ce,V,Ae=(e)=>(d?.(e),Promise.resolve()),Z=Ae;function Y(e){if(v=e,e===void 0)q()}function q(){if(_)clearTimeout(_),_=null}function Se(){if(S)return;if(v===void 0)return;if(g!==0)return;q();let e=Math.max(0,v*1000),t=setTimeout(()=>{_=null,Je()},e);t.unref?.(),_=t}function E(){g++,q()}function T(){if(g=Math.max(0,g-1),g===0)Se()}async function Je(){if(S)return;if(S=!0,V?.(),N)await N.shutdown();await A.drain(xe),await Z({type:"lease_exit"}),Q()}function St(){q(),g=0,v=void 0,S=!1,N=void 0,Q=Ce,V=void 0,Z=Ae}function Rt(e){Q=e}function wt(){return{inFlight:g,rememberedSecs:v,timerArmed:_!==null,draining:S}}var et=30000;function tt(){let e=process.env.NODE_APP_MEMORY_SAMPLE_INTERVAL_MS,t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>=1000?t:et}var h=null,nt=be;function ve(e){e({type:"app_memory",...nt()})}function ot(e){if(h)return;ve(e),h=setInterval(()=>ve(e),tt()),h.unref?.()}function M(){if(h)clearInterval(h),h=null}var rt=_e;async function it(e,t,n=rt){try{let o=await n(e.path);t({type:"heap_snapshot_response",id:e.id,success:!0,size_bytes:o.size_bytes})}catch{t({type:"heap_snapshot_response",id:e.id,success:!1,error:"heap_snapshot_failed"})}}function st(e,t){let n=t.indexOf("?"),o=n>=0?t.slice(0,n):t,i=e.split("/"),r=o.split("/"),a=0,c=0;while(a<i.length){if(i[a]==="**")return!0;if(c>=r.length)return!1;if(i[a]!=="*"&&i[a]!==r[c])return!1;a++,c++}return c===r.length}class at{_routes=[];route(e,t,n,o){this._routes.push({method:e,path:t,policy:n,handler:o})}async init(e){}async shutdown(){}async handleRequest(e){if(this._routes.length>0)return this._dispatchRoute(e);return{status:501,headers:{},body:{error:"Not implemented"}}}async _dispatchRoute(e){let t=e.method.toUpperCase(),n=e.path;for(let o of this._routes){if(!(o.method==="*"||o.method.toUpperCase()===t))continue;if(!st(o.path,n))continue;let r=o.policy.requiredPermissions??[],a=e.caller?.granted_permissions??[],c=r.filter((x)=>!a.includes(x));if(c.length>0)return y.warn(`SDK scope denied: [${c.join(", ")}] missing for ${t} ${n}`),{status:403,headers:{},body:{error:`Missing permissions: ${c.join(", ")}`}};return o.handler(e)}return this.notFound()}async handleEvent(e){}providedCapabilities(){return[]}async handleCapability(e){return{id:e.id,success:!1,payload:{error:"Capability handling not implemented"}}}json(e,t=200){return{status:t,headers:{"Content-Type":"application/json"},body:e}}error(e,t=500){return{status:t,headers:{"Content-Type":"application/json"},body:{error:e}}}notFound(){return this.error("Not found",404)}}function Pt(e){me(),Ze(e.metadata?.name??"node-app");let t=ye({onConnected:(o)=>{y.debug(`Connected to host via ${o}`)},onFrame:(o)=>Re(e,o,n),onFrameError:(o)=>{y.error(`Failed to parse IPC message: ${o}`)},onError:(o)=>{console.error(`[node-app-sdk] Socket error: ${o.message}`),L(1)},onClose:()=>{M(),L(0),y.debug("Socket closed, shutting down")}});function n(o){t.send(o)}d=n,V=()=>{t.stopAccepting()},Z=(o)=>t.sendAndFlush(o),process.on("SIGTERM",async()=>{if(!U)return;M(),await e.shutdown(),t.end(),process.exit(0)}),process.on("SIGINT",async()=>{if(!U)return;M(),await e.shutdown(),t.end(),process.exit(0)})}async function Re(e,t,n){switch(N=e,t.type){case"ping":{n({type:"pong",id:t.id});break}case"init":{let o=t.config;await e.init(o),n({type:"ready",protocol_features:["ipc_ping_v1"],metadata:e.metadata}),A.inBackground(),ot(n);break}case"lease_update":{let o=t.lease_secs;if(o!==v)Y(o),Se();break}case"request":{let{id:o,request:i}=t;E();try{let r=await e.handleRequest(i);n({type:"response",id:o,response:r})}catch(r){n({type:"response",id:o,response:{status:500,headers:{},body:{error:`Internal app error: ${r}`}}})}finally{T()}break}case"event":{let{event:o,lease_secs:i}=t;Y(i),E();try{await e.handleEvent(o)}catch(r){y.error(`Event handler error: ${r}`)}finally{T()}break}case"capability_request":{let{id:o,request:i}=t;Y(i.lease_secs),E();let r={id:i.invocation_context_id,active:!0};try{let a=await Ie.run(r,async()=>{try{return await Ve(i.capability,i.trace_context,()=>e.handleCapability(i))}finally{r.active=!1}});n({type:"capability_response",id:o,response:a})}catch(a){n({type:"capability_response",id:o,response:{id:i.id,success:!1,payload:{error:`Capability handler error: ${a}`}}})}finally{T()}break}case"invoke_capability_result":{let{id:o,response:i}=t,r=C.get(o);if(r)C.delete(o),r.resolve(i);break}case"shutdown":{y.info("Received shutdown signal from host"),M(),await e.shutdown(),await A.drain(xe),L(0);break}case"heap_snapshot_request":{await it(t,n);break}default:y.warn(`Unknown IPC message type: ${t.type}`)}}async function kt(e,t,n){d=n,await Re(e,t,d)}export{at as NodeApp,rt as _captureHeapSnapshotTo,it as _handleHeapSnapshotRequest,vt as _resolveCtx,nt as _sampleMemory,It as _testExitWorker,kt as _testHandleMessage,wt as _testLeaseState,St as _testResetLeaseState,xt as _testRunNodeAppPath,Rt as _testSetLeaseExitFn,y as host,_t as incrementCounter,Ze as initAppTelemetry,Ct as invokeCapability,ht as openDatabase,At as publishEvent,Pt as runNodeApp,bt as telemetryActive};