@foxford/den 4.0.0 → 4.2.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.
package/serve/index.cjs CHANGED
@@ -6,8 +6,8 @@ var _chunkKQAB6C6Qcjs = require('../chunk-KQAB6C6Q.cjs');
6
6
 
7
7
 
8
8
 
9
- var _chunkQTWJTYZWcjs = require('../chunk-QTWJTYZW.cjs');
10
- require('../chunk-XOJ2VWX4.cjs');
9
+ var _chunkNOI7FSBXcjs = require('../chunk-NOI7FSBX.cjs');
10
+ require('../chunk-MWDNN7Q4.cjs');
11
11
  require('../chunk-6QV4L6R2.cjs');
12
12
 
13
13
 
@@ -17,11 +17,8 @@ var _chunkA6ZPAM6Zcjs = require('../chunk-A6ZPAM6Z.cjs');
17
17
 
18
18
 
19
19
 
20
- var _chunk2P5TAWRWcjs = require('../chunk-2P5TAWRW.cjs');
21
20
 
22
-
23
-
24
- var _chunkT5QVCXVBcjs = require('../chunk-T5QVCXVB.cjs');
21
+ var _chunkMH2WIOTQcjs = require('../chunk-MH2WIOTQ.cjs');
25
22
 
26
23
  // src/serve/index.ts
27
24
  var _fastify = require('fastify'); var _fastify2 = _interopRequireDefault(_fastify);
