All files / src/type-identity index.js

99.27% Statements 274/276
87.03% Branches 47/54
100% Functions 5/5
99.27% Lines 274/276

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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 3311x   1x               1x 1x   1x 1x   1x   1x 1x   1x   1x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 305x   305x 303x 303x   303x 303x 303x 303x 279x   279x 279x   279x 279x 279x   279x 279x 279x   279x   279x 279x 279x 279x 72x 279x 72x 279x 279x 279x   279x 279x 72x 66x 66x 279x 279x 303x 305x 305x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 102x   102x 102x 7x 7x   7x   7x 7x   7x 7x 7x   7x 7x 7x   7x   7x 4x 4x 7x 102x 102x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 102x   102x 102x 102x 102x   102x 7x 7x   7x   7x 7x   7x 7x 7x   7x 7x 7x   7x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x   7x 7x 7x     7x   7x 7x 7x 7x 102x 102x   1x   1x 1x 1x 1x 1x 1x 34x 34x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 37x 37x 9x 9x 9x 9x 28x 37x 2x 2x 2x 2x   26x 37x 2x 2x 24x 24x 24x   24x 37x 2x 2x 37x 6x 37x 16x 16x 16x 16x   22x 37x 2x 2x 20x   20x 20x 20x 20x 20x 20x   20x 37x   37x 37x   37x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 20x 20x   1x  
// @ts-check
 
import {
  getDefinedConstructor,
  getOwnPropertyDescriptor,
  getPrototypeOf,
  getTaggedType,
  resolveType
} from '../utility';
 
import { isFunction, isString } from '../base';
import { isClass, isES3Function } from '../function';
 
import { isConstructable } from '../function/utility';
import { doesMatchStableNonEnumerableDescriptor } from './utility';
 
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
 
/** @typedef {import('../function/typedef.js').ES3Function} ES3Function */
/** @typedef {import('../function/typedef.js').ClassConstructor<typeof Function>} ClassConstructor */
 
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
 
const defineProperty = Object.defineProperty;
 
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
 
/**
 * Does approve whether the passed value features the type-identity of any built-in type
 * that is ...the passed value is an instance of one of the language core's built-in
 * types and either does not have any `Symbol.toStringTag` related slots or features
 * just the type's standard-conform default `Symbol.toStringTag` property-descriptor.
 * @param {...any} args
 *  A variadic argument list. The first argument (`args[0]`) is the optional
 *  `value` parameter. Its **presence** is detected via `args.length`, allowing
 *  the function to distinguish between an explicitly passed `undefined` value
 *  and a completely omitted argument.
 * @returns {boolean}
 *  Whether the passed value features the built-in type-identity.
 * @category Type Identity
 */
export function hasBuiltinTypeIdentity(...args) {
  let isConfirmed = args.length >= 1;
 
  if (isConfirmed) {
    /** @type {any} */
    const value = args[0] ?? null;
 
    // - `null` and `undefined` both have a stable type-identity.
    //   Thus, further checks are not necessary; stability already
    //   is confirmed.
    if (value !== null && (isConfirmed = !isClass(value.constructor))) {
      const toStringTagSymbol = Symbol.toStringTag;
 
      /** @type {Object | undefined} */
      const prototype = getPrototypeOf(value);
 
      // eslint-disable-next-line jsdoc/no-undefined-types
      /** @type {PropertyDescriptor | undefined} */
      const typeTagDescriptor = getOwnPropertyDescriptor(value, toStringTagSymbol);
 
      // eslint-disable-next-line jsdoc/no-undefined-types
      /** @type {PropertyDescriptor | undefined} */
      const prototypeTagDescriptor = getOwnPropertyDescriptor(prototype ?? {}, toStringTagSymbol);
 
      const descriptor = typeTagDescriptor || prototypeTagDescriptor;
 
      // - valid only in case ...
      const isValidDefaultDescriptor =
        // ... a descriptor does exist at all ... and/but ...
        !!descriptor &&
        // ... it does exist exclusively ...
        !(typeTagDescriptor && prototypeTagDescriptor) &&
        // ... and does match the built-in default as well.
        descriptor.configurable === true &&
        descriptor.writable === false &&
        descriptor.enumerable === false;
 
      isConfirmed =
        !descriptor ||
        (isValidDefaultDescriptor &&
          (prototypeTagDescriptor
            ? builtInToStringTagPrototypes.has(resolveType(value))
            : builtInToStringTagTypes.has(getTaggedType(value))));
    }
  }
  return isConfirmed;
}
const builtInToStringTagPrototypes = new Set([
  'BigInt',
  'Symbol',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'Promise',
  'Generator',
  'AsyncGenerator',
  'AsyncFunction',
  'GeneratorFunction',
  'AsyncGeneratorFunction'
]);
const builtInToStringTagTypes = new Set(['Math', 'JSON', 'Reflect', 'Atomics']);
 
