@shotkit/shotium 0.1.0 → 0.3.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"daemon_main.js","names":[],"sources":["../src/lib/daemon.ts","../src/daemon_main.ts"],"sourcesContent":["import {EventEmitter} from 'node:events';\nimport fs from 'node:fs';\nimport net from 'node:net';\n\nimport type {DaemonOptions, DaemonStatus} from '../types.js';\n\nimport {resolveStartOptions} from './config.js';\nimport type {ResolvedStartOptions} from './config.js';\nimport {endpointFor} from './endpoint.js';\nimport {Pool} from './pool.js';\nimport {FrameReader, encodeFrame} from './protocol.js';\nimport type {WireRequest} from './request.js';\n\n// Our own version, for status(). Read rather than imported: an import\n// attribute would do it too, but only on a node new enough that this package\n// would not run on the rest. The URL is relative to the built module, which\n// sits one directory below the manifest.\nconst VERSION = (() => {\n try {\n const manifest =\n fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8');\n return (JSON.parse(manifest) as {version?: string}).version ?? '0.0.0';\n } catch {\n return '0.0.0';\n }\n})();\n\n// How much longer than the page's own deadline the daemon waits before it\n// decides a worker is not going to answer at all. Same margin, same reasoning\n// as index.ts: the worker fails a slow page by itself and replies.\nconst SUPERVISOR_MARGIN_MS = 10000;\nconst DEFAULT_TIMEOUT_MS = 30000;\nconst DEFAULT_IDLE_TIMEOUT_MS = 300000;\n\n// One message off the socket. `op` defaults to screenshot because that is what\n// almost every message is.\ninterface DaemonMessage {\n id?: number|null;\n op?: 'screenshot'|'status'|'ping'|'shutdown';\n request?: WireRequest;\n timeout?: number;\n retry?: number;\n}\n\ninterface DaemonReply {\n id: number|null;\n ok?: boolean;\n error?: string;\n bytes?: number;\n path?: string;\n stopping?: boolean;\n}\n\n// A worker pool that outlives the process that asked for it.\n//\n// The pool in index.ts is already resident, but only for as long as the Node\n// process holding it: a command-line invocation, a CI step, a serverless\n// handler and a `node -e` all pay for starting workers and then throw them\n// away. This is the same pool behind a socket, so the second caller -- in a\n// different process, minutes later -- pays a connect() and nothing else.\n//\n// The wire format is the worker's own, one level up: a request frame of JSON,\n// answered by a header frame and a payload frame. What it adds is `id`, so one\n// connection can have several requests in flight; the worker protocol cannot,\n// because a worker renders one document at a time, and multiplexing is exactly\n// what the pool in the middle is for.\n//\n// -> [len][{\"id\":7,\"op\":\"screenshot\",\"request\":{...}}]\n// <- [len][{\"id\":7,\"ok\":true,\"bytes\":97756}] [len][<PNG>]\n//\n// Events: ready, request, response, idle-exit, error, plus the pool's own.\nclass Daemon extends EventEmitter {\n private readonly options: ResolvedStartOptions;\n private readonly endpointPath: string;\n private readonly idleTimeoutMs: number;\n private readonly prewarmOnStart: boolean;\n private pool: Pool|null = null;\n private server: net.Server|null = null;\n private sockets = new Set<net.Socket>();\n private inFlight = 0;\n private served = 0;\n private warmed = false;\n private startedAt = Date.now();\n private idleTimer: NodeJS.Timeout|null = null;\n private closing = false;\n\n constructor(options: DaemonOptions = {}) {\n super();\n this.options = resolveStartOptions(options);\n this.endpointPath = endpointFor({\n ...this.options,\n name: options.name,\n endpoint: options.endpoint,\n });\n this.idleTimeoutMs = options.idleTimeoutMs === undefined ?\n DEFAULT_IDLE_TIMEOUT_MS :\n options.idleTimeoutMs;\n this.prewarmOnStart = options.prewarm !== false;\n }\n\n get endpoint(): string {\n return this.endpointPath;\n }\n\n get warm(): boolean {\n return this.warmed;\n }\n\n // Brings the pool up and starts listening. The pipe existing *is* the\n // readiness signal -- a client's connect() either succeeds or the daemon is\n // not up -- so nothing is bound until the pool has been asked to start.\n async listen(): Promise<this> {\n const pool = new Pool(this.options);\n this.pool = pool;\n for (const event of ['exit', 'crash', 'timeout', 'worker-restart',\n 'worker-error', 'stderr']) {\n pool.on(event, (payload) => this.emit(event, payload));\n }\n pool.start();\n\n this.server = net.createServer((socket) => this.accept(socket));\n this.server.on('error', (error) => this.emit('error', error));\n await this.bind();\n this.armIdleTimer();\n this.emit('ready',\n {endpoint: this.endpointPath, workers: this.options.workers});\n if (this.prewarmOnStart) {\n await this.prewarm();\n }\n return this;\n }\n\n private bind(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const server = this.server!;\n const onError = (error: NodeJS.ErrnoException) => {\n // A unix socket file outlives the process that made it, so EADDRINUSE\n // means either a live daemon or a leftover path. Connecting is the only\n // way to tell them apart: refused means nobody is home, and the file\n // can go.\n if (error.code === 'EADDRINUSE' && process.platform !== 'win32') {\n const probe = net.connect(this.endpointPath);\n probe.on('connect', () => {\n probe.destroy();\n reject(error);\n });\n probe.on('error', () => {\n try {\n fs.unlinkSync(this.endpointPath);\n } catch {\n reject(error);\n return;\n }\n server.listen(this.endpointPath, () => {\n this.restrict();\n resolve();\n });\n });\n return;\n }\n reject(error);\n };\n server.once('error', onError);\n server.listen(this.endpointPath, () => {\n server.removeListener('error', onError);\n this.restrict();\n resolve();\n });\n });\n }\n\n // Who may talk to this daemon.\n //\n // It matters because a request may set `allowFileAccess`, so a stranger who\n // can connect can have a document read this machine's filesystem and get the\n // result back as a picture. On POSIX the socket is a file and 0600 says only\n // its owner may connect.\n //\n // On Windows it is a named pipe, and node exposes no way to give one an ACL:\n // the default lets any account on the machine open it. A daemon on a shared\n // Windows host is therefore as trusted as the machine's users are -- render\n // in-process, or with a binary that has no file access, if that is not\n // acceptable.\n private restrict(): void {\n if (process.platform === 'win32') {\n return;\n }\n try {\n fs.chmodSync(this.endpointPath, 0o600);\n } catch (error) {\n this.emit('error', error);\n }\n }\n\n // Renders one throwaway document per worker so that the first real request\n // does not pay for whatever each process initialises lazily. The pool hands\n // one request to each free worker, and there are exactly as many requests as\n // workers, so every process is touched.\n //\n // `data:` rather than a file, because a daemon started without\n // --allow-file-access would otherwise be prewarmed by a request it refuses.\n async prewarm(): Promise<void> {\n const blank = 'data:text/html,<!doctype html><title>shotium</title>';\n await Promise.all(Array.from({length: this.options.workers}, () => {\n return this.pool!\n .submit({file: blank, width: 16, height: 16},\n {timeout: DEFAULT_TIMEOUT_MS + SUPERVISOR_MARGIN_MS, retry: 1})\n .catch(() => null);\n }));\n this.warmed = true;\n this.emit('warm', {workers: this.options.workers});\n }\n\n status(): DaemonStatus {\n return {\n ok: true,\n pid: process.pid,\n endpoint: this.endpointPath,\n binary: this.options.binary,\n workers: this.options.workers,\n cacheDir: this.options.cacheDir,\n args: this.options.args,\n warm: this.warmed,\n uptimeMs: Date.now() - this.startedAt,\n connections: this.sockets.size,\n inFlight: this.inFlight,\n served: this.served,\n idleTimeoutMs: this.idleTimeoutMs,\n version: VERSION,\n };\n }\n\n private accept(socket: net.Socket): void {\n socket.on('error', () => socket.destroy());\n this.sockets.add(socket);\n this.armIdleTimer();\n\n const reader = new FrameReader();\n socket.on('data', (chunk: Buffer) => {\n reader.push(chunk);\n for (;;) {\n const frame = reader.next();\n if (frame === null) {\n return;\n }\n this.dispatch(socket, frame);\n }\n });\n socket.on('close', () => {\n this.sockets.delete(socket);\n this.armIdleTimer();\n });\n }\n\n private dispatch(socket: net.Socket, frame: Buffer): void {\n let message: DaemonMessage;\n try {\n message = JSON.parse(frame.toString('utf8')) as DaemonMessage;\n } catch {\n this.reply(\n socket, {id: null, ok: false, error: 'shotium: request is not JSON'});\n return;\n }\n\n const id = message.id === undefined ? null : message.id;\n const op = message.op || 'screenshot';\n if (op === 'status') {\n this.reply(socket, {...this.status(), id});\n return;\n }\n if (op === 'ping') {\n this.reply(socket, {id, ok: true});\n return;\n }\n if (op === 'shutdown') {\n this.reply(socket, {id, ok: true, stopping: true});\n // After the reply is on the wire, not before: a client that asked for a\n // shutdown is entitled to hear that it happened.\n socket.end(() => void this.close());\n return;\n }\n if (op !== 'screenshot') {\n this.reply(socket, {id, ok: false, error: `shotium: unknown op \"${op}\"`});\n return;\n }\n\n const request = message.request || ({} as WireRequest);\n const timeout = (typeof message.timeout === 'number' ? message.timeout :\n DEFAULT_TIMEOUT_MS) +\n SUPERVISOR_MARGIN_MS;\n const retry = typeof message.retry === 'number' ? message.retry : 0;\n\n this.inFlight += 1;\n this.armIdleTimer();\n this.emit('request', {id, file: request.file});\n this.pool!.submit(request, {timeout, retry})\n .then((result) => {\n this.served += 1;\n this.reply(\n socket,\n {\n id,\n ok: true,\n bytes: result.image ? result.image.length : 0,\n path: result.header ? result.header.path : undefined,\n },\n result.image);\n })\n .catch((error: Error) => {\n this.reply(\n socket, {id, ok: false, error: String(error.message || error)});\n })\n .finally(() => {\n this.inFlight -= 1;\n this.emit('response', {id});\n this.armIdleTimer();\n });\n }\n\n private reply(\n socket: net.Socket, header: DaemonReply|(DaemonStatus&{id: number|null}),\n payload?: Buffer|null): void {\n if (socket.destroyed) {\n return;\n }\n socket.write(encodeFrame(Buffer.from(JSON.stringify(header), 'utf8')));\n socket.write(encodeFrame(payload || Buffer.alloc(0)));\n }\n\n // Idle is \"nobody connected and nothing rendering\". A client that holds its\n // socket open -- a long-lived service using connect() -- keeps the daemon\n // alive without having to poll it.\n private armIdleTimer(): void {\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n if (!this.idleTimeoutMs || this.closing) {\n return;\n }\n if (this.sockets.size > 0 || this.inFlight > 0) {\n return;\n }\n this.idleTimer = setTimeout(() => {\n this.emit('idle-exit', {idleTimeoutMs: this.idleTimeoutMs});\n void this.close();\n }, this.idleTimeoutMs);\n this.idleTimer.unref();\n }\n\n async close(): Promise<void> {\n if (this.closing) {\n return;\n }\n this.closing = true;\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n for (const socket of this.sockets) {\n socket.destroy();\n }\n this.sockets.clear();\n await new Promise<void>((resolve) => this.server!.close(() => resolve()));\n await this.pool!.stop();\n this.emit('close', {});\n }\n}\n\nexport {Daemon, DEFAULT_IDLE_TIMEOUT_MS};\n","// The entry point of a detached daemon process.\n//\n// The configuration arrives as one base64 argument rather than as flags,\n// because it contains paths that a Windows command line would otherwise quote\n// badly, and because the client and the daemon have to agree on it exactly:\n// the endpoint is a hash of these fields, so a value mangled in transit would\n// produce a daemon listening where nobody looks. See endpoint.ts.\n//\n// It is a build entry of its own, and not a chunk, because lib/client.ts\n// spawns it by path -- `node dist/daemon_main.js <base64 json>` -- and a name\n// the bundler chose would be a name that changes.\n\nimport {Daemon} from './lib/daemon.js';\nimport type {DaemonOptions} from './types.js';\n\nasync function main(): Promise<void> {\n const encoded = process.argv[2];\n if (!encoded) {\n process.stderr.write('shotium: daemon_main expects a base64 config\\n');\n process.exit(2);\n }\n const options = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8')) as\n DaemonOptions;\n const daemon = new Daemon(options);\n\n daemon.on('stderr', ({worker, line}: {worker: number, line: string}) => {\n process.stderr.write(`shotium worker ${worker}: ${line}\\n`);\n });\n for (const event of ['crash', 'timeout', 'worker-restart', 'worker-error',\n 'idle-exit']) {\n daemon.on(event, (payload: {error?: unknown}) => {\n // An Error does not survive JSON.stringify -- it comes out as {} -- and\n // its message is the whole point of logging a worker that would not\n // start.\n const detail = payload && payload.error ?\n {\n ...payload,\n error: String(\n (payload.error as Error).message ?? payload.error),\n } :\n payload;\n process.stderr.write(\n `shotium daemon ${event}: ${JSON.stringify(detail)}\\n`);\n });\n }\n // An 'error' with nobody listening is thrown by EventEmitter itself, which\n // would turn a socket that failed after binding -- something the daemon can\n // survive -- into a dead pool.\n daemon.on('error', (error: Error) => {\n process.stderr.write(\n `shotium daemon error: ${(error && error.message) || error}\\n`);\n });\n\n try {\n await daemon.listen();\n } catch (error) {\n // Losing the race to bind is the ordinary outcome when two clients start a\n // daemon at the same moment: the other one is up, this one is not needed,\n // and the client that spawned it will connect to the winner. Anything else\n // is a real failure and says so.\n if ((error as NodeJS.ErrnoException | null)?.code === 'EADDRINUSE') {\n process.exit(0);\n }\n process.stderr.write(`shotium: daemon failed to start: ${error}\\n`);\n process.exit(1);\n }\n\n const shutdown = () => {\n daemon.close().then(() => process.exit(0), () => process.exit(1));\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n daemon.on('close', () => process.exit(0));\n}\n\n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AC;CACD,KAAK,MAAM,SAAS;EAAC;EAAS;EAAW;EAAkB;EACtC;CAAW,GAC9B,OAAO,GAAG,QAAQ,YAA+B;EAI/C,MAAM,SAAS,WAAW,QAAQ,QAC9B;GACE,GAAG;GACH,OAAO,OACF,QAAQ,MAAgB,WAAW,QAAQ,KAAK;EACvD,IACA;EACJ,QAAQ,OAAO,MACX,kBAAkB,MAAM,IAAI,KAAK,UAAU,MAAM,EAAE,GAAG;CAC5D,CAAC;CAKH,OAAO,GAAG,UAAU,UAAiB;EACnC,QAAQ,OAAO,MACX,yBAA0B,SAAS,MAAM,WAAY,MAAM,GAAG;CACpE,CAAC;CAED,IAAI;EACF,MAAM,OAAO,OAAO;CACtB,SAAS,OAAO;EAKd,IAAK,OAAwC,SAAS,cACpD,QAAQ,KAAK,CAAC;EAEhB,QAAQ,OAAO,MAAM,oCAAoC,MAAM,GAAG;EAClE,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,iBAAiB;EACrB,OAAO,MAAM,CAAC,CAAC,WAAW,QAAQ,KAAK,CAAC,SAAS,QAAQ,KAAK,CAAC,CAAC;CAClE;CACA,QAAQ,GAAG,UAAU,QAAQ;CAC7B,QAAQ,GAAG,WAAW,QAAQ;CAC9B,OAAO,GAAG,eAAe,QAAQ,KAAK,CAAC,CAAC;AAC1C;AAEK,KAAK"}
1
+ {"version":3,"file":"daemon_main.js","names":[],"sources":["../src/lib/daemon.ts","../src/daemon_main.ts"],"sourcesContent":["import {EventEmitter} from 'node:events';\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport type {\n CaptureStats,\n DaemonOptions,\n DaemonStatus,\n} from '../types.js';\n\nimport {resolveStartOptions} from './config.js';\nimport type {ResolvedStartOptions} from './config.js';\nimport {endpointFor} from './endpoint.js';\nimport {Engine} from './engine.js';\nimport {FrameReader, encodeFrame} from './protocol.js';\nimport type {WireRequest} from './request.js';\n\n// Our own version, for status(). Read rather than imported: an import\n// attribute would do it too, but only on a node new enough that this package\n// would not run on the rest. The URL is relative to the built module, which\n// sits one directory below the manifest.\nconst VERSION = (() => {\n try {\n const manifest =\n fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8');\n return (JSON.parse(manifest) as {version?: string}).version ?? '0.0.0';\n } catch {\n return '0.0.0';\n }\n})();\n\nconst DEFAULT_IDLE_TIMEOUT_MS = 300000;\n\n// One message off the socket. `op` defaults to screenshot because that is what\n// almost every message is.\ninterface DaemonMessage {\n id?: number|null;\n op?: 'screenshot'|'status'|'ping'|'shutdown';\n request?: WireRequest;\n timeout?: number;\n retry?: number;\n}\n\ninterface DaemonReply {\n id: number|null;\n ok?: boolean;\n error?: string;\n bytes?: number;\n path?: string;\n stopping?: boolean;\n // What the capture cost, on the success header and on the failure one. The\n // client turns it back into the same CaptureStats the in-process engine\n // returns, so a program moving between the two changes an import and\n // nothing else.\n stats?: CaptureStats;\n}\n\n// An engine that outlives the process that asked for it.\n//\n// The engine in index.ts is already resident, but only for as long as the Node\n// process holding it: a command-line invocation, a CI step, a serverless\n// handler and a `node -e` all pay for starting Blink and then throw it away.\n// This is the same engine behind a socket, so the second caller -- in a\n// different process, minutes later -- pays a connect() and nothing else.\n//\n// A request frame of JSON, answered by a header frame and a payload frame:\n//\n// -> [len][{\"id\":7,\"op\":\"screenshot\",\"request\":{...}}]\n// <- [len][{\"id\":7,\"ok\":true,\"bytes\":97756}] [len][<PNG>]\n//\n// `id` is on the wire so that a client may have several requests outstanding\n// on one connection. That is a convenience for the client, not concurrency:\n// there is one renderer here, because Blink is a process-wide singleton, so\n// the requests queue and come back in the order the engine finished them.\n// Wanting two at once means wanting two daemons, addressed by `name`.\n//\n// Nothing supervises a capture. The pool this replaced could time a worker out\n// and kill it; an in-process engine has no such seam -- there is no way to\n// abandon a render without abandoning the process. A page's own deadline\n// (`pageGotoParams.timeout`) is what bounds it, and the engine answers slow\n// pages by itself. `timeout` and `retry` on the wire are accepted and ignored,\n// so that an older client still talks to this.\n//\n// Events: ready, warm, request, response, idle-exit, error, close.\nclass Daemon extends EventEmitter {\n private readonly options: ResolvedStartOptions;\n private readonly endpointPath: string;\n private readonly idleTimeoutMs: number;\n private readonly prewarmOnStart: boolean;\n private readonly engine = new Engine();\n private server: net.Server|null = null;\n private sockets = new Set<net.Socket>();\n private inFlight = 0;\n private served = 0;\n private warmed = false;\n private startedAt = Date.now();\n private idleTimer: NodeJS.Timeout|null = null;\n private closing = false;\n\n constructor(options: DaemonOptions = {}) {\n super();\n this.options = resolveStartOptions(options);\n this.endpointPath = endpointFor({\n ...this.options,\n name: options.name,\n endpoint: options.endpoint,\n });\n this.idleTimeoutMs = options.idleTimeoutMs === undefined ?\n DEFAULT_IDLE_TIMEOUT_MS :\n options.idleTimeoutMs;\n this.prewarmOnStart = options.prewarm !== false;\n }\n\n get endpoint(): string {\n return this.endpointPath;\n }\n\n get warm(): boolean {\n return this.warmed;\n }\n\n // Brings the engine up and starts listening. The pipe existing *is* the\n // readiness signal -- a client's connect() either succeeds or the daemon is\n // not up -- so nothing is bound until the engine has started.\n //\n // Starting it here rather than on the first request is deliberate: a machine\n // with no engine for its platform should fail while the caller is still\n // watching, not answer a connect() and then reject every request on it.\n async listen(): Promise<this> {\n this.engine.start(this.options);\n\n this.server = net.createServer((socket) => this.accept(socket));\n this.server.on('error', (error) => this.emit('error', error));\n await this.bind();\n this.armIdleTimer();\n this.emit('ready', {endpoint: this.endpointPath});\n if (this.prewarmOnStart) {\n await this.prewarm();\n }\n return this;\n }\n\n private bind(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const server = this.server!;\n const onError = (error: NodeJS.ErrnoException) => {\n // A unix socket file outlives the process that made it, so EADDRINUSE\n // means either a live daemon or a leftover path. Connecting is the only\n // way to tell them apart: refused means nobody is home, and the file\n // can go.\n if (error.code === 'EADDRINUSE' && process.platform !== 'win32') {\n const probe = net.connect(this.endpointPath);\n probe.on('connect', () => {\n probe.destroy();\n reject(error);\n });\n probe.on('error', () => {\n try {\n fs.unlinkSync(this.endpointPath);\n } catch {\n reject(error);\n return;\n }\n server.listen(this.endpointPath, () => {\n this.restrict();\n resolve();\n });\n });\n return;\n }\n reject(error);\n };\n server.once('error', onError);\n server.listen(this.endpointPath, () => {\n server.removeListener('error', onError);\n this.restrict();\n resolve();\n });\n });\n }\n\n // Who may talk to this daemon.\n //\n // It matters because a request may set `allowFileAccess`, so a stranger who\n // can connect can have a document read this machine's filesystem and get the\n // result back as a picture. On POSIX the socket is a file and 0600 says only\n // its owner may connect.\n //\n // On Windows it is a named pipe, and node exposes no way to give one an ACL:\n // the default lets any account on the machine open it. A daemon on a shared\n // Windows host is therefore as trusted as the machine's users are -- use the\n // engine in your own process, where nothing is listening, if that is not\n // acceptable.\n private restrict(): void {\n if (process.platform === 'win32') {\n return;\n }\n try {\n fs.chmodSync(this.endpointPath, 0o600);\n } catch (error) {\n this.emit('error', error);\n }\n }\n\n // Renders one throwaway document so that the first real request does not pay\n // for whatever the engine initialises lazily. One is enough: there is one\n // renderer, and it is the same one every request lands on.\n //\n // A temporary file, not a `data:` URL. This used to send\n // `data:text/html,...`, which the renderer rejects -- shot_capture.cc takes\n // file, http and https and nothing else -- so every prewarm failed into the\n // catch below and the step had never once done anything. The failure was\n // invisible because a prewarm that does not work looks exactly like one that\n // does, only slower on the first request.\n //\n // The document names no subresources, so it renders identically whether or\n // not this daemon allows file access -- which is what the `data:` URL was\n // reaching for. A top-level file: URL always loads; `allowFileAccess` gates\n // what the document may then pull in.\n async prewarm(): Promise<void> {\n const blank = path.join(\n os.tmpdir(), `shotium-prewarm-${process.pid}.html`);\n try {\n fs.writeFileSync(\n blank, '<!doctype html><title>shotium</title><p>shotium');\n await this.engine.capture({file: blank, width: 16, height: 16});\n this.warmed = true;\n } catch (error) {\n // Not fatal: a daemon that could not prewarm still serves. But it is not\n // warm, and status() should not claim it is.\n this.emit('error', error);\n } finally {\n fs.rmSync(blank, {force: true});\n }\n this.emit('warm', {warm: this.warmed});\n }\n\n status(): DaemonStatus {\n return {\n ok: true,\n pid: process.pid,\n endpoint: this.endpointPath,\n cacheDir: this.options.cacheDir,\n userAgent: this.options.userAgent,\n resourceDir: this.options.resourceDir,\n warm: this.warmed,\n uptimeMs: Date.now() - this.startedAt,\n connections: this.sockets.size,\n inFlight: this.inFlight,\n served: this.served,\n idleTimeoutMs: this.idleTimeoutMs,\n version: VERSION,\n };\n }\n\n private accept(socket: net.Socket): void {\n socket.on('error', () => socket.destroy());\n this.sockets.add(socket);\n this.armIdleTimer();\n\n const reader = new FrameReader();\n socket.on('data', (chunk: Buffer) => {\n reader.push(chunk);\n for (;;) {\n const frame = reader.next();\n if (frame === null) {\n return;\n }\n this.dispatch(socket, frame);\n }\n });\n socket.on('close', () => {\n this.sockets.delete(socket);\n this.armIdleTimer();\n });\n }\n\n private dispatch(socket: net.Socket, frame: Buffer): void {\n let message: DaemonMessage;\n try {\n message = JSON.parse(frame.toString('utf8')) as DaemonMessage;\n } catch {\n this.reply(\n socket, {id: null, ok: false, error: 'shotium: request is not JSON'});\n return;\n }\n\n const id = message.id === undefined ? null : message.id;\n const op = message.op || 'screenshot';\n if (op === 'status') {\n this.reply(socket, {...this.status(), id});\n return;\n }\n if (op === 'ping') {\n this.reply(socket, {id, ok: true});\n return;\n }\n if (op === 'shutdown') {\n this.reply(socket, {id, ok: true, stopping: true});\n // After the reply is on the wire, not before: a client that asked for a\n // shutdown is entitled to hear that it happened.\n socket.end(() => void this.close());\n return;\n }\n if (op !== 'screenshot') {\n this.reply(socket, {id, ok: false, error: `shotium: unknown op \"${op}\"`});\n return;\n }\n\n const request = message.request || ({} as WireRequest);\n\n this.inFlight += 1;\n this.armIdleTimer();\n this.emit('request', {id, file: request.file});\n this.engine.capture(request)\n .then(({image, stats}) => {\n this.served += 1;\n this.reply(\n socket,\n {\n id,\n ok: true,\n bytes: image ? image.length : 0,\n path: request.path,\n stats,\n },\n image);\n })\n .catch((error: Error&{stats?: CaptureStats}) => {\n // The counters go back with the failure, matching the in-process\n // engine: a capture that timed out after fetching forty subresources\n // has already said why, and the message alone has not.\n this.reply(socket, {\n id,\n ok: false,\n error: String(error.message || error),\n stats: error.stats,\n });\n })\n .finally(() => {\n this.inFlight -= 1;\n this.emit('response', {id});\n this.armIdleTimer();\n });\n }\n\n private reply(\n socket: net.Socket, header: DaemonReply|(DaemonStatus&{id: number|null}),\n payload?: Buffer|null): void {\n if (socket.destroyed) {\n return;\n }\n socket.write(encodeFrame(Buffer.from(JSON.stringify(header), 'utf8')));\n socket.write(encodeFrame(payload || Buffer.alloc(0)));\n }\n\n // Idle is \"nobody connected and nothing rendering\". A client that holds its\n // socket open -- a long-lived service using connect() -- keeps the daemon\n // alive without having to poll it.\n private armIdleTimer(): void {\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n if (!this.idleTimeoutMs || this.closing) {\n return;\n }\n if (this.sockets.size > 0 || this.inFlight > 0) {\n return;\n }\n this.idleTimer = setTimeout(() => {\n this.emit('idle-exit', {idleTimeoutMs: this.idleTimeoutMs});\n void this.close();\n }, this.idleTimeoutMs);\n this.idleTimer.unref();\n }\n\n async close(): Promise<void> {\n if (this.closing) {\n return;\n }\n this.closing = true;\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n for (const socket of this.sockets) {\n socket.destroy();\n }\n this.sockets.clear();\n await new Promise<void>((resolve) => this.server!.close(() => resolve()));\n // dispose() rather than stop(), and this is the one caller that should.\n // The daemon owns its process and is leaving it, so the real teardown is\n // available and worth taking: joining the engine thread unwinds the\n // network stack, which is what lets the disk cache write its index. A\n // daemon that merely stood the engine down would leave the index dirty and\n // make the next daemon rebuild it by scanning the directory.\n await this.engine.dispose();\n this.emit('close', {});\n }\n}\n\nexport {Daemon, DEFAULT_IDLE_TIMEOUT_MS};\n","// The entry point of a detached daemon process.\n//\n// The configuration arrives as one base64 argument rather than as flags,\n// because it contains paths that a Windows command line would otherwise quote\n// badly, and because the client and the daemon have to agree on it exactly:\n// the endpoint is a hash of these fields, so a value mangled in transit would\n// produce a daemon listening where nobody looks. See endpoint.ts.\n//\n// It is a build entry of its own, and not a chunk, because lib/client.ts\n// spawns it by path -- `node dist/daemon_main.js <base64 json>` -- and a name\n// the bundler chose would be a name that changes.\n\nimport {Daemon} from './lib/daemon.js';\nimport type {DaemonOptions} from './types.js';\n\nasync function main(): Promise<void> {\n const encoded = process.argv[2];\n if (!encoded) {\n process.stderr.write('shotium: daemon_main expects a base64 config\\n');\n process.exit(2);\n }\n const options = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8')) as\n DaemonOptions;\n const daemon = new Daemon(options);\n\n daemon.on('stderr', ({worker, line}: {worker: number, line: string}) => {\n process.stderr.write(`shotium worker ${worker}: ${line}\\n`);\n });\n for (const event of ['crash', 'timeout', 'worker-restart', 'worker-error',\n 'idle-exit']) {\n daemon.on(event, (payload: {error?: unknown}) => {\n // An Error does not survive JSON.stringify -- it comes out as {} -- and\n // its message is the whole point of logging a worker that would not\n // start.\n const detail = payload && payload.error ?\n {\n ...payload,\n error: String(\n (payload.error as Error).message ?? payload.error),\n } :\n payload;\n process.stderr.write(\n `shotium daemon ${event}: ${JSON.stringify(detail)}\\n`);\n });\n }\n // An 'error' with nobody listening is thrown by EventEmitter itself, which\n // would turn a socket that failed after binding -- something the daemon can\n // survive -- into a dead pool.\n daemon.on('error', (error: Error) => {\n process.stderr.write(\n `shotium daemon error: ${(error && error.message) || error}\\n`);\n });\n\n try {\n await daemon.listen();\n } catch (error) {\n // Losing the race to bind is the ordinary outcome when two clients start a\n // daemon at the same moment: the other one is up, this one is not needed,\n // and the client that spawned it will connect to the winner. Anything else\n // is a real failure and says so.\n if ((error as NodeJS.ErrnoException | null)?.code === 'EADDRINUSE') {\n process.exit(0);\n }\n process.stderr.write(`shotium: daemon failed to start: ${error}\\n`);\n process.exit(1);\n }\n\n const shutdown = () => {\n daemon.close().then(() => process.exit(0), () => process.exit(1));\n };\n process.on('SIGINT', shutdown);\n process.on('SIG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