@dev-anywhere/proxy 0.9.1 → 0.9.3

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.
Files changed (75) hide show
  1. package/README.md +25 -3
  2. package/dist/autostart-ZQ5YVCZY.js +292 -0
  3. package/dist/autostart-ZQ5YVCZY.js.map +1 -0
  4. package/dist/{chunk-NTL4CXBA.js → chunk-25JBQRJI.js} +46 -45
  5. package/dist/chunk-25JBQRJI.js.map +1 -0
  6. package/dist/chunk-2YUDGRJ6.js +379 -0
  7. package/dist/chunk-2YUDGRJ6.js.map +1 -0
  8. package/dist/chunk-44SDJYGT.js +344 -0
  9. package/dist/chunk-44SDJYGT.js.map +1 -0
  10. package/dist/chunk-77QVUYU7.js +42 -0
  11. package/dist/chunk-77QVUYU7.js.map +1 -0
  12. package/dist/chunk-CMADETTC.js +147 -0
  13. package/dist/chunk-CMADETTC.js.map +1 -0
  14. package/dist/chunk-DAFUSBKJ.js +299 -0
  15. package/dist/chunk-DAFUSBKJ.js.map +1 -0
  16. package/dist/{chunk-SEMZ7GW7.js → chunk-GYL5JKWQ.js} +3 -3
  17. package/dist/chunk-H623APEF.js +116 -0
  18. package/dist/chunk-H623APEF.js.map +1 -0
  19. package/dist/{chunk-57LA2LWY.js → chunk-HYDXGNKA.js} +2 -2
  20. package/dist/chunk-ICSO3ZIS.js +658 -0
  21. package/dist/chunk-ICSO3ZIS.js.map +1 -0
  22. package/dist/chunk-JZ7MWN24.js +22 -0
  23. package/dist/chunk-JZ7MWN24.js.map +1 -0
  24. package/dist/{chunk-ZNMJH7BK.js → chunk-KWODOJBK.js} +3 -3
  25. package/dist/chunk-M72SC32A.js +285 -0
  26. package/dist/chunk-M72SC32A.js.map +1 -0
  27. package/dist/{chunk-UJEZAG57.js → chunk-PCF2R2TG.js} +3 -1
  28. package/dist/{chunk-UJEZAG57.js.map → chunk-PCF2R2TG.js.map} +1 -1
  29. package/dist/{chunk-DZ4GXMP5.js → chunk-QZ3OZJBG.js} +56 -68
  30. package/dist/chunk-QZ3OZJBG.js.map +1 -0
  31. package/dist/{chunk-HLN3NOD2.js → chunk-WLXTXXNY.js} +315 -6
  32. package/dist/chunk-WLXTXXNY.js.map +1 -0
  33. package/dist/{chunk-OFD4UVPB.js → chunk-XADKKDUV.js} +29 -153
  34. package/dist/chunk-XADKKDUV.js.map +1 -0
  35. package/dist/{chunk-WRU3BXW6.js → chunk-YK2XKOP4.js} +26 -10
  36. package/dist/chunk-YK2XKOP4.js.map +1 -0
  37. package/dist/index.js +132 -345
  38. package/dist/index.js.map +1 -1
  39. package/dist/logger-24TGGN76.js +10 -0
  40. package/dist/logger-24TGGN76.js.map +1 -0
  41. package/dist/logger-B7B64O4P.js +14 -0
  42. package/dist/logger-B7B64O4P.js.map +1 -0
  43. package/dist/{quick-tunnel-RI62V2RH.js → quick-tunnel-ZIFTYUUD.js} +3 -3
  44. package/dist/{relay-token-ZP3PAZD2.js → relay-token-N3BSBURG.js} +5 -5
  45. package/dist/serve.js +4729 -4277
  46. package/dist/serve.js.map +1 -1
  47. package/dist/session-worker.js +91 -76
  48. package/dist/session-worker.js.map +1 -1
  49. package/dist/{terminal-BEXDQ5WK.js → terminal-PIFFUL2A.js} +98 -72
  50. package/dist/terminal-PIFFUL2A.js.map +1 -0
  51. package/dist/terminal-worker.js +258 -271
  52. package/dist/terminal-worker.js.map +1 -1
  53. package/dist/update-runner.js +86 -61
  54. package/dist/update-runner.js.map +1 -1
  55. package/package.json +9 -6
  56. package/scripts/postinstall.cjs +22 -0
  57. package/dist/chunk-77NR262K.js +0 -219
  58. package/dist/chunk-77NR262K.js.map +0 -1
  59. package/dist/chunk-7SYT65DN.js +0 -155
  60. package/dist/chunk-7SYT65DN.js.map +0 -1
  61. package/dist/chunk-DZ4GXMP5.js.map +0 -1
  62. package/dist/chunk-HLN3NOD2.js.map +0 -1
  63. package/dist/chunk-KGTYU4WO.js +0 -36
  64. package/dist/chunk-KGTYU4WO.js.map +0 -1
  65. package/dist/chunk-NTL4CXBA.js.map +0 -1
  66. package/dist/chunk-OFD4UVPB.js.map +0 -1
  67. package/dist/chunk-WC3KEY7N.js +0 -158
  68. package/dist/chunk-WC3KEY7N.js.map +0 -1
  69. package/dist/chunk-WRU3BXW6.js.map +0 -1
  70. package/dist/terminal-BEXDQ5WK.js.map +0 -1
  71. /package/dist/{chunk-SEMZ7GW7.js.map → chunk-GYL5JKWQ.js.map} +0 -0
  72. /package/dist/{chunk-57LA2LWY.js.map → chunk-HYDXGNKA.js.map} +0 -0
  73. /package/dist/{chunk-ZNMJH7BK.js.map → chunk-KWODOJBK.js.map} +0 -0
  74. /package/dist/{quick-tunnel-RI62V2RH.js.map → quick-tunnel-ZIFTYUUD.js.map} +0 -0
  75. /package/dist/{relay-token-ZP3PAZD2.js.map → relay-token-N3BSBURG.js.map} +0 -0