/**
 * Does approve whether the passed value features a custom applied type-identity,
 * which is ... there are `Symbol.toStringTag` related slots available, directly
 * owned either by the passed value itself or by its prototype, and none of them
 * can be matched against a built-in type-identity.
 * @param {...any} args
 *  A variadic argument list. The first argument (`args[0]`) is the optional
 *  `value` parameter. Its **presence** is detected via `args.length`, allowing
 *  the function to distinguish between an explicitly passed `undefined` value
 *  and a completely omitted argument.
 * @returns {boolean}
 *  Whether the passed value features a custom applied type-identity.
 * @category Type Identity
 */
export function hasCustomTypeIdentity(...args) {
  let isConfirmed = args.length >= 1 && !hasBuiltinTypeIdentity(...args);
 
  // - no built-in type-identity and available argument(s).
  if (isConfirmed) {
    /** @type {any} */
    const value = args[0];
 
    const toStringTagSymbol = Symbol.toStringTag;
 
    /** @type {Object | undefined} */
    let prototype = getPrototypeOf(value);
 
    // eslint-disable-next-line jsdoc/no-undefined-types
    /** @type {PropertyDescriptor | undefined} */
    const typeTagDescriptor = getOwnPropertyDescriptor(value, toStringTagSymbol);
 
    // eslint-disable-next-line jsdoc/no-undefined-types
    /** @type {PropertyDescriptor | undefined} */
    let prototypeTagDescriptor = getOwnPropertyDescriptor(prototype ?? {}, toStringTagSymbol);
 
    isConfirmed = !!typeTagDescriptor || !!prototypeTagDescriptor;
 
    while (!isConfirmed && (prototype = getPrototypeOf(prototype))) {
      isConfirmed = !!getOwnPropertyDescriptor(prototype, toStringTagSymbol);
    }
  }
  return isConfirmed;
}
 
/**
 * Does approve whether the passed value features a stable type-identity, which is ...
 * either the value comes with the built-in type-identity of one of the core language's
 * types, or the value has been processed via `defineStableTypeIdentity`, or it features
 * property-descriptors which are in line with the result of the latter process.
 * @param {...any} args
 *  A variadic argument list. The first argument (`args[0]`) is the optional
 *  `value` parameter. Its **presence** is detected via `args.length`, allowing
 *  the function to distinguish between an explicitly passed `undefined` value
 *  and a completely omitted argument.
 * @returns {boolean}
 *  Whether the passed value features a stable type-identity.
 * @category Type Identity
 */
export function hasStableTypeIdentity(...args) {
  let isConfirmed = hasBuiltinTypeIdentity(...args);
 
  // - A boolean `true` return value of `hasBuiltinTypeIdentity` already does cover
  //   both the `null` and the `undefined` value. Further checks only need to be made
  //   in case two conditions are met; a boolean `false` return value with an actually
  //   passed argument, where the latter represents the further to be checked `value`.
 
  if (!isConfirmed && args.length >= 1) {
    /** @type {any} */
    const value = args[0];
 
    const toStringTagSymbol = Symbol.toStringTag;
 
    /** @type {Object | undefined} */
    const prototype = getPrototypeOf(value);
 
    // eslint-disable-next-line jsdoc/no-undefined-types
    /** @type {PropertyDescriptor | undefined} */
    const typeTagDescriptor = getOwnPropertyDescriptor(value, toStringTagSymbol);
 
    // eslint-disable-next-line jsdoc/no-undefined-types
    /** @type {PropertyDescriptor | undefined} */
    const prototypeTagDescriptor = getOwnPropertyDescriptor(prototype ?? {}, toStringTagSymbol);
 
    const descriptor = typeTagDescriptor || prototypeTagDescriptor;
 
    // @IMPORTANT ... never change the inverse but explicitly excluding logic
    //                for the `writable` property. This is due to how the
    //                prototypal `[Symbol.toStringTag]` getter function of
    //                any class-based implementation does create its related
    //                property-descriptor.
    //  ```
    //  get [Symbol.toStringTag]() {
    //    return 'ExplicitlyTaggedType';
    //  }
    //  ```
    //                The above code generates following property-descriptor:
    //  ```
    //  { configurable: true, enumerable: false, get: ([Symbol.toStringTag]() { return 'ExplicitlyTaggedType'; }), set: undefined }
    //  ```
    //                The beneath check will be true for both an omitted `writable`
    //                property and one which has been set explicitly to `false`.
    const isStableTagDescriptor =
      !!descriptor &&
      descriptor.configurable === false &&
      descriptor.writable !== true &&
      descriptor.enumerable === false;
 
    /** @type {Function | undefined} */
    const constructor = getDefinedConstructor(value);
 
    const isStableTaggedType =
      isStableTagDescriptor &&
      isFunction(constructor) &&
      (isClass(constructor)
        ? !!prototypeTagDescriptor && !typeTagDescriptor
        : !!typeTagDescriptor && !prototypeTagDescriptor);
 
    isConfirmed =
      isStableTaggedType &&
      doesMatchStableNonEnumerableDescriptor(getOwnPropertyDescriptor(constructor, 'name'));
  }
  return isConfirmed;
}
 
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
 
