@phala/cloud 0.6.2 → 0.6.4

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.js CHANGED
@@ -969,7 +969,7 @@ function defaultUserAgent(runtime = globalThis) {
969
969
  if (runtime.window !== void 0 && runtime.document !== void 0) {
970
970
  return void 0;
971
971
  }
972
- const product = "phala-cloud-sdk-js/0.6.2";
972
+ const product = "phala-cloud-sdk-js/0.6.4";
973
973
  const token = runtimeToken(runtime);
974
974
  return token ? `${product} ${token}` : product;
975
975
  }
@@ -8015,20 +8015,24 @@ function parseRfc3339(value) {
8015
8015
  if (year < 1 || month < 1 || month > 12 || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
8016
8016
  return void 0;
8017
8017
  }
8018
- const fractionalMilliseconds = fraction ? Number(`0.${fraction}`) * 1e3 : 0;
8019
8018
  const offset = sign === "+" ? 1 : sign === "-" ? -1 : 0;
8020
- const offsetMilliseconds = offset * (offsetHour * 60 + offsetMinute) * 6e4;
8019
+ const offsetSeconds = offset * (offsetHour * 60 + offsetMinute) * 60;
8021
8020
  const date = /* @__PURE__ */ new Date(0);
8022
8021
  date.setUTCFullYear(year, month - 1, day);
8023
8022
  date.setUTCHours(hour, minute, second, 0);
8024
- return date.getTime() + fractionalMilliseconds - offsetMilliseconds;
8023
+ const seconds = Math.floor(date.getTime() / 1e3) - offsetSeconds;
8024
+ const fractionNonZero = Boolean(fraction && /[1-9]/.test(fraction));
8025
+ return { seconds, fractionNonZero };
8025
8026
  }
