All files / src/internal output.ts

100% Statements 68/68
100% Branches 43/43
100% Functions 16/16
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                          108x         108x       416x     108x         299952x       347x 347x 347x                         3541172x   299708x   2909871x   180x   244x 244x     410x   347x   330412x 330010x 329830x 328688x   386x 386x 323x 553x 323x     328302x                       990132x 989935x 1699332x 988606x                                                 738x 738x 648x 522x 522x 522x 681x 522x 522x                                   1014x                   164203x 164179x 164179x 164179x 919656x   164086x                                 56x 56x 54x 48x 48x 48x 48x 95x       48x                               6x    
// Printing collections: `toString` and Node's inspect hook.
 
import { isBranded } from './brand'
import { createGuard } from './cycle'
 
/** What printing needs from a collection. @internal */
export interface Printable {
  readonly size: number
  readonly [Symbol.toStringTag]: string
  [Symbol.iterator](): Iterator<unknown>
}
 
// The shared brand every collection carries, from `Symbol.for`, so any loaded copy recognises it.
export const COLLECTION_BRAND: unique symbol = /*#__PURE__*/ Symbol.for(
  'javascript-collections-framework/1/Collection',
)
 
// Node's custom inspect key, from `Symbol.for`, so no platform module is imported.
export const INSPECT: unique symbol = /*#__PURE__*/ Symbol.for(
  'nodejs.util.inspect.custom',
) as never
 
const CIRCULAR = () => '[Circular]'
 
/** The guard shared by printing and inspecting; other operations have their own. */
const printGuard = /*#__PURE__*/ createGuard()
 
/** Escapes text for single-quoted output: quotes, backslashes and control characters. */
function escapeText(text: string): string {
  // split/join rather than a regular expression: no pattern runs on user text.
  return JSON.stringify(text).slice(1, -1).split('\\"').join('"').split("'").join("\\'")
}
 
function functionName(fn: (...args: never[]) => unknown): string {
  const descriptor = Object.getOwnPropertyDescriptor(fn, 'name')
  const name = descriptor !== undefined && 'value' in descriptor ? descriptor.value : undefined
  return typeof name === 'string' && name !== '' ? `[Function: ${name}]` : '[Function (anonymous)]'
}
 
/**
 * Renders one element for `toString`: strings in single quotes, escaped; numbers with `String`
 * except `-0`; bigints with `n`; symbols as `Symbol(description)` with the description escaped;
 * `null`/`undefined` as written; library collections and arrays recursively, cycle-safe;
 * functions as `[Function: name]`; any other object with `String(value)`, as
 * `Array.prototype.join` does (its own `toString` runs; its errors propagate).
 *
 * @internal
 */
export function renderElement(value: unknown): string {
  switch (typeof value) {
    case 'string':
      return `'${escapeText(value)}'`
    case 'number':
      return value === 0 && 1 / value < 0 ? '-0' : String(value)
    case 'bigint':
      return `${String(value)}n`
    case 'symbol': {
      const text = String(value)
      return `Symbol(${escapeText(text.slice(7, -1))})`
    }
    case 'undefined':
      return 'undefined'
    case 'function':
      return functionName(value as (...args: never[]) => unknown)
    default:
      if (value === null) return 'null'
      if (typeof value !== 'object') return String(value)
      if (isBranded(value, COLLECTION_BRAND)) return String(value)
      if (Array.isArray(value)) {
        // An index loop, not `value.map`: an array subclass or an own `map` cannot take over.
        const array = value as unknown[]
        return printGuard(array, CIRCULAR, () => {
          const parts: string[] = []
          for (let i = 0; i < array.length; i++) parts.push(renderElement(array[i]))
          return `[${parts.join(', ')}]`
        })
      }
      return String(value)
  }
}
 
/**
 * Renders a collection: `ClassName(size) [a, b]` (or with braces for sets), `[Circular]` when it
 * is already being printed. Parts are collected and joined once, so the cost is linear in the
 * output for flat contents; each level of nested arrays or collections copies its text once more.
 *
 * @internal
 */
export function collectionToString(collection: Printable, open: string, close: string): string {
  return printGuard(collection, CIRCULAR, () => {
    const parts: string[] = []
    for (const element of collection as Iterable<unknown>) parts.push(renderElement(element))
    return `${collection[Symbol.toStringTag]}(${collection.size}) ${open}${parts.join(', ')}${close}`
  })
}
 