/**
 * @internal
 * @param {string} type
 * @returns {string}
 */
export function getTrustedType(type) {
  return type;
}
 
// /**
//  * @template {ClassConstructor | ES3Function} T
//  * @param {T} constructor
//  * @param {string} constructorName
//  * @param {string} [taggedType]
//  * @returns {T}
//  */
/**
 * Takes a constructor function, changes some of the function's related property
 * descriptors according to additionally passed name and tagged type parameters,
 * and returns a boolean value which indicates whether the "Stable Type Identity"
 * could be established successfully.
 * @param {ClassConstructor | ES3Function} constructor
 * @param {string} constructorName
 * @param {string} [taggedType]
 * @returns {boolean}
 *  Whether the "Stable Type Identity" could be
 *  successfully applied upon the passed constructor.
 * @category Type Identity
 */
export function defineStableTypeIdentity(constructor, constructorName, taggedType) {
  // guard.
  if (!isConstructable(constructor)) {
    throw new TypeError(
      'The provided "constructor" parameter has to be at least a constructable function-type.'
    );
  }
  // guard.
  if (!(isClass(constructor) || isES3Function(constructor))) {
    throw new TypeError(
      'Built-in constructors are not supported. The "Stable Type Identity" feature anyhow is useful for just ES5 class-constructors and ES3 constructor functions.'
    );
  }
 
  // guard.
  if (!isString(constructorName)) {
    throw new TypeError('The provided "constructorName" parameter needs to be a string.');
  }
  // - assure a string value primitive because that is what a name-descriptor will be checked
  //   for in order to pass as a stable descriptor for the reliable type-identity verification.
  constructorName = String(constructorName).trim();
 
  // guard.
  if (constructorName === '') {
    throw new RangeError('Invalid string value passed to "constructorName".');
  }
  if (!isString(taggedType)) {
    taggedType = constructorName;
  } else {
    // - assure a string value primitive because that is what a `Symbol.toStringTag`-descriptor will be
    //   checked for in order to pass as a stable descriptor for the reliable type-identity verification.
    taggedType = String(taggedType).trim();
  }
 
  // guard.
  if (taggedType === '') {
    throw new RangeError('Invalid string value passed to "taggedType".');
  }
  const toStringTagSymbol = Symbol.toStringTag;
 
  // // hint.
  // if (taggedType !== constructorName) {
  //   console.warn(
  //     `Just hinting ... \`defineStableTypeIdentity\` does assign 2 different types, "${constructorName}" as constructor name and "${taggedType}" as tagged type.`
  //   );
  // }
 
  const nameDescriptor = getOwnPropertyDescriptor(constructor, 'name');
  const tagDescriptor = getOwnPropertyDescriptor(constructor.prototype, toStringTagSymbol) ?? {};
 
  const canBeDefined =
    nameDescriptor.configurable !== false && tagDescriptor.configurable !== false;
 
  if (canBeDefined) {
    defineProperty(constructor, 'name', {
      // get: getTrustedType.bind(constructor, constructorName),
      value: constructorName,
      enumerable: false,
      configurable: false
    });
    defineProperty(constructor.prototype, toStringTagSymbol, {
      get: getTrustedType.bind(constructor.prototype, taggedType),
      enumerable: false,
      configurable: false
    });
  }
  return canBeDefined;
}
 
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----