8026
- function parseLogTime(value, nowMs) {
8027
+ function resolveLogInstant(value, nowMs, ceil) {
8028
+ if (typeof value === "number") {
8029
+ return ceil ? Math.ceil(value) : Math.floor(value);
8030
+ }
8027
8031
  if (/^-?\d+$/.test(value)) {
8028
8032
  const seconds = Number(value);
8029
8033
  const milliseconds = seconds * 1e3;
8030
8034
  if (Number.isSafeInteger(seconds) && Number.isSafeInteger(milliseconds)) {
8031
- return milliseconds;
8035
+ return seconds;
8032
8036
  }
8033
8037
  }
8034
8038
  const relative = /^(\d+)([smhd])$/.exec(value);
@@ -8042,18 +8046,20 @@ function parseLogTime(value, nowMs) {
8042
8046
  const duration = Number(relative[1]) * (DURATION_SECONDS[unit] ?? 0);
8043
8047
  const milliseconds = nowMs - duration * 1e3;
8044
8048
  if (Number.isFinite(milliseconds) && Number.isSafeInteger(Math.floor(milliseconds / 1e3))) {
8045
- return milliseconds;
8049
+ return ceil ? Math.ceil(milliseconds / 1e3) : Math.floor(milliseconds / 1e3);
8046
8050
  }
8047
8051
  }
8048
8052
  const rfc3339 = parseRfc3339(value);
8049
- if (rfc3339 !== void 0) return rfc3339;
8053
+ if (rfc3339 !== void 0) {
8054
+ return ceil && rfc3339.fractionNonZero ? rfc3339.seconds + 1 : rfc3339.seconds;
8055
+ }
8050
8056
  throw new Error(
8051
8057
  `Invalid log time '${value}'. Use RFC3339, Unix seconds, or a relative duration such as 10m.`
8052
8058
  );
8053
8059
  }
8054
8060
  function resolveLogTimeWindow(since, until, nowMs = Date.now()) {
8055
- const resolvedSince = since === void 0 ? void 0 : typeof since === "number" ? Math.floor(since) : Math.floor(parseLogTime(since, nowMs) / 1e3);
8056
- const resolvedUntil = until === void 0 ? void 0 : typeof until === "number" ? Math.ceil(until) : Math.ceil(parseLogTime(until, nowMs) / 1e3);
8061
+ const resolvedSince = since === void 0 ? void 0 : resolveLogInstant(since, nowMs, false);
8062
+ const resolvedUntil = until === void 0 ? void 0 : resolveLogInstant(until, nowMs, true);
8057
8063
  if (resolvedSince !== void 0 && !Number.isSafeInteger(resolvedSince) || resolvedUntil !== void 0 && !Number.isSafeInteger(resolvedUntil)) {
8058
8064
  throw new Error("Log time is outside the supported Unix seconds range.");
8059
8065
  }
@@ -8065,42 +8071,46 @@ function resolveLogTimeWindow(since, until, nowMs = Date.now()) {
8065
8071
 
8066
8072
  // src/actions/cvms/logs.ts
8067
8073
  var CVM_LOGS_INFO_API_VERSION = "2026-01-21";
8068
- var LOG_ERROR_HTTP_STATUS = {
8069
- "ERR-17-001": 400,
8070
- "ERR-17-002": 401,
8071
- "ERR-17-003": 401,
8072
- "ERR-17-004": 404,
8073
- "ERR-17-005": 409,
8074
- "ERR-17-006": 409,
8075
- "ERR-17-007": 404,
8076
- "ERR-17-008": 502,
8077
- "ERR-17-009": 502,
8078
- "ERR-17-010": 504,
8079
- "ERR-17-011": 429,
8080
- "ERR-17-012": 503,
8081
- "ERR-17-013": 404
8082
- };
8083
- function logErrorHttpStatus(code) {
8084
- return LOG_ERROR_HTTP_STATUS[code];
8074
+ var LOG_CHANNELS = /* @__PURE__ */ new Set(["stdout", "stderr", "stdin", "console"]);
8075
+ function logFetchHeaders(client) {
8076
+ const headers = new Headers();
8077
+ const ua = defaultUserAgent();
8078
+ if (ua) headers.set("User-Agent", ua);
8079
+ const extra = client.config?.headers;
8080
+ if (extra) {
8081
+ new Headers(extra).forEach((value, key) => {
8082
+ if (key.toLowerCase() === "user-agent") headers.set("User-Agent", value);
8083
+ });
8084
+ }
8085
+ return headers;
8086
+ }
8087
+ function logFetch(client, url, signal) {
8088
+ return fetch(url, {
8089
+ method: "GET",
8090
+ headers: logFetchHeaders(client),
8091
+ signal,
8092
+ redirect: "manual"
8093
+ });
8085
8094
  }
8086
8095
  var LogAccessError = class extends ResourceError {
8087
8096
  constructor(options) {
8088
- const details = options.code ? `${options.code}: ${options.message}` : options.message;
8089
- const suggestionText = options.suggestions?.length ? `
8090
- Suggestions:
8091
- ${options.suggestions.map((suggestion) => `- ${suggestion}`).join("\n")}` : "";
8092
- const status = options.fromStreamBody ? 0 : options.httpStatus ?? (options.code ? logErrorHttpStatus(options.code) : void 0) ?? 0;
8093
- super(`${details}${suggestionText}`, {
8097
+ const details = options.message;
8098
+ const status = options.fromStreamBody ? 0 : options.httpStatus && options.httpStatus > 0 ? options.httpStatus : 0;
8099
+ super(details, {
8094
8100
  status,
8095
8101
  statusText: "",
8096
8102
  errorCode: options.code,
8097
- suggestions: options.suggestions ? [...options.suggestions] : void 0
8103
+ suggestions: options.suggestions ? [...options.suggestions] : void 0,
8104
+ requestId: options.requestId,
8105
+ structuredDetails: options.details,
8106
+ links: options.links
8098
8107
  });
8099
8108
  this.name = "LogAccessError";
8100
8109
  this.code = options.code;
8101
- this.httpStatus = status || void 0;
8110
+ this.httpStatus = options.fromStreamBody || !options.httpStatus || options.httpStatus <= 0 ? void 0 : options.httpStatus;
8102
8111
  this.suggestions = options.suggestions ? [...options.suggestions] : [];
8103
8112
  this.fromStreamBody = options.fromStreamBody === true;
8113
+ this.gatewayStream = options.gatewayStream === true;
8104
8114
  }
8105
8115
  };
8106
8116
  function resolveCvmId(id) {
@@ -8118,12 +8128,13 @@ function buildLogUrl(baseUrl, options) {
8118
8128
  const sep = baseUrl.includes("?") ? "&" : "?";
8119
8129
  return params.length > 0 ? `${baseUrl}${sep}${params.join("&")}` : baseUrl;
8120
8130
  }
8121
- async function streamResponse(response, onData) {
8131
+ async function streamResponse(response, onData, markDelivered, ansi) {
8122
8132
  const reader = response.body?.getReader();
8123
8133
  if (!reader) throw new Error("No response body available for streaming");
8124
8134
  const decoder = new TextDecoder();
8125
8135
  let buffer = "";
8126
8136
  let finished = false;
8137
+ let delivered = false;
8127
8138
  try {
8128
8139
  while (true) {
8129
8140
  const { done, value } = await reader.read();
@@ -8135,7 +8146,9 @@ async function streamResponse(response, onData) {
8135
8146
  const content = line.replace(/\r?\n$/, "");
8136
8147
  if (content !== "[vmm heartbeat]" && content !== "[teepod heartbeat]") {
8137
8148
  throwTextStreamError(content);
8138
- onData(line);
8149
+ markDelivered?.();
8150
+ onData(applyAnsiPolicy(line, ansi));
8151
+ delivered = true;
8139
8152
  }
8140
8153
  newline = buffer.indexOf("\n");
8141
8154
  }
@@ -8146,13 +8159,16 @@ async function streamResponse(response, onData) {
8146
8159
  }
8147
8160
  if (buffer && buffer !== "[vmm heartbeat]" && buffer !== "[teepod heartbeat]") {
8148
8161
  throwTextStreamError(buffer);
8149
- onData(buffer);
8162
+ markDelivered?.();
8163
+ onData(applyAnsiPolicy(buffer, ansi));
8164
+ delivered = true;
8150
8165
  }
8151
8166
  } finally {
8152
8167
  if (!finished) await reader.cancel().catch(() => {
8153
8168
  });
8154
8169
  reader.releaseLock();
8155
8170
  }
8171
+ return delivered;
8156
8172
  }
8157
8173
  async function throwResponseError(response) {
8158
8174
  const body = await response.text();
@@ -8165,16 +8181,35 @@ async function throwResponseError(response) {
8165
8181
  const suggestions = Array.isArray(envelope.suggestions) ? envelope.suggestions.filter((item) => typeof item === "string") : [];
8166
8182
  throw new LogAccessError({
8167
8183
  code: typeof envelope.error_code === "string" ? envelope.error_code : void 0,
8168
- message: typeof envelope.message === "string" ? envelope.message : `HTTP ${response.status} ${response.statusText}`,
8184
+ message: typeof envelope.message === "string" ? envelope.message : `HTTP ${response.status}`,
8169
8185
  httpStatus: response.status,
8170
- suggestions
8186
+ suggestions,
8187
+ requestId: typeof envelope.request_id === "string" ? envelope.request_id : void 0,
8188
+ details: Array.isArray(envelope.details) ? envelope.details : void 0,
8189
+ links: Array.isArray(envelope.links) ? envelope.links : void 0
8171
8190
  });
8172
8191
  }
8192
+ function backoffDelayMs(attempt) {
8193
+ return Math.min(250 * 2 ** (Math.min(Math.max(attempt, 1), 6) - 1), 5e3);
8194
+ }
8173
8195
  function throwTextStreamError(line) {
8174
8196
  const match = /^\[error\] (ERR-17-\d{3}) (.*)$/.exec(line.trim());
8175
8197
  const code = match?.[1];
8176
8198
  const message = match?.[2];
8177
- if (code && message !== void 0) throw new LogAccessError({ code, message });
8199
+ if (code && message !== void 0) {
8200
+ throw new LogAccessError({
8201
+ code,
8202
+ message,
8203
+ gatewayStream: true
8204
+ });
8205
+ }
8206
+ }
8207
+ function throwIfTextBodyErrors(text) {
8208
+ throwIfGuestAgentError(text);
8209
+ for (const line of text.split(/\r?\n/)) throwTextStreamError(line);
8210
+ }
8211
+ function throwIfGatewayTextErrors(text) {
8212
+ for (const line of text.split(/\r?\n/)) throwTextStreamError(line);
8178
8213
  }
8179
8214
  function parseTimestampedMessage(message) {
8180
8215
  const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})) (.*)$/s.exec(
@@ -8189,13 +8224,9 @@ function parseTimestampedMessage(message) {
8189
8224
  message: match[2]
8190
8225
  };
8191
8226
  }
8192
- function formatFollowContainerEntry(entry, includeTimestamps) {
8193
- if (includeTimestamps) return { channel: entry.channel, message: entry.message };
8194
- const timestamp = parseTimestampedMessage(entry.message);
8195
- return {
8196
- channel: entry.channel,
8197
- message: timestamp.timestamp ? timestamp.message ?? "" : entry.message
8198
- };
8227
+ function formatFollowContainerEntry(entry, includeTimestamps, ansi) {
8228
+ const raw = includeTimestamps ? entry.message : parseTimestampedMessage(entry.message).timestamp ? parseTimestampedMessage(entry.message).message ?? "" : entry.message;
8229
+ return { channel: entry.channel, message: applyAnsiPolicy(raw, ansi) };
8199
8230
  }
8200
8231
  function guestAgentErrorMessage(text) {
8201
8232
  const trimmed = text.trim();
@@ -8211,6 +8242,18 @@ function guestAgentErrorMessage(text) {
8211
8242
  return void 0;
8212
8243
  }
8213
8244
  function throwIfGuestAgentError(text) {
8245
+ const taken = takeJsonObject(text);
8246
+ if (taken) {
8247
+ const parsed = taken.value;
8248
+ if (typeof parsed.error === "string" && parsed.channel === void 0 && parsed.message === void 0) {
8249
+ throw new LogAccessError({
8250
+ code: "ERR-17-009",
8251
+ message: parsed.error,
8252
+ fromStreamBody: true
8253
+ });
8254
+ }
8255
+ return;
8256
+ }
8214
8257
  const message = guestAgentErrorMessage(text);
8215
8258
  if (message !== void 0) {
8216
8259
  throw new LogAccessError({
@@ -8220,6 +8263,51 @@ function throwIfGuestAgentError(text) {
8220
8263
  });
8221
8264
  }
8222
8265
  }
8266
+ var ANSI_PATTERN = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])/g;
8267
+ function stripAnsi(text) {
8268
+ return text.replace(ANSI_PATTERN, "");
8269
+ }
8270
+ function applyAnsiPolicy(text, ansi) {
8271
+ return ansi ? text : stripAnsi(text);
8272
+ }
8273
+ function takeJsonObject(buffer) {
8274
+ let i = 0;
8275
+ while (i < buffer.length && /[\s]/.test(buffer[i])) i += 1;
8276
+ if (buffer[i] !== "{") return null;
8277
+ let depth = 0;
8278
+ let inString = false;
8279
+ let escaped = false;
8280
+ for (let j = i; j < buffer.length; j += 1) {
8281
+ const char = buffer[j];
8282
+ if (inString) {
8283
+ if (escaped) {
8284
+ escaped = false;
8285
+ continue;
8286
+ }
8287
+ if (char === "\\") {
8288
+ escaped = true;
8289
+ continue;
8290
+ }
8291
+ if (char === '"') inString = false;
8292
+ continue;
8293
+ }
8294
+ if (char === '"') {
8295
+ inString = true;
8296
+ continue;
8297
+ }
8298
+ if (char === "{") depth += 1;
8299
+ else if (char === "}") {
8300
+ depth -= 1;
8301
+ if (depth === 0) {
8302
+ return {
8303
+ value: JSON.parse(buffer.slice(i, j + 1)),
8304
+ rest: buffer.slice(j + 1)
8305
+ };
8306
+ }
8307
+ }
8308
+ }
8309
+ return null;
8310
+ }
8223
8311
  function parseStructuredLogLineToEntry(line) {
8224
8312
  const trimmed = line.trim();
8225
8313
  if (!trimmed) return null;
@@ -8240,10 +8328,14 @@ function parseStructuredLogLineToEntry(line) {
8240
8328
  throw new LogAccessError({
8241
8329
  code: parsed.error_code,
8242
8330
  message: typeof parsed.message === "string" ? parsed.message : "The log stream ended with an error.",
8243
- suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((item) => typeof item === "string") : []
8331
+ gatewayStream: true,
8332
+ suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((item) => typeof item === "string") : [],
8333
+ details: Array.isArray(parsed.details) ? parsed.details : void 0,
8334
+ links: Array.isArray(parsed.links) ? parsed.links : void 0,
8335
+ requestId: typeof parsed.request_id === "string" ? parsed.request_id : void 0
8244
8336
  });
8245
8337
  }
8246
- if (parsed.channel !== "stdout" && parsed.channel !== "stderr" || typeof parsed.message !== "string") {
8338
+ if (!LOG_CHANNELS.has(parsed.channel) || typeof parsed.message !== "string") {
8247
8339
  throw new LogAccessError({ message: "Invalid NDJSON log record." });
8248
8340
  }
8249
8341
  const entry = {
@@ -8256,9 +8348,24 @@ function parseStructuredLogLineToEntry(line) {
8256
8348
  }
8257
8349
  function parseStructuredLogsToEntries(input) {
8258
8350
  const entries = [];
8259
- for (const line of input.split(/\r?\n/)) {
8260
- const entry = parseStructuredLogLineToEntry(line);
8351
+ let buffer = input;
8352
+ while (buffer.length > 0) {
8353
+ const taken = takeJsonObject(buffer);
8354
+ if (!taken) {
8355
+ const newline = buffer.indexOf("\n");
8356
+ if (newline < 0) {
8357
+ const entry3 = parseStructuredLogLineToEntry(buffer);
8358
+ if (entry3) entries.push(entry3);
8359
+ break;
8360
+ }
8361
+ const entry2 = parseStructuredLogLineToEntry(buffer.slice(0, newline));
8362
+ if (entry2) entries.push(entry2);
8363
+ buffer = buffer.slice(newline + 1);
8364
+ continue;
8365
+ }
8366
+ const entry = parseStructuredLogLineToEntry(JSON.stringify(taken.value));
8261
8367
  if (entry) entries.push(entry);
8368
+ buffer = taken.rest;
8262
8369
  }
8263
8370
  return entries;
8264
8371
  }
@@ -8272,12 +8379,12 @@ async function streamNdjsonEntriesResponse(response, onEntry) {
8272
8379
  while (true) {
8273
8380
  const { done, value } = await reader.read();
8274
8381
  buffer += decoder.decode(value, { stream: !done });
8275
- let newline = buffer.indexOf("\n");
8276
- while (newline >= 0) {
8277
- const entry = parseStructuredLogLineToEntry(buffer.slice(0, newline));
8382
+ for (; ; ) {
8383
+ const taken = takeJsonObject(buffer);
8384
+ if (!taken) break;
8385
+ const entry = parseStructuredLogLineToEntry(JSON.stringify(taken.value));
8278
8386
  if (entry) onEntry(entry);
8279
- buffer = buffer.slice(newline + 1);
8280
- newline = buffer.indexOf("\n");
8387
+ buffer = taken.rest;
8281
8388
  }
8282
8389
  if (done) {
8283
8390
  finished = true;
@@ -8302,26 +8409,25 @@ function assertSupportedNodeLogOptions(options) {
8302
8409
  options.format === "ndjson" && "format=ndjson"
8303
8410
  ].filter((option) => Boolean(option));
8304
8411
  if (unsupported.length > 0) {
8305
- throw new Error(`${unsupported.join(", ")} not supported for serial/stdout/stderr logs`);
8306
- }
8307
- if (options.ansi && options.format === "ndjson") {
8308
- throw new LogAccessError({
8309
- code: "ERR-17-001",
8310
- message: "ansi is valid only with format=text"
8311
- });
8412
+ throw clientValidationError(
8413
+ `${unsupported.join(", ")} not supported for serial/stdout/stderr logs`
8414
+ );
8312
8415
  }
8313
8416
  }
8314
- async function getCvmInfoLogs(client, cvmId) {
8417
+ async function getCvmInfoLogs(client, cvmId, signal) {
8315
8418
  return await client.get(`/cvms/${cvmId}`, {
8316
- headers: { "X-Phala-Version": CVM_LOGS_INFO_API_VERSION }
8419
+ headers: { "X-Phala-Version": CVM_LOGS_INFO_API_VERSION },
8420
+ signal
8317
8421
  });
8318
8422
  }
8319
- async function getCvmLogEndpoint(client, id, channel) {
8423
+ async function getCvmLogEndpoint(client, id, channel, signal) {
8320
8424
  const cvmId = resolveCvmId(id);
8321
- const info = await getCvmInfoLogs(client, cvmId);
8425
+ const info = await getCvmInfoLogs(client, cvmId, signal);
8322
8426
  const endpoint = info.logs?.[channel];
8323
8427
  if (!endpoint) {
8324
- throw new Error(`No ${channel} log endpoint available for CVM '${cvmId}'`);
8428
+ throw new LogAccessError({
8429
+ message: `No ${channel} log endpoint available for CVM '${cvmId}'`
8430
+ });
8325
8431
  }
8326
8432
  return endpoint;
8327
8433
  }
@@ -8332,33 +8438,122 @@ function containerLogsDisabledError() {
8332
8438
  httpStatus: 409
8333
8439
  });
8334
8440
  }
8335
- async function getContainerLogEndpoint(client, id, containerName, matchContainerIdPrefix = true) {
8336
- const cvmId = resolveCvmId(id);
8337
- const info = await getCvmInfoLogs(client, cvmId);
8338
- if (info.public_logs === false) {
8339
- throw containerLogsDisabledError();
8441
+ var CONTAINER_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
8442
+ function clientValidationError(message) {
8443
+ return new LogAccessError({ code: "ERR-17-001", message });
8444
+ }
8445
+ function resolveTimes(since, until) {
8446
+ try {
8447
+ return resolveLogTimeWindow(since, until);
8448
+ } catch (error) {
8449
+ throw clientValidationError(error instanceof Error ? error.message : String(error));
8340
8450
  }
8341
- const composition = await client.get(`/cvms/${cvmId}/composition`);
8342
- if (!composition.containers?.length) {
8343
- throw new Error(`No containers found for CVM '${cvmId}'`);
8451
+ }
8452
+ function assertSafeContainerName(name) {
8453
+ if (!CONTAINER_NAME_RE.test(name) || name.includes("..")) {
8454
+ throw clientValidationError(
8455
+ `Invalid container name '${name}'. Use 1\u2013128 characters starting with a letter or digit, then letters, digits, '_', '.', and '-'.`
8456
+ );
8344
8457
  }
8345
- let containers = composition.containers;
8458
+ return name;
8459
+ }
8460
+ function assertContainerNameOption(name) {
8461
+ if (name) assertSafeContainerName(name);
8462
+ }
8463
+ function throwIfAborted(signal) {
8464
+ if (!signal?.aborted) return;
8465
+ const error = new Error("This operation was aborted");
8466
+ error.name = "AbortError";
8467
+ throw error;
8468
+ }
8469
+ function untilReached(until, cursorSince) {
8470
+ if (until === void 0) return false;
8471
+ if (cursorSince !== void 0 && cursorSince >= until) return true;
8472
+ return Math.floor(Date.now() / 1e3) >= until;
8473
+ }
8474
+ function joinContainerLogUrl(base2, name, authQuery) {
8475
+ const trimmed = base2.replace(/\/$/, "");
8476
+ const slug = assertSafeContainerName(name);
8477
+ const url = `${trimmed}/${slug}`;
8478
+ if (!authQuery) return url;
8479
+ return url.includes("?") ? `${url}&${authQuery}` : `${url}?${authQuery}`;
8480
+ }
8481
+ function reconnectSinceValue(cursorSince, first200Second, callerSince) {
8482
+ if (cursorSince !== void 0) return cursorSince;
8483
+ if (callerSince !== void 0) return callerSince;
8484
+ return first200Second;
8485
+ }
8486
+ function exactContainerNameMatch(container, name) {
8487
+ return container.names.some((n) => n === name || n === `/${name}`);
8488
+ }
8489
+ function containerSlug(container, fallback) {
8490
+ return container.names[0]?.replace(/^\//, "") ?? container.id ?? fallback;
8491
+ }
8492
+ async function resolveContainerSlug(client, id, containerName, matchContainerIdPrefix = true, signal) {
8493
+ throwIfAborted(signal);
8494
+ assertContainerNameOption(containerName);
8495
+ const cvmId = resolveCvmId(id);
8496
+ const composition = await client.get(`/cvms/${cvmId}/composition`, {
8497
+ signal
8498
+ });
8499
+ const containers = composition.containers ?? [];
8500
+ const compositionError = typeof composition.error === "string" && composition.error ? composition.error : void 0;
8346
8501
  if (containerName) {
8347
- containers = containers.filter((c) => {
8348
- const matchedByName = c.names.some((n) => n === containerName || n === `/${containerName}`);
8349
- if (matchedByName) return true;
8350
- if (!matchContainerIdPrefix) return false;
8351
- return c.id.startsWith(containerName);
8352
- });
8353
- if (!containers.length) {
8354
- throw new Error(`Container '${containerName}' not found in CVM '${cvmId}'`);
8502
+ const exact = containers.filter((item) => exactContainerNameMatch(item, containerName));
8503
+ if (exact[0]) return containerName;
8504
+ if (matchContainerIdPrefix) {
8505
+ const prefixed = containers.filter((item) => item.id.startsWith(containerName));
8506
+ if (prefixed.length > 1) {
8507
+ throw clientValidationError(
8508
+ `Ambiguous container prefix '${containerName}': ${prefixed.map((item) => item.names[0]?.replace(/^\//, "") ?? item.id).join(", ")}`
8509
+ );
8510
+ }
8511
+ if (prefixed[0]) return containerSlug(prefixed[0], containerName);
8512
+ }
8513
+ if (containers.length > 0) {
8514
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8515
+ }
8516
+ if (compositionError) {
8517
+ throw new LogAccessError({ message: compositionError });
8355
8518
  }
8519
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8356
8520
  }
8357
- const container = containers.find((c) => c.log_endpoint);
8358
- if (!container?.log_endpoint) {
8359
- throw new Error(`No log endpoints available for CVM '${cvmId}'`);
8521
+ if (compositionError) {
8522
+ throw new LogAccessError({ message: compositionError });
8360
8523
  }
8361
- return container.log_endpoint;
8524
+ if (!containers.length) {
8525
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8526
+ }
8527
+ const fallback = containers[0];
8528
+ if (!fallback) {
8529
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8530
+ }
8531
+ return containerSlug(fallback, "app");
8532
+ }
8533
+ async function loadCvmLogInfo(client, id, signal) {
8534
+ const info = await getCvmInfoLogs(client, resolveCvmId(id), signal);
8535
+ if (info.public_logs === false) {
8536
+ throw containerLogsDisabledError();
8537
+ }
8538
+ return info;
8539
+ }
8540
+ function urlFromLogInfo(info, slug, cvmId) {
8541
+ const base2 = info.logs?.container_log_base ?? null;
8542
+ if (!base2) {
8543
+ throw new LogAccessError({ message: `No log endpoints available for CVM '${cvmId}'` });
8544
+ }
8545
+ return joinContainerLogUrl(base2, slug, info.logs?.auth_query);
8546
+ }
8547
+ async function getContainerLogEndpoint(client, id, containerName, matchContainerIdPrefix = true, signal) {
8548
+ const info = await loadCvmLogInfo(client, id, signal);
8549
+ const slug = await resolveContainerSlug(
8550
+ client,
8551
+ id,
8552
+ containerName,
8553
+ matchContainerIdPrefix,
8554
+ signal
8555
+ );
8556
+ return urlFromLogInfo(info, slug, resolveCvmId(id));
8362
8557
  }
8363
8558
  function waitForReconnect(signal, delayMs) {
8364
8559
  if (signal?.aborted) return Promise.resolve();
@@ -8386,88 +8581,122 @@ function getErrorHttpStatus(error) {
8386
8581
  return void 0;
8387
8582
  }
8388
8583
  var EMPTY_STREAM_END_MESSAGE = "log stream keeps ending without new output; the container may have stopped";
8389
- async function followLogRequests(resolveUrl, consume, signal, refreshCvm, trackEmptyEnds = false) {
8584
+ var EMPTY_STREAM_QUIET_MS = 1e4;
8585
+ async function followLogRequests(client, resolveUrl, consume, signal, refreshCvm, trackEmptyEnds = false, onConnected, shouldStop) {
8390
8586
  let failureCount = 0;
8391
8587
  let expiredRetries = 0;
8392
8588
  let emptyEnds = 0;
8589
+ let lastConnectionStartedAt = 0;
8590
+ let haveStarted = false;
8393
8591
  while (!signal?.aborted) {
8592
+ if (haveStarted) {
8593
+ const waitMs = 1e3 - (performance.now() - lastConnectionStartedAt);
8594
+ if (waitMs > 0) await waitForReconnect(signal, waitMs);
8595
+ if (signal?.aborted) return;
8596
+ }
8597
+ lastConnectionStartedAt = performance.now();
8598
+ haveStarted = true;
8599
+ let deliveredThisConnection = false;
8600
+ const markDelivered = () => {
8601
+ deliveredThisConnection = true;
8602
+ };
8394
8603
  try {
8395
8604
  const url = await resolveUrl();
8396
8605
  if (signal?.aborted) return;
8397
- const response = await fetch(url, { signal });
8606
+ const response = await logFetch(client, url, signal);
8398
8607
  if (!response.ok) await throwResponseError(response);
8399
- failureCount = 0;
8400
- const delivered = await consume(response) ?? true;
8608
+ onConnected?.();
8609
+ const connectedAt = Date.now();
8610
+ const delivered = await consume(response, markDelivered) ?? deliveredThisConnection;
8401
8611
  expiredRetries = 0;
8612
+ if (delivered) {
8613
+ failureCount = 0;
8614
+ }
8615
+ if (shouldStop?.()) return;
8402
8616
  if (signal?.aborted) return;
8403
- if (trackEmptyEnds) {
8404
- if (delivered) {
8405
- emptyEnds = 0;
8406
- } else {
8407
- emptyEnds += 1;
8408
- if (emptyEnds >= 5) {
8409
- throw new LogAccessError({
8410
- message: EMPTY_STREAM_END_MESSAGE,
8411
- fromStreamBody: true
8412
- });
8413
- }
8414
- await waitForReconnect(signal, Math.min(250 * 2 ** (emptyEnds - 1), 5e3));
8617
+ if (delivered) {
8618
+ emptyEnds = 0;
8619
+ } else if (Date.now() - connectedAt >= EMPTY_STREAM_QUIET_MS) {
8620
+ emptyEnds = 0;
8621
+ } else {
8622
+ emptyEnds += 1;
8623
+ if (trackEmptyEnds && emptyEnds >= 5) {
8624
+ throw new LogAccessError({
8625
+ message: EMPTY_STREAM_END_MESSAGE,
8626
+ fromStreamBody: true
8627
+ });
8415
8628
  }
8629
+ await waitForReconnect(signal, backoffDelayMs(emptyEnds));
8416
8630
  }
8417
8631
  } catch (error) {
8418
8632
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
8419
8633
  return;
8420
8634
  }
8421
- let retryError = error;
8635
+ const retryError = error;
8422
8636
  if (error instanceof LogAccessError && error.fromStreamBody) {
8423
8637
  throw error;
8424
8638
  }
8425
- if (error instanceof LogAccessError && error.code === "ERR-17-003") {
8639
+ emptyEnds = 0;
8640
+ if (deliveredThisConnection) {
8641
+ expiredRetries = 0;
8642
+ }
8643
+ if (error instanceof LogAccessError && !error.gatewayStream && error.code === "ERR-17-003") {
8426
8644
  expiredRetries += 1;
8427
8645
  if (expiredRetries > 3) throw error;
8428
- try {
8429
- await refreshCvm?.();
8430
- continue;
8431
- } catch (refreshError) {
8432
- retryError = refreshError;
8433
- }
8646
+ continue;
8434
8647
  }
8435
8648
  const status = getErrorHttpStatus(retryError);
8436
- if (status !== void 0 && status < 500) throw retryError;
8437
- if (retryError instanceof LogAccessError && status === void 0) {
8649
+ const code = retryError instanceof LogAccessError ? retryError.code : void 0;
8650
+ const gatewayStream = retryError instanceof LogAccessError && retryError.gatewayStream;
8651
+ if (!gatewayStream && code === "ERR-17-002") {
8652
+ } else if (gatewayStream || status === 429 || status !== void 0 && status >= 500 || retryError instanceof TypeError || retryError instanceof UnknownError) {
8653
+ } else {
8438
8654
  throw retryError;
8439
8655
  }
8656
+ if (deliveredThisConnection) {
8657
+ failureCount = 0;
8658
+ }
8440
8659
  failureCount += 1;
8441
8660
  if (failureCount >= 5) throw retryError;
8442
- const delayMs = Math.min(250 * 2 ** (failureCount - 1), 5e3);
8661
+ const delayMs = backoffDelayMs(failureCount);
8443
8662
  await waitForReconnect(signal, delayMs);
8444
8663
  }
8445
8664
  }
8446
8665
  }
8447
8666
  async function fetchCvmChannelLogs(client, id, channel, options = {}) {
8667
+ throwIfAborted(options.signal);
8448
8668
  assertSupportedNodeLogOptions(options);
8449
- const times = resolveLogTimeWindow(options.since, options.until);
8450
- const baseUrl = await getCvmLogEndpoint(client, id, channel);
8669
+ const times = resolveTimes(options.since, options.until);
8670
+ const baseUrl = await getCvmLogEndpoint(client, id, channel, options.signal);
8451
8671
  const url = buildLogUrl(baseUrl, {
8452
8672
  since: times.since,
8453
8673
  until: times.until,
8454
8674
  tail: options.tail,
8455
8675
  ansi: options.ansi
8456
8676
  });
8457
- const response = await fetch(url, { signal: options.signal });
8677
+ const response = await logFetch(client, url, options.signal);
8458
8678
  if (!response.ok) await throwResponseError(response);
8459
- return response.text();
8679
+ const text = await response.text();
8680
+ throwIfGatewayTextErrors(text);
8681
+ return applyAnsiPolicy(
8682
+ text.split(/(?<=\n)/).filter((line) => {
8683
+ const content = line.replace(/\r?\n$/, "");
8684
+ return content !== "[vmm heartbeat]" && content !== "[teepod heartbeat]";
8685
+ }).join(""),
8686
+ options.ansi
8687
+ );
8460
8688
  }
8461
8689
  async function streamCvmChannelLogs(client, id, channel, onData, options = {}, signal) {
8690
+ throwIfAborted(signal ?? options.signal);
8462
8691
  assertSupportedNodeLogOptions(options);
8463
8692
  const abort = signal ?? options.signal;
8464
- const times = resolveLogTimeWindow(options.since, options.until);
8693
+ const times = resolveTimes(options.since, options.until);
8465
8694
  let firstRequest = true;
8466
8695
  await followLogRequests(
8696
+ client,
8467
8697
  async () => {
8468
- const baseUrl = await getCvmLogEndpoint(client, id, channel);
8698
+ const baseUrl = await getCvmLogEndpoint(client, id, channel, abort);
8469
8699
  const tail = firstRequest ? options.tail : 0;
8470
- firstRequest = false;
8471
8700
  return buildLogUrl(baseUrl, {
8472
8701
  since: times.since,
8473
8702
  until: times.until,
@@ -8476,40 +8705,50 @@ async function streamCvmChannelLogs(client, id, channel, onData, options = {}, s
8476
8705
  ansi: options.ansi
8477
8706
  });
8478
8707
  },
8479
- (response) => streamResponse(response, onData),
8708
+ (response, markDelivered) => streamResponse(response, onData, markDelivered, options.ansi),
8480
8709
  abort,
8481
- async () => {
8482
- await getCvmInfoLogs(client, resolveCvmId(id));
8710
+ void 0,
8711
+ false,
8712
+ () => {
8713
+ firstRequest = false;
8483
8714
  }
8484
8715
  );
8485
8716
  }
8486
8717
  async function fetchContainerLogsEntries(client, id, options = {}) {
8487
- const times = resolveLogTimeWindow(options.since, options.until);
8718
+ throwIfAborted(options.signal);
8719
+ assertContainerNameOption(options.container);
8720
+ const times = resolveTimes(options.since, options.until);
8488
8721
  const baseUrl = await getContainerLogEndpoint(
8489
8722
  client,
8490
8723
  id,
8491
8724
  options.container,
8492
- options.matchContainerIdPrefix ?? true
8725
+ options.matchContainerIdPrefix ?? true,
8726
+ options.signal
8493
8727
  );
8494
8728
  const url = buildLogUrl(baseUrl, {
8495
8729
  ...times,
8496
8730
  tail: options.tail,
8497
8731
  timestamps: options.timestamps,
8498
- ansi: options.ansi,
8499
8732
  format: options.format ?? "ndjson"
8500
8733
  });
8501
- const response = await fetch(url, { signal: options.signal });
8734
+ const response = await logFetch(client, url, options.signal);
8502
8735
  if (!response.ok) await throwResponseError(response);
8503
- return parseStructuredLogsToEntries(await response.text());
8736
+ return parseStructuredLogsToEntries(await response.text()).map((entry) => ({
8737
+ ...entry,
8738
+ message: applyAnsiPolicy(entry.message, options.ansi)
8739
+ }));
8504
8740
  }
8505
8741
  async function fetchContainerLogs(client, id, options = {}) {
8742
+ throwIfAborted(options.signal);
8743
+ assertContainerNameOption(options.container);
8506
8744
  if (options.format === "text") {
8507
- const times = resolveLogTimeWindow(options.since, options.until);
8745
+ const times = resolveTimes(options.since, options.until);
8508
8746
  const baseUrl = await getContainerLogEndpoint(
8509
8747
  client,
8510
8748
  id,
8511
8749
  options.container,
8512
- options.matchContainerIdPrefix ?? true
8750
+ options.matchContainerIdPrefix ?? true,
8751
+ options.signal
8513
8752
  );
8514
8753
  const url = buildLogUrl(baseUrl, {
8515
8754
  ...times,
@@ -8518,36 +8757,44 @@ async function fetchContainerLogs(client, id, options = {}) {
8518
8757
  ansi: options.ansi,
8519
8758
  format: "text"
8520
8759
  });
8521
- const response = await fetch(url, { signal: options.signal });
8760
+ const response = await logFetch(client, url, options.signal);
8522
8761
  if (!response.ok) await throwResponseError(response);
8523
8762
  const text = await response.text();
8524
- throwIfGuestAgentError(text);
8525
- return text;
8763
+ throwIfTextBodyErrors(text);
8764
+ return applyAnsiPolicy(text, options.ansi);
8526
8765
  }
8527
8766
  const entries = await fetchContainerLogsEntries(client, id, {
8528
8767
  ...options,
8529
8768
  format: "ndjson"
8530
8769
  });
8531
- return entries.map((entry) => entry.message === "" ? "\n" : entry.message).join("");
8770
+ return entries.map((entry) => entry.message).join("");
8532
8771
  }
8533
8772
  async function streamContainerLogsEntries(client, id, onEntry, options = {}, signal) {
8534
8773
  const abort = signal ?? options.signal;
8535
- const times = resolveLogTimeWindow(options.since, options.until);
8536
- const cursor = { since: times.since, boundaryCounts: /* @__PURE__ */ new Map() };
8774
+ throwIfAborted(abort);
8775
+ assertContainerNameOption(options.container);
8776
+ const times = resolveTimes(options.since, options.until);
8777
+ const cursor = { boundaryCounts: /* @__PURE__ */ new Map() };
8537
8778
  let replayCounts = /* @__PURE__ */ new Map();
8538
8779
  let firstRequest = true;
8780
+ let first200Second;
8781
+ let slug;
8539
8782
  const buildRequestUrl = async () => {
8540
- const baseUrl = await getContainerLogEndpoint(
8541
- client,
8542
- id,
8543
- options.container,
8544
- options.matchContainerIdPrefix ?? true
8545
- );
8546
- const tail = firstRequest ? options.tail : void 0;
8547
- firstRequest = false;
8783
+ const info = await loadCvmLogInfo(client, id, abort);
8784
+ if (slug === void 0) {
8785
+ slug = await resolveContainerSlug(
8786
+ client,
8787
+ id,
8788
+ options.container,
8789
+ options.matchContainerIdPrefix ?? true,
8790
+ abort
8791
+ );
8792
+ }
8793
+ const baseUrl = urlFromLogInfo(info, slug, resolveCvmId(id));
8794
+ const tail = firstRequest ? options.tail : "all";
8548
8795
  replayCounts = new Map(cursor.boundaryCounts);
8549
8796
  return buildLogUrl(baseUrl, {
8550
- since: cursor.since,
8797
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8551
8798
  until: times.until,
8552
8799
  tail,
8553
8800
  follow: true,
@@ -8556,20 +8803,23 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8556
8803
  });
8557
8804
  };
8558
8805
  await followLogRequests(
8806
+ client,
8559
8807
  buildRequestUrl,
8560
- async (response) => {
8808
+ async (response, markDelivered) => {
8561
8809
  let delivered = false;
8562
8810
  await streamNdjsonEntriesResponse(response, (entry) => {
8563
8811
  const timestamp = parseTimestampedMessage(entry.message);
8564
8812
  if (timestamp.second === void 0 || !timestamp.timestamp) {
8565
8813
  delivered = true;
8566
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8814
+ markDelivered();
8815
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8567
8816
  return;
8568
8817
  }
8569
8818
  const key = JSON.stringify([entry.channel, entry.message]);
8570
8819
  if (cursor.boundarySecond !== void 0 && timestamp.second < cursor.boundarySecond) {
8571
8820
  delivered = true;
8572
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8821
+ markDelivered();
8822
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8573
8823
  return;
8574
8824
  }
8575
8825
  if (timestamp.second === cursor.boundarySecond) {
@@ -8585,18 +8835,22 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8585
8835
  cursor.since = Math.max(cursor.since ?? timestamp.second, timestamp.second);
8586
8836
  cursor.boundaryCounts.set(key, (cursor.boundaryCounts.get(key) ?? 0) + 1);
8587
8837
  delivered = true;
8588
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8838
+ markDelivered();
8839
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8589
8840
  });
8590
8841
  return delivered;
8591
8842
  },
8592
8843
  abort,
8593
- async () => {
8594
- await getCvmInfoLogs(client, resolveCvmId(id));
8844
+ void 0,
8845
+ true,
8846
+ () => {
8847
+ firstRequest = false;
8848
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8595
8849
  },
8596
- true
8850
+ () => untilReached(times.until, cursor.since)
8597
8851
  );
8598
8852
  }
8599
- async function streamContainerText(response, onData) {
8853
+ async function streamContainerText(response, onData, ansi) {
8600
8854
  const reader = response.body?.getReader();
8601
8855
  if (!reader) throw new Error("No response body available for streaming");
8602
8856
  const decoder = new TextDecoder();
@@ -8611,8 +8865,9 @@ async function streamContainerText(response, onData) {
8611
8865
  while (newline >= 0) {
8612
8866
  const line = buffer.slice(0, newline);
8613
8867
  buffer = buffer.slice(newline + 1);
8614
- throwIfGuestAgentError(line);
8615
- onData(line + "\n");
8868
+ if (!delivered) throwIfGuestAgentError(line);
8869
+ throwTextStreamError(line);
8870
+ onData(applyAnsiPolicy(line + "\n", ansi));
8616
8871
  delivered = true;
8617
8872
  newline = buffer.indexOf("\n");
8618
8873
  }
@@ -8622,8 +8877,9 @@ async function streamContainerText(response, onData) {
8622
8877
  }
8623
8878
  }
8624
8879
  if (buffer) {
8625
- throwIfGuestAgentError(buffer);
8626
- onData(buffer);
8880
+ if (!delivered) throwIfGuestAgentError(buffer);
8881
+ throwTextStreamError(buffer);
8882
+ onData(applyAnsiPolicy(buffer, ansi));
8627
8883
  delivered = true;
8628
8884
  }
8629
8885
  } finally {
@@ -8636,45 +8892,101 @@ async function streamContainerText(response, onData) {
8636
8892
  async function streamContainerLogs(client, id, onData, options = {}, signal) {
8637
8893
  if (options.format === "text") {
8638
8894
  const abort = signal ?? options.signal;
8639
- const times = resolveLogTimeWindow(options.since, options.until);
8895
+ throwIfAborted(abort);
8896
+ assertContainerNameOption(options.container);
8897
+ const times = resolveTimes(options.since, options.until);
8898
+ const cursor = { boundaryCounts: /* @__PURE__ */ new Map() };
8899
+ let replayCounts = /* @__PURE__ */ new Map();
8640
8900
  let firstRequest = true;
8901
+ let first200Second;
8902
+ let slug;
8641
8903
  await followLogRequests(
8904
+ client,
8642
8905
  async () => {
8643
- const baseUrl = await getContainerLogEndpoint(
8644
- client,
8645
- id,
8646
- options.container,
8647
- options.matchContainerIdPrefix ?? true
8648
- );
8649
- const tail = firstRequest ? options.tail : void 0;
8650
- firstRequest = false;
8906
+ const info = await loadCvmLogInfo(client, id, abort);
8907
+ if (slug === void 0) {
8908
+ slug = await resolveContainerSlug(
8909
+ client,
8910
+ id,
8911
+ options.container,
8912
+ options.matchContainerIdPrefix ?? true,
8913
+ abort
8914
+ );
8915
+ }
8916
+ const baseUrl = urlFromLogInfo(info, slug, resolveCvmId(id));
8917
+ const tail = firstRequest ? options.tail : "all";
8918
+ replayCounts = new Map(cursor.boundaryCounts);
8651
8919
  return buildLogUrl(baseUrl, {
8652
- ...times,
8920
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8921
+ until: times.until,
8653
8922
  tail,
8654
8923
  follow: true,
8655
- timestamps: options.timestamps,
8924
+ timestamps: true,
8656
8925
  ansi: options.ansi,
8657
8926
  format: "text"
8658
8927
  });
8659
8928
  },
8660
- (response) => streamContainerText(response, onData),
8929
+ async (response, markDelivered) => {
8930
+ let delivered = false;
8931
+ await streamContainerText(
8932
+ response,
8933
+ (line) => {
8934
+ const raw = line.endsWith("\n") ? line.slice(0, -1) : line;
8935
+ throwTextStreamError(raw);
8936
+ const timestamp = parseTimestampedMessage(raw);
8937
+ const out = applyAnsiPolicy(
8938
+ options.timestamps ? line : timestamp.timestamp ? `${timestamp.message ?? ""}${line.endsWith("\n") ? "\n" : ""}` : line,
8939
+ options.ansi
8940
+ );
8941
+ if (timestamp.second === void 0 || !timestamp.timestamp) {
8942
+ delivered = true;
8943
+ markDelivered();
8944
+ onData(out);
8945
+ return;
8946
+ }
8947
+ const key = raw;
8948
+ if (cursor.boundarySecond !== void 0 && timestamp.second < cursor.boundarySecond) {
8949
+ delivered = true;
8950
+ markDelivered();
8951
+ onData(out);
8952
+ return;
8953
+ }
8954
+ if (timestamp.second === cursor.boundarySecond) {
8955
+ const replayCount = replayCounts.get(key) ?? 0;
8956
+ if (replayCount > 0) {
8957
+ replayCounts.set(key, replayCount - 1);
8958
+ return;
8959
+ }
8960
+ } else if (cursor.boundarySecond === void 0 || timestamp.second > cursor.boundarySecond) {
8961
+ cursor.boundarySecond = timestamp.second;
8962
+ cursor.boundaryCounts.clear();
8963
+ }
8964
+ cursor.since = Math.max(cursor.since ?? timestamp.second, timestamp.second);
8965
+ cursor.boundaryCounts.set(key, (cursor.boundaryCounts.get(key) ?? 0) + 1);
8966
+ delivered = true;
8967
+ markDelivered();
8968
+ onData(out);
8969
+ },
8970
+ options.ansi
8971
+ );
8972
+ return delivered;
8973
+ },
8661
8974
  abort,
8662
- async () => {
8663
- await getCvmInfoLogs(client, resolveCvmId(id));
8975
+ void 0,
8976
+ true,
8977
+ () => {
8978
+ firstRequest = false;
8979
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8664
8980
  },
8665
- true
8981
+ () => untilReached(times.until, cursor.since)
8666
8982
  );
8667
8983
  return;
8668
8984
  }
8669
- return streamContainerLogsEntries(
8670
- client,
8671
- id,
8672
- (entry) => onData(entry.message === "" ? "\n" : entry.message),
8673
- options,
8674
- signal
8675
- );
8985
+ return streamContainerLogsEntries(client, id, (entry) => onData(entry.message), options, signal);
8676
8986
  }
8677
8987
  async function fetchCvmLogs(client, id, source, options = {}) {
8988
+ throwIfAborted(options.signal);
8989
+ if (source.type === "container") assertContainerNameOption(source.name);
8678
8990
  if (source.type === "node") {
8679
8991
  return fetchCvmChannelLogs(client, id, source.channel, options);
8680
8992
  }
@@ -8692,15 +9004,22 @@ async function fetchCvmLogs(client, id, source, options = {}) {
8692
9004
  });
8693
9005
  }
8694
9006
  async function* followCvmLogs(client, id, source, options = {}) {
9007
+ if (source.type === "container") assertContainerNameOption(source.name);
8695
9008
  const pending = [];
8696
9009
  let wake;
8697
9010
  let done = false;
8698
9011
  let error;
9012
+ const abort = new AbortController();
9013
+ if (options.signal) {
9014
+ if (options.signal.aborted) abort.abort();
9015
+ else options.signal.addEventListener("abort", () => abort.abort(), { once: true });
9016
+ }
9017
+ const signal = abort.signal;
8699
9018
  const push = (item) => {
8700
9019
  pending.push(item);
8701
9020
  wake?.();
8702
9021
  };
8703
- const run = source.type === "node" ? streamCvmChannelLogs(client, id, source.channel, push, options, options.signal) : options.format === "text" ? streamContainerLogs(
9022
+ const run = source.type === "node" ? streamCvmChannelLogs(client, id, source.channel, push, options, signal) : options.format === "text" ? streamContainerLogs(
8704
9023
  client,
8705
9024
  id,
8706
9025
  (data) => push(data),
@@ -8709,7 +9028,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8709
9028
  container: source.name,
8710
9029
  matchContainerIdPrefix: source.matchContainerIdPrefix
8711
9030
  },
8712
- options.signal
9031
+ signal
8713
9032
  ) : streamContainerLogsEntries(
8714
9033
  client,
8715
9034
  id,
@@ -8719,7 +9038,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8719
9038
  container: source.name,
8720
9039
  matchContainerIdPrefix: source.matchContainerIdPrefix
8721
9040
  },
8722
- options.signal
9041
+ signal
8723
9042
  );
8724
9043
  void run.then(
8725
9044
  () => {
@@ -8732,16 +9051,20 @@ async function* followCvmLogs(client, id, source, options = {}) {
8732
9051
  wake?.();
8733
9052
  }
8734
9053
  );
8735
- while (!done || pending.length > 0) {
8736
- if (pending.length > 0) {
8737
- yield pending.shift();
8738
- continue;
9054
+ try {
9055
+ while (!done || pending.length > 0) {
9056
+ if (pending.length > 0) {
9057
+ yield pending.shift();
9058
+ continue;
9059
+ }
9060
+ await new Promise((resolve) => {
9061
+ wake = resolve;
9062
+ });
8739
9063
  }
8740
- await new Promise((resolve) => {
8741
- wake = resolve;
8742
- });
9064
+ if (error) throw error;
9065
+ } finally {
9066
+ abort.abort();
8743
9067
  }
8744
- if (error) throw error;
8745
9068
  }
8746
9069
 
8747
9070
  // src/parse_dotenv.ts