/** The options object Node passes to a custom inspect function (only what is used here). @internal */
export interface InspectOptions {
  depth?: number | null
}
 
/**
 * Node's custom inspect hook body: `ClassName(size) [ a, b ]` (braces for sets), each element
 * formatted by Node's own `inspect` one level deeper than the remaining `depth` Node passed in;
 * `[ClassName]` beyond the depth limit; `[Circular]` for a collection already being inspected.
 * The `inspect` function is the one Node passes in, so nothing platform-specific is imported.
 *
 * @internal
 */
export function inspectCollection(
  collection: Printable,
  depth: number | null,
  options: InspectOptions,
  inspect: (value: unknown, options: InspectOptions) => string,
  open: string,
  close: string,
): string {
  const tag = collection[Symbol.toStringTag]
  if (depth !== null && depth < 0) return `[${tag}]`
  return printGuard(collection, CIRCULAR, () => {
    const childOptions = Object.assign({}, options, { depth: depth === null ? null : depth - 1 })
    const parts: string[] = []
    for (const element of collection as Iterable<unknown>)
      parts.push(inspect(element, childOptions))
    const body = parts.length === 0 ? `${open}${close}` : `${open} ${parts.join(', ')} ${close}`
    return `${tag}(${collection.size}) ${body}`
  })
}
 
/** What printing needs from a map: its size, tag and `[key, value]` pairs. @internal */
export interface PrintableMap {
  readonly size: number
  readonly [Symbol.toStringTag]: string
  [Symbol.iterator](): Iterator<readonly [unknown, unknown]>
}
 
/**
 * Renders one mapping for `toString`: `key => value`, each part as {@link renderElement} renders
 * an element; `[Circular]` when `owner` (an entry) is already being printed.
 *
 * @internal
 */
export function mappingToString(owner: object, key: unknown, value: unknown): string {
  return printGuard(owner, CIRCULAR, () => `${renderElement(key)} => ${renderElement(value)}`)
}
 
/**
 * Renders a map: `ClassName(size) {k1 => v1, k2 => v2}`, `[Circular]` when it is already being
 * printed.
 *
 * @internal
 */
export function mapToString(map: PrintableMap): string {
  return printGuard(map, CIRCULAR, () => {
    const parts: string[] = []
    const pairs = map[Symbol.iterator]()
    for (let step = pairs.next(); step.done !== true; step = pairs.next()) {
      parts.push(`${renderElement(step.value[0])} => ${renderElement(step.value[1])}`)
    }
    return `${map[Symbol.toStringTag]}(${map.size}) {${parts.join(', ')}}`
  })
}
 
/**
 * Node's custom inspect hook body for a map: `ClassName(size) { k1 => v1 }`, keys and values
 * formatted by Node's `inspect` one level deeper; `[ClassName]` beyond the depth limit;
 * `[Circular]` for a map already being inspected.
 *
 * @internal
 */
export function inspectMap(
  map: PrintableMap,
  depth: number | null,
  options: InspectOptions,
  inspect: (value: unknown, options: InspectOptions) => string,
): string {
  const tag = map[Symbol.toStringTag]
  if (depth !== null && depth < 0) return `[${tag}]`
  return printGuard(map, CIRCULAR, () => {
    const childOptions = Object.assign({}, options, { depth: depth === null ? null : depth - 1 })
    const parts: string[] = []
    const pairs = map[Symbol.iterator]()
    for (let step = pairs.next(); step.done !== true; step = pairs.next()) {
      parts.push(
        `${inspect(step.value[0], childOptions)} => ${inspect(step.value[1], childOptions)}`,
      )
    }
    return `${tag}(${map.size}) ${parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`}`
  })
}
 
/**
 * Node's custom inspect hook body for a map entry: `key => value`, each formatted by Node's
 * `inspect` with the remaining depth.
 *
 * @internal
 */
export function inspectMapping(
  key: unknown,
  value: unknown,
  options: InspectOptions,
  inspect: (value: unknown, options: InspectOptions) => string,
): string {
  return `${inspect(key, options)} => ${inspect(value, options)}`
}