@@ -0,0 +1,658 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../../packages/shared/dist/logger.js
4
+ import { lstatSync, linkSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "fs";
5
+ import { randomUUID } from "crypto";
6
+ import { homedir } from "os";
7
+ import { basename, join } from "path";
8
+ import pino from "pino";
9
+ var DEFAULT_LOG_DIR = `${homedir()}/.dev-anywhere/logs`;
10
+ var DEFAULT_LOG_RETENTION = 50;
11
+ var DEFAULT_LOG_RETENTION_BYTES = 256 * 1024 * 1024;
12
+ var DEFAULT_MAX_FILE_BYTES = 16 * 1024 * 1024;
13
+ var DEFAULT_MAX_FILES_PER_RUN = 2;
14
+ var DEFAULT_MAX_RECORD_BYTES = 256 * 1024;
15
+ var DEFAULT_MAX_STDOUT_BUFFER_BYTES = 1024 * 1024;
16
+ var LOG_IO_OPERATION_TIMEOUT_MS = 5e3;
17
+ var LOG_RUN_LEASE_SUFFIX = ".active";
18
+ var LOG_RUN_LEASE_CANDIDATE_MARKER = `${LOG_RUN_LEASE_SUFFIX}.candidate-`;
19
+ var PROCESS_LOG_RUN_ID = sanitizeRunId(`${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${process.pid}`);
20
+ function sanitizeRunId(runId) {
21
+ return runId.replace(/[^a-zA-Z0-9._-]/g, "_");
22
+ }
23
+ function linkLatestLog(logDir, name, filePath, runId) {
24
+ const latestPath = join(logDir, `${name}.log`);
25
+ try {
26
+ const stat = lstatSync(latestPath);
27
+ if (stat.isSymbolicLink()) {
28
+ unlinkSync(latestPath);
29
+ } else {
30
+ renameSync(latestPath, join(logDir, `${name}-legacy-${runId}.log`));
31
+ }
32
+ } catch (err) {
33
+ const code = err.code;
34
+ if (code !== "ENOENT")
35
+ return;
36
+ }
37
+ try {
38
+ symlinkSync(basename(filePath), latestPath);
39
+ } catch {
40
+ }
41
+ }
42
+ function resolveRetention(retention) {
43
+ if (retention === void 0)
44
+ return DEFAULT_LOG_RETENTION;
45
+ return Number.isFinite(retention) && retention >= 0 ? Math.floor(retention) : DEFAULT_LOG_RETENTION;
46
+ }
47
+ function resolvePositiveInteger(value, fallback) {
48
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
49
+ }
50
+ function leasePathForLog(filePath) {
51
+ return `${filePath}${LOG_RUN_LEASE_SUFFIX}`;
52
+ }
53
+ function createLogRunLease(filePath, runId) {
54
+ const lease = {
55
+ version: 1,
56
+ pid: process.pid,
57
+ runId,
58
+ fileName: basename(filePath)
59
+ };
60
+ const leasePath = leasePathForLog(filePath);
61
+ const candidatePath = `${leasePath}.candidate-${process.pid}-${randomUUID()}`;
62
+ let candidateCreated = false;
63
+ try {
64
+ writeFileSync(candidatePath, `${JSON.stringify(lease)}
65
+ `, { flag: "wx" });
66
+ candidateCreated = true;
67
+ linkSync(candidatePath, leasePath);
68
+ } finally {
69
+ if (candidateCreated) {
70
+ try {
71
+ unlinkSync(candidatePath);
72
+ } catch {
73
+ }
74
+ }
75
+ }
76
+ }
77
+ function isProcessAlive(pid) {
78
+ try {
79
+ process.kill(pid, 0);
80
+ return true;
81
+ } catch (error) {
82
+ return error.code !== "ESRCH";
83
+ }
84
+ }
85
+ function readLogRunLease(leasePath, expectedFileName) {
86
+ let raw;
87
+ try {
88
+ raw = readFileSync(leasePath, "utf-8");
89
+ } catch (error) {
90
+ return error.code === "ENOENT" ? { state: "missing" } : { state: "invalid" };
91
+ }
92
+ try {
93
+ const parsed = JSON.parse(raw);
94
+ const pid = parsed.pid;
95
+ if (parsed.version !== 1 || !Number.isSafeInteger(pid) || typeof pid !== "number" || pid <= 0 || typeof parsed.runId !== "string" || parsed.runId.length === 0 || parsed.fileName !== expectedFileName) {
96
+ throw new Error("Invalid log run lease");
97
+ }
98
+ return { state: "valid", lease: parsed };
99
+ } catch {
100
+ return { state: "invalid" };
101
+ }
102
+ }
103
+ function hasLiveLogRunLease(filePath) {
104
+ const leasePath = leasePathForLog(filePath);
105
+ const result = readLogRunLease(leasePath, basename(filePath));
106
+ if (result.state === "missing")
107
+ return false;
108
+ if (result.state === "invalid")
109
+ return true;
110
+ if (isProcessAlive(result.lease.pid))
111
+ return true;
112
+ try {
113
+ unlinkSync(leasePath);
114
+ } catch {
115
+ }
116
+ return false;
117
+ }
118
+ function removeOwnedLogRunLease(filePath, runId) {
119
+ const leasePath = leasePathForLog(filePath);
120
+ const result = readLogRunLease(leasePath, basename(filePath));
121
+ if (result.state !== "valid" || result.lease.pid !== process.pid || result.lease.runId !== runId) {
122
+ return;
123
+ }
124
+ try {
125
+ unlinkSync(leasePath);
126
+ } catch {
127
+ }
128
+ }
129
+ function parseLeaseEntry(entry, name) {
130
+ const prefix = `${name}-`;
131
+ if (!entry.startsWith(prefix))
132
+ return null;
133
+ if (entry.endsWith(LOG_RUN_LEASE_SUFFIX)) {
134
+ const fileName2 = entry.slice(0, -LOG_RUN_LEASE_SUFFIX.length);
135
+ return fileName2.endsWith(".log") ? { fileName: fileName2, candidate: false } : null;
136
+ }
137
+ const markerIndex = entry.lastIndexOf(LOG_RUN_LEASE_CANDIDATE_MARKER);
138
+ if (markerIndex < 0 || markerIndex + LOG_RUN_LEASE_CANDIDATE_MARKER.length >= entry.length) {
139
+ return null;
140
+ }
141
+ const fileName = entry.slice(0, markerIndex);
142
+ return fileName.endsWith(".log") ? { fileName, candidate: true } : null;
143
+ }
144
+ function pruneOrphanedLogRunLeases(logDir, name) {
145
+ for (const entry of readdirSync(logDir)) {
146
+ const parsedEntry = parseLeaseEntry(entry, name);
147
+ if (!parsedEntry)
148
+ continue;
149
+ const leasePath = join(logDir, entry);
150
+ const result = readLogRunLease(leasePath, parsedEntry.fileName);
151
+ if (result.state !== "valid" || isProcessAlive(result.lease.pid))
152
+ continue;
153
+ let correspondingLogExists = false;
154
+ try {
155
+ statSync(join(logDir, parsedEntry.fileName));
156
+ correspondingLogExists = true;
157
+ } catch {
158
+ }
159
+ if (!parsedEntry.candidate && correspondingLogExists)
160
+ continue;
161
+ try {
162
+ unlinkSync(leasePath);
163
+ } catch {
164
+ }
165
+ }
166
+ }
167
+ function removeLogAndLease(filePath) {
168
+ unlinkSync(filePath);
169
+ try {
170
+ unlinkSync(leasePathForLog(filePath));
171
+ } catch {
172
+ }
173
+ }
174
+ function pruneOldLogs(logDir, name, currentFilePath, retention, retentionBytes) {
175
+ const keep = resolveRetention(retention);
176
+ const byteBudget = resolvePositiveInteger(retentionBytes, DEFAULT_LOG_RETENTION_BYTES);
177
+ pruneOrphanedLogRunLeases(logDir, name);
178
+ if (keep === 0)
179
+ return;
180
+ const currentFileName = basename(currentFilePath);
181
+ const prefix = `${name}-`;
182
+ const candidates = readdirSync(logDir).filter((entry) => entry.startsWith(prefix) && entry.endsWith(".log") && entry !== currentFileName).map((entry) => {
183
+ const path = join(logDir, entry);
184
+ try {
185
+ const stat = statSync(path);
186
+ return { path, mtimeMs: stat.mtimeMs, size: stat.size };
187
+ } catch {
188
+ return null;
189
+ }
190
+ }).filter((entry) => entry !== null).sort((a, b) => b.mtimeMs - a.mtimeMs);
191
+ const retained = [];
192
+ let retainedBytes = 0;
193
+ for (const candidate of candidates) {
194
+ if (hasLiveLogRunLease(candidate.path)) {
195
+ retained.push(candidate);
196
+ retainedBytes += candidate.size;
197
+ continue;
198
+ }
199
+ const withinCount = keep === 0 || retained.length < Math.max(0, keep - 1);
200
+ const withinBytes = retainedBytes + candidate.size <= byteBudget;
201
+ if (withinCount && withinBytes) {
202
+ retained.push(candidate);
203
+ retainedBytes += candidate.size;
204
+ continue;
205
+ }
206
+ try {
207
+ removeLogAndLease(candidate.path);
208
+ } catch {
209
+ }
210
+ }
211
+ }
212
+ function waitForDestinationEvent(destination, event, deadline) {
213
+ if (!destination.on || !destination.off)
214
+ return Promise.resolve(false);
215
+ const addListener = destination.on.bind(destination);
216
+ const removeListener = destination.off.bind(destination);
217
+ const remaining = deadline === void 0 ? void 0 : deadline - Date.now();
218
+ if (remaining !== void 0 && remaining <= 0)
219
+ return Promise.resolve(false);
220
+ return new Promise((resolve) => {
221
+ let settled = false;
222
+ let timer;
223
+ const cleanup = () => {
224
+ if (timer)
225
+ clearTimeout(timer);
226
+ removeListener(event, onEvent);
227
+ removeListener("error", onError);
228
+ };
229
+ const settle = (result) => {
230
+ if (settled)
231
+ return;
232
+ settled = true;
233
+ cleanup();
234
+ resolve(result);
235
+ };
236
+ const onEvent = () => settle(true);
237
+ const onError = () => settle(false);
238
+ addListener(event, onEvent);
239
+ addListener("error", onError);
240
+ if (remaining !== void 0) {
241
+ timer = setTimeout(() => settle(false), remaining);
242
+ timer.unref?.();
243
+ }
244
+ });
245
+ }
246
+ var BoundedWritableDestination = class {
247
+ destination;
248
+ maxPendingBytes;
249
+ droppedRecords = 0;
250
+ saturated = false;
251
+ constructor(destination, maxPendingBytes) {
252
+ this.destination = destination;
253
+ this.maxPendingBytes = maxPendingBytes;
254
+ }
255
+ write(serialized) {
256
+ if (this.saturated)
257
+ return;
258
+ const bytes = Buffer.byteLength(serialized);
259
+ const pendingBytes = this.destination.writableLength;
260
+ if (bytes > this.maxPendingBytes || typeof pendingBytes !== "number" || !Number.isFinite(pendingBytes)) {
261
+ this.droppedRecords += 1;
262
+ return;
263
+ }
264
+ const droppedDiagnostic = this.droppedRecords > 0 ? `${JSON.stringify({
265
+ level: 40,
266
+ time: Date.now(),
267
+ msg: "Log records were dropped while stdout was backpressured",
268
+ dropped: this.droppedRecords
269
+ })}
270
+ ` : null;
271
+ const diagnosticBytes = droppedDiagnostic ? Buffer.byteLength(droppedDiagnostic) : 0;
272
+ if (pendingBytes + diagnosticBytes + bytes > this.maxPendingBytes) {
273
+ this.droppedRecords += 1;
274
+ return;
275
+ }
276
+ try {
277
+ if (droppedDiagnostic)
278
+ this.destination.write(droppedDiagnostic);
279
+ this.destination.write(serialized);
280
+ this.droppedRecords = 0;
281
+ } catch {
282
+ this.saturated = true;
283
+ }
284
+ }
285
+ };
286
+ var BoundedLogDestination = class {
287
+ destination;
288
+ filePath;
289
+ runId;
290
+ logDir;
291
+ name;
292
+ retention;
293
+ retentionBytes;
294
+ maxFileBytes;
295
+ maxFilesPerRun;
296
+ maxRecordBytes;
297
+ currentBytes = 0;
298
+ rotating = false;
299
+ saturated = false;
300
+ droppedDuringRotation = 0;
301
+ pendingRecord = null;
302
+ rotationPromise = null;
303
+ rotationWaiters = /* @__PURE__ */ new Set();
304
+ constructor(destination, filePath, runId, logDir, name, retention, retentionBytes, maxFileBytes, maxFilesPerRun, maxRecordBytes, initialBytes) {
305
+ this.destination = destination;
306
+ this.filePath = filePath;
307
+ this.runId = runId;
308
+ this.logDir = logDir;
309
+ this.name = name;
310
+ this.retention = retention;
311
+ this.retentionBytes = retentionBytes;
312
+ this.maxFileBytes = maxFileBytes;
313
+ this.maxFilesPerRun = maxFilesPerRun;
314
+ this.maxRecordBytes = maxRecordBytes;
315
+ this.currentBytes = initialBytes;
316
+ this.destination.on?.("error", () => {
317
+ this.rotating = false;
318
+ this.saturated = true;
319
+ if (this.destination.fd == null || this.destination.fd < 0) {
320
+ removeOwnedLogRunLease(this.filePath, this.runId);
321
+ }
322
+ });
323
+ }
324
+ get fd() {
325
+ return this.destination.fd;
326
+ }
327
+ get _writing() {
328
+ return this.destination._writing;
329
+ }
330
+ once(event, cb) {
331
+ this.destination.once?.(event, cb);
332
+ }
333
+ on(event, cb) {
334
+ this.destination.on?.(event, cb);
335
+ }
336
+ off(event, cb) {
337
+ this.destination.off?.(event, cb);
338
+ }
339
+ listenerCount(event) {
340
+ return this.destination.listenerCount?.(event) ?? 0;
341
+ }
342
+ write(serialized) {
343
+ if (this.saturated)
344
+ return;
345
+ const record = this.boundRecord(serialized);
346
+ if (!record)
347
+ return;
348
+ const bytes = Buffer.byteLength(record);
349
+ if (this.rotating) {
350
+ this.droppedDuringRotation += 1;
351
+ return;
352
+ }
353
+ if (this.currentBytes + bytes > this.maxFileBytes) {
354
+ this.startRotation(record);
355
+ return;
356
+ }
357
+ this.writeActiveRecord(record);
358
+ }
359
+ flushSync() {
360
+ this.destination.flushSync?.();
361
+ }
362
+ async waitForRotation(deadline) {
363
+ while (this.rotationPromise) {
364
+ const remaining = deadline - Date.now();
365
+ if (remaining <= 0)
366
+ return false;
367
+ const settled = await new Promise((resolve) => {
368
+ let finished = false;
369
+ const waiter = () => finish(true);
370
+ const timer = setTimeout(() => finish(false), remaining);
371
+ timer.unref?.();
372
+ const finish = (result) => {
373
+ if (finished)
374
+ return;
375
+ finished = true;
376
+ clearTimeout(timer);
377
+ this.rotationWaiters.delete(waiter);
378
+ resolve(result);
379
+ };
380
+ this.rotationWaiters.add(waiter);
381
+ if (!this.rotationPromise)
382
+ finish(true);
383
+ });
384
+ if (!settled)
385
+ return false;
386
+ }
387
+ return true;
388
+ }
389
+ boundRecord(serialized) {
390
+ const bytes = Buffer.byteLength(serialized);
391
+ if (bytes <= this.maxRecordBytes && bytes <= this.maxFileBytes)
392
+ return serialized;
393
+ return this.boundDiagnostic({
394
+ level: 40,
395
+ time: Date.now(),
396
+ msg: "Log entry omitted because it exceeded the configured byte limit",
397
+ originalBytes: bytes
398
+ });
399
+ }
400
+ boundDiagnostic(value) {
401
+ const serialized = `${JSON.stringify(value)}
402
+ `;
403
+ const bytes = Buffer.byteLength(serialized);
404
+ return bytes <= this.maxRecordBytes && bytes <= this.maxFileBytes ? serialized : null;
405
+ }
406
+ segmentPath(index) {
407
+ return this.filePath.replace(/\.log$/, `.${index}.log`);
408
+ }
409
+ writeActiveRecord(record) {
410
+ const bytes = Buffer.byteLength(record);
411
+ if (!this.destination.write || this.currentBytes + bytes > this.maxFileBytes)
412
+ return false;
413
+ this.currentBytes += bytes;
414
+ try {
415
+ this.destination.write(record);
416
+ return !this.saturated;
417
+ } catch {
418
+ this.saturated = true;
419
+ return false;
420
+ }
421
+ }
422
+ startRotation(pendingRecord) {
423
+ if (this.rotating || this.saturated)
424
+ return;
425
+ this.rotating = true;
426
+ this.pendingRecord = pendingRecord;
427
+ const tracked = Promise.resolve().then(() => this.performRotation()).catch(() => {
428
+ this.saturated = true;
429
+ this.rotating = false;
430
+ this.pendingRecord = null;
431
+ this.droppedDuringRotation = 0;
432
+ }).finally(() => {
433
+ if (this.rotationPromise === tracked)
434
+ this.rotationPromise = null;
435
+ for (const waiter of this.rotationWaiters)
436
+ waiter();
437
+ this.rotationWaiters.clear();
438
+ });
439
+ this.rotationPromise = tracked;
440
+ }
441
+ async performRotation() {
442
+ if (!this.destination.reopen)
443
+ throw new Error("Log destination cannot be reopened");
444
+ const deadline = Date.now() + LOG_IO_OPERATION_TIMEOUT_MS;
445
+ if (this.destination.fd == null || this.destination.fd < 0) {
446
+ if (!await waitForDestinationEvent(this.destination, "ready", deadline)) {
447
+ throw new Error("Log destination did not become ready");
448
+ }
449
+ }
450
+ if (this.destination._writing) {
451
+ if (!await waitForDestinationEvent(this.destination, "drain", deadline)) {
452
+ throw new Error("Log destination did not drain");
453
+ }
454
+ }
455
+ this.rotateFiles();
456
+ this.destination.reopen(this.filePath);
457
+ if (!await waitForDestinationEvent(this.destination, "ready", deadline)) {
458
+ throw new Error("Rotated log destination did not become ready");
459
+ }
460
+ pruneOldLogs(this.logDir, this.name, this.filePath, this.retention, this.retentionBytes);
461
+ this.currentBytes = 0;
462
+ const pendingRecord = this.pendingRecord;
463
+ this.pendingRecord = null;
464
+ const dropped = this.droppedDuringRotation;
465
+ this.droppedDuringRotation = 0;
466
+ this.rotating = false;
467
+ if (pendingRecord && !this.writeActiveRecord(pendingRecord))
468
+ return;
469
+ if (dropped === 0 || this.saturated)
470
+ return;
471
+ const diagnostic = this.boundDiagnostic({
472
+ level: 40,
473
+ time: Date.now(),
474
+ msg: "Log records were dropped while rotating the active file",
475
+ dropped
476
+ });
477
+ if (diagnostic && this.currentBytes + Buffer.byteLength(diagnostic) <= this.maxFileBytes) {
478
+ this.writeActiveRecord(diagnostic);
479
+ }
480
+ }
481
+ rotateFiles() {
482
+ if (this.maxFilesPerRun > 1) {
483
+ try {
484
+ unlinkSync(this.segmentPath(this.maxFilesPerRun - 1));
485
+ } catch (error) {
486
+ if (error.code !== "ENOENT")
487
+ throw error;
488
+ }
489
+ for (let index = this.maxFilesPerRun - 2; index >= 1; index -= 1) {
490
+ try {
491
+ renameSync(this.segmentPath(index), this.segmentPath(index + 1));
492
+ } catch (error) {
493
+ if (error.code !== "ENOENT")
494
+ throw error;
495
+ }
496
+ }
497
+ renameSync(this.filePath, this.segmentPath(1));
498
+ } else {
499
+ unlinkSync(this.filePath);
500
+ }
501
+ }
502
+ };
503
+ var loggerMetaMap = /* @__PURE__ */ new WeakMap();
504
+ async function flushDestination(destination, deadline) {
505
+ while (true) {
506
+ if (!await destination.waitForRotation(deadline))
507
+ return;
508
+ if (destination.fd == null || destination.fd < 0) {
509
+ if (!await waitForDestinationEvent(destination, "ready", deadline))
510
+ return;
511
+ continue;
512
+ }
513
+ if (destination._writing) {
514
+ if (!await waitForDestinationEvent(destination, "drain", deadline))
515
+ return;
516
+ continue;
517
+ }
518
+ try {
519
+ destination.flushSync();
520
+ } catch {
521
+ }
522
+ return;
523
+ }
524
+ }
525
+ function resolveFlushTimeout(timeoutMs) {
526
+ return Number.isFinite(timeoutMs) && timeoutMs >= 0 ? Math.floor(timeoutMs) : 200;
527
+ }
528
+ function startFlushOperation(meta, destination) {
529
+ const operation = {
530
+ promise: flushDestination(destination, Date.now() + LOG_IO_OPERATION_TIMEOUT_MS),
531
+ settled: false,
532
+ waiters: /* @__PURE__ */ new Set()
533
+ };
534
+ meta.flushOperation = operation;
535
+ const finish = () => {
536
+ if (operation.settled)
537
+ return;
538
+ operation.settled = true;
539
+ if (meta.flushOperation === operation)
540
+ meta.flushOperation = null;
541
+ for (const waiter of operation.waiters)
542
+ waiter();
543
+ operation.waiters.clear();
544
+ };
545
+ void operation.promise.then(finish, finish);
546
+ return operation;
547
+ }
548
+ function waitForFlushOperation(operation, timeoutMs) {
549
+ if (operation.settled || timeoutMs <= 0)
550
+ return Promise.resolve();
551
+ return new Promise((resolve) => {
552
+ let settled = false;
553
+ const finish = () => {
554
+ if (settled)
555
+ return;
556
+ settled = true;
557
+ clearTimeout(timer);
558
+ operation.waiters.delete(finish);
559
+ resolve();
560
+ };
561
+ const timer = setTimeout(finish, timeoutMs);
562
+ operation.waiters.add(finish);
563
+ if (operation.settled) {
564
+ finish();
565
+ return;
566
+ }
567
+ });
568
+ }
569
+ function buildPinoLogger(options) {
570
+ const { name, level = "info", logDir = DEFAULT_LOG_DIR, retention, retentionBytes, maxFileBytes: requestedMaxFileBytes, maxFilesPerRun: requestedMaxFilesPerRun, maxRecordBytes: requestedMaxRecordBytes, stdout = false, silent = false, sync = false } = options;
571
+ if (silent) {
572
+ return { logger: pino({ level: "silent" }), destination: null };
573
+ }
574
+ mkdirSync(logDir, { recursive: true });
575
+ const runId = `${PROCESS_LOG_RUN_ID}-${randomUUID()}`;
576
+ const filePath = join(logDir, `${name}-${runId}.log`);
577
+ createLogRunLease(filePath, runId);
578
+ try {
579
+ linkLatestLog(logDir, name, filePath, runId);
580
+ pruneOldLogs(logDir, name, filePath, retention, retentionBytes);
581
+ const maxFileBytes = resolvePositiveInteger(requestedMaxFileBytes, DEFAULT_MAX_FILE_BYTES);
582
+ const maxFilesPerRun = resolvePositiveInteger(requestedMaxFilesPerRun, DEFAULT_MAX_FILES_PER_RUN);
583
+ const maxRecordBytes = Math.min(maxFileBytes, resolvePositiveInteger(requestedMaxRecordBytes, DEFAULT_MAX_RECORD_BYTES));
584
+ const sonicDestination = pino.destination({
585
+ dest: filePath,
586
+ sync,
587
+ // Bound data queued while the filesystem is stalled. Dropping diagnostics is preferable to
588
+ // allowing a logging failure to consume the application's heap.
589
+ maxLength: Math.min(maxFileBytes, 1024 * 1024)
590
+ });
591
+ let initialBytes = 0;
592
+ try {
593
+ initialBytes = statSync(filePath).size;
594
+ } catch {
595
+ }
596
+ const destination = new BoundedLogDestination(sonicDestination, filePath, runId, logDir, name, retention, retentionBytes, maxFileBytes, maxFilesPerRun, maxRecordBytes, initialBytes);
597
+ const streams = [{ stream: destination }];
598
+ if (stdout) {
599
+ streams.unshift({
600
+ stream: new BoundedWritableDestination(process.stdout, DEFAULT_MAX_STDOUT_BUFFER_BYTES)
601
+ });
602
+ }
603
+ return { logger: pino({ level }, pino.multistream(streams)), destination };
604
+ } catch (error) {
605
+ removeOwnedLogRunLease(filePath, runId);
606
+ throw error;
607
+ }
608
+ }
609
+ function createLogger(options) {
610
+ let real = null;
611
+ const meta = { materialized: false, destination: null, flushOperation: null };
612
+ const ensure = () => {
613
+ if (!real) {
614
+ const built = buildPinoLogger(options);
615
+ real = built.logger;
616
+ meta.materialized = true;
617
+ meta.destination = built.destination;
618
+ }
619
+ return real;
620
+ };
621
+ const proxy = new Proxy(/* @__PURE__ */ Object.create(null), {
622
+ get(_target, prop) {
623
+ const target = ensure();
624
+ const value = Reflect.get(target, prop, target);
625
+ return typeof value === "function" ? value.bind(target) : value;
626
+ },
627
+ set(_target, prop, value) {
628
+ return Reflect.set(ensure(), prop, value);
629
+ },
630
+ has(_target, prop) {
631
+ return Reflect.has(ensure(), prop);
632
+ },
633
+ ownKeys() {
634
+ return Reflect.ownKeys(ensure());
635
+ },
636
+ getOwnPropertyDescriptor(_target, prop) {
637
+ return Reflect.getOwnPropertyDescriptor(ensure(), prop);
638
+ }
639
+ });
640
+ loggerMetaMap.set(proxy, meta);
641
+ return proxy;
642
+ }
643
+ async function flushLogger(logger, timeoutMs = 200) {
644
+ const meta = loggerMetaMap.get(logger);
645
+ if (!meta || !meta.materialized)
646
+ return;
647
+ const dest = meta.destination;
648
+ if (!dest)
649
+ return;
650
+ const operation = meta.flushOperation ?? startFlushOperation(meta, dest);
651
+ await waitForFlushOperation(operation, resolveFlushTimeout(timeoutMs));
652
+ }
653
+
654
+ export {
655
+ createLogger,
656
+ flushLogger
657
+ };
658
+ //# sourceMappingURL=chunk-ICSO3ZIS.js.map