@coreframe/dev-supervisor 0.1.10 → 0.1.12
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.ts +4 -33
- package/dist/index.js +1 -1
- package/package.json +3 -4
package/dist/index.d.ts
CHANGED
|
@@ -4,25 +4,8 @@ import { CoreframeConfig } from "@coreframe/config";
|
|
|
4
4
|
|
|
5
5
|
//#region src/index.d.ts
|
|
6
6
|
declare const protocolVersion = 1;
|
|
7
|
-
type
|
|
8
|
-
type DevSupervisorViteResource = "vite:web" | `vite:flutter:${DevSupervisorFlutterPlatform}`;
|
|
9
|
-
type DevSupervisorResource = "managed-dev" | "postgres" | "sqlite" | DevSupervisorViteResource;
|
|
7
|
+
type DevSupervisorResource = "managed-dev" | "postgres" | "sqlite";
|
|
10
8
|
type DevSupervisorStream = "stdout" | "stderr";
|
|
11
|
-
type DevSupervisorProcessSpec = {
|
|
12
|
-
args: string[];
|
|
13
|
-
command: string;
|
|
14
|
-
cwd: string;
|
|
15
|
-
env: NodeJS.ProcessEnv;
|
|
16
|
-
};
|
|
17
|
-
type DevSupervisorViteSpec = {
|
|
18
|
-
configFingerprint: string;
|
|
19
|
-
endpoint: {
|
|
20
|
-
host: string;
|
|
21
|
-
port?: number;
|
|
22
|
-
};
|
|
23
|
-
processes: DevSupervisorProcessSpec[];
|
|
24
|
-
resource: DevSupervisorViteResource;
|
|
25
|
-
};
|
|
26
9
|
type DevSupervisorEvent = DevSupervisorLogEvent | DevSupervisorManagedDevEvent | DevSupervisorServiceEvent | DevSupervisorGapEvent | DevSupervisorReplayCompleteEvent;
|
|
27
10
|
type DevSupervisorLogEvent = {
|
|
28
11
|
event: "log";
|
|
@@ -155,13 +138,11 @@ declare function connectExistingDevSupervisor({
|
|
|
155
138
|
cwd?: string;
|
|
156
139
|
env?: NodeJS.ProcessEnv;
|
|
157
140
|
}): Promise<DevSupervisorClient | undefined>;
|
|
158
|
-
/** Stops
|
|
141
|
+
/** Stops the detached supervisor for a project directory. */
|
|
159
142
|
declare function stopDevSupervisor({
|
|
160
|
-
cwd
|
|
161
|
-
resource
|
|
143
|
+
cwd
|
|
162
144
|
}?: {
|
|
163
145
|
cwd?: string;
|
|
164
|
-
resource?: DevSupervisorViteResource;
|
|
165
146
|
}): Promise<boolean>;
|
|
166
147
|
declare class DevSupervisorClient {
|
|
167
148
|
readonly state: SupervisorState;
|
|
@@ -213,22 +194,12 @@ declare class DevSupervisorClient {
|
|
|
213
194
|
managedDevStatus(): Promise<{
|
|
214
195
|
status: unknown;
|
|
215
196
|
}>;
|
|
216
|
-
acquireVite(spec: DevSupervisorViteSpec, fresh?: boolean): Promise<{
|
|
217
|
-
endpoint: {
|
|
218
|
-
host: string;
|
|
219
|
-
port: number;
|
|
220
|
-
};
|
|
221
|
-
leaseId: string;
|
|
222
|
-
state: "reused" | "started";
|
|
223
|
-
}>;
|
|
224
197
|
release(leaseId: string): Promise<void>;
|
|
225
198
|
subscribe(resources: DevSupervisorResource[]): Promise<{
|
|
226
199
|
subscriptionId: string;
|
|
227
200
|
}>;
|
|
228
201
|
status(): Promise<unknown>;
|
|
229
202
|
shutdown(): Promise<void>;
|
|
230
|
-
/** Stops the managed Vite resource without shutting down the supervisor. */
|
|
231
|
-
stopVite(resource: DevSupervisorViteResource): Promise<boolean>;
|
|
232
203
|
onEvent(listener: (event: DevSupervisorEvent) => void): () => boolean;
|
|
233
204
|
waitForServiceExit(resource: DevSupervisorResource): Promise<void>;
|
|
234
205
|
close(): void;
|
|
@@ -249,4 +220,4 @@ declare function runDevSupervisorProcess({
|
|
|
249
220
|
startManagedDev?: DevSupervisorManagedDevStarter;
|
|
250
221
|
}): Promise<void>;
|
|
251
222
|
//#endregion
|
|
252
|
-
export { DevSupervisorClient, DevSupervisorEvent,
|
|
223
|
+
export { DevSupervisorClient, DevSupervisorEvent, DevSupervisorManagedDevEvent, DevSupervisorManagedDevSession, DevSupervisorManagedDevStarter, DevSupervisorPostgresSidecar, DevSupervisorPostgresStarter, DevSupervisorResource, DevSupervisorSqliteSidecar, DevSupervisorSqliteStarter, DevSupervisorStream, connectDevSupervisor, connectExistingDevSupervisor, runDevSupervisorProcess, stopDevSupervisor };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as e}from"node:child_process";import{createHash as t,randomUUID as n}from"node:crypto";import{appendFile as r,mkdir as i,readFile as a,rename as o,rm as s,stat as c,unlink as l,writeFile as u}from"node:fs/promises";import{createConnection as d,createServer as f}from"node:net";import{tmpdir as p}from"node:os";import m from"node:path";import h from"node:process";import{Writable as g}from"node:stream";import _ from"@alloc/tree-kill";const v=`.coreframe/dev-supervisor`,y=`supervisor.json`,b=`logs`,x=1*1024*1024,S=4*1024*1024,C=45e3,w=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ee=/^[\t ]*➜[\t ]+\S+:[\t ]+.+(?:\r?\n|$)/mu;async function te({cwd:e=h.cwd(),env:t=h.env,supervisorEntry:n}={}){let r=await T({cwd:e,env:t});if(r)return r;let i=await F(e),a=await re(e);if(!a)return i=await P(e),N({cwd:e,env:t,state:i});try{if(i=await F(e),i&&i.cwd===m.resolve(e)&&Z(i.pid))return await N({cwd:e,env:t,state:i});if(i&&await L(e,i),!n)throw Error(`A development supervisor process entry is required to start the supervisor.`);return await ne({cwd:e,env:t,entry:n}),i=await P(e),N({cwd:e,env:t,state:i})}finally{await a()}}async function T({cwd:e=h.cwd(),env:t=h.env}={}){let n=await F(e);if(!(!n||n.cwd!==m.resolve(e)||!Z(n.pid)))try{return await N({cwd:e,env:t,state:n})}catch{await L(e,n);return}}async function E({cwd:e=h.cwd(),resource:t}={}){let n=await F(e);if(!n||n.cwd!==m.resolve(e)||!Z(n.pid))return await L(e,n),!1;let r=await N({cwd:e,env:h.env,state:n});try{if(t)return await r.stopVite(t);await r.shutdown()}finally{r.close()}return await ie(e,n.supervisorId),!0}var D=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new j;closed=!1;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),C/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??h.env)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e}={}){let t=await this.request(`acquire`,{resource:`managed-dev`,env:Y(e??h.env)});return this.leases.add(t.leaseId),t}async managedDevAction({action:e,requestId:t}){return this.request(`managed-dev-action`,{action:e,requestId:t})}async managedDevStatus(){return this.request(`managed-dev-status`)}async acquireVite(e,t=!1){let n=await this.request(`acquire`,{resource:e.resource,spec:e,fresh:t});return this.leases.add(n.leaseId),n}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async stopVite(e){return this.request(`stop`,{resource:e})}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let r=n();return new Promise((n,i)=>{this.pending.set(r,{resolve:n,reject:i}),this.socket.write(M({id:r,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)await this.request(`renew`,{leaseId:e}).catch(()=>{this.leases.delete(e)})}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(ae(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let e of this.closeListeners)e();this.closeListeners.clear()}}};async function O({cwd:e=h.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=m.resolve(e,v);await i(a,{recursive:!0,mode:448}),await i(m.join(a,b),{recursive:!0,mode:448});let o=await F(e);if(o&&o.pid!==h.pid&&Z(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=R(e);h.platform!==`win32`&&await l(s).catch(()=>void 0);let c=new k({cwd:m.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r});await c.listen();let u=()=>{c.shutdown()};h.once(`SIGINT`,u),h.once(`SIGTERM`,u);try{await c.waitForShutdown()}finally{h.off(`SIGINT`,u),h.off(`SIGTERM`,u)}}var k=class{clients=new Set;leases=new Map;resourceOperations=new Map;resources=new Map;logEntries=[];server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:r,startPostgres:i,startSqlite:a,startManagedDev:o}){this.root=r,this.startPostgres=i,this.startSqlite=a,this.startManagedDev=o,this.state={cwd:e,endpoint:t,pid:h.pid,protocol:1,supervisorId:n(),token:n()},this.server=f(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await I(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear();for(let e of this.resources.keys())await this.stopVite(e);await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await l(this.state.endpoint).catch(()=>void 0),await l(m.join(this.root,y)).catch(()=>void 0),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new A(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(n.event===`log`&&n.resource!==`postgres`&&n.resource!==`sqlite`)for(this.logEntries.push(n);this.logEntries.length>2e3;)this.logEntries.shift();if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){e.subscribe(t);let r=this.logEntries.filter(e=>(e.resource===`postgres`||e.resource===`sqlite`)&&t.includes(e.resource));for(let t of r)e.publish(t);return e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:n()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,z(n.resources));case`acquire`:return this.withResourceOperation(B(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`stop`:{let e=V(n.resource);return this.withResourceOperation(e,async()=>{let t=await this.stopVite(e,!0);return this.maybeScheduleIdleShutdown(),t})}case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0,resources:[...this.resources.entries()].map(([e,t])=>({endpoint:t.spec.endpoint,leases:t.leases.size,resource:e,state:`running`}))}}async acquire(e,t){let n=B(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,G(t));if(n===`postgres`)return this.acquirePostgres(e,G(t));if(n===`sqlite`)return this.acquireSqlite(e,G(t));let r=H(t.spec);if(r.resource!==n)throw Q(`INVALID_REQUEST`,`The Vite resource does not match its specification.`,!1);let i=this.resources.get(n);if(i&&q(t.fresh)!==`true`){if(i.spec.configFingerprint!==r.configFingerprint||r.endpoint.port!==void 0&&i.spec.endpoint.port!==r.endpoint.port)throw Q(`CONFIG_MISMATCH`,`A ${n} Vite server already exists with different settings.`,!1,{existing:{configFingerprint:i.spec.configFingerprint,endpoint:i.spec.endpoint},requested:{configFingerprint:r.configFingerprint,endpoint:r.endpoint}});let t=this.createLease(e,n);i.leases.add(t.id);for(let t of i.startupLinks)e.publish(t);return{endpoint:i.spec.endpoint,leaseId:t.id,state:`reused`}}if(i){if(i.leases.size>0)throw Q(`RESOURCE_BUSY`,`Cannot replace active ${n} development.`,!0);await this.stopVite(n)}if(r.endpoint.port===void 0)throw Q(`INVALID_REQUEST`,`A ${n} Vite server requires a port when it is started.`,!1);let a={...r,endpoint:{...r.endpoint,port:r.endpoint.port}},o={children:[],leases:new Set,startupLinks:[],spec:a};this.resources.set(n,o),this.publish({event:`service`,resource:n,state:`starting`,endpoint:a.endpoint});try{for(let e of r.processes){let t=this.spawnProcess(n,e);o.children.push(t)}let t=this.createLease(e,n);return o.leases.add(t.id),this.publish({event:`service`,resource:n,state:`running`,endpoint:a.endpoint,pid:o.children[0]?.pid??void 0}),{endpoint:a.endpoint,leaseId:t.id,state:`started`}}catch(e){throw await this.stopVite(n),e}}async acquireManagedDev(e,t){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.managedDev){this.cancelManagedDevStop();let t=this.createLease(e,`managed-dev`);return this.managedDev.leases.add(t.id),{leaseId:t.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=J(t.env),a=await this.startManagedDev({cwd:this.state.cwd,env:Y(r),onFlutterRestart:async()=>{let e=m.resolve(this.state.cwd,`.coreframe`,`managed-dev-flutter-restart`);await i(m.dirname(e),{recursive:!0}),await u(e,`${n()}\n`,{mode:384})},onRestart:()=>{this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),o={leases:new Set,session:a};this.managedDev=o;try{await a.activate()}catch(e){throw this.managedDev=void 0,await a.close(),e}let s=this.createLease(e,`managed-dev`);return o.leases.add(s.id),{leaseId:s.id,state:`started`,status:a.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=q(t.requestId);if(!n)throw Q(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{return await this.managedDev.session.action(t.action,{onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let r={connection:e,expiresAt:Date.now()+C,id:n(),resource:t};return this.leases.set(r.id,r),r}renewLease(e){let t=this.leases.get(e);if(!t)throw Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+C,{expiresAt:t.expiresAt}}expireLeases(){for(let e of this.leases.values())e.expiresAt<=Date.now()&&this.releaseLease(e.id)}async releaseLease(e){let t=this.leases.get(e);if(t){if(this.leases.delete(e),t.resource===`postgres`)this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop();else if(t.resource===`sqlite`)this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop();else if(t.resource===`managed-dev`)this.managedDev?.leases.delete(e),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop();else{let n=this.resources.get(t.resource);n?.leases.delete(e),n?.leases.size===0&&await this.stopVite(t.resource)}this.maybeScheduleIdleShutdown()}}spawnProcess(t,n){let r=e(n.command,n.args,{cwd:n.cwd,env:Y(n.env),stdio:[`ignore`,`pipe`,`pipe`]}),i=(e,n)=>{let r=this.publish({event:`log`,resource:t,stream:e,data:String(n)});if(r.event!==`log`)return;let i=K(r.data);i&&this.resources.get(t)?.startupLinks.push({...r,data:i})};return r.stdout.on(`data`,e=>i(`stdout`,e)),r.stderr.on(`data`,e=>i(`stderr`,e)),r.on(`error`,e=>{this.publish({event:`service`,resource:t,state:`failed`,error:e.message})}),r.on(`exit`,(e,n)=>{this.resources.has(t)&&(this.publish({event:`service`,resource:t,state:e===0||n?`stopped`:`failed`,error:e&&!n?`Process exited with code ${e}.`:void 0}),this.stopVite(t))}),r}async stopVite(e,t=!1){let n=this.resources.get(e);if(!n)return!1;if(this.resources.delete(e),t){for(let e of n.leases)this.leases.delete(e);n.leases.clear()}return await Promise.all(n.children.map(e=>_(e,`SIGTERM`))),await Promise.all(n.children.map(e=>new Promise(t=>{if(e.exitCode!==null){t();return}e.once(`exit`,()=>t()),setTimeout(()=>{_(e,`SIGKILL`).then(t,t)},5e3).unref()}))),this.publish({event:`service`,resource:e,state:`stopped`}),!0}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.managedDev=void 0,await e.session.close()}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=m.join(this.root,b,`${e.replaceAll(`:`,`-`)}.log`);await i(m.dirname(t),{recursive:!0,mode:448}),await u(t,``);let n=0;return new g({write:(i,a,o)=>{let s=String(i),c=Buffer.from(s),l=c.subarray(Math.max(0,c.length-x)),d=n+l.length>x;(d?u(t,l):r(t,l)).then(()=>{n=d?l.length:n+l.length,o()},o),this.publish({event:`log`,resource:e,stream:`stdout`,data:s})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.resources.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&this.resources.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},A=class{authenticated=!1;decoder=new j;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(M({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=M({event:e,type:`event`});if(t.length>S){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=M({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>S;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=S){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},j=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function M(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function N(e){let t=await new Promise((t,n)=>{let r=d(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return D.create({...e,socket:t})}async function ne({cwd:t,env:n,entry:r}){e(h.execPath,[r,`--cwd`,t],{cwd:t,detached:!0,env:{...n,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function re(e){let t=m.join(e,v),n=m.join(t,`start.lock`),r=Date.now()+1e4;for(await i(t,{recursive:!0,mode:448});Date.now()<r;)try{return await u(n,`${h.pid}\n`,{flag:`wx`,mode:384}),async()=>{await l(n).catch(()=>void 0)}}catch(t){if(!(t instanceof Error&&t.code===`EEXIST`))throw t;let r=await F(e);if(r&&Z(r.pid))return;try{let e=await c(n);if(Date.now()-e.mtimeMs>1e4){await l(n).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function P(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await F(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function ie(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await F(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function F(e){try{let t=JSON.parse(await a(m.join(e,v,y),`utf8`));return t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||typeof t.token!=`string`?void 0:t}catch{return}}async function I(e,t){let r=m.join(t,y),a=`${r}.${n()}.tmp`;await i(m.dirname(r),{recursive:!0,mode:448});try{await u(a,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await o(a,r)}finally{await l(a).catch(()=>void 0)}}async function L(e,t){t&&t.cwd!==m.resolve(e)||(await s(m.join(e,v,y),{force:!0}),t&&h.platform!==`win32`&&await l(t.endpoint).catch(()=>void 0))}function R(e){if(h.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24)}`;let n=t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24);return m.join(p(),`coreframe-dev-${n}-supervisor.sock`)}function z(e){return Array.isArray(e)?e.map(B):[`managed-dev`,`postgres`,`sqlite`,`vite:web`,`vite:flutter:android`,`vite:flutter:ios`,`vite:flutter:linux`,`vite:flutter:macos`,`vite:flutter:windows`]}function B(e){if(e===`managed-dev`||e===`postgres`||e===`sqlite`||U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function V(e){if(U(e))return e;throw Q(`INVALID_REQUEST`,`Unknown Vite resource: ${String(e)}.`,!1)}function H(e){if(!e||typeof e!=`object`)throw Q(`INVALID_REQUEST`,`A Vite specification is required.`,!1);let t=e;if(!U(t.resource)||typeof t.configFingerprint!=`string`||!t.endpoint||typeof t.endpoint.host!=`string`||t.endpoint.port!==void 0&&(!Number.isSafeInteger(t.endpoint.port)||t.endpoint.port<=0||t.endpoint.port>65535)||!Array.isArray(t.processes)||!t.processes.every(W))throw Q(`INVALID_REQUEST`,`The Vite specification is invalid.`,!1);return t}function U(e){return e===`vite:web`||typeof e==`string`&&/^vite:flutter:(android|ios|linux|macos|windows)$/u.test(e)}function W(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.command==`string`&&typeof t.cwd==`string`&&Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`)&&!!t.env&&typeof t.env==`object`&&Object.values(t.env).every(e=>e===void 0||typeof e==`string`)}function G(e){return e&&typeof e==`object`?e:{}}function K(e){return e.split(/(?<=\n)/).filter(e=>ee.test(e.replace(w,``))).join(``)}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=G(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return h.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function ae(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{D as DevSupervisorClient,te as connectDevSupervisor,T as connectExistingDevSupervisor,O as runDevSupervisorProcess,E as stopDevSupervisor};
|
|
1
|
+
import{spawn as e}from"node:child_process";import{createHash as t,randomUUID as n}from"node:crypto";import{appendFile as r,mkdir as i,readFile as a,rename as o,rm as s,stat as c,unlink as l,writeFile as u}from"node:fs/promises";import{createConnection as d,createServer as f}from"node:net";import{tmpdir as p}from"node:os";import m from"node:path";import h from"node:process";import{Writable as g}from"node:stream";const _=`.coreframe/dev-supervisor`,v=`supervisor.json`,y=`logs`,b=1*1024*1024,x=4*1024*1024,S=45e3;async function C({cwd:e=h.cwd(),env:t=h.env,supervisorEntry:n}={}){let r=await w({cwd:e,env:t});if(r)return r;let i=await L(e),a=await P(e);if(!a)return i=await F(e),M({cwd:e,env:t,state:i});try{if(i=await L(e),i&&i.cwd===m.resolve(e)&&J(i.pid))return await M({cwd:e,env:t,state:i});if(i&&await z(e,i),!n)throw Error(`A development supervisor process entry is required to start the supervisor.`);return await N({cwd:e,env:t,entry:n}),i=await F(e),M({cwd:e,env:t,state:i})}finally{await a()}}async function w({cwd:e=h.cwd(),env:t=h.env}={}){let n=await L(e);if(!(!n||n.cwd!==m.resolve(e)||!J(n.pid)))try{return await M({cwd:e,env:t,state:n})}catch{await z(e,n);return}}async function T({cwd:e=h.cwd()}={}){let t=await L(e);if(!t||t.cwd!==m.resolve(e)||!J(t.pid))return await z(e,t),!1;let n=await M({cwd:e,env:h.env,state:t});try{await n.shutdown()}finally{n.close()}return await I(e,t.supervisorId),!0}var E=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new A;closed=!1;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),S/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:K(t??h.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:K(t??h.env)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e}={}){let t=await this.request(`acquire`,{resource:`managed-dev`,env:K(e??h.env)});return this.leases.add(t.leaseId),t}async managedDevAction({action:e,requestId:t}){return this.request(`managed-dev-action`,{action:e,requestId:t})}async managedDevStatus(){return this.request(`managed-dev-status`)}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let r=n();return new Promise((n,i)=>{this.pending.set(r,{resolve:n,reject:i}),this.socket.write(j({id:r,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)await this.request(`renew`,{leaseId:e}).catch(()=>{this.leases.delete(e)})}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(Z(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let e of this.closeListeners)e();this.closeListeners.clear()}}};async function D({cwd:e=h.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=m.resolve(e,_);await i(a,{recursive:!0,mode:448}),await i(m.join(a,y),{recursive:!0,mode:448});let o=await L(e);if(o&&o.pid!==h.pid&&J(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=B(e);h.platform!==`win32`&&await l(s).catch(()=>void 0);let c=new O({cwd:m.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r});await c.listen();let u=()=>{c.shutdown()};h.once(`SIGINT`,u),h.once(`SIGTERM`,u);try{await c.waitForShutdown()}finally{h.off(`SIGINT`,u),h.off(`SIGTERM`,u)}}var O=class{clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:r,startPostgres:i,startSqlite:a,startManagedDev:o}){this.root=r,this.startPostgres=i,this.startSqlite=a,this.startManagedDev=o,this.state={cwd:e,endpoint:t,pid:h.pid,protocol:1,supervisorId:n(),token:n()},this.server=f(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await R(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear(),await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await l(this.state.endpoint).catch(()=>void 0),await l(m.join(this.root,v)).catch(()=>void 0),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new k(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:X(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){return e.subscribe(t),e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:n()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Y(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,V(n.resources));case`acquire`:return this.withResourceOperation(H(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(W(n.leaseId));return;case`renew`:return this.renewLease(W(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;default:throw Y(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Y(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0}}async acquire(e,t){let n=H(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,U(t));if(n===`postgres`)return this.acquirePostgres(e,U(t));if(n===`sqlite`)return this.acquireSqlite(e,U(t));throw Y(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireManagedDev(e,t){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.managedDev){this.cancelManagedDevStop();let t=this.createLease(e,`managed-dev`);return this.managedDev.leases.add(t.id),{leaseId:t.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=G(t.env),a=await this.startManagedDev({cwd:this.state.cwd,env:K(r),onFlutterRestart:async()=>{let e=m.resolve(this.state.cwd,`.coreframe`,`managed-dev-flutter-restart`);await i(m.dirname(e),{recursive:!0}),await u(e,`${n()}\n`,{mode:384})},onRestart:()=>{this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),o={leases:new Set,session:a};this.managedDev=o;try{await a.activate()}catch(e){throw this.managedDev=void 0,await a.close(),e}let s=this.createLease(e,`managed-dev`);return o.leases.add(s.id),{leaseId:s.id,state:`started`,status:a.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=W(t.requestId);if(!n)throw Y(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{return await this.managedDev.session.action(t.action,{onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=G(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:K(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:q(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:K(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=G(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:K(n),tursoOutput:e});this.sqlite={env:q(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:K(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let r={connection:e,expiresAt:Date.now()+S,id:n(),resource:t};return this.leases.set(r.id,r),r}renewLease(e){let t=this.leases.get(e);if(!t)throw Y(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+S,{expiresAt:t.expiresAt}}expireLeases(){for(let e of this.leases.values())e.expiresAt<=Date.now()&&this.releaseLease(e.id)}async releaseLease(e){let t=this.leases.get(e);t&&(this.leases.delete(e),t.resource===`postgres`?(this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop()):t.resource===`sqlite`?(this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop()):t.resource===`managed-dev`&&(this.managedDev?.leases.delete(e),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop()),this.maybeScheduleIdleShutdown())}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.managedDev=void 0,await e.session.close()}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=m.join(this.root,y,`${e.replaceAll(`:`,`-`)}.log`);await i(m.dirname(t),{recursive:!0,mode:448}),await u(t,``);let n=0;return new g({write:(i,a,o)=>{let s=String(i),c=Buffer.from(s),l=c.subarray(Math.max(0,c.length-b)),d=n+l.length>b;(d?u(t,l):r(t,l)).then(()=>{n=d?l.length:n+l.length,o()},o),this.publish({event:`log`,resource:e,stream:`stdout`,data:s})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},k=class{authenticated=!1;decoder=new A;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:X(Y(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(j({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=j({event:e,type:`event`});if(t.length>x){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=j({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>x;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=x){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},A=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function j(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function M(e){let t=await new Promise((t,n)=>{let r=d(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return E.create({...e,socket:t})}async function N({cwd:t,env:n,entry:r}){e(h.execPath,[r,`--cwd`,t],{cwd:t,detached:!0,env:{...n,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function P(e){let t=m.join(e,_),n=m.join(t,`start.lock`),r=Date.now()+1e4;for(await i(t,{recursive:!0,mode:448});Date.now()<r;)try{return await u(n,`${h.pid}\n`,{flag:`wx`,mode:384}),async()=>{await l(n).catch(()=>void 0)}}catch(t){if(!(t instanceof Error&&t.code===`EEXIST`))throw t;let r=await L(e);if(r&&J(r.pid))return;try{let e=await c(n);if(Date.now()-e.mtimeMs>1e4){await l(n).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function F(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await L(e);if(t&&J(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function I(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await L(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function L(e){try{let t=JSON.parse(await a(m.join(e,_,v),`utf8`));return t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||typeof t.token!=`string`?void 0:t}catch{return}}async function R(e,t){let r=m.join(t,v),a=`${r}.${n()}.tmp`;await i(m.dirname(r),{recursive:!0,mode:448});try{await u(a,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await o(a,r)}finally{await l(a).catch(()=>void 0)}}async function z(e,t){t&&t.cwd!==m.resolve(e)||(await s(m.join(e,_,v),{force:!0}),t&&h.platform!==`win32`&&await l(t.endpoint).catch(()=>void 0))}function B(e){if(h.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24)}`;let n=t(`sha256`).update(m.resolve(e)).digest(`hex`).slice(0,24);return m.join(p(),`coreframe-dev-${n}-supervisor.sock`)}function V(e){return Array.isArray(e)?e.map(H):[`managed-dev`,`postgres`,`sqlite`]}function H(e){if(e===`managed-dev`||e===`postgres`||e===`sqlite`)return e;throw Y(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function U(e){return e&&typeof e==`object`?e:{}}function W(e){return typeof e==`string`?e:String(e??``)}function G(e){let t=U(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function K(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function q(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function J(e){try{return h.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Y(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function X(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function Z(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{E as DevSupervisorClient,C as connectDevSupervisor,w as connectExistingDevSupervisor,D as runDevSupervisorProcess,T as stopDevSupervisor};
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/dev-supervisor",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"description": "Process supervision utilities for Coreframe development workflows",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/
|
|
7
|
+
"url": "git+https://github.com/coreframe-js/coreframe.git",
|
|
8
8
|
"directory": "node/dev-supervisor"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
@@ -18,8 +18,7 @@
|
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@
|
|
22
|
-
"@coreframe/config": "^0.1.9"
|
|
21
|
+
"@coreframe/config": "^0.1.10"
|
|
23
22
|
},
|
|
24
23
|
"devDependencies": {
|
|
25
24
|
"@types/node": "^26.1.0",
|