@@ -49,7 +46,7 @@ var MIME = {
49
46
  var HASHED_DIR = "assets/";
50
47
  function assetsPrefix(base) {
51
48
  const { pathname } = new URL(base, "http://assets.invalid");
52
- return pathname.endsWith("/") ? pathname : `${pathname}/`;
49
+ return pathname.endsWith("/") ? pathname : "".concat(pathname, "/");
53
50
  }
54
51
  function assetFile(dir, relative) {
55
52
  const file = _path2.default.normalize(_path2.default.join(dir, relative));
@@ -58,7 +55,7 @@ function assetFile(dir, relative) {
58
55
  function registerAssets(instance, source) {
59
56
  const dir = _path2.default.resolve(source.dir);
60
57
  const prefix = assetsPrefix(source.base);
61
- instance.get(`${prefix}*`, (request, reply) => {
58
+ instance.get("".concat(prefix, "*"), (request, reply) => {
62
59
  var _a;
63
60
  const relative = request.params["*"];
64
61
  const file = assetFile(dir, relative);
@@ -77,14 +74,14 @@ function registerAssets(instance, source) {
77
74
 
78
75
  var DEFAULT_SLOW_RENDER_MS = 1e3;
79
76
  function claim(app) {
80
- return _chunkQTWJTYZWcjs.normalizeRoutes.call(void 0, app.routes).map((route) => route.source);
77
+ return _chunkNOI7FSBXcjs.normalizeRoutes.call(void 0, app.routes).map((route) => route.source);
81
78
  }
82
79
  function matchClaim(app, pathname) {
83
80
  var _a, _b;
84
81
  if (claim(app).length === 0) {
85
82
  return {};
86
83
  }
87
- return (_b = (_a = _chunkQTWJTYZWcjs.matchRoute.call(void 0, app.routes, pathname)) == null ? void 0 : _a.params) != null ? _b : null;
84
+ return (_b = (_a = _chunkNOI7FSBXcjs.matchRoute.call(void 0, app.routes, pathname)) == null ? void 0 : _a.params) != null ? _b : null;
88
85
  }
89
86
  function requestContextOf(req, fromBody) {
90
87
  const headers = {};
@@ -98,8 +95,11 @@ function requestContextOf(req, fromBody) {
98
95
  }
99
96
  }
100
97
  const cookie = req.headers.cookie;
101
- const backendHeaders = _chunkT5QVCXVBcjs.__spreadValues.call(void 0, _chunkT5QVCXVBcjs.__spreadValues.call(void 0, {}, typeof cookie === "string" && cookie !== "" ? { cookie } : {}), fromBody);
102
- return { backendHeaders, cookies: _chunkQTWJTYZWcjs.parseCookieHeader.call(void 0, cookie), headers };
98
+ const backendHeaders = {
99
+ ...typeof cookie === "string" && cookie !== "" ? { cookie } : {},
100
+ ...fromBody
101
+ };
102
+ return { backendHeaders, cookies: _chunkNOI7FSBXcjs.parseCookieHeader.call(void 0, cookie), headers };
103
103
  }
104
104
  function backendHeadersOf(value) {
105
105
  if (value === void 0) {
@@ -123,43 +123,41 @@ var appPlugin = (instance, options) => {
123
123
  void reply.header("cache-control", "no-store");
124
124
  return claim(app);
125
125
  });
126
- function handleRender(req, reply, target, inputs, rawBackendHeaders) {
127
- return _chunkT5QVCXVBcjs.__async.call(void 0, this, null, function* () {
128
- if (typeof target !== "string" || !target.startsWith("/")) {
129
- return reply.code(400).send({ error: "\u043D\u0435 \u043F\u0435\u0440\u0435\u0434\u0430\u043D \u0438\u043B\u0438 \u043D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 url" });
130
- }
131
- if (inputs !== void 0 && (typeof inputs !== "object" || inputs === null || Array.isArray(inputs))) {
132
- return reply.code(400).send({ error: "inputs \u0434\u043E\u043B\u0436\u043D\u044B \u0431\u044B\u0442\u044C \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u043C \u043F\u043E \u043A\u043B\u044E\u0447\u0443 token.description" });
133
- }
134
- const backendHeaders = backendHeadersOf(rawBackendHeaders);
135
- if (backendHeaders === "invalid") {
136
- return reply.code(400).send({ error: "backendHeaders \u0434\u043E\u043B\u0436\u043D\u044B \u0431\u044B\u0442\u044C \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u043C \xAB\u0438\u043C\u044F \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430 \u2192 \u0441\u0442\u0440\u043E\u043A\u0430\xBB" });
137
- }
138
- const { pathname, search } = new URL(target, "http://localhost");
139
- const params = matchClaim(app, pathname);
140
- if (params === null) {
141
- serveLog.error(`\u043F\u0443\u0442\u044C \xAB${pathname}\xBB \u0432\u043D\u0435 \u0437\u0430\u044F\u0432\u043A\u0438 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F`);
142
- return reply.code(404).send({ error: `\u043F\u0443\u0442\u044C \xAB${pathname}\xBB \u0432\u043D\u0435 \u0437\u0430\u044F\u0432\u043A\u0438 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F` });
143
- }
144
- const startedAt = Date.now();
145
- try {
146
- const result = yield _chunkQTWJTYZWcjs.renderApp.call(void 0, app, {
147
- context: requestContextOf(req, backendHeaders),
148
- inputs,
149
- params,
150
- pathname,
151
- search
152
- });
153
- const elapsed = Date.now() - startedAt;
154
- if (elapsed >= slowRenderMs) {
155
- serveLog.warn(`\u043C\u0435\u0434\u043B\u0435\u043D\u043D\u044B\u0439 \u0440\u0435\u043D\u0434\u0435\u0440 \xAB${pathname}\xBB: ${String(elapsed)}\u043C\u0441`);
156
- }
157
- return result;
158
- } catch (error) {
159
- serveLog.error(`\u0440\u0435\u043D\u0434\u0435\u0440 \xAB${pathname}\xBB \u0443\u043F\u0430\u043B \u0437\u0430 ${String(Date.now() - startedAt)}\u043C\u0441`, error);
160
- return reply.send(error instanceof Error ? error : new Error(String(error)));
126
+ async function handleRender(req, reply, target, inputs, rawBackendHeaders) {
127
+ if (typeof target !== "string" || !target.startsWith("/")) {
128
+ return reply.code(400).send({ error: "\u043D\u0435 \u043F\u0435\u0440\u0435\u0434\u0430\u043D \u0438\u043B\u0438 \u043D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 url" });
129
+ }
130
+ if (inputs !== void 0 && (typeof inputs !== "object" || inputs === null || Array.isArray(inputs))) {
131
+ return reply.code(400).send({ error: "inputs \u0434\u043E\u043B\u0436\u043D\u044B \u0431\u044B\u0442\u044C \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u043C \u043F\u043E \u043A\u043B\u044E\u0447\u0443 token.description" });
132
+ }
133
+ const backendHeaders = backendHeadersOf(rawBackendHeaders);
134
+ if (backendHeaders === "invalid") {
135
+ return reply.code(400).send({ error: "backendHeaders \u0434\u043E\u043B\u0436\u043D\u044B \u0431\u044B\u0442\u044C \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u043C \xAB\u0438\u043C\u044F \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430 \u2192 \u0441\u0442\u0440\u043E\u043A\u0430\xBB" });
136
+ }
137
+ const { pathname, search } = new URL(target, "http://localhost");
138
+ const params = matchClaim(app, pathname);
139
+ if (params === null) {
140
+ serveLog.error("\u043F\u0443\u0442\u044C \xAB".concat(pathname, "\xBB \u0432\u043D\u0435 \u0437\u0430\u044F\u0432\u043A\u0438 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F"));
141
+ return reply.code(404).send({ error: "\u043F\u0443\u0442\u044C \xAB".concat(pathname, "\xBB \u0432\u043D\u0435 \u0437\u0430\u044F\u0432\u043A\u0438 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F") });
142
+ }
143
+ const startedAt = Date.now();
144
+ try {
145
+ const result = await _chunkNOI7FSBXcjs.renderApp.call(void 0, app, {
146
+ context: requestContextOf(req, backendHeaders),
147
+ inputs,
148
+ params,
149
+ pathname,
150
+ search
151
+ });
152
+ const elapsed = Date.now() - startedAt;
153
+ if (elapsed >= slowRenderMs) {
154
+ serveLog.warn("\u043C\u0435\u0434\u043B\u0435\u043D\u043D\u044B\u0439 \u0440\u0435\u043D\u0434\u0435\u0440 \xAB".concat(pathname, "\xBB: ").concat(String(elapsed), "\u043C\u0441"));
161
155
  }
162
- });
156
+ return result;
157
+ } catch (error) {
158
+ serveLog.error("\u0440\u0435\u043D\u0434\u0435\u0440 \xAB".concat(pathname, "\xBB \u0443\u043F\u0430\u043B \u0437\u0430 ").concat(String(Date.now() - startedAt), "\u043C\u0441"), error);
159
+ return reply.send(error instanceof Error ? error : new Error(String(error)));
160
+ }
163
161
  }
164
162
  instance.get(
165
163
  "/_render",
@@ -177,76 +175,264 @@ var appPlugin = (instance, options) => {
177
175
  return Promise.resolve();
178
176
  };
179
177
 
180
- // src/serve/index.ts
181
- var SHUTDOWN_SIGNALS = ["SIGTERM", "SIGINT"];
182
- function serveApp(_0) {
183
- return _chunkT5QVCXVBcjs.__async.call(void 0, this, arguments, function* (app, options = {}) {
184
- var _a, _b, _c, _d, _e;
185
- const appLog = (_a = _logger.log.getLogger(app.name)) != null ? _a : _chunkA6ZPAM6Zcjs.logger;
186
- const serveLog = (_b = appLog.getLogger("serve")) != null ? _b : appLog;
187
- const instance = _fastify2.default.call(void 0, { logger: false });
188
- const metrics = _chunk2P5TAWRWcjs.getProcessMetrics.call(void 0, );
189
- metrics.startRuntime(app.name);
190
- let ops;
191
- const shutdown = () => {
192
- void instance.close();
193
- };
194
- instance.addHook("onRequest", (req, reply, done) => {
195
- if (_chunk2P5TAWRWcjs.isOpsPath.call(void 0, req.url)) {
196
- void reply.code(404).send();
197
- return;
178
+ // src/serve/process.ts
179
+ var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_cluster);
180
+
181
+
182
+ // src/serve/worker.ts
183
+
184
+ var ALIVE = "den:app-worker-alive";
185
+ var SIGNALS = ["SIGTERM", "SIGINT"];
186
+ var SHUTDOWN_MS = 1e4;
187
+ async function startWorker(appName, start) {
188
+ const aggregation = _chunkMH2WIOTQcjs.clusterMetrics.call(void 0, );
189
+ const logger2 = _logger.log.getLogger(appName).getLogger("cluster");
190
+ let timer;
191
+ let closing;
192
+ const starting = start();
193
+ const close = () => {
194
+ closing != null ? closing : closing = (async () => {
195
+ clearInterval(timer);
196
+ try {
197
+ const instance = await starting;
198
+ await instance.close();
199
+ } finally {
200
+ try {
201
+ if (process.connected) await aggregation.shutdown();
202
+ } finally {
203
+ for (const signal of SIGNALS) process.removeListener(signal, shutdown);
204
+ process.removeListener("disconnect", shutdown);
205
+ if (process.connected) process.disconnect();
206
+ }
198
207
  }
199
- metrics.trackHttp(req.raw, reply.raw, () => {
200
- var _a2;
201
- return (_a2 = req.routeOptions.url) != null ? _a2 : "unmatched";
202
- });
203
- done();
208
+ })();
209
+ return closing;
210
+ };
211
+ const shutdown = () => {
212
+ const deadline = setTimeout(() => process.exit(1), SHUTDOWN_MS);
213
+ deadline.unref();
214
+ void close().then(() => process.exit(0)).catch((error) => {
215
+ logger2.error("\u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u0432\u043E\u0440\u043A\u0435\u0440\u0430 \u043D\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B\u0430\u0441\u044C:", error);
216
+ process.exit(1);
204
217
  });
205
- instance.addHook("onClose", () => _chunkT5QVCXVBcjs.__async.call(void 0, null, null, function* () {
206
- for (const signal of SHUTDOWN_SIGNALS) {
207
- process.removeListener(signal, shutdown);
208
- }
209
- if (ops) {
210
- yield _chunk2P5TAWRWcjs.closeHttpServer.call(void 0, ops);
211
- }
212
- }));
213
- yield instance.register(appPlugin, { app, slowRenderMs: options.slowRenderMs });
214
- if (options.assets) {
215
- registerAssets(instance, options.assets);
216
- }
217
- instance.addHook("onRequest", (req, _reply, done) => {
218
- serveLog.debug(`\u2192 ${req.method} ${req.url}`);
219
- done();
218
+ };
219
+ for (const signal of SIGNALS) process.on(signal, shutdown);
220
+ process.once("disconnect", shutdown);
221
+ try {
222
+ await starting;
223
+ if (!closing) {
224
+ const notify = () => {
225
+ var _a;
226
+ if (process.connected) (_a = process.send) == null ? void 0 : _a.call(process, { type: ALIVE });
227
+ };
228
+ timer = setInterval(notify, 2e3);
229
+ timer.unref();
230
+ notify();
231
+ }
232
+ } catch (error) {
233
+ await close().catch(() => void 0);
234
+ throw error;
235
+ }
236
+ return { close };
237
+ }
238
+
239
+ // src/serve/process.ts
240
+ var STARTUP_MS = 6e4;
241
+ async function startAppProcess(appName, options, start) {
242
+ var _a;
243
+ const workers = (_a = options.workers) != null ? _a : 1;
244
+ if (!Number.isSafeInteger(workers) || workers < 1) {
245
+ throw new Error("WORKERS must be a positive integer");
246
+ }
247
+ if (workers === 1) {
248
+ const instance = await start(options);
249
+ return { close: () => instance.close() };
250
+ }
251
+ const metrics = _chunkMH2WIOTQcjs.getProcessMetrics.call(void 0, );
252
+ metrics.startRuntime(appName);
253
+ if (_cluster2.default.isWorker) {
254
+ return startWorker(appName, () => start({ ...options, gracefulShutdown: false, ops: false }));
255
+ }
256
+ return startPrimary(appName, options, workers);
257
+ }
258
+ async function startPrimary(appName, options, workers) {
259
+ const aggregation = _chunkMH2WIOTQcjs.clusterMetrics.call(void 0, );
260
+ const logger2 = _logger.log.getLogger(appName).getLogger("cluster");
261
+ const children = /* @__PURE__ */ new Set();
262
+ const alive = /* @__PURE__ */ new Map();
263
+ let ops;
264
+ let closing;
265
+ let started = false;
266
+ let resolveReady = () => void 0;
267
+ let rejectReady = () => void 0;
268
+ const ready = new Promise((resolve, reject) => {
269
+ resolveReady = resolve;
270
+ rejectReady = reject;
271
+ });
272
+ void ready.catch(() => void 0);
273
+ const timeout = setTimeout(() => rejectReady(new Error("Den workers startup timeout")), STARTUP_MS);
274
+ const onMessage = (worker, message) => {
275
+ if (children.has(worker) && typeof message === "object" && message !== null && "type" in message && message.type === ALIVE) {
276
+ alive.set(worker.id, Date.now());
277
+ if (alive.size === workers) resolveReady();
278
+ }
279
+ };
280
+ const close = () => {
281
+ closing != null ? closing : closing = (async () => {
282
+ clearTimeout(timeout);
283
+ resolveReady();
284
+ _cluster2.default.removeListener("message", onMessage);
285
+ await Promise.all([...children].map(stopWorker));
286
+ if (ops) await _chunkMH2WIOTQcjs.closeHttpServer.call(void 0, ops);
287
+ await aggregation.shutdown();
288
+ for (const signal of SIGNALS) process.removeListener(signal, shutdown);
289
+ })();
290
+ return closing;
291
+ };
292
+ const shutdown = () => {
293
+ void close().then(() => process.exit()).catch((error) => {
294
+ logger2.error("\u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 \u043D\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B\u0430\u0441\u044C:", error);
295
+ process.exit(1);
220
296
  });
221
- instance.addHook("onResponse", (req, reply, done) => {
222
- const elapsed = reply.elapsedTime.toFixed(1);
223
- serveLog.info(`\u2190 ${String(reply.statusCode)} ${req.method} ${req.url} ${elapsed}\u043C\u0441`);
224
- done();
297
+ };
298
+ const failed = (error) => {
299
+ if (closing) return;
300
+ if (!started) {
301
+ rejectReady(error);
302
+ } else {
303
+ logger2.error(error);
304
+ process.exitCode = 1;
305
+ shutdown();
306
+ }
307
+ };
308
+ _cluster2.default.on("message", onMessage);
309
+ if (options.gracefulShutdown !== false) {
310
+ for (const signal of SIGNALS) process.on(signal, shutdown);
311
+ }
312
+ try {
313
+ if (options.ops !== false) {
314
+ const supplied = options.ops;
315
+ ops = await _chunkMH2WIOTQcjs.startOpsServer.call(void 0, {
316
+ ...supplied,
317
+ collect: aggregation.collect,
318
+ contentType: aggregation.contentType,
319
+ isLive: () => {
320
+ var _a;
321
+ return [...children].some((worker) => {
322
+ var _a2;
323
+ return worker.isConnected() && Date.now() - ((_a2 = alive.get(worker.id)) != null ? _a2 : 0) < 1e4;
324
+ }) && ((_a = supplied == null ? void 0 : supplied.isLive) == null ? void 0 : _a.call(supplied)) !== false;
325
+ }
326
+ });
327
+ }
328
+ if (closing) {
329
+ if (ops) await _chunkMH2WIOTQcjs.closeHttpServer.call(void 0, ops);
330
+ await closing;
331
+ return { close };
332
+ }
333
+ for (let i = 0; i < workers; i++) {
334
+ const worker = _cluster2.default.fork();
335
+ children.add(worker);
336
+ worker.once("error", failed);
337
+ worker.once("exit", (code, signal) => {
338
+ alive.delete(worker.id);
339
+ failed(new Error("Den worker ".concat(String(worker.process.pid), " exited (").concat(String(code != null ? code : signal), ")")));
340
+ });
341
+ }
342
+ await ready;
343
+ started = true;
344
+ clearTimeout(timeout);
345
+ if (!closing) logger2.info("\u0437\u0430\u043F\u0443\u0449\u0435\u043D\u043E \u0432\u043E\u0440\u043A\u0435\u0440\u043E\u0432: ".concat(String(workers)));
346
+ return { close };
347
+ } catch (error) {
348
+ await close();
349
+ throw error;
350
+ }
351
+ }
352
+ async function stopWorker(worker) {
353
+ if (worker.isDead()) return;
354
+ await new Promise((resolve) => {
355
+ const timeout = setTimeout(() => worker.kill("SIGKILL"), SHUTDOWN_MS);
356
+ worker.once("exit", () => {
357
+ clearTimeout(timeout);
358
+ resolve();
225
359
  });
226
- try {
227
- yield (_c = options.configure) == null ? void 0 : _c.call(options, instance);
228
- if (options.ops !== false) {
229
- ops = yield _chunk2P5TAWRWcjs.startOpsServer.call(void 0, options.ops);
230
- }
231
- yield instance.listen({ host: (_d = options.host) != null ? _d : "0.0.0.0", port: (_e = options.port) != null ? _e : 8080 });
232
- } catch (error) {
233
- yield instance.close();
234
- throw error;
360
+ worker.kill("SIGTERM");
361
+ });
362
+ }
363
+
364
+ // src/serve/index.ts
365
+ function serveAppProcess(app, options = {}) {
366
+ return startAppProcess(app.name, options, (serveOptions) => serveApp(app, serveOptions));
367
+ }
368
+ var SHUTDOWN_SIGNALS = ["SIGTERM", "SIGINT"];
369
+ async function serveApp(app, options = {}) {
370
+ var _a, _b, _c, _d, _e;
371
+ const appLog = (_a = _logger.log.getLogger(app.name)) != null ? _a : _chunkA6ZPAM6Zcjs.logger;
372
+ const serveLog = (_b = appLog.getLogger("serve")) != null ? _b : appLog;
373
+ const instance = _fastify2.default.call(void 0, { logger: false });
374
+ const metrics = _chunkMH2WIOTQcjs.getProcessMetrics.call(void 0, );
375
+ metrics.startRuntime(app.name);
376
+ let ops;
377
+ const shutdown = () => {
378
+ void instance.close();
379
+ };
380
+ instance.addHook("onRequest", (req, reply, done) => {
381
+ if (_chunkMH2WIOTQcjs.isOpsPath.call(void 0, req.url)) {
382
+ void reply.code(404).send();
383
+ return;
235
384
  }
236
- if (options.gracefulShutdown !== false) {
237
- for (const signal of SHUTDOWN_SIGNALS) {
238
- process.once(signal, shutdown);
239
- }
385
+ metrics.trackHttp(req.raw, reply.raw, () => {
386
+ var _a2;
387
+ return (_a2 = req.routeOptions.url) != null ? _a2 : "unmatched";
388
+ });
389
+ done();
390
+ });
391
+ instance.addHook("onClose", async () => {
392
+ for (const signal of SHUTDOWN_SIGNALS) {
393
+ process.removeListener(signal, shutdown);
240
394
  }
241
- serveLog.info(
242
- `\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \xAB${app.name}\xBB \u0441\u043B\u0443\u0448\u0430\u0435\u0442 ${instance.addresses().map((a) => String(a.port)).join(", ")}`
243
- );
244
- return instance;
395
+ if (ops) {
396
+ await _chunkMH2WIOTQcjs.closeHttpServer.call(void 0, ops);
397
+ }
398
+ });
399
+ await instance.register(appPlugin, { app, slowRenderMs: options.slowRenderMs });
400
+ if (options.assets) {
401
+ registerAssets(instance, options.assets);
402
+ }
403
+ instance.addHook("onRequest", (req, _reply, done) => {
404
+ serveLog.debug("\u2192 ".concat(req.method, " ").concat(req.url));
405
+ done();
245
406
  });
407
+ instance.addHook("onResponse", (req, reply, done) => {
408
+ const elapsed = reply.elapsedTime.toFixed(1);
409
+ serveLog.info("\u2190 ".concat(String(reply.statusCode), " ").concat(req.method, " ").concat(req.url, " ").concat(elapsed, "\u043C\u0441"));
410
+ done();
411
+ });
412
+ try {
413
+ await ((_c = options.configure) == null ? void 0 : _c.call(options, instance));
414
+ if (options.ops !== false) {
415
+ ops = await _chunkMH2WIOTQcjs.startOpsServer.call(void 0, options.ops);
416
+ }
417
+ await instance.listen({ host: (_d = options.host) != null ? _d : "0.0.0.0", port: (_e = options.port) != null ? _e : 8080 });
418
+ } catch (error) {
419
+ await instance.close();
420
+ throw error;
421
+ }
422
+ if (options.gracefulShutdown !== false) {
423
+ for (const signal of SHUTDOWN_SIGNALS) {
424
+ process.once(signal, shutdown);
425
+ }
426
+ }
427
+ serveLog.info(
428
+ "\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \xAB".concat(app.name, "\xBB \u0441\u043B\u0443\u0448\u0430\u0435\u0442 ").concat(instance.addresses().map((a) => String(a.port)).join(", "))
429
+ );
430
+ return instance;
246
431
  }
247
432
 
248
433
 
249
434
 
250
435
 
251
436
 
252
- exports.appPlugin = appPlugin; exports.loadAppEnv = _chunkKQAB6C6Qcjs.loadAppEnv; exports.registerAssets = registerAssets; exports.serveApp = serveApp;
437
+
438
+ exports.appPlugin = appPlugin; exports.loadAppEnv = _chunkKQAB6C6Qcjs.loadAppEnv; exports.registerAssets = registerAssets; exports.serveApp = serveApp; exports.serveAppProcess = serveAppProcess;
package/serve/index.d.cts CHANGED
@@ -44,6 +44,14 @@ interface AppPluginOptions {
44
44
  */
45
45
  declare const appPlugin: FastifyPluginAsync<AppPluginOptions>;
46
46
 
47
+ interface AppProcess {
48
+ close: () => Promise<void>;
49
+ }
50
+ interface ServeAppProcessOptions extends ServeAppOptions {
51
+ /** Число процессов приложения; по умолчанию 1. Каждый воркер имеет свой контейнер. */
52
+ workers?: number;
53
+ }
54
+
47
55
  /**
48
56
  * Кладёт умолчания из `<root>/.env` в окружение процесса.
49
57
  *
@@ -53,6 +61,8 @@ declare const appPlugin: FastifyPluginAsync<AppPluginOptions>;
53
61
  */
54
62
  declare function loadAppEnv(root: string): void;
55
63
 
64
+ /** Точка входа самостоятельного процесса: один инстанс либо cluster с общим портом. */
65
+ declare function serveAppProcess(app: ServableApp, options?: ServeAppProcessOptions): Promise<AppProcess>;
56
66
  /** Настройки инстанса. */
57
67
  interface ServeAppOptions {
58
68
  /** Порт; `0` — свободный, фактический смотри в `server.addresses()`. */
@@ -93,4 +103,4 @@ interface ServeAppOptions {
93
103
  */
94
104
  declare function serveApp(app: ServableApp, options?: ServeAppOptions): Promise<FastifyInstance>;
95
105
 
96
- export { type AppAssetsSource, type AppPluginOptions, type ServableApp, type ServeAppOptions, appPlugin, loadAppEnv, registerAssets, serveApp };
106
+ export { type AppAssetsSource, type AppPluginOptions, type AppProcess, type ServableApp, type ServeAppOptions, type ServeAppProcessOptions, appPlugin, loadAppEnv, registerAssets, serveApp, serveAppProcess };
package/serve/index.d.ts CHANGED
@@ -44,6 +44,14 @@ interface AppPluginOptions {
44
44
  */
45
45
  declare const appPlugin: FastifyPluginAsync<AppPluginOptions>;
46
46
 
47
+ interface AppProcess {
48
+ close: () => Promise<void>;
49
+ }
50
+ interface ServeAppProcessOptions extends ServeAppOptions {
51
+ /** Число процессов приложения; по умолчанию 1. Каждый воркер имеет свой контейнер. */
52
+ workers?: number;
53
+ }
54
+
47
55
  /**
48
56
  * Кладёт умолчания из `<root>/.env` в окружение процесса.
49
57
  *
@@ -53,6 +61,8 @@ declare const appPlugin: FastifyPluginAsync<AppPluginOptions>;
53
61
  */
54
62
  declare function loadAppEnv(root: string): void;
55
63
 
64
+ /** Точка входа самостоятельного процесса: один инстанс либо cluster с общим портом. */
65
+ declare function serveAppProcess(app: ServableApp, options?: ServeAppProcessOptions): Promise<AppProcess>;
56
66
  /** Настройки инстанса. */
57
67
  interface ServeAppOptions {
58
68
  /** Порт; `0` — свободный, фактический смотри в `server.addresses()`. */
@@ -93,4 +103,4 @@ interface ServeAppOptions {
93
103
  */
94
104
  declare function serveApp(app: ServableApp, options?: ServeAppOptions): Promise<FastifyInstance>;
95
105
 
96
- export { type AppAssetsSource, type AppPluginOptions, type ServableApp, type ServeAppOptions, appPlugin, loadAppEnv, registerAssets, serveApp };
106
+ export { type AppAssetsSource, type AppPluginOptions, type AppProcess, type ServableApp, type ServeAppOptions, type ServeAppProcessOptions, appPlugin, loadAppEnv, registerAssets, serveApp, serveAppProcess };