deno_node 0.182.0

Node compatibility for Deno
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2018-2026 the Deno authors. MIT license.
// Copyright Joyent, Inc. and Node.js contributors. All rights reserved. MIT license.
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

// deno-lint-ignore-file no-process-global

import { primordials } from "ext:core/mod.js";
const {
  ArrayPrototypeSome,
  FunctionPrototypeCall,
  ObjectEntries,
  ObjectPrototypeHasOwnProperty,
  ObjectPrototypeIsPrototypeOf,
  ObjectSetPrototypeOf,
  RegExpPrototypeExec,
  SafeMap,
  SafeMapIterator,
  SafeRegExp,
  SafeSet,
  SafeSetIterator,
  SetPrototypeAdd,
  SetPrototypeDelete,
  SetPrototypeGetSize,
  StringPrototypeSplit,
  StringPrototypeToLowerCase,
} = primordials;

import {
  ERR_INVALID_FD,
  ERR_TTY_INIT_FAILED,
  errnoException,
} from "ext:deno_node/internal/errors.ts";
import { validateInteger } from "ext:deno_node/internal/validators.mjs";
import { op_tty_check_fd_permission, TTY } from "ext:core/ops";
import { Socket } from "node:net";
import {
  clearLine,
  clearScreenDown,
  cursorTo,
  moveCursor,
} from "ext:deno_node/internal/readline/callbacks.mjs";
import { release } from "node:os";

// Color depth constants
const COLORS_2 = 1;
const COLORS_16 = 4;
const COLORS_256 = 8;
const COLORS_16M = 24;

// Terminal environments supporting specific color depths
const TERM_ENVS = {
  "eterm": COLORS_16,
  "cons25": COLORS_16,
  "console": COLORS_16,
  "cygwin": COLORS_16,
  "dtterm": COLORS_16,
  "gnome": COLORS_16,
  "hurd": COLORS_16,
  "jfbterm": COLORS_16,
  "konsole": COLORS_16,
  "kterm": COLORS_16,
  "mlterm": COLORS_16,
  "mosh": COLORS_16M,
  "putty": COLORS_16,
  "st": COLORS_16,
  "rxvt-unicode-24bit": COLORS_16M,
  "terminator": COLORS_16M,
  "xterm-kitty": COLORS_16M,
};

// CI environments and their color support
const CI_ENVS_MAP = new SafeMap(ObjectEntries({
  APPVEYOR: COLORS_256,
  BUILDKITE: COLORS_256,
  CIRCLECI: COLORS_16M,
  DRONE: COLORS_256,
  GITEA_ACTIONS: COLORS_16M,
  GITHUB_ACTIONS: COLORS_16M,
  GITLAB_CI: COLORS_256,
  TRAVIS: COLORS_256,
}));

// Regular expressions for terminal types
const TERM_ENVS_REG_EXP = [
  new SafeRegExp("ansi"),
  new SafeRegExp("color"),
  new SafeRegExp("linux"),
  new SafeRegExp("direct"),
  new SafeRegExp("^con[0-9]*x[0-9]"),
  new SafeRegExp("^rxvt"),
  new SafeRegExp("^screen"),
  new SafeRegExp("^xterm"),
  new SafeRegExp("^vt100"),
  new SafeRegExp("^vt220"),
];

let warned = false;
function warnOnDeactivatedColors(env) {
  if (warned) {
    return;
  }
  let name = "";
  if (env.NODE_DISABLE_COLORS !== undefined && env.NODE_DISABLE_COLORS !== "") {
    name = "NODE_DISABLE_COLORS";
  }
  if (env.NO_COLOR !== undefined && env.NO_COLOR !== "") {
    if (name !== "") {
      name += "' and '";
    }
    name += "NO_COLOR";
  }

  if (name !== "") {
    process.emitWarning(
      "The '" + name +
        "' env is ignored due to the 'FORCE_COLOR' env being set.",
      "Warning",
    );
    warned = true;
  }
}

let OSRelease;

/**
 * @param {Record<string, string>} [env]
 * @returns {1 | 4 | 8 | 24}
 */
