71406dc765d92b0464ce59de47aa18932a1355a77fbb8947beeaf31f78103021bf1de33128e96eaa9f4ab3d9ea481161f22f8019578356ebbd95d8a7206462 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584
  1. /**
  2. * The `node:util` module supports the needs of Node.js internal APIs. Many of the
  3. * utilities are useful for application and module developers as well. To access
  4. * it:
  5. *
  6. * ```js
  7. * import util from 'node:util';
  8. * ```
  9. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/util.js)
  10. */
  11. declare module "util" {
  12. import * as types from "node:util/types";
  13. export interface InspectOptions {
  14. /**
  15. * If `true`, object's non-enumerable symbols and properties are included in the formatted result.
  16. * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties).
  17. * @default false
  18. */
  19. showHidden?: boolean | undefined;
  20. /**
  21. * Specifies the number of times to recurse while formatting object.
  22. * This is useful for inspecting large objects.
  23. * To recurse up to the maximum call stack size pass `Infinity` or `null`.
  24. * @default 2
  25. */
  26. depth?: number | null | undefined;
  27. /**
  28. * If `true`, the output is styled with ANSI color codes. Colors are customizable.
  29. */
  30. colors?: boolean | undefined;
  31. /**
  32. * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked.
  33. * @default true
  34. */
  35. customInspect?: boolean | undefined;
  36. /**
  37. * If `true`, `Proxy` inspection includes the target and handler objects.
  38. * @default false
  39. */
  40. showProxy?: boolean | undefined;
  41. /**
  42. * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements
  43. * to include when formatting. Set to `null` or `Infinity` to show all elements.
  44. * Set to `0` or negative to show no elements.
  45. * @default 100
  46. */
  47. maxArrayLength?: number | null | undefined;
  48. /**
  49. * Specifies the maximum number of characters to
  50. * include when formatting. Set to `null` or `Infinity` to show all elements.
  51. * Set to `0` or negative to show no characters.
  52. * @default 10000
  53. */
  54. maxStringLength?: number | null | undefined;
  55. /**
  56. * The length at which input values are split across multiple lines.
  57. * Set to `Infinity` to format the input as a single line
  58. * (in combination with `compact` set to `true` or any number >= `1`).
  59. * @default 80
  60. */
  61. breakLength?: number | undefined;
  62. /**
  63. * Setting this to `false` causes each object key
  64. * to be displayed on a new line. It will also add new lines to text that is
  65. * longer than `breakLength`. If set to a number, the most `n` inner elements
  66. * are united on a single line as long as all properties fit into
  67. * `breakLength`. Short array elements are also grouped together. Note that no
  68. * text will be reduced below 16 characters, no matter the `breakLength` size.
  69. * For more information, see the example below.
  70. * @default true
  71. */
  72. compact?: boolean | number | undefined;
  73. /**
  74. * If set to `true` or a function, all properties of an object, and `Set` and `Map`
  75. * entries are sorted in the resulting string.
  76. * If set to `true` the default sort is used.
  77. * If set to a function, it is used as a compare function.
  78. */
  79. sorted?: boolean | ((a: string, b: string) => number) | undefined;
  80. /**
  81. * If set to `true`, getters are going to be
  82. * inspected as well. If set to `'get'` only getters without setter are going
  83. * to be inspected. If set to `'set'` only getters having a corresponding
  84. * setter are going to be inspected. This might cause side effects depending on
  85. * the getter function.
  86. * @default false
  87. */
  88. getters?: "get" | "set" | boolean | undefined;
  89. /**
  90. * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers.
  91. * @default false
  92. */
  93. numericSeparator?: boolean | undefined;
  94. }
  95. export type Style =
  96. | "special"
  97. | "number"
  98. | "bigint"
  99. | "boolean"
  100. | "undefined"
  101. | "null"
  102. | "string"
  103. | "symbol"
  104. | "date"
  105. | "regexp"
  106. | "module";
  107. export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect
  108. export interface InspectOptionsStylized extends InspectOptions {
  109. stylize(text: string, styleType: Style): string;
  110. }
  111. export interface CallSiteObject {
  112. /**
  113. * Returns the name of the function associated with this call site.
  114. */
  115. functionName: string;
  116. /**
  117. * Returns the name of the resource that contains the script for the
  118. * function for this call site.
  119. */
  120. scriptName: string;
  121. /**
  122. * Returns the unique id of the script, as in Chrome DevTools protocol
  123. * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId).
  124. * @since v22.14.0
  125. */
  126. scriptId: string;
  127. /**
  128. * Returns the number, 1-based, of the line for the associate function call.
  129. */
  130. lineNumber: number;
  131. /**
  132. * Returns the 1-based column offset on the line for the associated function call.
  133. */
  134. columnNumber: number;
  135. }
  136. export type DiffEntry = [operation: -1 | 0 | 1, value: string];
  137. /**
  138. * `util.diff()` compares two string or array values and returns an array of difference entries.
  139. * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm
  140. * used internally by assertion error messages.
  141. *
  142. * If the values are equal, an empty array is returned.
  143. *
  144. * ```js
  145. * const { diff } = require('node:util');
  146. *
  147. * // Comparing strings
  148. * const actualString = '12345678';
  149. * const expectedString = '12!!5!7!';
  150. * console.log(diff(actualString, expectedString));
  151. * // [
  152. * // [0, '1'],
  153. * // [0, '2'],
  154. * // [1, '3'],
  155. * // [1, '4'],
  156. * // [-1, '!'],
  157. * // [-1, '!'],
  158. * // [0, '5'],
  159. * // [1, '6'],
  160. * // [-1, '!'],
  161. * // [0, '7'],
  162. * // [1, '8'],
  163. * // [-1, '!'],
  164. * // ]
  165. * // Comparing arrays
  166. * const actualArray = ['1', '2', '3'];
  167. * const expectedArray = ['1', '3', '4'];
  168. * console.log(diff(actualArray, expectedArray));
  169. * // [
  170. * // [0, '1'],
  171. * // [1, '2'],
  172. * // [0, '3'],
  173. * // [-1, '4'],
  174. * // ]
  175. * // Equal values return empty array
  176. * console.log(diff('same', 'same'));
  177. * // []
  178. * ```
  179. * @since v22.15.0
  180. * @experimental
  181. * @param actual The first value to compare
  182. * @param expected The second value to compare
  183. * @returns An array of difference entries. Each entry is an array with two elements:
  184. * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert
  185. * * Index 1: `string` The value associated with the operation
  186. */
  187. export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[];
  188. /**
  189. * The `util.format()` method returns a formatted string using the first argument
  190. * as a `printf`-like format string which can contain zero or more format
  191. * specifiers. Each specifier is replaced with the converted value from the
  192. * corresponding argument. Supported specifiers are:
  193. *
  194. * If a specifier does not have a corresponding argument, it is not replaced:
  195. *
  196. * ```js
  197. * util.format('%s:%s', 'foo');
  198. * // Returns: 'foo:%s'
  199. * ```
  200. *
  201. * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`.
  202. *
  203. * If there are more arguments passed to the `util.format()` method than the
  204. * number of specifiers, the extra arguments are concatenated to the returned
  205. * string, separated by spaces:
  206. *
  207. * ```js
  208. * util.format('%s:%s', 'foo', 'bar', 'baz');
  209. * // Returns: 'foo:bar baz'
  210. * ```
  211. *
  212. * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces:
  213. *
  214. * ```js
  215. * util.format(1, 2, 3);
  216. * // Returns: '1 2 3'
  217. * ```
  218. *
  219. * If only one argument is passed to `util.format()`, it is returned as it is
  220. * without any formatting:
  221. *
  222. * ```js
  223. * util.format('%% %s');
  224. * // Returns: '%% %s'
  225. * ```
  226. *
  227. * `util.format()` is a synchronous method that is intended as a debugging tool.
  228. * Some input values can have a significant performance overhead that can block the
  229. * event loop. Use this function with care and never in a hot code path.
  230. * @since v0.5.3
  231. * @param format A `printf`-like format string.
  232. */
  233. export function format(format?: any, ...param: any[]): string;
  234. /**
  235. * This function is identical to {@link format}, except in that it takes
  236. * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}.
  237. *
  238. * ```js
  239. * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
  240. * // Returns 'See object { foo: 42 }', where `42` is colored as a number
  241. * // when printed to a terminal.
  242. * ```
  243. * @since v10.0.0
  244. */
  245. export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string;
  246. interface GetCallSitesOptions {
  247. /**
  248. * Reconstruct the original location in the stacktrace from the source-map.
  249. * Enabled by default with the flag `--enable-source-maps`.
  250. */
  251. sourceMap?: boolean | undefined;
  252. }
  253. /**
  254. * Returns an array of call site objects containing the stack of
  255. * the caller function.
  256. *
  257. * ```js
  258. * import { getCallSites } from 'node:util';
  259. *
  260. * function exampleFunction() {
  261. * const callSites = getCallSites();
  262. *
  263. * console.log('Call Sites:');
  264. * callSites.forEach((callSite, index) => {
  265. * console.log(`CallSite ${index + 1}:`);
  266. * console.log(`Function Name: ${callSite.functionName}`);
  267. * console.log(`Script Name: ${callSite.scriptName}`);
  268. * console.log(`Line Number: ${callSite.lineNumber}`);
  269. * console.log(`Column Number: ${callSite.column}`);
  270. * });
  271. * // CallSite 1:
  272. * // Function Name: exampleFunction
  273. * // Script Name: /home/example.js
  274. * // Line Number: 5
  275. * // Column Number: 26
  276. *
  277. * // CallSite 2:
  278. * // Function Name: anotherFunction
  279. * // Script Name: /home/example.js
  280. * // Line Number: 22
  281. * // Column Number: 3
  282. *
  283. * // ...
  284. * }
  285. *
  286. * // A function to simulate another stack layer
  287. * function anotherFunction() {
  288. * exampleFunction();
  289. * }
  290. *
  291. * anotherFunction();
  292. * ```
  293. *
  294. * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`.
  295. * If the source map is not available, the original location will be the same as the current location.
  296. * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`,
  297. * `sourceMap` will be true by default.
  298. *
  299. * ```ts
  300. * import { getCallSites } from 'node:util';
  301. *
  302. * interface Foo {
  303. * foo: string;
  304. * }
  305. *
  306. * const callSites = getCallSites({ sourceMap: true });
  307. *
  308. * // With sourceMap:
  309. * // Function Name: ''
  310. * // Script Name: example.js
  311. * // Line Number: 7
  312. * // Column Number: 26
  313. *
  314. * // Without sourceMap:
  315. * // Function Name: ''
  316. * // Script Name: example.js
  317. * // Line Number: 2
  318. * // Column Number: 26
  319. * ```
  320. * @param frameCount Number of frames to capture as call site objects.
  321. * **Default:** `10`. Allowable range is between 1 and 200.
  322. * @return An array of call site objects
  323. * @since v22.9.0
  324. */
  325. export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[];
  326. export function getCallSites(options: GetCallSitesOptions): CallSiteObject[];
  327. /**
  328. * Returns the string name for a numeric error code that comes from a Node.js API.
  329. * The mapping between error codes and error names is platform-dependent.
  330. * See `Common System Errors` for the names of common errors.
  331. *
  332. * ```js
  333. * fs.access('file/that/does/not/exist', (err) => {
  334. * const name = util.getSystemErrorName(err.errno);
  335. * console.error(name); // ENOENT
  336. * });
  337. * ```
  338. * @since v9.7.0
  339. */
  340. export function getSystemErrorName(err: number): string;
  341. /**
  342. * Returns a Map of all system error codes available from the Node.js API.
  343. * The mapping between error codes and error names is platform-dependent.
  344. * See `Common System Errors` for the names of common errors.
  345. *
  346. * ```js
  347. * fs.access('file/that/does/not/exist', (err) => {
  348. * const errorMap = util.getSystemErrorMap();
  349. * const name = errorMap.get(err.errno);
  350. * console.error(name); // ENOENT
  351. * });
  352. * ```
  353. * @since v16.0.0, v14.17.0
  354. */
  355. export function getSystemErrorMap(): Map<number, [string, string]>;
  356. /**
  357. * Returns the string message for a numeric error code that comes from a Node.js
  358. * API.
  359. * The mapping between error codes and string messages is platform-dependent.
  360. *
  361. * ```js
  362. * fs.access('file/that/does/not/exist', (err) => {
  363. * const message = util.getSystemErrorMessage(err.errno);
  364. * console.error(message); // no such file or directory
  365. * });
  366. * ```
  367. * @since v22.12.0
  368. */
  369. export function getSystemErrorMessage(err: number): string;
  370. /**
  371. * The `util.log()` method prints the given `string` to `stdout` with an included
  372. * timestamp.
  373. *
  374. * ```js
  375. * import util from 'node:util';
  376. *
  377. * util.log('Timestamped message.');
  378. * ```
  379. * @since v0.3.0
  380. * @deprecated Since v6.0.0 - Use a third party module instead.
  381. */
  382. export function log(string: string): void;
  383. /**
  384. * Returns the `string` after replacing any surrogate code points
  385. * (or equivalently, any unpaired surrogate code units) with the
  386. * Unicode "replacement character" U+FFFD.
  387. * @since v16.8.0, v14.18.0
  388. */
  389. export function toUSVString(string: string): string;
  390. /**
  391. * Creates and returns an `AbortController` instance whose `AbortSignal` is marked
  392. * as transferable and can be used with `structuredClone()` or `postMessage()`.
  393. * @since v18.11.0
  394. * @returns A transferable AbortController
  395. */
  396. export function transferableAbortController(): AbortController;
  397. /**
  398. * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`.
  399. *
  400. * ```js
  401. * const signal = transferableAbortSignal(AbortSignal.timeout(100));
  402. * const channel = new MessageChannel();
  403. * channel.port2.postMessage(signal, [signal]);
  404. * ```
  405. * @since v18.11.0
  406. * @param signal The AbortSignal
  407. * @returns The same AbortSignal
  408. */
  409. export function transferableAbortSignal(signal: AbortSignal): AbortSignal;
  410. /**
  411. * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted.
  412. * If `resource` is provided, it weakly references the operation's associated object,
  413. * so if `resource` is garbage collected before the `signal` aborts,
  414. * then returned promise shall remain pending.
  415. * This prevents memory leaks in long-running or non-cancelable operations.
  416. *
  417. * ```js
  418. * import { aborted } from 'node:util';
  419. *
  420. * // Obtain an object with an abortable signal, like a custom resource or operation.
  421. * const dependent = obtainSomethingAbortable();
  422. *
  423. * // Pass `dependent` as the resource, indicating the promise should only resolve
  424. * // if `dependent` is still in memory when the signal is aborted.
  425. * aborted(dependent.signal, dependent).then(() => {
  426. * // This code runs when `dependent` is aborted.
  427. * console.log('Dependent resource was aborted.');
  428. * });
  429. *
  430. * // Simulate an event that triggers the abort.
  431. * dependent.on('event', () => {
  432. * dependent.abort(); // This will cause the `aborted` promise to resolve.
  433. * });
  434. * ```
  435. * @since v19.7.0
  436. * @experimental
  437. * @param resource Any non-null object tied to the abortable operation and held weakly.
  438. * If `resource` is garbage collected before the `signal` aborts, the promise remains pending,
  439. * allowing Node.js to stop tracking it.
  440. * This helps prevent memory leaks in long-running or non-cancelable operations.
  441. */
  442. export function aborted(signal: AbortSignal, resource: any): Promise<void>;
  443. /**
  444. * The `util.inspect()` method returns a string representation of `object` that is
  445. * intended for debugging. The output of `util.inspect` may change at any time
  446. * and should not be depended upon programmatically. Additional `options` may be
  447. * passed that alter the result.
  448. * `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make
  449. * an identifiable tag for an inspected value.
  450. *
  451. * ```js
  452. * class Foo {
  453. * get [Symbol.toStringTag]() {
  454. * return 'bar';
  455. * }
  456. * }
  457. *
  458. * class Bar {}
  459. *
  460. * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
  461. *
  462. * util.inspect(new Foo()); // 'Foo [bar] {}'
  463. * util.inspect(new Bar()); // 'Bar {}'
  464. * util.inspect(baz); // '[foo] {}'
  465. * ```
  466. *
  467. * Circular references point to their anchor by using a reference index:
  468. *
  469. * ```js
  470. * import { inspect } from 'node:util';
  471. *
  472. * const obj = {};
  473. * obj.a = [obj];
  474. * obj.b = {};
  475. * obj.b.inner = obj.b;
  476. * obj.b.obj = obj;
  477. *
  478. * console.log(inspect(obj));
  479. * // <ref *1> {
  480. * // a: [ [Circular *1] ],
  481. * // b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
  482. * // }
  483. * ```
  484. *
  485. * The following example inspects all properties of the `util` object:
  486. *
  487. * ```js
  488. * import util from 'node:util';
  489. *
  490. * console.log(util.inspect(util, { showHidden: true, depth: null }));
  491. * ```
  492. *
  493. * The following example highlights the effect of the `compact` option:
  494. *
  495. * ```js
  496. * import { inspect } from 'node:util';
  497. *
  498. * const o = {
  499. * a: [1, 2, [[
  500. * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
  501. * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
  502. * 'test',
  503. * 'foo']], 4],
  504. * b: new Map([['za', 1], ['zb', 'test']]),
  505. * };
  506. * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
  507. *
  508. * // { a:
  509. * // [ 1,
  510. * // 2,
  511. * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
  512. * // 'test',
  513. * // 'foo' ] ],
  514. * // 4 ],
  515. * // b: Map(2) { 'za' => 1, 'zb' => 'test' } }
  516. *
  517. * // Setting `compact` to false or an integer creates more reader friendly output.
  518. * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
  519. *
  520. * // {
  521. * // a: [
  522. * // 1,
  523. * // 2,
  524. * // [
  525. * // [
  526. * // 'Lorem ipsum dolor sit amet,\n' +
  527. * // 'consectetur adipiscing elit, sed do eiusmod \n' +
  528. * // 'tempor incididunt ut labore et dolore magna aliqua.',
  529. * // 'test',
  530. * // 'foo'
  531. * // ]
  532. * // ],
  533. * // 4
  534. * // ],
  535. * // b: Map(2) {
  536. * // 'za' => 1,
  537. * // 'zb' => 'test'
  538. * // }
  539. * // }
  540. *
  541. * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
  542. * // single line.
  543. * ```
  544. *
  545. * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be
  546. * inspected. If there are more entries than `maxArrayLength`, there is no
  547. * guarantee which entries are displayed. That means retrieving the same
  548. * `WeakSet` entries twice may result in different output. Furthermore, entries
  549. * with no remaining strong references may be garbage collected at any time.
  550. *
  551. * ```js
  552. * import { inspect } from 'node:util';
  553. *
  554. * const obj = { a: 1 };
  555. * const obj2 = { b: 2 };
  556. * const weakSet = new WeakSet([obj, obj2]);
  557. *
  558. * console.log(inspect(weakSet, { showHidden: true }));
  559. * // WeakSet { { a: 1 }, { b: 2 } }
  560. * ```
  561. *
  562. * The `sorted` option ensures that an object's property insertion order does not
  563. * impact the result of `util.inspect()`.
  564. *
  565. * ```js
  566. * import { inspect } from 'node:util';
  567. * import assert from 'node:assert';
  568. *
  569. * const o1 = {
  570. * b: [2, 3, 1],
  571. * a: '`a` comes before `b`',
  572. * c: new Set([2, 3, 1]),
  573. * };
  574. * console.log(inspect(o1, { sorted: true }));
  575. * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
  576. * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
  577. * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
  578. *
  579. * const o2 = {
  580. * c: new Set([2, 1, 3]),
  581. * a: '`a` comes before `b`',
  582. * b: [2, 3, 1],
  583. * };
  584. * assert.strict.equal(
  585. * inspect(o1, { sorted: true }),
  586. * inspect(o2, { sorted: true }),
  587. * );
  588. * ```
  589. *
  590. * The `numericSeparator` option adds an underscore every three digits to all
  591. * numbers.
  592. *
  593. * ```js
  594. * import { inspect } from 'node:util';
  595. *
  596. * const thousand = 1000;
  597. * const million = 1000000;
  598. * const bigNumber = 123456789n;
  599. * const bigDecimal = 1234.12345;
  600. *
  601. * console.log(inspect(thousand, { numericSeparator: true }));
  602. * // 1_000
  603. * console.log(inspect(million, { numericSeparator: true }));
  604. * // 1_000_000
  605. * console.log(inspect(bigNumber, { numericSeparator: true }));
  606. * // 123_456_789n
  607. * console.log(inspect(bigDecimal, { numericSeparator: true }));
  608. * // 1_234.123_45
  609. * ```
  610. *
  611. * `util.inspect()` is a synchronous method intended for debugging. Its maximum
  612. * output length is approximately 128 MiB. Inputs that result in longer output will
  613. * be truncated.
  614. * @since v0.3.0
  615. * @param object Any JavaScript primitive or `Object`.
  616. * @return The representation of `object`.
  617. */
  618. export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string;
  619. export function inspect(object: any, options?: InspectOptions): string;
  620. export namespace inspect {
  621. let colors: NodeJS.Dict<[number, number]>;
  622. let styles: {
  623. [K in Style]: string;
  624. };
  625. let defaultOptions: InspectOptions;
  626. /**
  627. * Allows changing inspect settings from the repl.
  628. */
  629. let replDefaults: InspectOptions;
  630. /**
  631. * That can be used to declare custom inspect functions.
  632. */
  633. const custom: unique symbol;
  634. }
  635. /**
  636. * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray).
  637. *
  638. * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
  639. *
  640. * ```js
  641. * import util from 'node:util';
  642. *
  643. * util.isArray([]);
  644. * // Returns: true
  645. * util.isArray(new Array());
  646. * // Returns: true
  647. * util.isArray({});
  648. * // Returns: false
  649. * ```
  650. * @since v0.6.0
  651. * @deprecated Since v4.0.0 - Use `isArray` instead.
  652. */
  653. export function isArray(object: unknown): object is unknown[];
  654. /**
  655. * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
  656. *
  657. * ```js
  658. * import util from 'node:util';
  659. *
  660. * util.isRegExp(/some regexp/);
  661. * // Returns: true
  662. * util.isRegExp(new RegExp('another regexp'));
  663. * // Returns: true
  664. * util.isRegExp({});
  665. * // Returns: false
  666. * ```
  667. * @since v0.6.0
  668. * @deprecated Since v4.0.0 - Deprecated
  669. */
  670. export function isRegExp(object: unknown): object is RegExp;
  671. /**
  672. * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
  673. *
  674. * ```js
  675. * import util from 'node:util';
  676. *
  677. * util.isDate(new Date());
  678. * // Returns: true
  679. * util.isDate(Date());
  680. * // false (without 'new' returns a String)
  681. * util.isDate({});
  682. * // Returns: false
  683. * ```
  684. * @since v0.6.0
  685. * @deprecated Since v4.0.0 - Use {@link types.isDate} instead.
  686. */
  687. export function isDate(object: unknown): object is Date;
  688. /**
  689. * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`.
  690. *
  691. * ```js
  692. * import util from 'node:util';
  693. *
  694. * util.isError(new Error());
  695. * // Returns: true
  696. * util.isError(new TypeError());
  697. * // Returns: true
  698. * util.isError({ name: 'Error', message: 'an error occurred' });
  699. * // Returns: false
  700. * ```
  701. *
  702. * This method relies on `Object.prototype.toString()` behavior. It is
  703. * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`.
  704. *
  705. * ```js
  706. * import util from 'node:util';
  707. * const obj = { name: 'Error', message: 'an error occurred' };
  708. *
  709. * util.isError(obj);
  710. * // Returns: false
  711. * obj[Symbol.toStringTag] = 'Error';
  712. * util.isError(obj);
  713. * // Returns: true
  714. * ```
  715. * @since v0.6.0
  716. * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead.
  717. */
  718. export function isError(object: unknown): object is Error;
  719. /**
  720. * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and
  721. * `extends` keywords to get language level inheritance support. Also note
  722. * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179).
  723. *
  724. * Inherit the prototype methods from one
  725. * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The
  726. * prototype of `constructor` will be set to a new object created from
  727. * `superConstructor`.
  728. *
  729. * This mainly adds some input validation on top of
  730. * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`.
  731. * As an additional convenience, `superConstructor` will be accessible
  732. * through the `constructor.super_` property.
  733. *
  734. * ```js
  735. * const util = require('node:util');
  736. * const EventEmitter = require('node:events');
  737. *
  738. * function MyStream() {
  739. * EventEmitter.call(this);
  740. * }
  741. *
  742. * util.inherits(MyStream, EventEmitter);
  743. *
  744. * MyStream.prototype.write = function(data) {
  745. * this.emit('data', data);
  746. * };
  747. *
  748. * const stream = new MyStream();
  749. *
  750. * console.log(stream instanceof EventEmitter); // true
  751. * console.log(MyStream.super_ === EventEmitter); // true
  752. *
  753. * stream.on('data', (data) => {
  754. * console.log(`Received data: "${data}"`);
  755. * });
  756. * stream.write('It works!'); // Received data: "It works!"
  757. * ```
  758. *
  759. * ES6 example using `class` and `extends`:
  760. *
  761. * ```js
  762. * import EventEmitter from 'node:events';
  763. *
  764. * class MyStream extends EventEmitter {
  765. * write(data) {
  766. * this.emit('data', data);
  767. * }
  768. * }
  769. *
  770. * const stream = new MyStream();
  771. *
  772. * stream.on('data', (data) => {
  773. * console.log(`Received data: "${data}"`);
  774. * });
  775. * stream.write('With ES6');
  776. * ```
  777. * @since v0.3.0
  778. * @legacy Use ES2015 class syntax and `extends` keyword instead.
  779. */
  780. export function inherits(constructor: unknown, superConstructor: unknown): void;
  781. export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void;
  782. export interface DebugLogger extends DebugLoggerFunction {
  783. /**
  784. * The `util.debuglog().enabled` getter is used to create a test that can be used
  785. * in conditionals based on the existence of the `NODE_DEBUG` environment variable.
  786. * If the `section` name appears within the value of that environment variable,
  787. * then the returned value will be `true`. If not, then the returned value will be
  788. * `false`.
  789. *
  790. * ```js
  791. * import { debuglog } from 'node:util';
  792. * const enabled = debuglog('foo').enabled;
  793. * if (enabled) {
  794. * console.log('hello from foo [%d]', 123);
  795. * }
  796. * ```
  797. *
  798. * If this program is run with `NODE_DEBUG=foo` in the environment, then it will
  799. * output something like:
  800. *
  801. * ```console
  802. * hello from foo [123]
  803. * ```
  804. */
  805. enabled: boolean;
  806. }
  807. /**
  808. * The `util.debuglog()` method is used to create a function that conditionally
  809. * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`
  810. * environment variable. If the `section` name appears within the value of that
  811. * environment variable, then the returned function operates similar to
  812. * `console.error()`. If not, then the returned function is a no-op.
  813. *
  814. * ```js
  815. * import { debuglog } from 'node:util';
  816. * const log = debuglog('foo');
  817. *
  818. * log('hello from foo [%d]', 123);
  819. * ```
  820. *
  821. * If this program is run with `NODE_DEBUG=foo` in the environment, then
  822. * it will output something like:
  823. *
  824. * ```console
  825. * FOO 3245: hello from foo [123]
  826. * ```
  827. *
  828. * where `3245` is the process id. If it is not run with that
  829. * environment variable set, then it will not print anything.
  830. *
  831. * The `section` supports wildcard also:
  832. *
  833. * ```js
  834. * import { debuglog } from 'node:util';
  835. * const log = debuglog('foo');
  836. *
  837. * log('hi there, it\'s foo-bar [%d]', 2333);
  838. * ```
  839. *
  840. * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
  841. * something like:
  842. *
  843. * ```console
  844. * FOO-BAR 3257: hi there, it's foo-bar [2333]
  845. * ```
  846. *
  847. * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
  848. * environment variable: `NODE_DEBUG=fs,net,tls`.
  849. *
  850. * The optional `callback` argument can be used to replace the logging function
  851. * with a different function that doesn't have any initialization or
  852. * unnecessary wrapping.
  853. *
  854. * ```js
  855. * import { debuglog } from 'node:util';
  856. * let log = debuglog('internals', (debug) => {
  857. * // Replace with a logging function that optimizes out
  858. * // testing if the section is enabled
  859. * log = debug;
  860. * });
  861. * ```
  862. * @since v0.11.3
  863. * @param section A string identifying the portion of the application for which the `debuglog` function is being created.
  864. * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.
  865. * @return The logging function
  866. */
  867. export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger;
  868. export { debuglog as debug };
  869. /**
  870. * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
  871. *
  872. * ```js
  873. * import util from 'node:util';
  874. *
  875. * util.isBoolean(1);
  876. * // Returns: false
  877. * util.isBoolean(0);
  878. * // Returns: false
  879. * util.isBoolean(false);
  880. * // Returns: true
  881. * ```
  882. * @since v0.11.5
  883. * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead.
  884. */
  885. export function isBoolean(object: unknown): object is boolean;
  886. /**
  887. * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
  888. *
  889. * ```js
  890. * import util from 'node:util';
  891. *
  892. * util.isBuffer({ length: 0 });
  893. * // Returns: false
  894. * util.isBuffer([]);
  895. * // Returns: false
  896. * util.isBuffer(Buffer.from('hello world'));
  897. * // Returns: true
  898. * ```
  899. * @since v0.11.5
  900. * @deprecated Since v4.0.0 - Use `isBuffer` instead.
  901. */
  902. export function isBuffer(object: unknown): object is Buffer;
  903. /**
  904. * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`.
  905. *
  906. * ```js
  907. * import util from 'node:util';
  908. *
  909. * function Foo() {}
  910. * const Bar = () => {};
  911. *
  912. * util.isFunction({});
  913. * // Returns: false
  914. * util.isFunction(Foo);
  915. * // Returns: true
  916. * util.isFunction(Bar);
  917. * // Returns: true
  918. * ```
  919. * @since v0.11.5
  920. * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead.
  921. */
  922. export function isFunction(object: unknown): boolean;
  923. /**
  924. * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`.
  925. *
  926. * ```js
  927. * import util from 'node:util';
  928. *
  929. * util.isNull(0);
  930. * // Returns: false
  931. * util.isNull(undefined);
  932. * // Returns: false
  933. * util.isNull(null);
  934. * // Returns: true
  935. * ```
  936. * @since v0.11.5
  937. * @deprecated Since v4.0.0 - Use `value === null` instead.
  938. */
  939. export function isNull(object: unknown): object is null;
  940. /**
  941. * Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
  942. * returns `false`.
  943. *
  944. * ```js
  945. * import util from 'node:util';
  946. *
  947. * util.isNullOrUndefined(0);
  948. * // Returns: false
  949. * util.isNullOrUndefined(undefined);
  950. * // Returns: true
  951. * util.isNullOrUndefined(null);
  952. * // Returns: true
  953. * ```
  954. * @since v0.11.5
  955. * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead.
  956. */
  957. export function isNullOrUndefined(object: unknown): object is null | undefined;
  958. /**
  959. * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
  960. *
  961. * ```js
  962. * import util from 'node:util';
  963. *
  964. * util.isNumber(false);
  965. * // Returns: false
  966. * util.isNumber(Infinity);
  967. * // Returns: true
  968. * util.isNumber(0);
  969. * // Returns: true
  970. * util.isNumber(NaN);
  971. * // Returns: true
  972. * ```
  973. * @since v0.11.5
  974. * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead.
  975. */
  976. export function isNumber(object: unknown): object is number;
  977. /**
  978. * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript).
  979. * Otherwise, returns `false`.
  980. *
  981. * ```js
  982. * import util from 'node:util';
  983. *
  984. * util.isObject(5);
  985. * // Returns: false
  986. * util.isObject(null);
  987. * // Returns: false
  988. * util.isObject({});
  989. * // Returns: true
  990. * util.isObject(() => {});
  991. * // Returns: false
  992. * ```
  993. * @since v0.11.5
  994. * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead.
  995. */
  996. export function isObject(object: unknown): boolean;
  997. /**
  998. * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`.
  999. *
  1000. * ```js
  1001. * import util from 'node:util';
  1002. *
  1003. * util.isPrimitive(5);
  1004. * // Returns: true
  1005. * util.isPrimitive('foo');
  1006. * // Returns: true
  1007. * util.isPrimitive(false);
  1008. * // Returns: true
  1009. * util.isPrimitive(null);
  1010. * // Returns: true
  1011. * util.isPrimitive(undefined);
  1012. * // Returns: true
  1013. * util.isPrimitive({});
  1014. * // Returns: false
  1015. * util.isPrimitive(() => {});
  1016. * // Returns: false
  1017. * util.isPrimitive(/^$/);
  1018. * // Returns: false
  1019. * util.isPrimitive(new Date());
  1020. * // Returns: false
  1021. * ```
  1022. * @since v0.11.5
  1023. * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead.
  1024. */
  1025. export function isPrimitive(object: unknown): boolean;
  1026. /**
  1027. * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
  1028. *
  1029. * ```js
  1030. * import util from 'node:util';
  1031. *
  1032. * util.isString('');
  1033. * // Returns: true
  1034. * util.isString('foo');
  1035. * // Returns: true
  1036. * util.isString(String('foo'));
  1037. * // Returns: true
  1038. * util.isString(5);
  1039. * // Returns: false
  1040. * ```
  1041. * @since v0.11.5
  1042. * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead.
  1043. */
  1044. export function isString(object: unknown): object is string;
  1045. /**
  1046. * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
  1047. *
  1048. * ```js
  1049. * import util from 'node:util';
  1050. *
  1051. * util.isSymbol(5);
  1052. * // Returns: false
  1053. * util.isSymbol('foo');
  1054. * // Returns: false
  1055. * util.isSymbol(Symbol('foo'));
  1056. * // Returns: true
  1057. * ```
  1058. * @since v0.11.5
  1059. * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead.
  1060. */
  1061. export function isSymbol(object: unknown): object is symbol;
  1062. /**
  1063. * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
  1064. *
  1065. * ```js
  1066. * import util from 'node:util';
  1067. *
  1068. * const foo = undefined;
  1069. * util.isUndefined(5);
  1070. * // Returns: false
  1071. * util.isUndefined(foo);
  1072. * // Returns: true
  1073. * util.isUndefined(null);
  1074. * // Returns: false
  1075. * ```
  1076. * @since v0.11.5
  1077. * @deprecated Since v4.0.0 - Use `value === undefined` instead.
  1078. */
  1079. export function isUndefined(object: unknown): object is undefined;
  1080. /**
  1081. * The `util.deprecate()` method wraps `fn` (which may be a function or class) in
  1082. * such a way that it is marked as deprecated.
  1083. *
  1084. * ```js
  1085. * import { deprecate } from 'node:util';
  1086. *
  1087. * export const obsoleteFunction = deprecate(() => {
  1088. * // Do something here.
  1089. * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
  1090. * ```
  1091. *
  1092. * When called, `util.deprecate()` will return a function that will emit a
  1093. * `DeprecationWarning` using the `'warning'` event. The warning will
  1094. * be emitted and printed to `stderr` the first time the returned function is
  1095. * called. After the warning is emitted, the wrapped function is called without
  1096. * emitting a warning.
  1097. *
  1098. * If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
  1099. * the warning will be emitted only once for that `code`.
  1100. *
  1101. * ```js
  1102. * import { deprecate } from 'node:util';
  1103. *
  1104. * const fn1 = deprecate(
  1105. * () => 'a value',
  1106. * 'deprecation message',
  1107. * 'DEP0001',
  1108. * );
  1109. * const fn2 = deprecate(
  1110. * () => 'a different value',
  1111. * 'other dep message',
  1112. * 'DEP0001',
  1113. * );
  1114. * fn1(); // Emits a deprecation warning with code DEP0001
  1115. * fn2(); // Does not emit a deprecation warning because it has the same code
  1116. * ```
  1117. *
  1118. * If either the `--no-deprecation` or `--no-warnings` command-line flags are
  1119. * used, or if the `process.noDeprecation` property is set to `true` _prior_ to
  1120. * the first deprecation warning, the `util.deprecate()` method does nothing.
  1121. *
  1122. * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set,
  1123. * or the `process.traceDeprecation` property is set to `true`, a warning and a
  1124. * stack trace are printed to `stderr` the first time the deprecated function is
  1125. * called.
  1126. *
  1127. * If the `--throw-deprecation` command-line flag is set, or the
  1128. * `process.throwDeprecation` property is set to `true`, then an exception will be
  1129. * thrown when the deprecated function is called.
  1130. *
  1131. * The `--throw-deprecation` command-line flag and `process.throwDeprecation`
  1132. * property take precedence over `--trace-deprecation` and
  1133. * `process.traceDeprecation`.
  1134. * @since v0.8.0
  1135. * @param fn The function that is being deprecated.
  1136. * @param msg A warning message to display when the deprecated function is invoked.
  1137. * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes.
  1138. * @return The deprecated function wrapped to emit a warning.
  1139. */
  1140. export function deprecate<T extends Function>(fn: T, msg: string, code?: string): T;
  1141. /**
  1142. * Returns `true` if there is deep strict equality between `val1` and `val2`.
  1143. * Otherwise, returns `false`.
  1144. *
  1145. * See `assert.deepStrictEqual()` for more information about deep strict
  1146. * equality.
  1147. * @since v9.0.0
  1148. */
  1149. export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean;
  1150. /**
  1151. * Returns `str` with any ANSI escape codes removed.
  1152. *
  1153. * ```js
  1154. * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
  1155. * // Prints "value"
  1156. * ```
  1157. * @since v16.11.0
  1158. */
  1159. export function stripVTControlCharacters(str: string): string;
  1160. /**
  1161. * Takes an `async` function (or a function that returns a `Promise`) and returns a
  1162. * function following the error-first callback style, i.e. taking
  1163. * an `(err, value) => ...` callback as the last argument. In the callback, the
  1164. * first argument will be the rejection reason (or `null` if the `Promise`
  1165. * resolved), and the second argument will be the resolved value.
  1166. *
  1167. * ```js
  1168. * import { callbackify } from 'node:util';
  1169. *
  1170. * async function fn() {
  1171. * return 'hello world';
  1172. * }
  1173. * const callbackFunction = callbackify(fn);
  1174. *
  1175. * callbackFunction((err, ret) => {
  1176. * if (err) throw err;
  1177. * console.log(ret);
  1178. * });
  1179. * ```
  1180. *
  1181. * Will print:
  1182. *
  1183. * ```text
  1184. * hello world
  1185. * ```
  1186. *
  1187. * The callback is executed asynchronously, and will have a limited stack trace.
  1188. * If the callback throws, the process will emit an `'uncaughtException'`
  1189. * event, and if not handled will exit.
  1190. *
  1191. * Since `null` has a special meaning as the first argument to a callback, if a
  1192. * wrapped function rejects a `Promise` with a falsy value as a reason, the value
  1193. * is wrapped in an `Error` with the original value stored in a field named
  1194. * `reason`.
  1195. *
  1196. * ```js
  1197. * function fn() {
  1198. * return Promise.reject(null);
  1199. * }
  1200. * const callbackFunction = util.callbackify(fn);
  1201. *
  1202. * callbackFunction((err, ret) => {
  1203. * // When the Promise was rejected with `null` it is wrapped with an Error and
  1204. * // the original value is stored in `reason`.
  1205. * err && Object.hasOwn(err, 'reason') && err.reason === null; // true
  1206. * });
  1207. * ```
  1208. * @since v8.2.0
  1209. * @param fn An `async` function
  1210. * @return a callback style function
  1211. */
  1212. export function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void;
  1213. export function callbackify<TResult>(
  1214. fn: () => Promise<TResult>,
  1215. ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
  1216. export function callbackify<T1>(
  1217. fn: (arg1: T1) => Promise<void>,
  1218. ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void;
  1219. export function callbackify<T1, TResult>(
  1220. fn: (arg1: T1) => Promise<TResult>,
  1221. ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
  1222. export function callbackify<T1, T2>(
  1223. fn: (arg1: T1, arg2: T2) => Promise<void>,
  1224. ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void;
  1225. export function callbackify<T1, T2, TResult>(
  1226. fn: (arg1: T1, arg2: T2) => Promise<TResult>,
  1227. ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
  1228. export function callbackify<T1, T2, T3>(
  1229. fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>,
  1230. ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void;
  1231. export function callbackify<T1, T2, T3, TResult>(
  1232. fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>,
  1233. ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void;
  1234. export function callbackify<T1, T2, T3, T4>(
  1235. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>,
  1236. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void;
  1237. export function callbackify<T1, T2, T3, T4, TResult>(
  1238. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>,
  1239. ): (
  1240. arg1: T1,
  1241. arg2: T2,
  1242. arg3: T3,
  1243. arg4: T4,
  1244. callback: (err: NodeJS.ErrnoException | null, result: TResult) => void,
  1245. ) => void;
  1246. export function callbackify<T1, T2, T3, T4, T5>(
  1247. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>,
  1248. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void;
  1249. export function callbackify<T1, T2, T3, T4, T5, TResult>(
  1250. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>,
  1251. ): (
  1252. arg1: T1,
  1253. arg2: T2,
  1254. arg3: T3,
  1255. arg4: T4,
  1256. arg5: T5,
  1257. callback: (err: NodeJS.ErrnoException | null, result: TResult) => void,
  1258. ) => void;
  1259. export function callbackify<T1, T2, T3, T4, T5, T6>(
  1260. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>,
  1261. ): (
  1262. arg1: T1,
  1263. arg2: T2,
  1264. arg3: T3,
  1265. arg4: T4,
  1266. arg5: T5,
  1267. arg6: T6,
  1268. callback: (err: NodeJS.ErrnoException) => void,
  1269. ) => void;
  1270. export function callbackify<T1, T2, T3, T4, T5, T6, TResult>(
  1271. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>,
  1272. ): (
  1273. arg1: T1,
  1274. arg2: T2,
  1275. arg3: T3,
  1276. arg4: T4,
  1277. arg5: T5,
  1278. arg6: T6,
  1279. callback: (err: NodeJS.ErrnoException | null, result: TResult) => void,
  1280. ) => void;
  1281. export interface CustomPromisifyLegacy<TCustom extends Function> extends Function {
  1282. __promisify__: TCustom;
  1283. }
  1284. export interface CustomPromisifySymbol<TCustom extends Function> extends Function {
  1285. [promisify.custom]: TCustom;
  1286. }
  1287. export type CustomPromisify<TCustom extends Function> =
  1288. | CustomPromisifySymbol<TCustom>
  1289. | CustomPromisifyLegacy<TCustom>;
  1290. /**
  1291. * Takes a function following the common error-first callback style, i.e. taking
  1292. * an `(err, value) => ...` callback as the last argument, and returns a version
  1293. * that returns promises.
  1294. *
  1295. * ```js
  1296. * import { promisify } from 'node:util';
  1297. * import { stat } from 'node:fs';
  1298. *
  1299. * const promisifiedStat = promisify(stat);
  1300. * promisifiedStat('.').then((stats) => {
  1301. * // Do something with `stats`
  1302. * }).catch((error) => {
  1303. * // Handle the error.
  1304. * });
  1305. * ```
  1306. *
  1307. * Or, equivalently using `async function`s:
  1308. *
  1309. * ```js
  1310. * import { promisify } from 'node:util';
  1311. * import { stat } from 'node:fs';
  1312. *
  1313. * const promisifiedStat = promisify(stat);
  1314. *
  1315. * async function callStat() {
  1316. * const stats = await promisifiedStat('.');
  1317. * console.log(`This directory is owned by ${stats.uid}`);
  1318. * }
  1319. *
  1320. * callStat();
  1321. * ```
  1322. *
  1323. * If there is an `original[util.promisify.custom]` property present, `promisify`
  1324. * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v22.x/api/util.html#custom-promisified-functions).
  1325. *
  1326. * `promisify()` assumes that `original` is a function taking a callback as its
  1327. * final argument in all cases. If `original` is not a function, `promisify()`
  1328. * will throw an error. If `original` is a function but its last argument is not
  1329. * an error-first callback, it will still be passed an error-first
  1330. * callback as its last argument.
  1331. *
  1332. * Using `promisify()` on class methods or other methods that use `this` may not
  1333. * work as expected unless handled specially:
  1334. *
  1335. * ```js
  1336. * import { promisify } from 'node:util';
  1337. *
  1338. * class Foo {
  1339. * constructor() {
  1340. * this.a = 42;
  1341. * }
  1342. *
  1343. * bar(callback) {
  1344. * callback(null, this.a);
  1345. * }
  1346. * }
  1347. *
  1348. * const foo = new Foo();
  1349. *
  1350. * const naiveBar = promisify(foo.bar);
  1351. * // TypeError: Cannot read properties of undefined (reading 'a')
  1352. * // naiveBar().then(a => console.log(a));
  1353. *
  1354. * naiveBar.call(foo).then((a) => console.log(a)); // '42'
  1355. *
  1356. * const bindBar = naiveBar.bind(foo);
  1357. * bindBar().then((a) => console.log(a)); // '42'
  1358. * ```
  1359. * @since v8.0.0
  1360. */
  1361. export function promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustom;
  1362. export function promisify<TResult>(
  1363. fn: (callback: (err: any, result: TResult) => void) => void,
  1364. ): () => Promise<TResult>;
  1365. export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>;
  1366. export function promisify<T1, TResult>(
  1367. fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void,
  1368. ): (arg1: T1) => Promise<TResult>;
  1369. export function promisify<T1>(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise<void>;
  1370. export function promisify<T1, T2, TResult>(
  1371. fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void,
  1372. ): (arg1: T1, arg2: T2) => Promise<TResult>;
  1373. export function promisify<T1, T2>(
  1374. fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void,
  1375. ): (arg1: T1, arg2: T2) => Promise<void>;
  1376. export function promisify<T1, T2, T3, TResult>(
  1377. fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void,
  1378. ): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>;
  1379. export function promisify<T1, T2, T3>(
  1380. fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void,
  1381. ): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>;
  1382. export function promisify<T1, T2, T3, T4, TResult>(
  1383. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void,
  1384. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>;
  1385. export function promisify<T1, T2, T3, T4>(
  1386. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void,
  1387. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>;
  1388. export function promisify<T1, T2, T3, T4, T5, TResult>(
  1389. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void,
  1390. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>;
  1391. export function promisify<T1, T2, T3, T4, T5>(
  1392. fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void,
  1393. ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>;
  1394. export function promisify(fn: Function): Function;
  1395. export namespace promisify {
  1396. /**
  1397. * That can be used to declare custom promisified variants of functions.
  1398. */
  1399. const custom: unique symbol;
  1400. }
  1401. /**
  1402. * Stability: 1.1 - Active development
  1403. * Given an example `.env` file:
  1404. *
  1405. * ```js
  1406. * import { parseEnv } from 'node:util';
  1407. *
  1408. * parseEnv('HELLO=world\nHELLO=oh my\n');
  1409. * // Returns: { HELLO: 'oh my' }
  1410. * ```
  1411. * @param content The raw contents of a `.env` file.
  1412. * @since v20.12.0
  1413. */
  1414. export function parseEnv(content: string): object;
  1415. // https://nodejs.org/docs/latest/api/util.html#foreground-colors
  1416. type ForegroundColors =
  1417. | "black"
  1418. | "blackBright"
  1419. | "blue"
  1420. | "blueBright"
  1421. | "cyan"
  1422. | "cyanBright"
  1423. | "gray"
  1424. | "green"
  1425. | "greenBright"
  1426. | "grey"
  1427. | "magenta"
  1428. | "magentaBright"
  1429. | "red"
  1430. | "redBright"
  1431. | "white"
  1432. | "whiteBright"
  1433. | "yellow"
  1434. | "yellowBright";
  1435. // https://nodejs.org/docs/latest/api/util.html#background-colors
  1436. type BackgroundColors =
  1437. | "bgBlack"
  1438. | "bgBlackBright"
  1439. | "bgBlue"
  1440. | "bgBlueBright"
  1441. | "bgCyan"
  1442. | "bgCyanBright"
  1443. | "bgGray"
  1444. | "bgGreen"
  1445. | "bgGreenBright"
  1446. | "bgGrey"
  1447. | "bgMagenta"
  1448. | "bgMagentaBright"
  1449. | "bgRed"
  1450. | "bgRedBright"
  1451. | "bgWhite"
  1452. | "bgWhiteBright"
  1453. | "bgYellow"
  1454. | "bgYellowBright";
  1455. // https://nodejs.org/docs/latest/api/util.html#modifiers
  1456. type Modifiers =
  1457. | "blink"
  1458. | "bold"
  1459. | "dim"
  1460. | "doubleunderline"
  1461. | "framed"
  1462. | "hidden"
  1463. | "inverse"
  1464. | "italic"
  1465. | "overlined"
  1466. | "reset"
  1467. | "strikethrough"
  1468. | "underline";
  1469. export interface StyleTextOptions {
  1470. /**
  1471. * When true, `stream` is checked to see if it can handle colors.
  1472. * @default true
  1473. */
  1474. validateStream?: boolean | undefined;
  1475. /**
  1476. * A stream that will be validated if it can be colored.
  1477. * @default process.stdout
  1478. */
  1479. stream?: NodeJS.WritableStream | undefined;
  1480. }
  1481. /**
  1482. * This function returns a formatted text considering the `format` passed
  1483. * for printing in a terminal. It is aware of the terminal's capabilities
  1484. * and acts according to the configuration set via `NO_COLORS`,
  1485. * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables.
  1486. *
  1487. * ```js
  1488. * import { styleText } from 'node:util';
  1489. * import { stderr } from 'node:process';
  1490. *
  1491. * const successMessage = styleText('green', 'Success!');
  1492. * console.log(successMessage);
  1493. *
  1494. * const errorMessage = styleText(
  1495. * 'red',
  1496. * 'Error! Error!',
  1497. * // Validate if process.stderr has TTY
  1498. * { stream: stderr },
  1499. * );
  1500. * console.error(errorMessage);
  1501. * ```
  1502. *
  1503. * `util.inspect.colors` also provides text formats such as `italic`, and
  1504. * `underline` and you can combine both:
  1505. *
  1506. * ```js
  1507. * console.log(
  1508. * util.styleText(['underline', 'italic'], 'My italic underlined message'),
  1509. * );
  1510. * ```
  1511. *
  1512. * When passing an array of formats, the order of the format applied
  1513. * is left to right so the following style might overwrite the previous one.
  1514. *
  1515. * ```js
  1516. * console.log(
  1517. * util.styleText(['red', 'green'], 'text'), // green
  1518. * );
  1519. * ```
  1520. *
  1521. * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers).
  1522. * @param format A text format or an Array of text formats defined in `util.inspect.colors`.
  1523. * @param text The text to to be formatted.
  1524. * @since v20.12.0
  1525. */
  1526. export function styleText(
  1527. format:
  1528. | ForegroundColors
  1529. | BackgroundColors
  1530. | Modifiers
  1531. | Array<ForegroundColors | BackgroundColors | Modifiers>,
  1532. text: string,
  1533. options?: StyleTextOptions,
  1534. ): string;
  1535. /**
  1536. * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API.
  1537. *
  1538. * ```js
  1539. * const decoder = new TextDecoder();
  1540. * const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
  1541. * console.log(decoder.decode(u8arr)); // Hello
  1542. * ```
  1543. * @since v8.3.0
  1544. */
  1545. export class TextDecoder {
  1546. /**
  1547. * The encoding supported by the `TextDecoder` instance.
  1548. */
  1549. readonly encoding: string;
  1550. /**
  1551. * The value will be `true` if decoding errors result in a `TypeError` being
  1552. * thrown.
  1553. */
  1554. readonly fatal: boolean;
  1555. /**
  1556. * The value will be `true` if the decoding result will include the byte order
  1557. * mark.
  1558. */
  1559. readonly ignoreBOM: boolean;
  1560. constructor(
  1561. encoding?: string,
  1562. options?: {
  1563. fatal?: boolean | undefined;
  1564. ignoreBOM?: boolean | undefined;
  1565. },
  1566. );
  1567. /**
  1568. * Decodes the `input` and returns a string. If `options.stream` is `true`, any
  1569. * incomplete byte sequences occurring at the end of the `input` are buffered
  1570. * internally and emitted after the next call to `textDecoder.decode()`.
  1571. *
  1572. * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown.
  1573. * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data.
  1574. */
  1575. decode(
  1576. input?: NodeJS.ArrayBufferView | ArrayBuffer | null,
  1577. options?: {
  1578. stream?: boolean | undefined;
  1579. },
  1580. ): string;
  1581. }
  1582. export interface EncodeIntoResult {
  1583. /**
  1584. * The read Unicode code units of input.
  1585. */
  1586. read: number;
  1587. /**
  1588. * The written UTF-8 bytes of output.
  1589. */
  1590. written: number;
  1591. }
  1592. export { types };
  1593. //// TextEncoder/Decoder
  1594. /**
  1595. * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
  1596. * instances of `TextEncoder` only support UTF-8 encoding.
  1597. *
  1598. * ```js
  1599. * const encoder = new TextEncoder();
  1600. * const uint8array = encoder.encode('this is some data');
  1601. * ```
  1602. *
  1603. * The `TextEncoder` class is also available on the global object.
  1604. * @since v8.3.0
  1605. */
  1606. export class TextEncoder {
  1607. /**
  1608. * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`.
  1609. */
  1610. readonly encoding: string;
  1611. /**
  1612. * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the
  1613. * encoded bytes.
  1614. * @param [input='an empty string'] The text to encode.
  1615. */
  1616. encode(input?: string): Uint8Array;
  1617. /**
  1618. * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
  1619. * containing the read Unicode code units and written UTF-8 bytes.
  1620. *
  1621. * ```js
  1622. * const encoder = new TextEncoder();
  1623. * const src = 'this is some data';
  1624. * const dest = new Uint8Array(10);
  1625. * const { read, written } = encoder.encodeInto(src, dest);
  1626. * ```
  1627. * @param src The text to encode.
  1628. * @param dest The array to hold the encode result.
  1629. */
  1630. encodeInto(src: string, dest: Uint8Array): EncodeIntoResult;
  1631. }
  1632. import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util";
  1633. global {
  1634. /**
  1635. * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'`
  1636. * https://nodejs.org/api/globals.html#textdecoder
  1637. * @since v11.0.0
  1638. */
  1639. var TextDecoder: typeof globalThis extends {
  1640. onmessage: any;
  1641. TextDecoder: infer TextDecoder;
  1642. } ? TextDecoder
  1643. : typeof _TextDecoder;
  1644. /**
  1645. * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'`
  1646. * https://nodejs.org/api/globals.html#textencoder
  1647. * @since v11.0.0
  1648. */
  1649. var TextEncoder: typeof globalThis extends {
  1650. onmessage: any;
  1651. TextEncoder: infer TextEncoder;
  1652. } ? TextEncoder
  1653. : typeof _TextEncoder;
  1654. }
  1655. //// parseArgs
  1656. /**
  1657. * Provides a higher level API for command-line argument parsing than interacting
  1658. * with `process.argv` directly. Takes a specification for the expected arguments
  1659. * and returns a structured object with the parsed options and positionals.
  1660. *
  1661. * ```js
  1662. * import { parseArgs } from 'node:util';
  1663. * const args = ['-f', '--bar', 'b'];
  1664. * const options = {
  1665. * foo: {
  1666. * type: 'boolean',
  1667. * short: 'f',
  1668. * },
  1669. * bar: {
  1670. * type: 'string',
  1671. * },
  1672. * };
  1673. * const {
  1674. * values,
  1675. * positionals,
  1676. * } = parseArgs({ args, options });
  1677. * console.log(values, positionals);
  1678. * // Prints: [Object: null prototype] { foo: true, bar: 'b' } []
  1679. * ```
  1680. * @since v18.3.0, v16.17.0
  1681. * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties:
  1682. * @return The parsed command line arguments:
  1683. */
  1684. export function parseArgs<T extends ParseArgsConfig>(config?: T): ParsedResults<T>;
  1685. /**
  1686. * Type of argument used in {@link parseArgs}.
  1687. */
  1688. export type ParseArgsOptionsType = "boolean" | "string";
  1689. export interface ParseArgsOptionDescriptor {
  1690. /**
  1691. * Type of argument.
  1692. */
  1693. type: ParseArgsOptionsType;
  1694. /**
  1695. * Whether this option can be provided multiple times.
  1696. * If `true`, all values will be collected in an array.
  1697. * If `false`, values for the option are last-wins.
  1698. * @default false.
  1699. */
  1700. multiple?: boolean | undefined;
  1701. /**
  1702. * A single character alias for the option.
  1703. */
  1704. short?: string | undefined;
  1705. /**
  1706. * The default value to
  1707. * be used if (and only if) the option does not appear in the arguments to be
  1708. * parsed. It must be of the same type as the `type` property. When `multiple`
  1709. * is `true`, it must be an array.
  1710. * @since v18.11.0
  1711. */
  1712. default?: string | boolean | string[] | boolean[] | undefined;
  1713. }
  1714. export interface ParseArgsOptionsConfig {
  1715. [longOption: string]: ParseArgsOptionDescriptor;
  1716. }
  1717. export interface ParseArgsConfig {
  1718. /**
  1719. * Array of argument strings.
  1720. */
  1721. args?: string[] | undefined;
  1722. /**
  1723. * Used to describe arguments known to the parser.
  1724. */
  1725. options?: ParseArgsOptionsConfig | undefined;
  1726. /**
  1727. * Should an error be thrown when unknown arguments are encountered,
  1728. * or when arguments are passed that do not match the `type` configured in `options`.
  1729. * @default true
  1730. */
  1731. strict?: boolean | undefined;
  1732. /**
  1733. * Whether this command accepts positional arguments.
  1734. */
  1735. allowPositionals?: boolean | undefined;
  1736. /**
  1737. * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`.
  1738. * @default false
  1739. * @since v22.4.0
  1740. */
  1741. allowNegative?: boolean | undefined;
  1742. /**
  1743. * Return the parsed tokens. This is useful for extending the built-in behavior,
  1744. * from adding additional checks through to reprocessing the tokens in different ways.
  1745. * @default false
  1746. */
  1747. tokens?: boolean | undefined;
  1748. }
  1749. /*
  1750. IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties.
  1751. TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936
  1752. This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present".
  1753. But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present.
  1754. So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value.
  1755. This is technically incorrect but is a much nicer UX for the common case.
  1756. The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false.
  1757. */
  1758. type IfDefaultsTrue<T, IfTrue, IfFalse> = T extends true ? IfTrue
  1759. : T extends false ? IfFalse
  1760. : IfTrue;
  1761. // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false`
  1762. type IfDefaultsFalse<T, IfTrue, IfFalse> = T extends false ? IfFalse
  1763. : T extends true ? IfTrue
  1764. : IfFalse;
  1765. type ExtractOptionValue<T extends ParseArgsConfig, O extends ParseArgsOptionDescriptor> = IfDefaultsTrue<
  1766. T["strict"],
  1767. O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean,
  1768. string | boolean
  1769. >;
  1770. type ApplyOptionalModifiers<O extends ParseArgsOptionsConfig, V extends Record<keyof O, unknown>> = (
  1771. & { -readonly [LongOption in keyof O]?: V[LongOption] }
  1772. & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] }
  1773. ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object
  1774. type ParsedValues<T extends ParseArgsConfig> =
  1775. & IfDefaultsTrue<T["strict"], unknown, { [longOption: string]: undefined | string | boolean }>
  1776. & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers<
  1777. T["options"],
  1778. {
  1779. [LongOption in keyof T["options"]]: IfDefaultsFalse<
  1780. T["options"][LongOption]["multiple"],
  1781. Array<ExtractOptionValue<T, T["options"][LongOption]>>,
  1782. ExtractOptionValue<T, T["options"][LongOption]>
  1783. >;
  1784. }
  1785. >
  1786. : {});
  1787. type ParsedPositionals<T extends ParseArgsConfig> = IfDefaultsTrue<
  1788. T["strict"],
  1789. IfDefaultsFalse<T["allowPositionals"], string[], []>,
  1790. IfDefaultsTrue<T["allowPositionals"], string[], []>
  1791. >;
  1792. type PreciseTokenForOptions<
  1793. K extends string,
  1794. O extends ParseArgsOptionDescriptor,
  1795. > = O["type"] extends "string" ? {
  1796. kind: "option";
  1797. index: number;
  1798. name: K;
  1799. rawName: string;
  1800. value: string;
  1801. inlineValue: boolean;
  1802. }
  1803. : O["type"] extends "boolean" ? {
  1804. kind: "option";
  1805. index: number;
  1806. name: K;
  1807. rawName: string;
  1808. value: undefined;
  1809. inlineValue: undefined;
  1810. }
  1811. : OptionToken & { name: K };
  1812. type TokenForOptions<
  1813. T extends ParseArgsConfig,
  1814. K extends keyof T["options"] = keyof T["options"],
  1815. > = K extends unknown
  1816. ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions<K & string, T["options"][K]>
  1817. : OptionToken
  1818. : never;
  1819. type ParsedOptionToken<T extends ParseArgsConfig> = IfDefaultsTrue<T["strict"], TokenForOptions<T>, OptionToken>;
  1820. type ParsedPositionalToken<T extends ParseArgsConfig> = IfDefaultsTrue<
  1821. T["strict"],
  1822. IfDefaultsFalse<T["allowPositionals"], { kind: "positional"; index: number; value: string }, never>,
  1823. IfDefaultsTrue<T["allowPositionals"], { kind: "positional"; index: number; value: string }, never>
  1824. >;
  1825. type ParsedTokens<T extends ParseArgsConfig> = Array<
  1826. ParsedOptionToken<T> | ParsedPositionalToken<T> | { kind: "option-terminator"; index: number }
  1827. >;
  1828. type PreciseParsedResults<T extends ParseArgsConfig> = IfDefaultsFalse<
  1829. T["tokens"],
  1830. {
  1831. values: ParsedValues<T>;
  1832. positionals: ParsedPositionals<T>;
  1833. tokens: ParsedTokens<T>;
  1834. },
  1835. {
  1836. values: ParsedValues<T>;
  1837. positionals: ParsedPositionals<T>;
  1838. }
  1839. >;
  1840. type OptionToken =
  1841. | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean }
  1842. | {
  1843. kind: "option";
  1844. index: number;
  1845. name: string;
  1846. rawName: string;
  1847. value: undefined;
  1848. inlineValue: undefined;
  1849. };
  1850. type Token =
  1851. | OptionToken
  1852. | { kind: "positional"; index: number; value: string }
  1853. | { kind: "option-terminator"; index: number };
  1854. // If ParseArgsConfig extends T, then the user passed config constructed elsewhere.
  1855. // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above.
  1856. type ParsedResults<T extends ParseArgsConfig> = ParseArgsConfig extends T ? {
  1857. values: {
  1858. [longOption: string]: undefined | string | boolean | Array<string | boolean>;
  1859. };
  1860. positionals: string[];
  1861. tokens?: Token[];
  1862. }
  1863. : PreciseParsedResults<T>;
  1864. /**
  1865. * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/).
  1866. *
  1867. * In accordance with browser conventions, all properties of `MIMEType` objects
  1868. * are implemented as getters and setters on the class prototype, rather than as
  1869. * data properties on the object itself.
  1870. *
  1871. * A MIME string is a structured string containing multiple meaningful
  1872. * components. When parsed, a `MIMEType` object is returned containing
  1873. * properties for each of these components.
  1874. * @since v19.1.0, v18.13.0
  1875. */
  1876. export class MIMEType {
  1877. /**
  1878. * Creates a new MIMEType object by parsing the input.
  1879. *
  1880. * A `TypeError` will be thrown if the `input` is not a valid MIME.
  1881. * Note that an effort will be made to coerce the given values into strings.
  1882. * @param input The input MIME to parse.
  1883. */
  1884. constructor(input: string | { toString: () => string });
  1885. /**
  1886. * Gets and sets the type portion of the MIME.
  1887. *
  1888. * ```js
  1889. * import { MIMEType } from 'node:util';
  1890. *
  1891. * const myMIME = new MIMEType('text/javascript');
  1892. * console.log(myMIME.type);
  1893. * // Prints: text
  1894. * myMIME.type = 'application';
  1895. * console.log(myMIME.type);
  1896. * // Prints: application
  1897. * console.log(String(myMIME));
  1898. * // Prints: application/javascript
  1899. * ```
  1900. */
  1901. type: string;
  1902. /**
  1903. * Gets and sets the subtype portion of the MIME.
  1904. *
  1905. * ```js
  1906. * import { MIMEType } from 'node:util';
  1907. *
  1908. * const myMIME = new MIMEType('text/ecmascript');
  1909. * console.log(myMIME.subtype);
  1910. * // Prints: ecmascript
  1911. * myMIME.subtype = 'javascript';
  1912. * console.log(myMIME.subtype);
  1913. * // Prints: javascript
  1914. * console.log(String(myMIME));
  1915. * // Prints: text/javascript
  1916. * ```
  1917. */
  1918. subtype: string;
  1919. /**
  1920. * Gets the essence of the MIME. This property is read only.
  1921. * Use `mime.type` or `mime.subtype` to alter the MIME.
  1922. *
  1923. * ```js
  1924. * import { MIMEType } from 'node:util';
  1925. *
  1926. * const myMIME = new MIMEType('text/javascript;key=value');
  1927. * console.log(myMIME.essence);
  1928. * // Prints: text/javascript
  1929. * myMIME.type = 'application';
  1930. * console.log(myMIME.essence);
  1931. * // Prints: application/javascript
  1932. * console.log(String(myMIME));
  1933. * // Prints: application/javascript;key=value
  1934. * ```
  1935. */
  1936. readonly essence: string;
  1937. /**
  1938. * Gets the `MIMEParams` object representing the
  1939. * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details.
  1940. */
  1941. readonly params: MIMEParams;
  1942. /**
  1943. * The `toString()` method on the `MIMEType` object returns the serialized MIME.
  1944. *
  1945. * Because of the need for standard compliance, this method does not allow users
  1946. * to customize the serialization process of the MIME.
  1947. */
  1948. toString(): string;
  1949. }
  1950. /**
  1951. * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`.
  1952. * @since v19.1.0, v18.13.0
  1953. */
  1954. export class MIMEParams {
  1955. /**
  1956. * Remove all name-value pairs whose name is `name`.
  1957. */
  1958. delete(name: string): void;
  1959. /**
  1960. * Returns an iterator over each of the name-value pairs in the parameters.
  1961. * Each item of the iterator is a JavaScript `Array`. The first item of the array
  1962. * is the `name`, the second item of the array is the `value`.
  1963. */
  1964. entries(): NodeJS.Iterator<[name: string, value: string]>;
  1965. /**
  1966. * Returns the value of the first name-value pair whose name is `name`. If there
  1967. * are no such pairs, `null` is returned.
  1968. * @return or `null` if there is no name-value pair with the given `name`.
  1969. */
  1970. get(name: string): string | null;
  1971. /**
  1972. * Returns `true` if there is at least one name-value pair whose name is `name`.
  1973. */
  1974. has(name: string): boolean;
  1975. /**
  1976. * Returns an iterator over the names of each name-value pair.
  1977. *
  1978. * ```js
  1979. * import { MIMEType } from 'node:util';
  1980. *
  1981. * const { params } = new MIMEType('text/plain;foo=0;bar=1');
  1982. * for (const name of params.keys()) {
  1983. * console.log(name);
  1984. * }
  1985. * // Prints:
  1986. * // foo
  1987. * // bar
  1988. * ```
  1989. */
  1990. keys(): NodeJS.Iterator<string>;
  1991. /**
  1992. * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`,
  1993. * set the first such pair's value to `value`.
  1994. *
  1995. * ```js
  1996. * import { MIMEType } from 'node:util';
  1997. *
  1998. * const { params } = new MIMEType('text/plain;foo=0;bar=1');
  1999. * params.set('foo', 'def');
  2000. * params.set('baz', 'xyz');
  2001. * console.log(params.toString());
  2002. * // Prints: foo=def;bar=1;baz=xyz
  2003. * ```
  2004. */
  2005. set(name: string, value: string): void;
  2006. /**
  2007. * Returns an iterator over the values of each name-value pair.
  2008. */
  2009. values(): NodeJS.Iterator<string>;
  2010. /**
  2011. * Returns an iterator over each of the name-value pairs in the parameters.
  2012. */
  2013. [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>;
  2014. }
  2015. }
  2016. declare module "util/types" {
  2017. import { KeyObject, webcrypto } from "node:crypto";
  2018. /**
  2019. * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or
  2020. * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance.
  2021. *
  2022. * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`.
  2023. *
  2024. * ```js
  2025. * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
  2026. * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
  2027. * ```
  2028. * @since v10.0.0
  2029. */
  2030. function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike;
  2031. /**
  2032. * Returns `true` if the value is an `arguments` object.
  2033. *
  2034. * ```js
  2035. * function foo() {
  2036. * util.types.isArgumentsObject(arguments); // Returns true
  2037. * }
  2038. * ```
  2039. * @since v10.0.0
  2040. */
  2041. function isArgumentsObject(object: unknown): object is IArguments;
  2042. /**
  2043. * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance.
  2044. * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is
  2045. * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that.
  2046. *
  2047. * ```js
  2048. * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
  2049. * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
  2050. * ```
  2051. * @since v10.0.0
  2052. */
  2053. function isArrayBuffer(object: unknown): object is ArrayBuffer;
  2054. /**
  2055. * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed
  2056. * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to
  2057. * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
  2058. *
  2059. * ```js
  2060. * util.types.isArrayBufferView(new Int8Array()); // true
  2061. * util.types.isArrayBufferView(Buffer.from('hello world')); // true
  2062. * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true
  2063. * util.types.isArrayBufferView(new ArrayBuffer()); // false
  2064. * ```
  2065. * @since v10.0.0
  2066. */
  2067. function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView;
  2068. /**
  2069. * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
  2070. * This only reports back what the JavaScript engine is seeing;
  2071. * in particular, the return value may not match the original source code if
  2072. * a transpilation tool was used.
  2073. *
  2074. * ```js
  2075. * util.types.isAsyncFunction(function foo() {}); // Returns false
  2076. * util.types.isAsyncFunction(async function foo() {}); // Returns true
  2077. * ```
  2078. * @since v10.0.0
  2079. */
  2080. function isAsyncFunction(object: unknown): boolean;
  2081. /**
  2082. * Returns `true` if the value is a `BigInt64Array` instance.
  2083. *
  2084. * ```js
  2085. * util.types.isBigInt64Array(new BigInt64Array()); // Returns true
  2086. * util.types.isBigInt64Array(new BigUint64Array()); // Returns false
  2087. * ```
  2088. * @since v10.0.0
  2089. */
  2090. function isBigInt64Array(value: unknown): value is BigInt64Array;
  2091. /**
  2092. * Returns `true` if the value is a BigInt object, e.g. created
  2093. * by `Object(BigInt(123))`.
  2094. *
  2095. * ```js
  2096. * util.types.isBigIntObject(Object(BigInt(123))); // Returns true
  2097. * util.types.isBigIntObject(BigInt(123)); // Returns false
  2098. * util.types.isBigIntObject(123); // Returns false
  2099. * ```
  2100. * @since v10.4.0
  2101. */
  2102. function isBigIntObject(object: unknown): object is BigInt;
  2103. /**
  2104. * Returns `true` if the value is a `BigUint64Array` instance.
  2105. *
  2106. * ```js
  2107. * util.types.isBigUint64Array(new BigInt64Array()); // Returns false
  2108. * util.types.isBigUint64Array(new BigUint64Array()); // Returns true
  2109. * ```
  2110. * @since v10.0.0
  2111. */
  2112. function isBigUint64Array(value: unknown): value is BigUint64Array;
  2113. /**
  2114. * Returns `true` if the value is a boolean object, e.g. created
  2115. * by `new Boolean()`.
  2116. *
  2117. * ```js
  2118. * util.types.isBooleanObject(false); // Returns false
  2119. * util.types.isBooleanObject(true); // Returns false
  2120. * util.types.isBooleanObject(new Boolean(false)); // Returns true
  2121. * util.types.isBooleanObject(new Boolean(true)); // Returns true
  2122. * util.types.isBooleanObject(Boolean(false)); // Returns false
  2123. * util.types.isBooleanObject(Boolean(true)); // Returns false
  2124. * ```
  2125. * @since v10.0.0
  2126. */
  2127. function isBooleanObject(object: unknown): object is Boolean;
  2128. /**
  2129. * Returns `true` if the value is any boxed primitive object, e.g. created
  2130. * by `new Boolean()`, `new String()` or `Object(Symbol())`.
  2131. *
  2132. * For example:
  2133. *
  2134. * ```js
  2135. * util.types.isBoxedPrimitive(false); // Returns false
  2136. * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
  2137. * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
  2138. * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
  2139. * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
  2140. * ```
  2141. * @since v10.11.0
  2142. */
  2143. function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol;
  2144. /**
  2145. * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance.
  2146. *
  2147. * ```js
  2148. * const ab = new ArrayBuffer(20);
  2149. * util.types.isDataView(new DataView(ab)); // Returns true
  2150. * util.types.isDataView(new Float64Array()); // Returns false
  2151. * ```
  2152. *
  2153. * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
  2154. * @since v10.0.0
  2155. */
  2156. function isDataView(object: unknown): object is DataView;
  2157. /**
  2158. * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance.
  2159. *
  2160. * ```js
  2161. * util.types.isDate(new Date()); // Returns true
  2162. * ```
  2163. * @since v10.0.0
  2164. */
  2165. function isDate(object: unknown): object is Date;
  2166. /**
  2167. * Returns `true` if the value is a native `External` value.
  2168. *
  2169. * A native `External` value is a special type of object that contains a
  2170. * raw C++ pointer (`void*`) for access from native code, and has no other
  2171. * properties. Such objects are created either by Node.js internals or native
  2172. * addons. In JavaScript, they are
  2173. * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a
  2174. * `null` prototype.
  2175. *
  2176. * ```c
  2177. * #include <js_native_api.h>
  2178. * #include <stdlib.h>
  2179. * napi_value result;
  2180. * static napi_value MyNapi(napi_env env, napi_callback_info info) {
  2181. * int* raw = (int*) malloc(1024);
  2182. * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
  2183. * if (status != napi_ok) {
  2184. * napi_throw_error(env, NULL, "napi_create_external failed");
  2185. * return NULL;
  2186. * }
  2187. * return result;
  2188. * }
  2189. * ...
  2190. * DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
  2191. * ...
  2192. * ```
  2193. *
  2194. * ```js
  2195. * import native from 'napi_addon.node';
  2196. * import { types } from 'node:util';
  2197. *
  2198. * const data = native.myNapi();
  2199. * types.isExternal(data); // returns true
  2200. * types.isExternal(0); // returns false
  2201. * types.isExternal(new String('foo')); // returns false
  2202. * ```
  2203. *
  2204. * For further information on `napi_create_external`, refer to
  2205. * [`napi_create_external()`](https://nodejs.org/docs/latest-v22.x/api/n-api.html#napi_create_external).
  2206. * @since v10.0.0
  2207. */
  2208. function isExternal(object: unknown): boolean;
  2209. /**
  2210. * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance.
  2211. *
  2212. * ```js
  2213. * util.types.isFloat32Array(new ArrayBuffer()); // Returns false
  2214. * util.types.isFloat32Array(new Float32Array()); // Returns true
  2215. * util.types.isFloat32Array(new Float64Array()); // Returns false
  2216. * ```
  2217. * @since v10.0.0
  2218. */
  2219. function isFloat32Array(object: unknown): object is Float32Array;
  2220. /**
  2221. * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance.
  2222. *
  2223. * ```js
  2224. * util.types.isFloat64Array(new ArrayBuffer()); // Returns false
  2225. * util.types.isFloat64Array(new Uint8Array()); // Returns false
  2226. * util.types.isFloat64Array(new Float64Array()); // Returns true
  2227. * ```
  2228. * @since v10.0.0
  2229. */
  2230. function isFloat64Array(object: unknown): object is Float64Array;
  2231. /**
  2232. * Returns `true` if the value is a generator function.
  2233. * This only reports back what the JavaScript engine is seeing;
  2234. * in particular, the return value may not match the original source code if
  2235. * a transpilation tool was used.
  2236. *
  2237. * ```js
  2238. * util.types.isGeneratorFunction(function foo() {}); // Returns false
  2239. * util.types.isGeneratorFunction(function* foo() {}); // Returns true
  2240. * ```
  2241. * @since v10.0.0
  2242. */
  2243. function isGeneratorFunction(object: unknown): object is GeneratorFunction;
  2244. /**
  2245. * Returns `true` if the value is a generator object as returned from a
  2246. * built-in generator function.
  2247. * This only reports back what the JavaScript engine is seeing;
  2248. * in particular, the return value may not match the original source code if
  2249. * a transpilation tool was used.
  2250. *
  2251. * ```js
  2252. * function* foo() {}
  2253. * const generator = foo();
  2254. * util.types.isGeneratorObject(generator); // Returns true
  2255. * ```
  2256. * @since v10.0.0
  2257. */
  2258. function isGeneratorObject(object: unknown): object is Generator;
  2259. /**
  2260. * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance.
  2261. *
  2262. * ```js
  2263. * util.types.isInt8Array(new ArrayBuffer()); // Returns false
  2264. * util.types.isInt8Array(new Int8Array()); // Returns true
  2265. * util.types.isInt8Array(new Float64Array()); // Returns false
  2266. * ```
  2267. * @since v10.0.0
  2268. */
  2269. function isInt8Array(object: unknown): object is Int8Array;
  2270. /**
  2271. * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance.
  2272. *
  2273. * ```js
  2274. * util.types.isInt16Array(new ArrayBuffer()); // Returns false
  2275. * util.types.isInt16Array(new Int16Array()); // Returns true
  2276. * util.types.isInt16Array(new Float64Array()); // Returns false
  2277. * ```
  2278. * @since v10.0.0
  2279. */
  2280. function isInt16Array(object: unknown): object is Int16Array;
  2281. /**
  2282. * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance.
  2283. *
  2284. * ```js
  2285. * util.types.isInt32Array(new ArrayBuffer()); // Returns false
  2286. * util.types.isInt32Array(new Int32Array()); // Returns true
  2287. * util.types.isInt32Array(new Float64Array()); // Returns false
  2288. * ```
  2289. * @since v10.0.0
  2290. */
  2291. function isInt32Array(object: unknown): object is Int32Array;
  2292. /**
  2293. * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
  2294. *
  2295. * ```js
  2296. * util.types.isMap(new Map()); // Returns true
  2297. * ```
  2298. * @since v10.0.0
  2299. */
  2300. function isMap<T>(
  2301. object: T | {},
  2302. ): object is T extends ReadonlyMap<any, any> ? (unknown extends T ? never : ReadonlyMap<any, any>)
  2303. : Map<unknown, unknown>;
  2304. /**
  2305. * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
  2306. *
  2307. * ```js
  2308. * const map = new Map();
  2309. * util.types.isMapIterator(map.keys()); // Returns true
  2310. * util.types.isMapIterator(map.values()); // Returns true
  2311. * util.types.isMapIterator(map.entries()); // Returns true
  2312. * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
  2313. * ```
  2314. * @since v10.0.0
  2315. */
  2316. function isMapIterator(object: unknown): boolean;
  2317. /**
  2318. * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects).
  2319. *
  2320. * ```js
  2321. * import * as ns from './a.js';
  2322. *
  2323. * util.types.isModuleNamespaceObject(ns); // Returns true
  2324. * ```
  2325. * @since v10.0.0
  2326. */
  2327. function isModuleNamespaceObject(value: unknown): boolean;
  2328. /**
  2329. * Returns `true` if the value was returned by the constructor of a
  2330. * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects).
  2331. *
  2332. * ```js
  2333. * console.log(util.types.isNativeError(new Error())); // true
  2334. * console.log(util.types.isNativeError(new TypeError())); // true
  2335. * console.log(util.types.isNativeError(new RangeError())); // true
  2336. * ```
  2337. *
  2338. * Subclasses of the native error types are also native errors:
  2339. *
  2340. * ```js
  2341. * class MyError extends Error {}
  2342. * console.log(util.types.isNativeError(new MyError())); // true
  2343. * ```
  2344. *
  2345. * A value being `instanceof` a native error class is not equivalent to `isNativeError()`
  2346. * returning `true` for that value. `isNativeError()` returns `true` for errors
  2347. * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false`
  2348. * for these errors:
  2349. *
  2350. * ```js
  2351. * import { createContext, runInContext } from 'node:vm';
  2352. * import { types } from 'node:util';
  2353. *
  2354. * const context = createContext({});
  2355. * const myError = runInContext('new Error()', context);
  2356. * console.log(types.isNativeError(myError)); // true
  2357. * console.log(myError instanceof Error); // false
  2358. * ```
  2359. *
  2360. * Conversely, `isNativeError()` returns `false` for all objects which were not
  2361. * returned by the constructor of a native error. That includes values
  2362. * which are `instanceof` native errors:
  2363. *
  2364. * ```js
  2365. * const myError = { __proto__: Error.prototype };
  2366. * console.log(util.types.isNativeError(myError)); // false
  2367. * console.log(myError instanceof Error); // true
  2368. * ```
  2369. * @since v10.0.0
  2370. */
  2371. function isNativeError(object: unknown): object is Error;
  2372. /**
  2373. * Returns `true` if the value is a number object, e.g. created
  2374. * by `new Number()`.
  2375. *
  2376. * ```js
  2377. * util.types.isNumberObject(0); // Returns false
  2378. * util.types.isNumberObject(new Number(0)); // Returns true
  2379. * ```
  2380. * @since v10.0.0
  2381. */
  2382. function isNumberObject(object: unknown): object is Number;
  2383. /**
  2384. * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  2385. *
  2386. * ```js
  2387. * util.types.isPromise(Promise.resolve(42)); // Returns true
  2388. * ```
  2389. * @since v10.0.0
  2390. */
  2391. function isPromise(object: unknown): object is Promise<unknown>;
  2392. /**
  2393. * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance.
  2394. *
  2395. * ```js
  2396. * const target = {};
  2397. * const proxy = new Proxy(target, {});
  2398. * util.types.isProxy(target); // Returns false
  2399. * util.types.isProxy(proxy); // Returns true
  2400. * ```
  2401. * @since v10.0.0
  2402. */
  2403. function isProxy(object: unknown): boolean;
  2404. /**
  2405. * Returns `true` if the value is a regular expression object.
  2406. *
  2407. * ```js
  2408. * util.types.isRegExp(/abc/); // Returns true
  2409. * util.types.isRegExp(new RegExp('abc')); // Returns true
  2410. * ```
  2411. * @since v10.0.0
  2412. */
  2413. function isRegExp(object: unknown): object is RegExp;
  2414. /**
  2415. * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
  2416. *
  2417. * ```js
  2418. * util.types.isSet(new Set()); // Returns true
  2419. * ```
  2420. * @since v10.0.0
  2421. */
  2422. function isSet<T>(
  2423. object: T | {},
  2424. ): object is T extends ReadonlySet<any> ? (unknown extends T ? never : ReadonlySet<any>) : Set<unknown>;
  2425. /**
  2426. * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
  2427. *
  2428. * ```js
  2429. * const set = new Set();
  2430. * util.types.isSetIterator(set.keys()); // Returns true
  2431. * util.types.isSetIterator(set.values()); // Returns true
  2432. * util.types.isSetIterator(set.entries()); // Returns true
  2433. * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
  2434. * ```
  2435. * @since v10.0.0
  2436. */
  2437. function isSetIterator(object: unknown): boolean;
  2438. /**
  2439. * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance.
  2440. * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is
  2441. * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that.
  2442. *
  2443. * ```js
  2444. * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false
  2445. * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
  2446. * ```
  2447. * @since v10.0.0
  2448. */
  2449. function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer;
  2450. /**
  2451. * Returns `true` if the value is a string object, e.g. created
  2452. * by `new String()`.
  2453. *
  2454. * ```js
  2455. * util.types.isStringObject('foo'); // Returns false
  2456. * util.types.isStringObject(new String('foo')); // Returns true
  2457. * ```
  2458. * @since v10.0.0
  2459. */
  2460. function isStringObject(object: unknown): object is String;
  2461. /**
  2462. * Returns `true` if the value is a symbol object, created
  2463. * by calling `Object()` on a `Symbol` primitive.
  2464. *
  2465. * ```js
  2466. * const symbol = Symbol('foo');
  2467. * util.types.isSymbolObject(symbol); // Returns false
  2468. * util.types.isSymbolObject(Object(symbol)); // Returns true
  2469. * ```
  2470. * @since v10.0.0
  2471. */
  2472. function isSymbolObject(object: unknown): object is Symbol;
  2473. /**
  2474. * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance.
  2475. *
  2476. * ```js
  2477. * util.types.isTypedArray(new ArrayBuffer()); // Returns false
  2478. * util.types.isTypedArray(new Uint8Array()); // Returns true
  2479. * util.types.isTypedArray(new Float64Array()); // Returns true
  2480. * ```
  2481. *
  2482. * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
  2483. * @since v10.0.0
  2484. */
  2485. function isTypedArray(object: unknown): object is NodeJS.TypedArray;
  2486. /**
  2487. * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance.
  2488. *
  2489. * ```js
  2490. * util.types.isUint8Array(new ArrayBuffer()); // Returns false
  2491. * util.types.isUint8Array(new Uint8Array()); // Returns true
  2492. * util.types.isUint8Array(new Float64Array()); // Returns false
  2493. * ```
  2494. * @since v10.0.0
  2495. */
  2496. function isUint8Array(object: unknown): object is Uint8Array;
  2497. /**
  2498. * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance.
  2499. *
  2500. * ```js
  2501. * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false
  2502. * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
  2503. * util.types.isUint8ClampedArray(new Float64Array()); // Returns false
  2504. * ```
  2505. * @since v10.0.0
  2506. */
  2507. function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray;
  2508. /**
  2509. * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance.
  2510. *
  2511. * ```js
  2512. * util.types.isUint16Array(new ArrayBuffer()); // Returns false
  2513. * util.types.isUint16Array(new Uint16Array()); // Returns true
  2514. * util.types.isUint16Array(new Float64Array()); // Returns false
  2515. * ```
  2516. * @since v10.0.0
  2517. */
  2518. function isUint16Array(object: unknown): object is Uint16Array;
  2519. /**
  2520. * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance.
  2521. *
  2522. * ```js
  2523. * util.types.isUint32Array(new ArrayBuffer()); // Returns false
  2524. * util.types.isUint32Array(new Uint32Array()); // Returns true
  2525. * util.types.isUint32Array(new Float64Array()); // Returns false
  2526. * ```
  2527. * @since v10.0.0
  2528. */
  2529. function isUint32Array(object: unknown): object is Uint32Array;
  2530. /**
  2531. * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance.
  2532. *
  2533. * ```js
  2534. * util.types.isWeakMap(new WeakMap()); // Returns true
  2535. * ```
  2536. * @since v10.0.0
  2537. */
  2538. function isWeakMap(object: unknown): object is WeakMap<object, unknown>;
  2539. /**
  2540. * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance.
  2541. *
  2542. * ```js
  2543. * util.types.isWeakSet(new WeakSet()); // Returns true
  2544. * ```
  2545. * @since v10.0.0
  2546. */
  2547. function isWeakSet(object: unknown): object is WeakSet<object>;
  2548. /**
  2549. * Returns `true` if `value` is a `KeyObject`, `false` otherwise.
  2550. * @since v16.2.0
  2551. */
  2552. function isKeyObject(object: unknown): object is KeyObject;
  2553. /**
  2554. * Returns `true` if `value` is a `CryptoKey`, `false` otherwise.
  2555. * @since v16.2.0
  2556. */
  2557. function isCryptoKey(object: unknown): object is webcrypto.CryptoKey;
  2558. }
  2559. declare module "node:util" {
  2560. export * from "util";
  2561. }
  2562. declare module "node:util/types" {
  2563. export * from "util/types";
  2564. }