export function getColorDepth(env = process.env) {
  // Use level 0-3 to support the same levels as `chalk` does.
  if (env.FORCE_COLOR !== undefined) {
    switch (env.FORCE_COLOR) {
      case "":
      case "1":
      case "true":
        warnOnDeactivatedColors(env);
        return COLORS_16;
      case "2":
        warnOnDeactivatedColors(env);
        return COLORS_256;
      case "3":
        warnOnDeactivatedColors(env);
        return COLORS_16M;
      default:
        return COLORS_2;
    }
  }

  if (
    (env.NODE_DISABLE_COLORS !== undefined &&
      env.NODE_DISABLE_COLORS !== "") ||
    (env.NO_COLOR !== undefined && env.NO_COLOR !== "") ||
    env.TERM === "dumb"
  ) {
    return COLORS_2;
  }

  if (process.platform === "win32") {
    if (OSRelease === undefined) {
      OSRelease = StringPrototypeSplit(release(), ".", 3);
    }
    if (+OSRelease[0] >= 10) {
      const build = +OSRelease[2];
      if (build >= 14931) {
        return COLORS_16M;
      }
      if (build >= 10586) {
        return COLORS_256;
      }
    }
    return COLORS_16;
  }

  if (env.TMUX) {
    return COLORS_16M;
  }

  // Azure DevOps
  if (
    ObjectPrototypeHasOwnProperty(env, "TF_BUILD") &&
    ObjectPrototypeHasOwnProperty(env, "AGENT_NAME")
  ) {
    return COLORS_16;
  }

  if (ObjectPrototypeHasOwnProperty(env, "CI")) {
    for (const { 0: envName, 1: colors } of new SafeMapIterator(CI_ENVS_MAP)) {
      if (ObjectPrototypeHasOwnProperty(env, envName)) {
        return colors;
      }
    }
    if (env.CI_NAME === "codeship") {
      return COLORS_256;
    }
    return COLORS_2;
  }

  if (ObjectPrototypeHasOwnProperty(env, "TEAMCITY_VERSION")) {
    return RegExpPrototypeExec(
        new SafeRegExp("^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)"),
        env.TEAMCITY_VERSION,
      ) !== null
      ? COLORS_16
      : COLORS_2;
  }

  switch (env.TERM_PROGRAM) {
    case "iTerm.app":
      if (
        !env.TERM_PROGRAM_VERSION ||
        RegExpPrototypeExec(
            new SafeRegExp("^[0-2]\\."),
            env.TERM_PROGRAM_VERSION,
          ) !== null
      ) {
        return COLORS_256;
      }
      return COLORS_16M;
    case "HyperTerm":
    case "MacTerm":
      return COLORS_16M;
    case "Apple_Terminal":
      return COLORS_256;
  }

  if (env.COLORTERM === "truecolor" || env.COLORTERM === "24bit") {
    return COLORS_16M;
  }

  if (env.TERM) {
    if (RegExpPrototypeExec(new SafeRegExp("truecolor"), env.TERM) !== null) {
      return COLORS_16M;
    }

    if (RegExpPrototypeExec(new SafeRegExp("^xterm-256"), env.TERM) !== null) {
      return COLORS_256;
    }

    const termEnv = StringPrototypeToLowerCase(env.TERM);

    if (TERM_ENVS[termEnv]) {
      return TERM_ENVS[termEnv];
    }
    if (
      ArrayPrototypeSome(
        TERM_ENVS_REG_EXP,
        (term) => RegExpPrototypeExec(term, termEnv) !== null,
      )
    ) {
      return COLORS_16;
    }
  }

  // Move 16 color COLORTERM below 16m and 256
  if (env.COLORTERM) {
    return COLORS_16;
  }

  return COLORS_2;
}

// Lazy SIGWINCH handling: only register the signal listener when at least one
// WriteStream has a "resize" listener, and unregister when none do. This avoids
// creating a persistent pending op that interferes with event loop exit / TLA
// stall detection. Uses Deno.addSignalListener directly to avoid circular
// dependency with node:process.
const sigwinchStreams = new SafeSet();
let sigwinchRegistered = false;

function onSigwinch() {
  for (const stream of new SafeSetIterator(sigwinchStreams)) {
    stream._refreshSize();
  }
}

function addSigwinchListener(stream) {
  SetPrototypeAdd(sigwinchStreams, stream);
  if (!sigwinchRegistered) {
    sigwinchRegistered = true;
    Deno.addSignalListener("SIGWINCH", onSigwinch);
  }
}

function removeSigwinchListener(stream) {
  SetPrototypeDelete(sigwinchStreams, stream);
  if (SetPrototypeGetSize(sigwinchStreams) === 0 && sigwinchRegistered) {
    sigwinchRegistered = false;
    Deno.removeSignalListener("SIGWINCH", onSigwinch);
  }
}

// WriteStream needs to be callable without `new` to match Node.js behavior.
function WriteStream(fd) {
  if (!ObjectPrototypeIsPrototypeOf(WriteStream.prototype, this)) {
    return new WriteStream(fd);
  }

  if (fd >> 0 !== fd || fd < 0) {
    throw new ERR_INVALID_FD(fd);
  }

  // Non-stdio fds require --allow-all
  op_tty_check_fd_permission(fd);

  const ctx = {};
  const tty = new TTY(fd, ctx);
  if (ctx.code !== undefined) {
    throw new ERR_TTY_INIT_FAILED(ctx);
  }

  FunctionPrototypeCall(Socket, this, {
    readableHighWaterMark: 0,
    handle: tty,
    manualStart: true,
  });

  // Prevents interleaved or dropped stdout/stderr output for terminals.
  // As noted in the following reference, local TTYs tend to be quite fast and
  // this behavior has become expected due historical functionality on OS X,
  // even though it was originally intended to change in v1.0.2 (Libuv 1.2.1).
  // Ref: https://github.com/nodejs/node/pull/1771#issuecomment-119351671
  this._handle.setBlocking(true);

  const winSize = [0, 0];
  const err = tty.getWindowSize(winSize);
  if (!err) {
    this.columns = winSize[0];
    this.rows = winSize[1];
  }
}

ObjectSetPrototypeOf(WriteStream.prototype, Socket.prototype);
ObjectSetPrototypeOf(WriteStream, Socket);

WriteStream.prototype.isTTY = true;

WriteStream.prototype.on = function on(event, listener) {
  FunctionPrototypeCall(Socket.prototype.on, this, event, listener);
  if (event === "resize" && this.listenerCount("resize") === 1) {
    addSigwinchListener(this);
  }
  return this;
};

WriteStream.prototype.addListener = function addListener(event, listener) {
  return this.on(event, listener);
};

WriteStream.prototype.removeListener = function removeListener(
  event,
  listener,
) {
  FunctionPrototypeCall(Socket.prototype.removeListener, this, event, listener);
  if (event === "resize" && this.listenerCount("resize") === 0) {
    removeSigwinchListener(this);
  }
  return this;
};

WriteStream.prototype.off = function off(event, listener) {
  return this.removeListener(event, listener);
};

WriteStream.prototype.removeAllListeners = function removeAllListeners(event) {
  FunctionPrototypeCall(Socket.prototype.removeAllListeners, this, event);
  if (!event || event === "resize") {
    removeSigwinchListener(this);
  }
  return this;
};

WriteStream.prototype._refreshSize = function _refreshSize() {
  const oldCols = this.columns;
  const oldRows = this.rows;
  const winSize = [0, 0];
  const err = this._handle.getWindowSize(winSize);
  if (err) {
    this.emit("error", errnoException(err, "getWindowSize"));
    return;
  }
  const { 0: newCols, 1: newRows } = winSize;
  if (oldCols !== newCols || oldRows !== newRows) {
    this.columns = newCols;
    this.rows = newRows;
    this.emit("resize");
  }
};

WriteStream.prototype.cursorTo = function cursorTo_(x, y, callback) {
  return cursorTo(this, x, y, callback);
};

WriteStream.prototype.moveCursor = function moveCursor_(dx, dy, callback) {
  return moveCursor(this, dx, dy, callback);
};

WriteStream.prototype.clearLine = function clearLine_(dir, callback) {
  return clearLine(this, dir, callback);
};

WriteStream.prototype.clearScreenDown = function clearScreenDown_(callback) {
  return clearScreenDown(this, callback);
};

WriteStream.prototype.getWindowSize = function getWindowSize() {
  return [this.columns, this.rows];
};

/**
 * @param {number | Record<string, string>} [count]
 * @param {Record<string, string>} [env]
 * @returns {boolean}
 */
WriteStream.prototype.hasColors = function hasColors(count, env) {
  if (
    env === undefined &&
    (count === undefined || typeof count === "object" && count !== null)
  ) {
    env = count;
    count = 16;
  } else {
    validateInteger(count, "count", 2);
  }

  const depth = this.getColorDepth(env);
  return count <= 2 ** depth;
};

/**
 * @param {Record<string, string>} [env]
 * @returns {1 | 4 | 8 | 24}
 */
WriteStream.prototype.getColorDepth = function getColorDepth_(env) {
  return getColorDepth(env);
};

export { WriteStream };
export default WriteStream;