diff --git a/docker-compose.yml b/docker-compose.yml index ab92cc9..9996962 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,7 +16,7 @@ services: - DATABASE_URL=postgres://postgres:postgres@postgres:5432/auth?sslmode=disable volumes: - "./db:/db:ro" - command: up + command: --wait up profiles: ["migrations"] depends_on: - postgres diff --git a/src/handlers/post.go b/src/handlers/post.go index b13da5c..e1c3340 100644 --- a/src/handlers/post.go +++ b/src/handlers/post.go @@ -29,9 +29,11 @@ type AuthInput struct { // @Accept json // @Produce json // @Param body body AccountInput true "Account object to be written to database" -// @Success 200 {object} db.CreatedAccount +// @Success 201 {object} db.CreatedAccount +// @Failure 400 {object} []ResJSONError // @Failure 401 {object} []ResJSONError // @Failure 403 {object} []ResJSONError +// @Failure 409 {object} []ResJSONError // @Failure 415 {object} []ResJSONError // @Failure 500 {object} []ResJSONError // @Router /account [post] @@ -79,7 +81,7 @@ func (h Handlers) AccountCreate(c *fiber.Ctx) error { if err != nil { if strings.HasPrefix(err.Error(), "ERROR: duplicate key") { - return c.Status(409).JSON([]ResJSONError{{Error: "accountName is already taken"}}) + return c.Status(409).JSON([]ResJSONError{{Error: "Name is already taken", Field: "name"}}) } return c.Status(500).JSON([]ResJSONError{{Error: err.Error()}}) } diff --git a/tests/.env_example b/tests/.env_example new file mode 100644 index 0000000..fb54241 --- /dev/null +++ b/tests/.env_example @@ -0,0 +1,3 @@ +ADMIN_API_KEY=hihi +AUTH_URL=http://localhost:4000 +JWT_SHARED_SECRET=hihi diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 0000000..2eea525 --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1 @@ +.env \ No newline at end of file diff --git a/tests/node_modules/.bin/ignored b/tests/node_modules/.bin/ignored new file mode 120000 index 0000000..0e0ac00 --- /dev/null +++ b/tests/node_modules/.bin/ignored @@ -0,0 +1 @@ +../dotignore/bin/ignored \ No newline at end of file diff --git a/tests/node_modules/.bin/semver b/tests/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/tests/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/tests/node_modules/.bin/tap-out b/tests/node_modules/.bin/tap-out new file mode 120000 index 0000000..cb6a60e --- /dev/null +++ b/tests/node_modules/.bin/tap-out @@ -0,0 +1 @@ +../tap-out/bin/cmd.js \ No newline at end of file diff --git a/tests/node_modules/.bin/tap-spec b/tests/node_modules/.bin/tap-spec new file mode 120000 index 0000000..a22b7e1 --- /dev/null +++ b/tests/node_modules/.bin/tap-spec @@ -0,0 +1 @@ +../tap-spec/bin/cmd.js \ No newline at end of file diff --git a/tests/node_modules/.bin/tape b/tests/node_modules/.bin/tape new file mode 120000 index 0000000..dc4bc23 --- /dev/null +++ b/tests/node_modules/.bin/tape @@ -0,0 +1 @@ +../tape/bin/tape \ No newline at end of file diff --git a/tests/node_modules/.bin/tape-es b/tests/node_modules/.bin/tape-es new file mode 120000 index 0000000..e270703 --- /dev/null +++ b/tests/node_modules/.bin/tape-es @@ -0,0 +1 @@ +../tape-es/bin/tape-es.js \ No newline at end of file diff --git a/tests/node_modules/.bin/tape-watch-es b/tests/node_modules/.bin/tape-watch-es new file mode 120000 index 0000000..c631e87 --- /dev/null +++ b/tests/node_modules/.bin/tape-watch-es @@ -0,0 +1 @@ +../tape-es/bin/tape-watch-es.js \ No newline at end of file diff --git a/tests/node_modules/.bin/tspec b/tests/node_modules/.bin/tspec new file mode 120000 index 0000000..a22b7e1 --- /dev/null +++ b/tests/node_modules/.bin/tspec @@ -0,0 +1 @@ +../tap-spec/bin/cmd.js \ No newline at end of file diff --git a/tests/node_modules/@sindresorhus/is/dist/index.d.ts b/tests/node_modules/@sindresorhus/is/dist/index.d.ts new file mode 100644 index 0000000..3687767 --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/dist/index.d.ts @@ -0,0 +1,220 @@ +/// +/// +/// +import { Class, TypedArray, ObservableLike, Primitive } from './types'; +export { Class, TypedArray, ObservableLike, Primitive }; +declare const objectTypeNames: readonly ["Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "HTMLElement", ...("Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "BigInt64Array" | "BigUint64Array")[]]; +declare type ObjectTypeName = typeof objectTypeNames[number]; +declare const primitiveTypeNames: readonly ["null", "undefined", "string", "number", "bigint", "boolean", "symbol"]; +declare type PrimitiveTypeName = typeof primitiveTypeNames[number]; +export declare type TypeName = ObjectTypeName | PrimitiveTypeName; +declare function is(value: unknown): TypeName; +declare namespace is { + var undefined: (value: unknown) => value is undefined; + var string: (value: unknown) => value is string; + var number: (value: unknown) => value is number; + var bigint: (value: unknown) => value is bigint; + var function_: (value: unknown) => value is Function; + var null_: (value: unknown) => value is null; + var class_: (value: unknown) => value is Class; + var boolean: (value: unknown) => value is boolean; + var symbol: (value: unknown) => value is symbol; + var numericString: (value: unknown) => value is string; + var array: (value: unknown, assertion?: ((value: T) => value is T) | undefined) => value is T[]; + var buffer: (value: unknown) => value is Buffer; + var nullOrUndefined: (value: unknown) => value is null | undefined; + var object: (value: unknown) => value is object; + var iterable: (value: unknown) => value is IterableIterator; + var asyncIterable: (value: unknown) => value is AsyncIterableIterator; + var generator: (value: unknown) => value is Generator; + var asyncGenerator: (value: unknown) => value is AsyncGenerator; + var nativePromise: (value: unknown) => value is Promise; + var promise: (value: unknown) => value is Promise; + var generatorFunction: (value: unknown) => value is GeneratorFunction; + var asyncGeneratorFunction: (value: unknown) => value is (...args: any[]) => Promise; + var asyncFunction: (value: unknown) => value is (...args: any[]) => Promise; + var boundFunction: (value: unknown) => value is Function; + var regExp: (value: unknown) => value is RegExp; + var date: (value: unknown) => value is Date; + var error: (value: unknown) => value is Error; + var map: (value: unknown) => value is Map; + var set: (value: unknown) => value is Set; + var weakMap: (value: unknown) => value is WeakMap; + var weakSet: (value: unknown) => value is WeakSet; + var int8Array: (value: unknown) => value is Int8Array; + var uint8Array: (value: unknown) => value is Uint8Array; + var uint8ClampedArray: (value: unknown) => value is Uint8ClampedArray; + var int16Array: (value: unknown) => value is Int16Array; + var uint16Array: (value: unknown) => value is Uint16Array; + var int32Array: (value: unknown) => value is Int32Array; + var uint32Array: (value: unknown) => value is Uint32Array; + var float32Array: (value: unknown) => value is Float32Array; + var float64Array: (value: unknown) => value is Float64Array; + var bigInt64Array: (value: unknown) => value is BigInt64Array; + var bigUint64Array: (value: unknown) => value is BigUint64Array; + var arrayBuffer: (value: unknown) => value is ArrayBuffer; + var sharedArrayBuffer: (value: unknown) => value is SharedArrayBuffer; + var dataView: (value: unknown) => value is DataView; + var directInstanceOf: (instance: unknown, class_: Class) => instance is T; + var urlInstance: (value: unknown) => value is URL; + var urlString: (value: unknown) => value is string; + var truthy: (value: unknown) => boolean; + var falsy: (value: unknown) => boolean; + var nan: (value: unknown) => boolean; + var primitive: (value: unknown) => value is Primitive; + var integer: (value: unknown) => value is number; + var safeInteger: (value: unknown) => value is number; + var plainObject: (value: unknown) => value is Record; + var typedArray: (value: unknown) => value is TypedArray; + var arrayLike: (value: unknown) => value is ArrayLike; + var inRange: (value: number, range: number | number[]) => value is number; + var domElement: (value: unknown) => value is HTMLElement; + var observable: (value: unknown) => value is ObservableLike; + var nodeStream: (value: unknown) => value is NodeStream; + var infinite: (value: unknown) => value is number; + var evenInteger: (value: number) => value is number; + var oddInteger: (value: number) => value is number; + var emptyArray: (value: unknown) => value is never[]; + var nonEmptyArray: (value: unknown) => value is unknown[]; + var emptyString: (value: unknown) => value is ""; + var nonEmptyString: (value: unknown) => value is string; + var emptyStringOrWhitespace: (value: unknown) => value is string; + var emptyObject: (value: unknown) => value is Record; + var nonEmptyObject: (value: unknown) => value is Record; + var emptySet: (value: unknown) => value is Set; + var nonEmptySet: (value: unknown) => value is Set; + var emptyMap: (value: unknown) => value is Map; + var nonEmptyMap: (value: unknown) => value is Map; + var any: (predicate: Predicate | Predicate[], ...values: unknown[]) => boolean; + var all: (predicate: Predicate, ...values: unknown[]) => boolean; +} +declare type ObjectKey = string | number | symbol; +export interface ArrayLike { + readonly [index: number]: T; + readonly length: number; +} +export interface NodeStream extends NodeJS.EventEmitter { + pipe(destination: T, options?: { + end?: boolean; + }): T; +} +export declare type Predicate = (value: unknown) => boolean; +export declare const enum AssertionTypeDescription { + class_ = "Class", + numericString = "string with a number", + nullOrUndefined = "null or undefined", + iterable = "Iterable", + asyncIterable = "AsyncIterable", + nativePromise = "native Promise", + urlString = "string with a URL", + truthy = "truthy", + falsy = "falsy", + nan = "NaN", + primitive = "primitive", + integer = "integer", + safeInteger = "integer", + plainObject = "plain object", + arrayLike = "array-like", + typedArray = "TypedArray", + domElement = "HTMLElement", + nodeStream = "Node.js Stream", + infinite = "infinite number", + emptyArray = "empty array", + nonEmptyArray = "non-empty array", + emptyString = "empty string", + nonEmptyString = "non-empty string", + emptyStringOrWhitespace = "empty string or whitespace", + emptyObject = "empty object", + nonEmptyObject = "non-empty object", + emptySet = "empty set", + nonEmptySet = "non-empty set", + emptyMap = "empty map", + nonEmptyMap = "non-empty map", + evenInteger = "even integer", + oddInteger = "odd integer", + directInstanceOf = "T", + inRange = "in range", + any = "predicate returns truthy for any value", + all = "predicate returns truthy for all values" +} +interface Assert { + undefined: (value: unknown) => asserts value is undefined; + string: (value: unknown) => asserts value is string; + number: (value: unknown) => asserts value is number; + bigint: (value: unknown) => asserts value is bigint; + function_: (value: unknown) => asserts value is Function; + null_: (value: unknown) => asserts value is null; + class_: (value: unknown) => asserts value is Class; + boolean: (value: unknown) => asserts value is boolean; + symbol: (value: unknown) => asserts value is symbol; + numericString: (value: unknown) => asserts value is string; + array: (value: unknown, assertion?: (element: unknown) => asserts element is T) => asserts value is T[]; + buffer: (value: unknown) => asserts value is Buffer; + nullOrUndefined: (value: unknown) => asserts value is null | undefined; + object: (value: unknown) => asserts value is Record; + iterable: (value: unknown) => asserts value is Iterable; + asyncIterable: (value: unknown) => asserts value is AsyncIterable; + generator: (value: unknown) => asserts value is Generator; + asyncGenerator: (value: unknown) => asserts value is AsyncGenerator; + nativePromise: (value: unknown) => asserts value is Promise; + promise: (value: unknown) => asserts value is Promise; + generatorFunction: (value: unknown) => asserts value is GeneratorFunction; + asyncGeneratorFunction: (value: unknown) => asserts value is AsyncGeneratorFunction; + asyncFunction: (value: unknown) => asserts value is Function; + boundFunction: (value: unknown) => asserts value is Function; + regExp: (value: unknown) => asserts value is RegExp; + date: (value: unknown) => asserts value is Date; + error: (value: unknown) => asserts value is Error; + map: (value: unknown) => asserts value is Map; + set: (value: unknown) => asserts value is Set; + weakMap: (value: unknown) => asserts value is WeakMap; + weakSet: (value: unknown) => asserts value is WeakSet; + int8Array: (value: unknown) => asserts value is Int8Array; + uint8Array: (value: unknown) => asserts value is Uint8Array; + uint8ClampedArray: (value: unknown) => asserts value is Uint8ClampedArray; + int16Array: (value: unknown) => asserts value is Int16Array; + uint16Array: (value: unknown) => asserts value is Uint16Array; + int32Array: (value: unknown) => asserts value is Int32Array; + uint32Array: (value: unknown) => asserts value is Uint32Array; + float32Array: (value: unknown) => asserts value is Float32Array; + float64Array: (value: unknown) => asserts value is Float64Array; + bigInt64Array: (value: unknown) => asserts value is BigInt64Array; + bigUint64Array: (value: unknown) => asserts value is BigUint64Array; + arrayBuffer: (value: unknown) => asserts value is ArrayBuffer; + sharedArrayBuffer: (value: unknown) => asserts value is SharedArrayBuffer; + dataView: (value: unknown) => asserts value is DataView; + urlInstance: (value: unknown) => asserts value is URL; + urlString: (value: unknown) => asserts value is string; + truthy: (value: unknown) => asserts value is unknown; + falsy: (value: unknown) => asserts value is unknown; + nan: (value: unknown) => asserts value is unknown; + primitive: (value: unknown) => asserts value is Primitive; + integer: (value: unknown) => asserts value is number; + safeInteger: (value: unknown) => asserts value is number; + plainObject: (value: unknown) => asserts value is Record; + typedArray: (value: unknown) => asserts value is TypedArray; + arrayLike: (value: unknown) => asserts value is ArrayLike; + domElement: (value: unknown) => asserts value is HTMLElement; + observable: (value: unknown) => asserts value is ObservableLike; + nodeStream: (value: unknown) => asserts value is NodeStream; + infinite: (value: unknown) => asserts value is number; + emptyArray: (value: unknown) => asserts value is never[]; + nonEmptyArray: (value: unknown) => asserts value is unknown[]; + emptyString: (value: unknown) => asserts value is ''; + nonEmptyString: (value: unknown) => asserts value is string; + emptyStringOrWhitespace: (value: unknown) => asserts value is string; + emptyObject: (value: unknown) => asserts value is Record; + nonEmptyObject: (value: unknown) => asserts value is Record; + emptySet: (value: unknown) => asserts value is Set; + nonEmptySet: (value: unknown) => asserts value is Set; + emptyMap: (value: unknown) => asserts value is Map; + nonEmptyMap: (value: unknown) => asserts value is Map; + evenInteger: (value: number) => asserts value is number; + oddInteger: (value: number) => asserts value is number; + directInstanceOf: (instance: unknown, class_: Class) => asserts instance is T; + inRange: (value: number, range: number | number[]) => asserts value is number; + any: (predicate: Predicate | Predicate[], ...values: unknown[]) => void | never; + all: (predicate: Predicate, ...values: unknown[]) => void | never; +} +export declare const assert: Assert; +export default is; diff --git a/tests/node_modules/@sindresorhus/is/dist/index.js b/tests/node_modules/@sindresorhus/is/dist/index.js new file mode 100644 index 0000000..f86cf5c --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/dist/index.js @@ -0,0 +1,418 @@ +"use strict"; +/// +/// +/// +Object.defineProperty(exports, "__esModule", { value: true }); +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; +function isTypedArrayName(name) { + return typedArrayTypeNames.includes(name); +} +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'HTMLElement', + ...typedArrayTypeNames +]; +function isObjectTypeName(name) { + return objectTypeNames.includes(name); +} +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol' +]; +function isPrimitiveTypeName(name) { + return primitiveTypeNames.includes(name); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isOfType(type) { + return (value) => typeof value === type; +} +const { toString } = Object.prototype; +const getObjectType = (value) => { + const objectTypeName = toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { + return 'HTMLElement'; + } + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': + return 'undefined'; + case 'string': + return 'string'; + case 'number': + return 'number'; + case 'boolean': + return 'boolean'; + case 'function': + return 'Function'; + case 'bigint': + return 'bigint'; + case 'symbol': + return 'symbol'; + default: + } + if (is.observable(value)) { + return 'Observable'; + } + if (is.array(value)) { + return 'Array'; + } + if (is.buffer(value)) { + return 'Buffer'; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; +} +is.undefined = isOfType('undefined'); +is.string = isOfType('string'); +const isNumberType = isOfType('number'); +is.number = (value) => isNumberType(value) && !is.nan(value); +is.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is.function_ = isOfType('function'); +is.null_ = (value) => value === null; +is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); +is.boolean = (value) => value === true || value === false; +is.symbol = isOfType('symbol'); +is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +is.array = (value, assertion) => { + if (!Array.isArray(value)) { + return false; + } + if (!is.function_(assertion)) { + return true; + } + return value.every(assertion); +}; +is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; +is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); +is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); +is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; +is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; +is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw); +is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); +is.nativePromise = (value) => isObjectOfType('Promise')(value); +const hasPromiseAPI = (value) => { + var _a, _b; + return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && + is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); +}; +is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); +is.generatorFunction = isObjectOfType('GeneratorFunction'); +is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; +is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); +is.regExp = isObjectOfType('RegExp'); +is.date = isObjectOfType('Date'); +is.error = isObjectOfType('Error'); +is.map = (value) => isObjectOfType('Map')(value); +is.set = (value) => isObjectOfType('Set')(value); +is.weakMap = (value) => isObjectOfType('WeakMap')(value); +is.weakSet = (value) => isObjectOfType('WeakSet')(value); +is.int8Array = isObjectOfType('Int8Array'); +is.uint8Array = isObjectOfType('Uint8Array'); +is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); +is.int16Array = isObjectOfType('Int16Array'); +is.uint16Array = isObjectOfType('Uint16Array'); +is.int32Array = isObjectOfType('Int32Array'); +is.uint32Array = isObjectOfType('Uint32Array'); +is.float32Array = isObjectOfType('Float32Array'); +is.float64Array = isObjectOfType('Float64Array'); +is.bigInt64Array = isObjectOfType('BigInt64Array'); +is.bigUint64Array = isObjectOfType('BigUint64Array'); +is.arrayBuffer = isObjectOfType('ArrayBuffer'); +is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); +is.dataView = isObjectOfType('DataView'); +is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is.urlInstance = (value) => isObjectOfType('URL')(value); +is.urlString = (value) => { + if (!is.string(value)) { + return false; + } + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch (_a) { + return false; + } +}; +// TODO: Use the `not` operator with a type guard here when it's available. +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is.truthy = (value) => Boolean(value); +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +is.falsy = (value) => !value; +is.nan = (value) => Number.isNaN(value); +is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); +is.integer = (value) => Number.isInteger(value); +is.safeInteger = (value) => Number.isSafeInteger(value); +is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (toString.call(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; +is.typedArray = (value) => isTypedArrayName(getObjectType(value)); +const isValidLength = (value) => is.safeInteger(value) && value >= 0; +is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); +is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; +const NODE_TYPE_ELEMENT = 1; +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue' +]; +is.domElement = (value) => { + return is.object(value) && + value.nodeType === NODE_TYPE_ELEMENT && + is.string(value.nodeName) && + !is.plainObject(value) && + DOM_PROPERTIES_TO_CHECK.every(property => property in value); +}; +is.observable = (value) => { + var _a, _b, _c, _d; + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { + return true; + } + if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { + return true; + } + return false; +}; +is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); +is.infinite = (value) => value === Infinity || value === -Infinity; +const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; +is.evenInteger = isAbsoluteMod2(0); +is.oddInteger = isAbsoluteMod2(1); +is.emptyArray = (value) => is.array(value) && value.length === 0; +is.nonEmptyArray = (value) => is.array(value) && value.length > 0; +is.emptyString = (value) => is.string(value) && value.length === 0; +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyString = (value) => is.string(value) && value.length > 0; +const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); +is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); +is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; +is.emptySet = (value) => is.set(value) && value.size === 0; +is.nonEmptySet = (value) => is.set(value) && value.size > 0; +is.emptyMap = (value) => is.map(value) && value.size === 0; +is.nonEmptyMap = (value) => is.map(value) && value.size > 0; +const predicateOnArray = (method, predicate, values) => { + if (!is.function_(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +}; +is.any = (predicate, ...values) => { + const predicates = is.array(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); +}; +is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); +const assertType = (condition, description, value, options = {}) => { + if (!condition) { + const { multipleValues } = options; + const valuesMessage = multipleValues ? + `received values of types ${[ + ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) + ].join(', ')}` : + `received value of type \`${is(value)}\``; + throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); + } +}; +exports.assert = { + // Unknowns. + undefined: (value) => assertType(is.undefined(value), 'undefined', value), + string: (value) => assertType(is.string(value), 'string', value), + number: (value) => assertType(is.number(value), 'number', value), + bigint: (value) => assertType(is.bigint(value), 'bigint', value), + // eslint-disable-next-line @typescript-eslint/ban-types + function_: (value) => assertType(is.function_(value), 'Function', value), + null_: (value) => assertType(is.null_(value), 'null', value), + class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), + boolean: (value) => assertType(is.boolean(value), 'boolean', value), + symbol: (value) => assertType(is.symbol(value), 'symbol', value), + numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is.array(value), 'Array', value); + if (assertion) { + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is.buffer(value), 'Buffer', value), + nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), + object: (value) => assertType(is.object(value), 'Object', value), + iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), + asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), + generator: (value) => assertType(is.generator(value), 'Generator', value), + asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), + nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), + promise: (value) => assertType(is.promise(value), 'Promise', value), + generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), + asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), + regExp: (value) => assertType(is.regExp(value), 'RegExp', value), + date: (value) => assertType(is.date(value), 'Date', value), + error: (value) => assertType(is.error(value), 'Error', value), + map: (value) => assertType(is.map(value), 'Map', value), + set: (value) => assertType(is.set(value), 'Set', value), + weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), + weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), + int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), + uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), + uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), + int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), + uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), + int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), + uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), + float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), + float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), + bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), + bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), + arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), + sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), + dataView: (value) => assertType(is.dataView(value), 'DataView', value), + urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), + urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), + truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), + falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), + nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), + primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), + integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), + safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), + plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), + typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), + arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), + domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), + observable: (value) => assertType(is.observable(value), 'Observable', value), + nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), + infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), + emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), + nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), + emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), + nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), + emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), + emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), + nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), + emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), + nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), + emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), + nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), + // Numbers. + evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), + oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), + // Two arguments. + directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), + inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), + // Variadic functions. + any: (predicate, ...values) => { + return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); + }, + all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) +}; +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is, { + class: { + value: is.class_ + }, + function: { + value: is.function_ + }, + null: { + value: is.null_ + } +}); +Object.defineProperties(exports.assert, { + class: { + value: exports.assert.class_ + }, + function: { + value: exports.assert.function_ + }, + null: { + value: exports.assert.null_ + } +}); +exports.default = is; +// For CommonJS default export support +module.exports = is; +module.exports.default = is; +module.exports.assert = exports.assert; diff --git a/tests/node_modules/@sindresorhus/is/dist/types.d.ts b/tests/node_modules/@sindresorhus/is/dist/types.d.ts new file mode 100644 index 0000000..a63acda --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/dist/types.d.ts @@ -0,0 +1,24 @@ +/** +Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +*/ +export declare type Primitive = null | undefined | string | number | boolean | symbol | bigint; +/** +Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +*/ +export declare type Class = new (...arguments_: Arguments) => T; +/** +Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +*/ +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} +/** +Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). +*/ +export interface ObservableLike { + subscribe(observer: (value: unknown) => void): void; + [Symbol.observable](): ObservableLike; +} diff --git a/tests/node_modules/@sindresorhus/is/dist/types.js b/tests/node_modules/@sindresorhus/is/dist/types.js new file mode 100644 index 0000000..0930323 --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/dist/types.js @@ -0,0 +1,3 @@ +"use strict"; +// Extracted from https://github.com/sindresorhus/type-fest/blob/78019f42ea888b0cdceb41a4a78163868de57555/index.d.ts +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/tests/node_modules/@sindresorhus/is/license b/tests/node_modules/@sindresorhus/is/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/@sindresorhus/is/package.json b/tests/node_modules/@sindresorhus/is/package.json new file mode 100644 index 0000000..f10f394 --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/package.json @@ -0,0 +1,129 @@ +{ + "_from": "@sindresorhus/is@^4.0.0", + "_id": "@sindresorhus/is@4.0.1", + "_inBundle": false, + "_integrity": "sha512-Qm9hBEBu18wt1PO2flE7LPb30BHMQt1eQgbV76YntdNk73XZGpn3izvGTYxbGgzXKgbCjiia0uxTd3aTNQrY/g==", + "_location": "/@sindresorhus/is", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@sindresorhus/is@^4.0.0", + "name": "@sindresorhus/is", + "escapedName": "@sindresorhus%2fis", + "scope": "@sindresorhus", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.0.1.tgz", + "_shasum": "d26729db850fa327b7cacc5522252194404226f5", + "_spec": "@sindresorhus/is@^4.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "ava": { + "extensions": [ + "ts" + ], + "require": [ + "ts-node/register" + ] + }, + "bugs": { + "url": "https://github.com/sindresorhus/is/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Type check values", + "devDependencies": { + "@sindresorhus/tsconfig": "^0.7.0", + "@types/jsdom": "^16.1.0", + "@types/node": "^14.0.13", + "@types/zen-observable": "^0.8.0", + "@typescript-eslint/eslint-plugin": "^2.20.0", + "@typescript-eslint/parser": "^2.20.0", + "ava": "^3.3.0", + "del-cli": "^2.0.0", + "eslint-config-xo-typescript": "^0.26.0", + "jsdom": "^16.0.1", + "rxjs": "^6.4.0", + "tempy": "^0.4.0", + "ts-node": "^8.3.0", + "typescript": "~3.8.2", + "xo": "^0.26.1", + "zen-observable": "^0.8.8" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "dist" + ], + "funding": "https://github.com/sindresorhus/is?sponsor=1", + "homepage": "https://github.com/sindresorhus/is#readme", + "keywords": [ + "type", + "types", + "is", + "check", + "checking", + "validate", + "validation", + "utility", + "util", + "typeof", + "instanceof", + "object", + "assert", + "assertion", + "test", + "kind", + "primitive", + "verify", + "compare", + "typescript", + "typeguards", + "types" + ], + "license": "MIT", + "main": "dist/index.js", + "name": "@sindresorhus/is", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is.git" + }, + "scripts": { + "build": "del dist && tsc", + "prepare": "npm run build", + "test": "xo && ava" + }, + "sideEffects": false, + "types": "dist/index.d.ts", + "version": "4.0.1", + "xo": { + "extends": "xo-typescript", + "extensions": [ + "ts" + ], + "parserOptions": { + "project": "./tsconfig.xo.json" + }, + "globals": [ + "BigInt", + "BigInt64Array", + "BigUint64Array" + ], + "rules": { + "@typescript-eslint/promise-function-async": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/explicit-function-return-type": "off" + } + } +} diff --git a/tests/node_modules/@sindresorhus/is/readme.md b/tests/node_modules/@sindresorhus/is/readme.md new file mode 100644 index 0000000..adb9910 --- /dev/null +++ b/tests/node_modules/@sindresorhus/is/readme.md @@ -0,0 +1,602 @@ +# is + +> Type check values + +For example, `is.string('🦄') //=> true` + + + +## Highlights + +- Written in TypeScript +- [Extensive use of type guards](#type-guards) +- [Supports type assertions](#type-assertions) +- [Aware of generic type parameters](#generic-type-parameters) (use with caution) +- Actively maintained +- ![Millions of downloads per week](https://img.shields.io/npm/dw/@sindresorhus/is) + +## Install + +``` +$ npm install @sindresorhus/is +``` + +## Usage + +```js +const is = require('@sindresorhus/is'); + +is('🦄'); +//=> 'string' + +is(new Map()); +//=> 'Map' + +is.number(6); +//=> true +``` + +[Assertions](#type-assertions) perform the same type checks, but throw an error if the type does not match. + +```js +const {assert} = require('@sindresorhus/is'); + +assert.string(2); +//=> Error: Expected value which is `string`, received value of type `number`. +``` + +And with TypeScript: + +```ts +import {assert} from '@sindresorhus/is'; + +assert.string(foo); +// `foo` is now typed as a `string`. +``` + +## API + +### is(value) + +Returns the type of `value`. + +Primitives are lowercase and object types are camelcase. + +Example: + +- `'undefined'` +- `'null'` +- `'string'` +- `'symbol'` +- `'Array'` +- `'Function'` +- `'Object'` + +Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`. + +### is.{method} + +All the below methods accept a value and returns a boolean for whether the value is of the desired type. + +#### Primitives + +##### .undefined(value) +##### .null(value) +##### .string(value) +##### .number(value) + +Note: `is.number(NaN)` returns `false`. This intentionally deviates from `typeof` behavior to increase user-friendliness of `is` type checks. + +##### .boolean(value) +##### .symbol(value) +##### .bigint(value) + +#### Built-in types + +##### .array(value, assertion?) + +Returns true if `value` is an array and all of its items match the assertion (if provided). + +```js +is.array(value); // Validate `value` is an array. +is.array(value, is.number); // Validate `value` is an array and all of its items are numbers. +``` + +##### .function(value) +##### .buffer(value) +##### .object(value) + +Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions). + +##### .numericString(value) + +Returns `true` for a string that represents a number satisfying `is.number`, for example, `'42'` and `'-8.3'`. + +Note: `'NaN'` returns `false`, but `'Infinity'` and `'-Infinity'` return `true`. + +##### .regExp(value) +##### .date(value) +##### .error(value) +##### .nativePromise(value) +##### .promise(value) + +Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too. + +##### .generator(value) + +Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`. + +##### .generatorFunction(value) + +##### .asyncFunction(value) + +Returns `true` for any `async` function that can be called with the `await` operator. + +```js +is.asyncFunction(async () => {}); +//=> true + +is.asyncFunction(() => {}); +//=> false +``` + +##### .asyncGenerator(value) + +```js +is.asyncGenerator( + (async function * () { + yield 4; + })() +); +//=> true + +is.asyncGenerator( + (function * () { + yield 4; + })() +); +//=> false +``` + +##### .asyncGeneratorFunction(value) + +```js +is.asyncGeneratorFunction(async function * () { + yield 4; +}); +//=> true + +is.asyncGeneratorFunction(function * () { + yield 4; +}); +//=> false +``` + +##### .boundFunction(value) + +Returns `true` for any `bound` function. + +```js +is.boundFunction(() => {}); +//=> true + +is.boundFunction(function () {}.bind(null)); +//=> true + +is.boundFunction(function () {}); +//=> false +``` + +##### .map(value) +##### .set(value) +##### .weakMap(value) +##### .weakSet(value) + +#### Typed arrays + +##### .int8Array(value) +##### .uint8Array(value) +##### .uint8ClampedArray(value) +##### .int16Array(value) +##### .uint16Array(value) +##### .int32Array(value) +##### .uint32Array(value) +##### .float32Array(value) +##### .float64Array(value) +##### .bigInt64Array(value) +##### .bigUint64Array(value) + +#### Structured data + +##### .arrayBuffer(value) +##### .sharedArrayBuffer(value) +##### .dataView(value) + +#### Emptiness + +##### .emptyString(value) + +Returns `true` if the value is a `string` and the `.length` is 0. + +##### .nonEmptyString(value) + +Returns `true` if the value is a `string` and the `.length` is more than 0. + +##### .emptyStringOrWhitespace(value) + +Returns `true` if `is.emptyString(value)` or if it's a `string` that is all whitespace. + +##### .emptyArray(value) + +Returns `true` if the value is an `Array` and the `.length` is 0. + +##### .nonEmptyArray(value) + +Returns `true` if the value is an `Array` and the `.length` is more than 0. + +##### .emptyObject(value) + +Returns `true` if the value is an `Object` and `Object.keys(value).length` is 0. + +Please note that `Object.keys` returns only own enumerable properties. Hence something like this can happen: + +```js +const object1 = {}; + +Object.defineProperty(object1, 'property1', { + value: 42, + writable: true, + enumerable: false, + configurable: true +}); + +is.emptyObject(object1); +//=> true +``` + +##### .nonEmptyObject(value) + +Returns `true` if the value is an `Object` and `Object.keys(value).length` is more than 0. + +##### .emptySet(value) + +Returns `true` if the value is a `Set` and the `.size` is 0. + +##### .nonEmptySet(Value) + +Returns `true` if the value is a `Set` and the `.size` is more than 0. + +##### .emptyMap(value) + +Returns `true` if the value is a `Map` and the `.size` is 0. + +##### .nonEmptyMap(value) + +Returns `true` if the value is a `Map` and the `.size` is more than 0. + +#### Miscellaneous + +##### .directInstanceOf(value, class) + +Returns `true` if `value` is a direct instance of `class`. + +```js +is.directInstanceOf(new Error(), Error); +//=> true + +class UnicornError extends Error {} + +is.directInstanceOf(new UnicornError(), Error); +//=> false +``` + +##### .urlInstance(value) + +Returns `true` if `value` is an instance of the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL). + +```js +const url = new URL('https://example.com'); + +is.urlInstance(url); +//=> true +``` + +##### .urlString(value) + +Returns `true` if `value` is a URL string. + +Note: this only does basic checking using the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor. + +```js +const url = 'https://example.com'; + +is.urlString(url); +//=> true + +is.urlString(new URL(url)); +//=> false +``` + +##### .truthy(value) + +Returns `true` for all values that evaluate to true in a boolean context: + +```js +is.truthy('🦄'); +//=> true + +is.truthy(undefined); +//=> false +``` + +##### .falsy(value) + +Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `NaN`. + +##### .nan(value) +##### .nullOrUndefined(value) +##### .primitive(value) + +JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`. + +##### .integer(value) + +##### .safeInteger(value) + +Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + +##### .plainObject(value) + +An object is plain if it's created by either `{}`, `new Object()`, or `Object.create(null)`. + +##### .iterable(value) +##### .asyncIterable(value) +##### .class(value) + +Returns `true` for instances created by a class. + +##### .typedArray(value) + +##### .arrayLike(value) + +A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0. + +```js +is.arrayLike(document.forms); +//=> true + +function foo() { + is.arrayLike(arguments); + //=> true +} +foo(); +``` + +##### .inRange(value, range) + +Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order. + +```js +is.inRange(3, [0, 5]); +is.inRange(3, [5, 0]); +is.inRange(0, [-2, 2]); +``` + +##### .inRange(value, upperBound) + +Check if `value` (number) is in the range of `0` to `upperBound`. + +```js +is.inRange(3, 10); +``` + +##### .domElement(value) + +Returns `true` if `value` is a DOM Element. + +##### .nodeStream(value) + +Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html). + +```js +const fs = require('fs'); + +is.nodeStream(fs.createReadStream('unicorn.png')); +//=> true +``` + +##### .observable(value) + +Returns `true` if `value` is an `Observable`. + +```js +const {Observable} = require('rxjs'); + +is.observable(new Observable()); +//=> true +``` + +##### .infinite(value) + +Check if `value` is `Infinity` or `-Infinity`. + +##### .evenInteger(value) + +Returns `true` if `value` is an even integer. + +##### .oddInteger(value) + +Returns `true` if `value` is an odd integer. + +##### .any(predicate | predicate[], ...values) + +Using a single `predicate` argument, returns `true` if **any** of the input `values` returns true in the `predicate`: + +```js +is.any(is.string, {}, true, '🦄'); +//=> true + +is.any(is.boolean, 'unicorns', [], new Map()); +//=> false +``` + +Using an array of `predicate[]`, returns `true` if **any** of the input `values` returns true for **any** of the `predicates` provided in an array: + +```js +is.any([is.string, is.number], {}, true, '🦄'); +//=> true + +is.any([is.boolean, is.number], 'unicorns', [], new Map()); +//=> false +``` + +##### .all(predicate, ...values) + +Returns `true` if **all** of the input `values` returns true in the `predicate`: + +```js +is.all(is.object, {}, new Map(), new Set()); +//=> true + +is.all(is.string, '🦄', [], 'unicorns'); +//=> false +``` + +## Type guards + +When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used extensively to infer the correct type inside if-else statements. + +```ts +import is from '@sindresorhus/is'; + +const padLeft = (value: string, padding: string | number) => { + if (is.number(padding)) { + // `padding` is typed as `number` + return Array(padding + 1).join(' ') + value; + } + + if (is.string(padding)) { + // `padding` is typed as `string` + return padding + value; + } + + throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`); +} + +padLeft('🦄', 3); +//=> ' 🦄' + +padLeft('🦄', '🌈'); +//=> '🌈🦄' +``` + +## Type assertions + +The type guards are also available as [type assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions), which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern. + +```ts +import {assert} from '@sindresorhus/is'; + +const handleMovieRatingApiResponse = (response: unknown) => { + assert.plainObject(response); + // `response` is now typed as a plain `object` with `unknown` properties. + + assert.number(response.rating); + // `response.rating` is now typed as a `number`. + + assert.string(response.title); + // `response.title` is now typed as a `string`. + + return `${response.title} (${response.rating * 10})`; +}; + +handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'}); +//=> 'The Matrix (8.7)' + +// This throws an error. +handleMovieRatingApiResponse({rating: '🦄'}); +``` + +## Generic type parameters + +The type guards and type assertions are aware of [generic type parameters](https://www.typescriptlang.org/docs/handbook/generics.html), such as `Promise` and `Map`. The default is `unknown` for most cases, since `is` cannot check them at runtime. If the generic type is known at compile-time, either implicitly (inferred) or explicitly (provided), `is` propagates the type so it can be used later. + +Use generic type parameters with caution. They are only checked by the TypeScript compiler, and not checked by `is` at runtime. This can lead to unexpected behavior, where the generic type is _assumed_ at compile-time, but actually is something completely different at runtime. It is best to use `unknown` (default) and type-check the value of the generic type parameter at runtime with `is` or `assert`. + +```ts +import {assert} from '@sindresorhus/is'; + +async function badNumberAssumption(input: unknown) { + // Bad assumption about the generic type parameter fools the compile-time type system. + assert.promise(input); + // `input` is a `Promise` but only assumed to be `Promise`. + + const resolved = await input; + // `resolved` is typed as `number` but was not actually checked at runtime. + + // Multiplication will return NaN if the input promise did not actually contain a number. + return 2 * resolved; +} + +async function goodNumberAssertion(input: unknown) { + assert.promise(input); + // `input` is typed as `Promise` + + const resolved = await input; + // `resolved` is typed as `unknown` + + assert.number(resolved); + // `resolved` is typed as `number` + + // Uses runtime checks so only numbers will reach the multiplication. + return 2 * resolved; +} + +badNumberAssumption(Promise.resolve('An unexpected string')); +//=> NaN + +// This correctly throws an error because of the unexpected string value. +goodNumberAssertion(Promise.resolve('An unexpected string')); +``` + +## FAQ + +### Why yet another type checking module? + +There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs: + +- Includes both type methods and ability to get the type +- Types of primitives returned as lowercase and object types as camelcase +- Covers all built-ins +- Unsurprising behavior +- Well-maintained +- Comprehensive test suite + +For the ones I found, pick 3 of these. + +The most common mistakes I noticed in these modules was using `instanceof` for type checking, forgetting that functions are objects, and omitting `symbol` as a primitive. + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of @sindresorhus/is and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-sindresorhus-is?utm_source=npm-sindresorhus-is&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [ow](https://github.com/sindresorhus/ow) - Function argument validation for humans +- [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream +- [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable +- [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array +- [is-ip](https://github.com/sindresorhus/is-ip) - Check if a string is an IP address +- [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted +- [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor +- [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty +- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data +- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Giora Guttsait](https://github.com/gioragutt) +- [Brandon Smith](https://github.com/brandon93s) diff --git a/tests/node_modules/@szmarczak/http-timer/LICENSE b/tests/node_modules/@szmarczak/http-timer/LICENSE new file mode 100644 index 0000000..15ad2e8 --- /dev/null +++ b/tests/node_modules/@szmarczak/http-timer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Szymon Marczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/@szmarczak/http-timer/README.md b/tests/node_modules/@szmarczak/http-timer/README.md new file mode 100644 index 0000000..4f6a615 --- /dev/null +++ b/tests/node_modules/@szmarczak/http-timer/README.md @@ -0,0 +1,89 @@ +# http-timer +> Timings for HTTP requests + +[![Build Status](https://travis-ci.org/szmarczak/http-timer.svg?branch=master)](https://travis-ci.org/szmarczak/http-timer) +[![Coverage Status](https://coveralls.io/repos/github/szmarczak/http-timer/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/http-timer?branch=master) +[![install size](https://packagephobia.now.sh/badge?p=@szmarczak/http-timer)](https://packagephobia.now.sh/result?p=@szmarczak/http-timer) + +Inspired by the [`request` package](https://github.com/request/request). + +## Installation + +NPM: + +> `npm install @szmarczak/http-timer` + +Yarn: + +> `yarn add @szmarczak/http-timer` + +## Usage +```js +const https = require('https'); +const timer = require('@szmarczak/http-timer'); + +const request = https.get('https://httpbin.org/anything'); +timer(request); + +request.once('response', response => { + response.resume(); + response.once('end', () => { + console.log(response.timings); // You can use `request.timings` as well + }); +}); + +// { +// start: 1572712180361, +// socket: 1572712180362, +// lookup: 1572712180415, +// connect: 1572712180571, +// upload: 1572712180884, +// response: 1572712181037, +// end: 1572712181039, +// error: undefined, +// abort: undefined, +// phases: { +// wait: 1, +// dns: 53, +// tcp: 156, +// request: 313, +// firstByte: 153, +// download: 2, +// total: 678 +// } +// } +``` + +## API + +### timer(request) + +Returns: `Object` + +**Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + +- `start` - Time when the request started. +- `socket` - Time when a socket was assigned to the request. +- `lookup` - Time when the DNS lookup finished. +- `connect` - Time when the socket successfully connected. +- `secureConnect` - Time when the socket securely connected. +- `upload` - Time when the request finished uploading. +- `response` - Time when the request fired `response` event. +- `end` - Time when the response fired `end` event. +- `error` - Time when the request fired `error` event. +- `abort` - Time when the request fired `abort` event. +- `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + +If something has not been measured yet, it will be `undefined`. + +## License + +MIT diff --git a/tests/node_modules/@szmarczak/http-timer/dist/source/index.d.ts b/tests/node_modules/@szmarczak/http-timer/dist/source/index.d.ts new file mode 100644 index 0000000..2620b4a --- /dev/null +++ b/tests/node_modules/@szmarczak/http-timer/dist/source/index.d.ts @@ -0,0 +1,32 @@ +/// +import { ClientRequest, IncomingMessage } from 'http'; +export interface Timings { + start: number; + socket?: number; + lookup?: number; + connect?: number; + secureConnect?: number; + upload?: number; + response?: number; + end?: number; + error?: number; + abort?: number; + phases: { + wait?: number; + dns?: number; + tcp?: number; + tls?: number; + request?: number; + firstByte?: number; + download?: number; + total?: number; + }; +} +export interface ClientRequestWithTimings extends ClientRequest { + timings?: Timings; +} +export interface IncomingMessageWithTimings extends IncomingMessage { + timings?: Timings; +} +declare const timer: (request: ClientRequestWithTimings) => Timings; +export default timer; diff --git a/tests/node_modules/@szmarczak/http-timer/dist/source/index.js b/tests/node_modules/@szmarczak/http-timer/dist/source/index.js new file mode 100644 index 0000000..c120ace --- /dev/null +++ b/tests/node_modules/@szmarczak/http-timer/dist/source/index.js @@ -0,0 +1,117 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const defer_to_connect_1 = require("defer-to-connect"); +const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); +const timer = (request) => { + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined + } + }; + request.timings = timings; + const handleError = (origin) => { + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + origin.emit = emit; + } + // Saves the original behavior + return emit(event, ...args); + }; + }; + handleError(request); + request.prependOnceListener('abort', () => { + timings.abort = Date.now(); + // Let the `end` response event be responsible for setting the total phase, + // unless the Node.js major version is >= 13. + if (!timings.response || nodejsMajorVersion >= 13) { + timings.phases.total = Date.now() - timings.start; + } + }); + const onSocket = (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + defer_to_connect_1.default(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + // This callback is called before flushing any data, + // so we don't need to set `timings.phases.request` here. + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + } + }); + }; + if (request.socket) { + onSocket(request.socket); + } + else { + request.prependOnceListener('socket', onSocket); + } + const onUpload = () => { + var _a; + timings.upload = Date.now(); + timings.phases.request = timings.upload - (_a = timings.secureConnect, (_a !== null && _a !== void 0 ? _a : timings.connect)); + }; + const writableFinished = () => { + if (typeof request.writableFinished === 'boolean') { + return request.writableFinished; + } + // Node.js doesn't have `request.writableFinished` property + return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); + }; + if (writableFinished()) { + onUpload(); + } + else { + request.prependOnceListener('finish', onUpload); + } + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + }); + return timings; +}; +exports.default = timer; +// For CommonJS default export support +module.exports = timer; +module.exports.default = timer; diff --git a/tests/node_modules/@szmarczak/http-timer/package.json b/tests/node_modules/@szmarczak/http-timer/package.json new file mode 100644 index 0000000..0636fe8 --- /dev/null +++ b/tests/node_modules/@szmarczak/http-timer/package.json @@ -0,0 +1,102 @@ +{ + "_from": "@szmarczak/http-timer@^4.0.5", + "_id": "@szmarczak/http-timer@4.0.5", + "_inBundle": false, + "_integrity": "sha512-PyRA9sm1Yayuj5OIoJ1hGt2YISX45w9WcFbh6ddT0Z/0yaFxOtGLInr4jUfU1EAFVs0Yfyfev4RNwBlUaHdlDQ==", + "_location": "/@szmarczak/http-timer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@szmarczak/http-timer@^4.0.5", + "name": "@szmarczak/http-timer", + "escapedName": "@szmarczak%2fhttp-timer", + "scope": "@szmarczak", + "rawSpec": "^4.0.5", + "saveSpec": null, + "fetchSpec": "^4.0.5" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.5.tgz", + "_shasum": "bfbd50211e9dfa51ba07da58a14cdfd333205152", + "_spec": "@szmarczak/http-timer@^4.0.5", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "author": { + "name": "Szymon Marczak" + }, + "ava": { + "typescript": { + "rewritePaths": { + "tests/": "dist/tests/" + } + } + }, + "bugs": { + "url": "https://github.com/szmarczak/http-timer/issues" + }, + "bundleDependencies": false, + "dependencies": { + "defer-to-connect": "^2.0.0" + }, + "deprecated": false, + "description": "Timings for HTTP requests", + "devDependencies": { + "@ava/typescript": "^1.1.0", + "@sindresorhus/tsconfig": "^0.7.0", + "@types/node": "^13.5.1", + "@typescript-eslint/eslint-plugin": "^2.18.0", + "@typescript-eslint/parser": "^2.18.0", + "ava": "^3.2.0", + "coveralls": "^3.0.9", + "del-cli": "^3.0.0", + "eslint-config-xo-typescript": "^0.24.1", + "nyc": "^15.0.0", + "p-event": "^4.1.0", + "typescript": "^3.7.5", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "dist/source" + ], + "homepage": "https://github.com/szmarczak/http-timer#readme", + "keywords": [ + "http", + "https", + "timer", + "timings" + ], + "license": "MIT", + "main": "dist/source", + "name": "@szmarczak/http-timer", + "nyc": { + "extension": [ + ".ts" + ], + "exclude": [ + "**/tests/**" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/szmarczak/http-timer.git" + }, + "scripts": { + "build": "del-cli dist && tsc", + "coveralls": "nyc report --reporter=text-lcov | coveralls", + "prepare": "npm run build", + "test": "xo && tsc --noEmit && nyc ava" + }, + "types": "dist/source", + "version": "4.0.5", + "xo": { + "extends": "xo-typescript", + "extensions": [ + "ts" + ] + } +} diff --git a/tests/node_modules/@types/cacheable-request/LICENSE b/tests/node_modules/@types/cacheable-request/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/tests/node_modules/@types/cacheable-request/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/node_modules/@types/cacheable-request/README.md b/tests/node_modules/@types/cacheable-request/README.md new file mode 100644 index 0000000..8a6bd07 --- /dev/null +++ b/tests/node_modules/@types/cacheable-request/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/cacheable-request` + +# Summary +This package contains type definitions for cacheable-request ( https://github.com/lukechilds/cacheable-request#readme ). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cacheable-request + +Additional Details + * Last updated: Mon, 25 Mar 2019 16:32:10 GMT + * Dependencies: @types/keyv, @types/http-cache-semantics, @types/responselike, @types/node + * Global values: none + +# Credits +These definitions were written by BendingBender , Paul Melnikow . diff --git a/tests/node_modules/@types/cacheable-request/index.d.ts b/tests/node_modules/@types/cacheable-request/index.d.ts new file mode 100644 index 0000000..16e7782 --- /dev/null +++ b/tests/node_modules/@types/cacheable-request/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Paul Melnikow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { request, RequestOptions, ClientRequest, ServerResponse } from 'http'; +import { URL } from 'url'; +import { EventEmitter } from 'events'; +import { Store } from 'keyv'; +import { Options as CacheSemanticsOptions } from 'http-cache-semantics'; +import ResponseLike = require('responselike'); + +export = CacheableRequest; + +declare const CacheableRequest: CacheableRequest; + +type RequestFn = typeof request; + +interface CacheableRequest { + new (requestFn: RequestFn, storageAdapter?: string | CacheableRequest.StorageAdapter): ( + opts: string | URL | (RequestOptions & CacheSemanticsOptions), + cb?: (response: ServerResponse | ResponseLike) => void + ) => CacheableRequest.Emitter; + + RequestError: typeof RequestErrorCls; + CacheError: typeof CacheErrorCls; +} + +declare namespace CacheableRequest { + type StorageAdapter = Store; + + interface Options { + /** + * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. + * @default true + */ + cache?: boolean; + + /** + * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + * + * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated + * on the next request with `If-None-Match`/`If-Modified-Since` headers. + * @default false + */ + strictTtl?: boolean; + + /** + * Limits TTL. The `number` represents milliseconds. + * @default undefined + */ + maxTtl?: number; + + /** + * When set to `true`, if the DB connection fails we will automatically fallback to a network request. + * DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + * @default false + */ + automaticFailover?: boolean; + + /** + * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a + * new request and override the cache instead. + * @default false + */ + forceRefresh?: boolean; + } + + interface Emitter extends EventEmitter { + addListener(event: 'request', listener: (request: ClientRequest) => void): this; + addListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + on(event: 'request', listener: (request: ClientRequest) => void): this; + on(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + on(event: 'error', listener: (error: RequestError | CacheError) => void): this; + once(event: 'request', listener: (request: ClientRequest) => void): this; + once(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + once(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependOnceListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependOnceListener( + event: 'error', + listener: (error: RequestError | CacheError) => void + ): this; + removeListener(event: 'request', listener: (request: ClientRequest) => void): this; + removeListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + off(event: 'request', listener: (request: ClientRequest) => void): this; + off(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + off(event: 'error', listener: (error: RequestError | CacheError) => void): this; + removeAllListeners(event?: 'request' | 'response' | 'error'): this; + listeners(event: 'request'): Array<(request: ClientRequest) => void>; + listeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + rawListeners(event: 'request'): Array<(request: ClientRequest) => void>; + rawListeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + emit(event: 'request', request: ClientRequest): boolean; + emit(event: 'response', response: ServerResponse | ResponseLike): boolean; + emit(event: 'error', error: RequestError | CacheError): boolean; + eventNames(): Array<'request' | 'response' | 'error'>; + listenerCount(type: 'request' | 'response' | 'error'): number; + } + + type RequestError = RequestErrorCls; + type CacheError = CacheErrorCls; +} + +declare class RequestErrorCls extends Error { + readonly name: 'RequestError'; + + constructor(error: Error); +} +declare class CacheErrorCls extends Error { + readonly name: 'CacheError'; + + constructor(error: Error); +} diff --git a/tests/node_modules/@types/cacheable-request/package.json b/tests/node_modules/@types/cacheable-request/package.json new file mode 100644 index 0000000..d8b30ec --- /dev/null +++ b/tests/node_modules/@types/cacheable-request/package.json @@ -0,0 +1,62 @@ +{ + "_from": "@types/cacheable-request@^6.0.1", + "_id": "@types/cacheable-request@6.0.1", + "_inBundle": false, + "_integrity": "sha512-ykFq2zmBGOCbpIXtoVbz4SKY5QriWPh3AjyU4G74RYbtt5yOc5OfaY75ftjg7mikMOla1CTGpX3lLbuJh8DTrQ==", + "_location": "/@types/cacheable-request", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/cacheable-request@^6.0.1", + "name": "@types/cacheable-request", + "escapedName": "@types%2fcacheable-request", + "scope": "@types", + "rawSpec": "^6.0.1", + "saveSpec": null, + "fetchSpec": "^6.0.1" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.1.tgz", + "_shasum": "5d22f3dded1fd3a84c0bbeb5039a7419c2c91976", + "_spec": "@types/cacheable-request@^6.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "BendingBender", + "url": "https://github.com/BendingBender" + }, + { + "name": "Paul Melnikow", + "url": "https://github.com/paulmelnikow" + } + ], + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "*", + "@types/node": "*", + "@types/responselike": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for cacheable-request", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/cacheable-request", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/cacheable-request" + }, + "scripts": {}, + "typeScriptVersion": "2.3", + "types": "index", + "typesPublisherContentHash": "c6afce5b9ca6ee2952549da29e2d4af2bd367dbf44a175a005063192d46b7814", + "version": "6.0.1" +} diff --git a/tests/node_modules/@types/http-cache-semantics/LICENSE b/tests/node_modules/@types/http-cache-semantics/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/tests/node_modules/@types/http-cache-semantics/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/node_modules/@types/http-cache-semantics/README.md b/tests/node_modules/@types/http-cache-semantics/README.md new file mode 100644 index 0000000..6245fb3 --- /dev/null +++ b/tests/node_modules/@types/http-cache-semantics/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/http-cache-semantics` + +# Summary +This package contains type definitions for http-cache-semantics ( https://github.com/kornelski/http-cache-semantics#readme ). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/http-cache-semantics + +Additional Details + * Last updated: Wed, 30 Jan 2019 18:47:31 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by BendingBender . diff --git a/tests/node_modules/@types/http-cache-semantics/index.d.ts b/tests/node_modules/@types/http-cache-semantics/index.d.ts new file mode 100644 index 0000000..40545f3 --- /dev/null +++ b/tests/node_modules/@types/http-cache-semantics/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for http-cache-semantics 4.0 +// Project: https://github.com/kornelski/http-cache-semantics#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = CachePolicy; + +declare class CachePolicy { + constructor(req: CachePolicy.Request, res: CachePolicy.Response, options?: CachePolicy.Options); + + /** + * Returns `true` if the response can be stored in a cache. + * If it's `false` then you MUST NOT store either the request or the response. + */ + storable(): boolean; + + /** + * This is the most important method. Use this method to check whether the cached response is still fresh + * in the context of the new request. + * + * If it returns `true`, then the given `request` matches the original response this cache policy has been + * created with, and the response can be reused without contacting the server. Note that the old response + * can't be returned without being updated, see `responseHeaders()`. + * + * If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), + * or may require to be refreshed first (see `revalidationHeaders()`). + */ + satisfiesWithoutRevalidation(newRequest: CachePolicy.Request): boolean; + + /** + * Returns updated, filtered set of response headers to return to clients receiving the cached response. + * This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) + * and update response's `Age` to avoid doubling cache time. + * + * @example + * cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); + */ + responseHeaders(): CachePolicy.Headers; + + /** + * Returns approximate time in milliseconds until the response becomes stale (i.e. not fresh). + * + * After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, + * there are exceptions, e.g. a client can explicitly allow stale responses, so always check with + * `satisfiesWithoutRevalidation()`. + */ + timeToLive(): number; + + /** + * Chances are you'll want to store the `CachePolicy` object along with the cached response. + * `obj = policy.toObject()` gives a plain JSON-serializable object. + */ + toObject(): CachePolicy.CachePolicyObject; + + /** + * `policy = CachePolicy.fromObject(obj)` creates an instance from object created by `toObject()`. + */ + static fromObject(obj: CachePolicy.CachePolicyObject): CachePolicy; + + /** + * Returns updated, filtered set of request headers to send to the origin server to check if the cached + * response can be reused. These headers allow the origin server to return status 304 indicating the + * response is still fresh. All headers unrelated to caching are passed through as-is. + * + * Use this method when updating cache from the origin server. + * + * @example + * updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); + */ + revalidationHeaders(newRequest: CachePolicy.Request): CachePolicy.Headers; + + /** + * Use this method to update the cache after receiving a new response from the origin server. + */ + revalidatedPolicy( + revalidationRequest: CachePolicy.Request, + revalidationResponse: CachePolicy.Response + ): CachePolicy.RevalidationPolicy; +} + +declare namespace CachePolicy { + interface Request { + url?: string; + method?: string; + headers: Headers; + } + + interface Response { + status?: number; + headers: Headers; + } + + interface Options { + /** + * If `true`, then the response is evaluated from a perspective of a shared cache (i.e. `private` is not + * cacheable and `s-maxage` is respected). If `false`, then the response is evaluated from a perspective + * of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). + * `true` is recommended for HTTP clients. + * @default true + */ + shared?: boolean; + /** + * A fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), + * e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. + * @default 0.1 + */ + cacheHeuristic?: number; + /** + * A number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. + * Note that [per RFC](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension) + * these can become stale, so `max-age` still overrides the default. + * @default 24*3600*1000 (24h) + */ + immutableMinTimeToLive?: number; + /** + * If `true`, common anti-cache directives will be completely ignored if the non-standard `pre-check` + * and `post-check` directives are present. These two useless directives are most commonly found + * in bad StackOverflow answers and PHP's "session limiter" defaults. + * @default false + */ + ignoreCargoCult?: boolean; + /** + * If `false`, then server's `Date` header won't be used as the base for `max-age`. This is against the RFC, + * but it's useful if you want to cache responses with very short `max-age`, but your local clock + * is not exactly in sync with the server's. + * @default true + */ + trustServerDate?: boolean; + } + + interface CachePolicyObject { + v: number; + t: number; + sh: boolean; + ch: number; + imm: number; + st: number; + resh: Headers; + rescc: { [key: string]: string }; + m: string; + u?: string; + h?: string; + a: boolean; + reqh: Headers | null; + reqcc: { [key: string]: string }; + } + + interface Headers { + [header: string]: string | string[] | undefined; + } + + interface RevalidationPolicy { + /** + * A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace + * the old cached `CachePolicy` with the new one. + */ + policy: CachePolicy; + /** + * Boolean indicating whether the response body has changed. + * + * - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old + * cached response body. + * - If `true`, you should use new response's body (if present), or make another request to the origin + * server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get + * the new resource. + */ + modified: boolean; + matches: boolean; + } +} diff --git a/tests/node_modules/@types/http-cache-semantics/package.json b/tests/node_modules/@types/http-cache-semantics/package.json new file mode 100644 index 0000000..96450fa --- /dev/null +++ b/tests/node_modules/@types/http-cache-semantics/package.json @@ -0,0 +1,52 @@ +{ + "_from": "@types/http-cache-semantics@*", + "_id": "@types/http-cache-semantics@4.0.0", + "_inBundle": false, + "_integrity": "sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==", + "_location": "/@types/http-cache-semantics", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/http-cache-semantics@*", + "name": "@types/http-cache-semantics", + "escapedName": "@types%2fhttp-cache-semantics", + "scope": "@types", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "/@types/cacheable-request" + ], + "_resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz", + "_shasum": "9140779736aa2655635ee756e2467d787cfe8a2a", + "_spec": "@types/http-cache-semantics@*", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/@types/cacheable-request", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for http-cache-semantics", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/http-cache-semantics", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "types": "index", + "typesPublisherContentHash": "0f2f0f2e4444736e9747a8b7b3cd04c9064067e0181263cfb85337511ae13a35", + "version": "4.0.0" +} diff --git a/tests/node_modules/@types/keyv/LICENSE b/tests/node_modules/@types/keyv/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/tests/node_modules/@types/keyv/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/node_modules/@types/keyv/README.md b/tests/node_modules/@types/keyv/README.md new file mode 100644 index 0000000..681af21 --- /dev/null +++ b/tests/node_modules/@types/keyv/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/keyv` + +# Summary +This package contains type definitions for keyv (https://github.com/lukechilds/keyv). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/keyv. + +### Additional Details + * Last updated: Mon, 23 Dec 2019 16:40:54 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + * Global values: none + +# Credits +These definitions were written by AryloYeung (https://github.com/Arylo), and BendingBender (https://github.com/BendingBender). diff --git a/tests/node_modules/@types/keyv/index.d.ts b/tests/node_modules/@types/keyv/index.d.ts new file mode 100644 index 0000000..d95745b --- /dev/null +++ b/tests/node_modules/@types/keyv/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for keyv 3.1 +// Project: https://github.com/lukechilds/keyv +// Definitions by: AryloYeung +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import { EventEmitter } from 'events'; + +declare class Keyv extends EventEmitter { + /** + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(opts?: Keyv.Options); + /** + * @param uri The connection string URI. + * + * Merged into the options object as options.uri. + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(uri?: string, opts?: Keyv.Options); + + /** Returns the value. */ + get(key: string): Promise; + /** + * Set a value. + * + * By default keys are persistent. You can set an expiry TTL in milliseconds. + */ + set(key: string, value: TValue, ttl?: number): Promise; + /** + * Deletes an entry. + * + * Returns `true` if the key existed, `false` if not. + */ + delete(key: string): Promise; + /** Delete all entries in the current namespace. */ + clear(): Promise; +} + +declare namespace Keyv { + interface Options { + /** Namespace for the current instance. */ + namespace?: string; + /** A custom serialization function. */ + serialize?: (data: TValue) => string; + /** A custom deserialization function. */ + deserialize?: (data: string) => TValue; + /** The connection string URI. */ + uri?: string; + /** The storage adapter instance to be used by Keyv. */ + store?: Store; + /** Default TTL. Can be overridden by specififying a TTL on `.set()`. */ + ttl?: number; + /** Specify an adapter to use. e.g `'redis'` or `'mongodb'`. */ + adapter?: 'redis' | 'mongodb' | 'mongo' | 'sqlite' | 'postgresql' | 'postgres' | 'mysql'; + + [key: string]: any; + } + + interface Store { + get(key: string): TValue | Promise | undefined; + set(key: string, value: TValue, ttl?: number): any; + delete(key: string): boolean | Promise; + clear(): void | Promise; + } +} + +export = Keyv; diff --git a/tests/node_modules/@types/keyv/package.json b/tests/node_modules/@types/keyv/package.json new file mode 100644 index 0000000..0122b98 --- /dev/null +++ b/tests/node_modules/@types/keyv/package.json @@ -0,0 +1,59 @@ +{ + "_from": "@types/keyv@*", + "_id": "@types/keyv@3.1.1", + "_inBundle": false, + "_integrity": "sha512-MPtoySlAZQ37VoLaPcTHCu1RWJ4llDkULYZIzOYxlhxBqYPB0RsRlmMU0R6tahtFe27mIdkHV+551ZWV4PLmVw==", + "_location": "/@types/keyv", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/keyv@*", + "name": "@types/keyv", + "escapedName": "@types%2fkeyv", + "scope": "@types", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "/@types/cacheable-request" + ], + "_resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.1.tgz", + "_shasum": "e45a45324fca9dab716ab1230ee249c9fb52cfa7", + "_spec": "@types/keyv@*", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/@types/cacheable-request", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "AryloYeung", + "url": "https://github.com/Arylo" + }, + { + "name": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "dependencies": { + "@types/node": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for keyv", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/keyv", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/keyv" + }, + "scripts": {}, + "typeScriptVersion": "2.8", + "types": "index.d.ts", + "typesPublisherContentHash": "883f9e92997b7991324e37284aa16e71d6f43731110ec0e7f62ccca68960aec3", + "version": "3.1.1" +} diff --git a/tests/node_modules/@types/node/LICENSE b/tests/node_modules/@types/node/LICENSE new file mode 100755 index 0000000..9e841e7 --- /dev/null +++ b/tests/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/node_modules/@types/node/README.md b/tests/node_modules/@types/node/README.md new file mode 100755 index 0000000..e272818 --- /dev/null +++ b/tests/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (http://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Fri, 18 Jun 2021 21:01:11 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), [Victor Perin](https://github.com/victorperin), and [Yongsheng Zhang](https://github.com/ZYSzys). diff --git a/tests/node_modules/@types/node/assert.d.ts b/tests/node_modules/@types/node/assert.d.ts new file mode 100755 index 0000000..e9e3585 --- /dev/null +++ b/tests/node_modules/@types/node/assert.d.ts @@ -0,0 +1,124 @@ +declare module 'assert' { + /** An alias of `assert.ok()`. */ + function assert(value: any, message?: string | Error): asserts value; + namespace assert { + class AssertionError extends Error { + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string; + /** The `actual` property on the error instance. */ + actual?: any; + /** The `expected` property on the error instance. */ + expected?: any; + /** The `operator` property on the error instance. */ + operator?: string; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function; + }); + } + + class CallTracker { + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + report(): CallTrackerReportInformation[]; + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + + type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error; + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: any, + expected: any, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function, + ): never; + function ok(value: any, message?: string | Error): asserts value; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: () => any, message?: string | Error): void; + function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; + function doesNotThrow(block: () => any, message?: string | Error): void; + function doesNotThrow(block: () => any, error: AssertPredicate, message?: string | Error): void; + + function ifError(value: any): asserts value is null | undefined; + + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + + function match(value: string, regExp: RegExp, message?: string | Error): void; + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + + const strict: Omit< + typeof assert, + | 'equal' + | 'notEqual' + | 'deepEqual' + | 'notDeepEqual' + | 'ok' + | 'strictEqual' + | 'deepStrictEqual' + | 'ifError' + | 'strict' + > & { + (value: any, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + + export = assert; +} diff --git a/tests/node_modules/@types/node/assert/strict.d.ts b/tests/node_modules/@types/node/assert/strict.d.ts new file mode 100755 index 0000000..bc3b2a7 --- /dev/null +++ b/tests/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,4 @@ +declare module 'assert/strict' { + import { strict } from 'assert'; + export = strict; +} diff --git a/tests/node_modules/@types/node/async_hooks.d.ts b/tests/node_modules/@types/node/async_hooks.d.ts new file mode 100755 index 0000000..92cc9ad --- /dev/null +++ b/tests/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,226 @@ +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module 'async_hooks' { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * The resource representing the current execution. + * Useful to store data within the resource. + * + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + */ + function executionAsyncResource(): object; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Binds the given function to the current execution context. + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource }; + + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func & { asyncResource: AsyncResource }; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): this; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } + + /** + * When having multiple instances of `AsyncLocalStorage`, they are independent + * from each other. It is safe to instantiate this class multiple times. + */ + class AsyncLocalStorage { + /** + * This method disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until + * `asyncLocalStorage.run()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the + * `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * This method is to be used when the `asyncLocalStorage` is not in use anymore + * in the current process. + */ + disable(): void; + + /** + * This method returns the current store. If this method is called outside of an + * asynchronous context initialized by calling `asyncLocalStorage.run`, it will + * return `undefined`. + */ + getStore(): T | undefined; + + /** + * This methods runs a function synchronously within a context and return its + * return value. The store is not accessible outside of the callback function or + * the asynchronous operations created within the callback. + * + * Optionally, arguments can be passed to the function. They will be passed to the + * callback function. + * + * I the callback function throws an error, it will be thrown by `run` too. The + * stacktrace will not be impacted by this call and the context will be exited. + */ + // TODO: Apply generic vararg once available + run(store: T, callback: (...args: any[]) => R, ...args: any[]): R; + + /** + * This methods runs a function synchronously outside of a context and return its + * return value. The store is not accessible within the callback function or the + * asynchronous operations created within the callback. + * + * Optionally, arguments can be passed to the function. They will be passed to the + * callback function. + * + * If the callback function throws an error, it will be thrown by `exit` too. The + * stacktrace will not be impacted by this call and the context will be + * re-entered. + */ + // TODO: Apply generic vararg once available + exit(callback: (...args: any[]) => R, ...args: any[]): R; + + /** + * Calling `asyncLocalStorage.enterWith(store)` will transition into the context + * for the remainder of the current synchronous execution and will persist + * through any following asynchronous calls. + */ + enterWith(store: T): void; + } +} diff --git a/tests/node_modules/@types/node/base.d.ts b/tests/node_modules/@types/node/base.d.ts new file mode 100755 index 0000000..fa67179 --- /dev/null +++ b/tests/node_modules/@types/node/base.d.ts @@ -0,0 +1,19 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// TypeScript 3.7-specific augmentations: +/// diff --git a/tests/node_modules/@types/node/buffer.d.ts b/tests/node_modules/@types/node/buffer.d.ts new file mode 100755 index 0000000..a415a4d --- /dev/null +++ b/tests/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,84 @@ +declare module 'buffer' { + import { BinaryLike } from 'crypto'; + + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + const BuffType: typeof Buffer; + + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; + + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding; + + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string; + } + + /** + * @experimental + */ + export class Blob { + /** + * Returns a promise that fulfills with an {ArrayBuffer} containing a copy of the `Blob` data. + */ + readonly size: number; + + /** + * The content-type of the `Blob`. + */ + readonly type: string; + + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array<(BinaryLike | Blob)>, options?: BlobOptions); + + arrayBuffer(): Promise; + + /** + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + + /** + * Returns a promise that resolves the contents of the `Blob` decoded as a UTF-8 string. + */ + text(): Promise; + } +} + +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/tests/node_modules/@types/node/child_process.d.ts b/tests/node_modules/@types/node/child_process.d.ts new file mode 100755 index 0000000..37fd485 --- /dev/null +++ b/tests/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,526 @@ +declare module 'child_process' { + import { BaseEncodingOptions } from 'fs'; + import { EventEmitter, Abortable } from 'events'; + import * as net from 'net'; + import { Writable, Readable, Stream, Pipe } from 'stream'; + + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + + interface ChildProcess extends EventEmitter { + stdin: Writable | null; + stdout: Readable | null; + stderr: Readable | null; + readonly channel?: Pipe | null; + readonly stdio: [ + Writable | null, // stdin + Readable | null, // stdout + Readable | null, // stderr + Readable | Writable | null | undefined, // extra + Readable | Writable | null | undefined // extra + ]; + readonly killed: boolean; + readonly pid?: number; + readonly connected: boolean; + readonly exitCode: number | null; + readonly signalCode: NodeJS.Signals | null; + readonly spawnargs: string[]; + readonly spawnfile: string; + kill(signal?: NodeJS.Signals | number): boolean; + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, // stdin + Readable, // stdout + Readable, // stderr + Readable | Writable | null | undefined, // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio< + I extends null | Writable, + O extends null | Readable, + E extends null | Readable, + > extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + + type StdioOptions = IOType | Array<(IOType | "ipc" | Stream | number | null | undefined)>; + + type SerializationType = 'json' | 'advanced'; + + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType; + + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number; + } + + interface ProcessEnvOptions { + uid?: number; + gid?: number; + cwd?: string; + env?: NodeJS.ProcessEnv; + } + + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean; + /** + * @default 0 + */ + timeout?: number; + } + + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string; + stdio?: StdioOptions; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + } + + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean; + } + + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[]; + } + + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + + // overloads of spawn without 'args' + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + + function spawn(command: string, options: SpawnOptions): ChildProcess; + + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: ReadonlyArray, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + + interface ExecOptions extends CommonOptions { + shell?: string; + maxBuffer?: number; + killSignal?: NodeJS.Signals | number; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { encoding: BufferEncoding } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (BaseEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: (BaseEncodingOptions & ExecOptions) | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number; + killSignal?: NodeJS.Signals | number; + windowsVerbatimArguments?: boolean; + shell?: boolean | string; + signal?: AbortSignal; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + detached?: boolean; + windowsVerbatimArguments?: boolean; + } + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView; + maxBuffer?: number; + encoding?: BufferEncoding | 'buffer' | null; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null; + } + interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + interface ExecSyncOptions extends CommonOptions { + input?: string | Uint8Array; + stdio?: StdioOptions; + shell?: string; + killSignal?: NodeJS.Signals | number; + maxBuffer?: number; + encoding?: BufferEncoding | 'buffer' | null; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null; + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView; + stdio?: StdioOptions; + killSignal?: NodeJS.Signals | number; + maxBuffer?: number; + encoding?: BufferEncoding; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} diff --git a/tests/node_modules/@types/node/cluster.d.ts b/tests/node_modules/@types/node/cluster.d.ts new file mode 100755 index 0000000..5117639 --- /dev/null +++ b/tests/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,262 @@ +declare module 'cluster' { + import * as child from 'child_process'; + import EventEmitter = require('events'); + import * as net from 'net'; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends EventEmitter { + id: number; + process: child.ChildProcess; + send(message: child.Serializable, sendHandle?: child.SendHandle, callback?: (error: Error | null) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends EventEmitter { + Worker: Worker; + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + schedulingPolicy: number; + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: NodeJS.Dict; + + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + + const SCHED_NONE: number; + const SCHED_RR: number; + + function disconnect(callback?: () => void): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + let schedulingPolicy: number; + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: NodeJS.Dict; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: ClusterSettings): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function eventNames(): string[]; +} diff --git a/tests/node_modules/@types/node/console.d.ts b/tests/node_modules/@types/node/console.d.ts new file mode 100755 index 0000000..e5f9cba --- /dev/null +++ b/tests/node_modules/@types/node/console.d.ts @@ -0,0 +1,133 @@ +declare module 'console' { + import { InspectOptions } from 'util'; + + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls {@link console.log} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group}. + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info} function is an alias for {@link console.log}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn} function is an alias for {@link console.error}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + + var console: Console; + + namespace NodeJS { + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface Global { + console: typeof console; + } + } + } + + export = console; +} diff --git a/tests/node_modules/@types/node/constants.d.ts b/tests/node_modules/@types/node/constants.d.ts new file mode 100755 index 0000000..98ff976 --- /dev/null +++ b/tests/node_modules/@types/node/constants.d.ts @@ -0,0 +1,13 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'os'; + import { constants as cryptoConstants } from 'crypto'; + import { constants as fsConstants } from 'fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} diff --git a/tests/node_modules/@types/node/crypto.d.ts b/tests/node_modules/@types/node/crypto.d.ts new file mode 100755 index 0000000..db06d15 --- /dev/null +++ b/tests/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,1580 @@ +declare module 'crypto' { + import * as stream from 'stream'; + import { PeerCertificate } from 'tls'; + + interface Certificate { + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new(): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; + + /** + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + }; + + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + + const ALPN_ENABLED: number; + + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number; + } + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + function createHash(algorithm: string, options?: HashOptions): Hash; + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'hex'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + + class Hash extends stream.Transform { + private constructor(); + copy(): Hash; + update(data: BinaryLike): Hash; + update(data: string, input_encoding: Encoding): Hash; + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + class Hmac extends stream.Transform { + private constructor(); + update(data: BinaryLike): Hmac; + update(data: string, input_encoding: Encoding): Hmac; + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + + type KeyObjectType = 'secret' | 'public' | 'private'; + + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string; + passphrase?: string | Buffer; + } + + interface JwkKeyExportOptions { + format: 'jwk'; + } + + interface JsonWebKey { + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + k?: string; + kty?: string; + n?: string; + p?: string; + q?: string; + qi?: string; + x?: string; + y?: string; + } + + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + + class KeyObject { + private constructor(); + asymmetricKeyType?: KeyType; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise the + * security of the key. + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + symmetricKeySize?: number; + type: KeyObjectType; + } + + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + + type BinaryLike = string | NodeJS.ArrayBufferView; + + type CipherKey = BinaryLike | KeyObject; + + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + + class Cipher extends stream.Transform { + private constructor(); + update(data: BinaryLike): Buffer; + update(data: string, input_encoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string; + update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string; + final(): Buffer; + final(output_encoding: BufferEncoding): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: NodeJS.ArrayBufferView): this; + } + interface CipherCCM extends Cipher { + setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + + class Decipher extends stream.Transform { + private constructor(); + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, input_encoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string; + update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string; + final(): Buffer; + final(output_encoding: BufferEncoding): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: NodeJS.ArrayBufferView): this; + // setAAD(buffer: NodeJS.ArrayBufferView): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; + } + + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'pkcs8' | 'sec1'; + passphrase?: string | Buffer; + } + + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'spki'; + } + + function generateKey(type: 'hmac' | 'aes', options: {length: number}, callback: (err: Error | null, key: KeyObject) => void): void; + + function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject; + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + + type DSAEncoding = 'der' | 'ieee-p1363'; + + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number; + saltLength?: number; + dsaEncoding?: DSAEncoding; + } + + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions { } + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions { } + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + + type KeyLike = string | Buffer | KeyObject; + + class Signer extends stream.Writable { + private constructor(); + + update(data: BinaryLike): Signer; + update(data: string, input_encoding: Encoding): Signer; + sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign( + private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + output_format: BinaryToTextEncoding, + ): string; + } + + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + class Verify extends stream.Writable { + private constructor(); + + update(data: BinaryLike): Verify; + update(data: string, input_encoding: Encoding): Verify; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman( + prime: string, + prime_encoding: BinaryToTextEncoding, + generator: number | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + prime_encoding: BinaryToTextEncoding, + generator: string, + generator_encoding: BinaryToTextEncoding, + ): DiffieHellman; + class DiffieHellman { + private constructor(); + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; + computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer; + computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string; + computeSecret( + other_public_key: string, + input_encoding: BinaryToTextEncoding, + output_encoding: BinaryToTextEncoding, + ): string; + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + setPublicKey(public_key: NodeJS.ArrayBufferView): void; + setPublicKey(public_key: string, encoding: BufferEncoding): void; + setPrivateKey(private_key: NodeJS.ArrayBufferView): void; + setPrivateKey(private_key: string, encoding: BufferEncoding): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + + function randomFillSync(buffer: T, offset?: number, size?: number): T; + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + + interface ScryptOptions { + cost?: number; + blockSize?: number; + parallelization?: number; + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: KeyLike; + padding?: number; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string; + /** + * @default 'sha1' + */ + oaepHash?: string; + oaepLabel?: NodeJS.TypedArray; + padding?: number; + } + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getFips(): 1 | 0; + function getHashes(): string[]; + class ECDH { + private constructor(); + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64', + format?: 'uncompressed' | 'compressed' | 'hybrid', + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; + computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer; + computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string; + computeSecret( + other_public_key: string, + input_encoding: BinaryToTextEncoding, + output_encoding: BinaryToTextEncoding, + ): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: NodeJS.ArrayBufferView): void; + setPrivateKey(private_key: string, encoding: BinaryToTextEncoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + + type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string; + passphrase?: string; + } + + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + + interface ED25519KeyPairKeyObjectOptions { + /** + * No options. + */ + } + + interface ED448KeyPairKeyObjectOptions { + /** + * No options. + */ + } + + interface X25519KeyPairKeyObjectOptions { + /** + * No options. + */ + } + + interface X448KeyPairKeyObjectOptions { + /** + * No options. + */ + } + + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * @default 0x10001 + */ + publicExponent?: number; + } + + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * Size of q in bits + */ + divisorLength: number; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'>, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'>, + ): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPair( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'rsa', + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'dsa', + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ec', + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ed25519', + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'ed448', + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'x25519', + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + function generateKeyPair( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'>, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'>, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'>, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: 'x448', + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__( + type: 'ed25519', + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__( + type: 'x25519', + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'>, + ): Promise<{ publicKey: string; privateKey: string }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'>, + ): Promise<{ publicKey: string; privateKey: Buffer }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'>, + ): Promise<{ publicKey: Buffer; privateKey: string }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'>, + ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to `crypto.createPrivateKey(). + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to `crypto.createPublicKey()`. + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + + /** + * Computes the Diffie-Hellman secret based on a privateKey and a publicKey. + * Both keys must have the same asymmetricKeyType, which must be one of + * 'dh' (for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES). + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number; + /** + * A test IV length. + */ + ivLength?: number; + } + + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. + * By default, the `crypto.getCipherInfo()` method will return the default + * values for these ciphers. To test if a given key length or iv length + * is acceptable for given cipher, use the `keyLenth` and `ivLenth` options. + * If the given values are unacceptable, `undefined` will be returned. + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + + /** + * HKDF is a simple key derivation function defined in RFC 5869. + * The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. + * If an errors occurs while deriving the key, `err` will be set; otherwise `err` will be `null`. + * The successfully generated `derivedKey` will be passed to the callback as an `ArrayBuffer`. + * An error will be thrown if any of the input aguments specify invalid values or types. + */ + function hkdf(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => any): void; + + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869. + * The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an `ArrayBuffer`. + * An error will be thrown if any of the input aguments specify invalid values or types, + * or if the derived key cannot be generated. + */ + function hkdfSync(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + + function secureHeapUsed(): SecureHeapUsage; + + // TODO: X509Certificate + + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean; + } + + function randomUUID(options?: RandomUUIDOptions): string; + + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + + /** + * @default true + */ + wildcards: boolean; + + /** + * @default true + */ + partialWildcards: boolean; + + /** + * @default false + */ + multiLabelWildcards: boolean; + + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + + class X509Certificate { + /** + * Will be `true` if this is a Certificate Authority (ca) certificate. + */ + readonly ca: boolean; + + /** + * The SHA-1 fingerprint of this certificate. + */ + readonly fingerprint: string; + + /** + * The SHA-256 fingerprint of this certificate. + */ + readonly fingerprint256: string; + + /** + * The complete subject of this certificate. + */ + readonly subject: string; + + /** + * The subject alternative name specified for this certificate. + */ + readonly subjectAltName: string; + + /** + * The information access content of this certificate. + */ + readonly infoAccess: string; + + /** + * An array detailing the key usages for this certificate. + */ + readonly keyUsage: string[]; + + /** + * The issuer identification included in this certificate. + */ + readonly issuer: string; + + /** + * The issuer certificate or `undefined` if the issuer certificate is not available. + */ + readonly issuerCertificate?: X509Certificate; + + /** + * The public key for this certificate. + */ + readonly publicKey: KeyObject; + + /** + * A `Buffer` containing the DER encoding of this certificate. + */ + readonly raw: Buffer; + + /** + * The serial number of this certificate. + */ + readonly serialNumber: string; + + /** + * Returns the PEM-encoded certificate. + */ + readonly validFrom: string; + + /** + * The date/time from which this certificate is considered valid. + */ + readonly validTo: string; + + constructor(buffer: BinaryLike); + + /** + * Checks whether the certificate matches the given email address. + * + * Returns `email` if the certificate matches,`undefined` if it does not. + */ + checkEmail(email: string, options?: X509CheckOptions): string | undefined; + + /** + * Checks whether the certificate matches the given host name. + * + * Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string, options?: X509CheckOptions): string | undefined; + + /** + * Checks whether this certificate was issued by the given `otherCert`. + */ + checkIssued(otherCert: X509Certificate): boolean; + + /** + * Checks whether this certificate was issued by the given `otherCert`. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + + /** + * There is no standard JSON encoding for X509 certificates. The + * `toJSON()` method returns a string containing the PEM encoded + * certificate. + */ + toJSON(): string; + + /** + * Returns information about this certificate using the legacy certificate object encoding. + */ + toLegacyObject(): PeerCertificate; + + /** + * Returns the PEM-encoded certificate. + */ + toString(): string; + + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + */ + verify(publicKey: KeyObject): boolean; + } + + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + + interface GeneratePrimeOptions { + add?: LargeNumberLike; + rem?: LargeNumberLike; + /** + * @default false + */ + safe?: boolean; + bigint?: boolean; + } + + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false; + } + + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number; + } + + /** + * Checks the primality of the candidate. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + + /** + * Checks the primality of the candidate. + */ + function checkPrimeSync(value: LargeNumberLike, options?: CheckPrimeOptions): boolean; +} diff --git a/tests/node_modules/@types/node/dgram.d.ts b/tests/node_modules/@types/node/dgram.d.ts new file mode 100755 index 0000000..9aa2a6c --- /dev/null +++ b/tests/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,141 @@ +declare module 'dgram' { + import { AddressInfo } from 'net'; + import * as dns from 'dns'; + import { EventEmitter, Abortable } from 'events'; + + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + + interface BindOptions { + port?: number; + address?: string; + exclusive?: boolean; + fd?: number; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends EventEmitter { + addMembership(multicastAddress: string, multicastInterface?: string): void; + address(): AddressInfo; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + close(callback?: () => void): void; + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + disconnect(): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + ref(): this; + remoteAddress(): AddressInfo; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + setBroadcast(flag: boolean): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + setTTL(ttl: number): void; + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given + * `sourceAddress` and `groupAddress`, using the `multicastInterface` with the + * `IP_ADD_SOURCE_MEMBERSHIP` socket option. + * If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. + * To add membership to every available interface, call + * `socket.addSourceSpecificMembership()` multiple times, once per interface. + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + + /** + * Instructs the kernel to leave a source-specific multicast channel at the given + * `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` + * socket option. This method is automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} diff --git a/tests/node_modules/@types/node/diagnostic_channel.d.ts b/tests/node_modules/@types/node/diagnostic_channel.d.ts new file mode 100755 index 0000000..952c94d --- /dev/null +++ b/tests/node_modules/@types/node/diagnostic_channel.d.ts @@ -0,0 +1,34 @@ +/** + * @experimental + */ +declare module 'diagnostic_channel' { + /** + * Returns wether a named channel has subscribers or not. + */ + function hasSubscribers(name: string): boolean; + + /** + * Gets or create a diagnostic channel by name. + */ + function channel(name: string): Channel; + + type ChannelListener = (name: string, message: unknown) => void; + + /** + * Simple diagnostic channel that allows + */ + class Channel { + readonly name: string; + readonly hashSubscribers: boolean; + private constructor(name: string); + + /** + * Add a listener to the message channel. + */ + subscribe(listener: ChannelListener): void; + /** + * Removes a previously registered listener. + */ + unsubscribe(listener: ChannelListener): void; + } +} diff --git a/tests/node_modules/@types/node/dns.d.ts b/tests/node_modules/@types/node/dns.d.ts new file mode 100755 index 0000000..62c75ef --- /dev/null +++ b/tests/node_modules/@types/node/dns.d.ts @@ -0,0 +1,322 @@ +declare module 'dns' { + import * as dnsPromises from "dns/promises"; + + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + + export namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + export interface ResolveOptions { + ttl: boolean; + } + + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + export interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + export interface CaaRecord { + critial: number; + issue?: string; + issuewild?: string; + iodef?: string; + contactemail?: string; + contactphone?: string; + } + + export interface MxRecord { + priority: number; + exchange: string; + } + + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + export interface AnyNsRecord { + type: "NS"; + value: string; + } + + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + export type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + export function setServers(servers: ReadonlyArray): void; + export function getServers(): string[]; + + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + + export interface ResolverOptions { + timeout?: number; + } + + export class Resolver { + constructor(options?: ResolverOptions); + + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + + export { dnsPromises as promises }; +} diff --git a/tests/node_modules/@types/node/dns/promises.d.ts b/tests/node_modules/@types/node/dns/promises.d.ts new file mode 100755 index 0000000..2feb874 --- /dev/null +++ b/tests/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,97 @@ +declare module "dns/promises" { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from "dns"; + + function getServers(): string[]; + + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + + function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; + + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise; + + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + + function resolveAny(hostname: string): Promise; + + function resolveCaa(hostname: string): Promise; + + function resolveCname(hostname: string): Promise; + + function resolveMx(hostname: string): Promise; + + function resolveNaptr(hostname: string): Promise; + + function resolveNs(hostname: string): Promise; + + function resolvePtr(hostname: string): Promise; + + function resolveSoa(hostname: string): Promise; + + function resolveSrv(hostname: string): Promise; + + function resolveTxt(hostname: string): Promise; + + function reverse(ip: string): Promise; + + function setServers(servers: ReadonlyArray): void; + + class Resolver { + constructor(options?: ResolverOptions); + + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} diff --git a/tests/node_modules/@types/node/domain.d.ts b/tests/node_modules/@types/node/domain.d.ts new file mode 100755 index 0000000..6423ebf --- /dev/null +++ b/tests/node_modules/@types/node/domain.d.ts @@ -0,0 +1,24 @@ +declare module 'domain' { + import EventEmitter = require('events'); + + global { + namespace NodeJS { + interface Domain extends EventEmitter { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: EventEmitter | Timer): void; + remove(emitter: EventEmitter | Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + } + } + } + + interface Domain extends NodeJS.Domain {} + class Domain extends EventEmitter { + members: Array; + enter(): void; + exit(): void; + } + + function create(): Domain; +} diff --git a/tests/node_modules/@types/node/events.d.ts b/tests/node_modules/@types/node/events.d.ts new file mode 100755 index 0000000..0d5d247 --- /dev/null +++ b/tests/node_modules/@types/node/events.d.ts @@ -0,0 +1,93 @@ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean; + } + + interface NodeEventTarget { + once(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DOMEventTarget { + addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any; + } + + interface StaticEventEmitterOptions { + signal?: AbortSignal; + } + + interface EventEmitter extends NodeJS.EventEmitter {} + class EventEmitter { + constructor(options?: EventEmitterOptions); + + static once(emitter: NodeEventTarget, event: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, event: string, options?: StaticEventEmitterOptions): Promise; + static on(emitter: NodeJS.EventEmitter, event: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; + + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: NodeJS.EventEmitter, event: string | symbol): number; + /** + * Returns a list listener for a specific emitter event name. + */ + static getEventListener(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + + import internal = require('events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal; + } + } + + global { + namespace NodeJS { + interface EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(event: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + } + } + + export = EventEmitter; +} diff --git a/tests/node_modules/@types/node/fs.d.ts b/tests/node_modules/@types/node/fs.d.ts new file mode 100755 index 0000000..e6b95cc --- /dev/null +++ b/tests/node_modules/@types/node/fs.d.ts @@ -0,0 +1,2239 @@ +declare module 'fs' { + import * as stream from 'stream'; + import { Abortable, EventEmitter } from 'events'; + import { URL } from 'url'; + import * as promises from 'fs/promises'; + + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + + export type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }; + + export interface BaseEncodingOptions { + encoding?: BufferEncoding | null; + } + + export type OpenMode = number | string; + + export type Mode = number | string; + + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + export interface Stats extends StatsBase { + } + + export class Stats { + } + + export class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + /** + * A class representing a directory stream. + */ + export class Dir { + readonly path: string; + + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + close(): Promise; + close(cb: NoParamCallback): void; + + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + closeSync(): void; + + /** + * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. + * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + + /** + * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. + * If there are no more directory entries to read, null will be returned. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + readSync(): Dirent | null; + } + + export interface FSWatcher extends EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Changes the access and modification times of a file in the same way as `fs.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Change the file system timestamps of the symbolic link referenced by `path`. Returns `undefined`, + * or throws an exception when parameters are incorrect or the operation fails. + * This is the synchronous version of `fs.lutimes()`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function lutimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmodSync(path: PathLike, mode: Mode): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmodSync(fd: number, mode: Mode): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat(path: PathLike, options: StatOptions & { bigint?: false } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat(path: PathLike, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: StatOptions & { bigint?: false }): Promise; + function __promisify__(path: PathLike, options: StatOptions & { bigint: true }): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + + export interface StatSyncFn extends Function { + (path: TDescriptor, options?: undefined): Stats; + (path: TDescriptor, options?: StatOptions & { bigint?: false; throwIfNoEntry: false }): Stats | undefined; + (path: TDescriptor, options: StatOptions & { bigint: true; throwIfNoEntry: false }): BigIntStats | undefined; + (path: TDescriptor, options?: StatOptions & { bigint?: false }): Stats; + (path: TDescriptor, options: StatOptions & { bigint: true }): BigIntStats; + (path: TDescriptor, options: StatOptions & { bigint: boolean; throwIfNoEntry?: false }): Stats | BigIntStats; + (path: TDescriptor, options?: StatOptions): Stats | BigIntStats | undefined; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat(fd: number, options: StatOptions & { bigint?: false } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat(fd: number, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, options?: StatOptions & { bigint?: false }): Promise; + function __promisify__(fd: number, options: StatOptions & { bigint: true }): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export const fstatSync: StatSyncFn; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat(path: PathLike, options: StatOptions & { bigint?: false } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat(path: PathLike, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: StatOptions & { bigint?: false }): Promise; + function __promisify__(path: PathLike, options: StatOptions & { bigint: true }): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void + ): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + + function native( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + + export namespace realpathSync { + function native(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlinkSync(path: PathLike): void; + + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number; + /** + * @deprecated since v14.14.0 In future versions of Node.js, + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, errors are not reported if `path` does not exist, and + * operations are retried on failure. + * @default false + */ + recursive?: boolean; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number; + } + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, errors are not reported if `path` does not exist, and + * operations are retried on failure. + * @default false + */ + recursive?: boolean; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number; + } + + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string | undefined; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): void; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: BaseEncodingOptions | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: BaseEncodingOptions | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): string[] | Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function close(fd: number, callback?: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + + export type ReadPosition = number | bigint; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number; + /** + * @default `length of buffer` + */ + length?: number; + /** + * @default null + */ + position?: ReadPosition | null; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathLike | number, + options: { encoding?: null; flag?: string; } & Abortable | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathLike | number, + options: { encoding: BufferEncoding; flag?: string; } & Abortable | string, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathLike | number, + // TODO: unify the options across all readfile functions + options: BaseEncodingOptions & { flag?: string; } & Abortable | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | BufferEncoding): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | BufferEncoding | null): string | Buffer; + + export type WriteFileOptions = (BaseEncodingOptions & Abortable & { mode?: Mode; flag?: string; }) | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFileSync(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFile(file: PathLike | number, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathLike | number, data: string | Uint8Array, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer"; + persistent?: boolean; + recursive?: boolean; + } + + export type WatchListener = (event: "rename" | "change", filename: T) => void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions & { encoding: "buffer" } | "buffer", listener?: WatchListener): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated since v1.0.0 Use `fs.stat()` or `fs.access()` instead + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function existsSync(path: PathLike): boolean; + + export namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function accessSync(path: PathLike, mode?: number): void; + + interface StreamOptions { + flags?: string; + encoding?: BufferEncoding; + fd?: number | promises.FileHandle; + mode?: number; + autoClose?: boolean; + /** + * @default false + */ + emitClose?: boolean; + start?: number; + highWaterMark?: number; + } + + interface ReadStreamOptions extends StreamOptions { + end?: number; + } + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function createReadStream(path: PathLike, options?: string | ReadStreamOptions): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function createWriteStream(path: PathLike, options?: string | StreamOptions): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + /** + * Write an array of ArrayBufferViews to the file specified by fd using writev(). + * position is the offset from the beginning of the file where this data should be written. + * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to the end of the file. + */ + export function writev( + fd: number, + buffers: ReadonlyArray, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + + /** + * See `writev`. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + + export function readv( + fd: number, + buffers: ReadonlyArray, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + + /** + * See `readv`. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + + export interface OpenDirOptions { + encoding?: BufferEncoding; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number; + } + + export function opendirSync(path: string, options?: OpenDirOptions): Dir; + + export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + + export namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + + export interface BigIntStats extends StatsBase { + } + + export class BigIntStats { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + + export interface BigIntOptions { + bigint: true; + } + + export interface StatOptions { + bigint?: boolean; + throwIfNoEntry?: boolean; + } +} diff --git a/tests/node_modules/@types/node/fs/promises.d.ts b/tests/node_modules/@types/node/fs/promises.d.ts new file mode 100755 index 0000000..465e8e6 --- /dev/null +++ b/tests/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,592 @@ +declare module 'fs/promises' { + import { Abortable } from 'events'; + import { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + BaseEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + } from 'fs'; + + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: Mode): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: OpenMode } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: BaseEncodingOptions & { flag?: OpenMode } | BufferEncoding | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(opts?: StatOptions & { bigint?: false }): Promise; + stat(opts: StatOptions & { bigint: true }): Promise; + stat(opts?: StatOptions): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: string | Uint8Array, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } & Abortable | BufferEncoding | null): Promise; + + /** + * See `fs.writev` promisified version. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + + /** + * See `fs.readv` promisified version. + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: Mode): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function rm(path: PathLike, options?: RmOptions): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, opts?: StatOptions & { bigint?: false }): Promise; + function lstat(path: PathLike, opts: StatOptions & { bigint: true }): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, opts?: StatOptions & { bigint?: false }): Promise; + function stat(path: PathLike, opts: StatOptions & { bigint: true }): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: Mode): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: Mode): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } & Abortable | BufferEncoding | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: OpenMode } & Abortable | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode } & Abortable | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: BaseEncodingOptions & Abortable & { flag?: OpenMode } | BufferEncoding | null): Promise; + + function opendir(path: string, options?: OpenDirOptions): Promise; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions & { encoding: "buffer" } | "buffer"): AsyncIterable; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding + ): AsyncIterable; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable | AsyncIterable; +} diff --git a/tests/node_modules/@types/node/globals.d.ts b/tests/node_modules/@types/node/globals.d.ts new file mode 100755 index 0000000..fd6836c --- /dev/null +++ b/tests/node_modules/@types/node/globals.d.ts @@ -0,0 +1,655 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +interface ImportMeta { + url: string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +declare function queueMicrotask(callback: () => void): void; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"; + +type WithImplicitCoercion = T | { valueOf(): T }; + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare class Buffer extends Uint8Array { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + constructor(str: string, encoding?: BufferEncoding); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: ReadonlyArray); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + constructor(buffer: Buffer); + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + static from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + static from(data: Uint8Array | ReadonlyArray): Buffer; + static from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + static from(str: WithImplicitCoercion | { [Symbol.toPrimitive](hint: 'string'): string }, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + static of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding + ): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + static poolSize: number; + + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + toJSON(): { type: 'Buffer'; data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare( + otherBuffer: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number + ): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + slice(begin?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is compatible with `Uint8Array#subarray()`. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + subarray(begin?: number, end?: number): Buffer; + writeBigInt64BE(value: bigint, offset?: number): number; + writeBigInt64LE(value: bigint, offset?: number): number; + writeBigUInt64BE(value: bigint, offset?: number): number; + writeBigUInt64LE(value: bigint, offset?: number): number; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readBigUInt64BE(offset?: number): bigint; + readBigUInt64LE(offset?: number): bigint; + readBigInt64BE(offset?: number): bigint; + readBigInt64LE(offset?: number): bigint; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset?: number): number; + readUInt16LE(offset?: number): number; + readUInt16BE(offset?: number): number; + readUInt32LE(offset?: number): number; + readUInt32BE(offset?: number): number; + readInt8(offset?: number): number; + readInt16LE(offset?: number): number; + readInt16BE(offset?: number): number; + readInt32LE(offset?: number): number; + readInt32BE(offset?: number): number; + readFloatLE(offset?: number): number; + readFloatBE(offset?: number): number; + readDoubleLE(offset?: number): number; + readDoubleBE(offset?: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset?: number): number; + writeUInt16LE(value: number, offset?: number): number; + writeUInt16BE(value: number, offset?: number): number; + writeUInt32LE(value: number, offset?: number): number; + writeUInt32BE(value: number, offset?: number): number; + writeInt8(value: number, offset?: number): number; + writeInt16LE(value: number, offset?: number): number; + writeInt16BE(value: number, offset?: number): number; + writeInt32LE(value: number, offset?: number): number; + writeInt32BE(value: number, offset?: number): number; + writeFloatLE(value: number, offset?: number): number; + writeFloatBE(value: number, offset?: number): number; + writeDoubleLE(value: number, offset?: number): number; + writeDoubleBE(value: number, offset?: number): number; + + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Global { + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: typeof Promise; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: typeof Uint8ClampedArray; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms?: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms?: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface RefCounted { + ref(): this; + unref(): this; + } + + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + + interface Immediate extends RefCounted { + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + interface Timeout extends Timer { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/tests/node_modules/@types/node/globals.global.d.ts b/tests/node_modules/@types/node/globals.global.d.ts new file mode 100755 index 0000000..d66acba --- /dev/null +++ b/tests/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: NodeJS.Global & typeof globalThis; diff --git a/tests/node_modules/@types/node/http.d.ts b/tests/node_modules/@types/node/http.d.ts new file mode 100755 index 0000000..8c138c2 --- /dev/null +++ b/tests/node_modules/@types/node/http.d.ts @@ -0,0 +1,434 @@ +declare module 'http' { + import * as stream from 'stream'; + import { URL } from 'url'; + import { Socket, Server as NetServer } from 'net'; + + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + 'accept'?: string; + 'accept-language'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-request-headers'?: string; + 'access-control-request-method'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'etag'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'origin'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'sec-websocket-accept'?: string; + 'sec-websocket-extensions'?: string; + 'sec-websocket-key'?: string; + 'sec-websocket-protocol'?: string; + 'sec-websocket-version'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'tk'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + + interface OutgoingHttpHeaders extends NodeJS.Dict { + } + + interface ClientRequestArgs { + abort?: AbortSignal; + protocol?: string | null; + host?: string | null; + hostname?: string | null; + family?: number; + port?: number | string | null; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + /** + * @default 8192 + */ + maxHeaderSize?: number; + method?: string; + path?: string | null; + headers?: OutgoingHttpHeaders; + auth?: string | null; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket; + } + + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage; + ServerResponse?: typeof ServerResponse; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean; + } + + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + + interface HttpBase { + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @default 2000 + * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount} + */ + maxHeadersCount: number | null; + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP headers. + * @default 60000 + * {@link https://nodejs.org/api/http.html#http_server_headerstimeout} + */ + headersTimeout: number; + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @default 0 + * {@link https://nodejs.org/api/http.html#http_server_requesttimeout} + */ + requestTimeout: number; + } + + interface Server extends HttpBase {} + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + readonly headersSent: boolean; + /** + * @deprecated Use `socket` instead. + */ + readonly connection: Socket | null; + readonly socket: Socket | null; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | ReadonlyArray): this; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeProcessing(): void; + } + + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + aborted: boolean; + host: string; + protocol: string; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + method: string; + path: string; + /** @deprecated since v14.1.0 Use `request.destroy()` instead. */ + abort(): void; + onSocket(socket: Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + + aborted: boolean; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + complete: boolean; + /** + * @deprecated since v13.0.0 - Use `socket` instead. + */ + connection: Socket; + socket: Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: NodeJS.Dict; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo'; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + maxTotalSockets: number; + readonly freeSockets: NodeJS.ReadOnlyDict; + readonly sockets: NodeJS.ReadOnlyDict; + readonly requests: NodeJS.ReadOnlyDict; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + + /** + * + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; +} diff --git a/tests/node_modules/@types/node/http2.d.ts b/tests/node_modules/@types/node/http2.d.ts new file mode 100755 index 0000000..d26344e --- /dev/null +++ b/tests/node_modules/@types/node/http2.d.ts @@ -0,0 +1,976 @@ +declare module 'http2' { + import EventEmitter = require('events'); + import * as fs from 'fs'; + import * as net from 'net'; + import * as stream from 'stream'; + import * as tls from 'tls'; + import * as url from 'url'; + + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + OutgoingHttpHeaders, + IncomingMessage, + ServerResponse, + } from 'http'; + export { OutgoingHttpHeaders } from 'http'; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + localClose?: number; + remoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + readonly bufferSize: number; + readonly closed: boolean; + readonly destroyed: boolean; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + readonly id?: number; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + sendTrailers(headers: OutgoingHttpHeaders): void; + + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "continue", listener: () => {}): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "continue", listener: () => {}): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "continue", listener: () => {}): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + readonly headersSent: boolean; + readonly pushAllowed: boolean; + additionalHeaders(headers: OutgoingHttpHeaders): void; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + enableConnectProtocol?: boolean; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + waitForTrailers?: boolean; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends EventEmitter { + readonly alpnProtocol?: string; + readonly closed: boolean; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly encrypted?: boolean; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + readonly remoteSettings: Settings; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + readonly type: number; + + close(callback?: () => void): void; + destroy(error?: Error, code?: number): void; + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + setLocalWindowSize(windowSize: number): void; + setTimeout(msecs: number, callback?: () => void): void; + settings(settings: Settings): void; + unref(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: ReadonlyArray): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + origin(...args: Array): void; + + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxSessionMemory?: number; + maxHeaderListPairs?: number; + maxOutstandingPings?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + settings?: Settings; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number; + + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number; + createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; + protocol?: 'http:' | 'https:'; + } + + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage; + Http1ServerResponse?: typeof ServerResponse; + Http2ServerRequest?: typeof Http2ServerRequest; + Http2ServerResponse?: typeof Http2ServerResponse; + } + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + origins?: string[]; + } + + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + + readonly aborted: boolean; + readonly authority: string; + readonly connection: net.Socket | tls.TLSSocket; + readonly complete: boolean; + readonly headers: IncomingHttpHeaders; + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + readonly method: string; + readonly rawHeaders: string[]; + readonly rawTrailers: string[]; + readonly scheme: string; + readonly socket: net.Socket | tls.TLSSocket; + readonly stream: ServerHttp2Stream; + readonly trailers: IncomingHttpHeaders; + readonly url: string; + + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + + readonly connection: net.Socket | tls.TLSSocket; + readonly finished: boolean; + readonly headersSent: boolean; + readonly socket: net.Socket | tls.TLSSocket; + readonly stream: ServerHttp2Stream; + sendDate: boolean; + statusCode: number; + statusMessage: ''; + addTrailers(trailers: OutgoingHttpHeaders): void; + end(callback?: () => void): void; + end(data: string | Uint8Array, callback?: () => void): void; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): void; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + setHeader(name: string, value: number | string | ReadonlyArray): void; + setTimeout(msecs: number, callback?: () => void): void; + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Buffer; + export function getUnpackedSettings(buf: Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} diff --git a/tests/node_modules/@types/node/https.d.ts b/tests/node_modules/@types/node/https.d.ts new file mode 100755 index 0000000..23f9568 --- /dev/null +++ b/tests/node_modules/@types/node/https.d.ts @@ -0,0 +1,36 @@ +declare module 'https' { + import * as tls from 'tls'; + import * as http from 'http'; + import { URL } from 'url'; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + interface Server extends http.HttpBase {} + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + } + + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} diff --git a/tests/node_modules/@types/node/index.d.ts b/tests/node_modules/@types/node/index.d.ts new file mode 100755 index 0000000..aa5aaea --- /dev/null +++ b/tests/node_modules/@types/node/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for non-npm package Node.js 15.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Anna Henningsen +// Jason Kwok +// Victor Perin +// Yongsheng Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// Typically type modifications should be made in base.d.ts instead of here + +/// + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.6/index.d.ts - Definitions specific to TypeScript 3.6 + +// NOTE: Augmentations for TypeScript 3.6 and later should use individual files for overrides +// within the respective ~/ts3.6 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.6, so the older definitions will be found here. diff --git a/tests/node_modules/@types/node/inspector.d.ts b/tests/node_modules/@types/node/inspector.d.ts new file mode 100755 index 0000000..7403c52 --- /dev/null +++ b/tests/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3041 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'inspector' { + import EventEmitter = require('events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview; + /** + * @experimental + */ + customPreview?: CustomPreview; + } + + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[]; + } + + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + } + + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId; + } + + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace; + /** + * Exception object if available. + */ + exception?: RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId; + } + + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean; + } + + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + } + + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean; + } + + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId; + } + + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string; + } + + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + + /** + * Call frame identifier. + */ + type CallFrameId = string; + + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Location; + } + + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string; + } + + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean; + } + + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + } + + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + } + + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[]; + } + + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean; + } + + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number; + } + + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface DetachParameterType { + sessionId: SessionID; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if there is already a connected session established either + * through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * session.connect() will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. + * callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent + * `Runtime.runIfWaitingForDebugger` command. + * An exception will be thrown if there is no active inspector. + */ + function waitForDebugger(): void; +} diff --git a/tests/node_modules/@types/node/module.d.ts b/tests/node_modules/@types/node/module.d.ts new file mode 100755 index 0000000..787955a --- /dev/null +++ b/tests/node_modules/@types/node/module.d.ts @@ -0,0 +1,52 @@ +declare module 'module' { + import { URL } from 'url'; + namespace Module { + /** + * Updates all the live bindings for builtin ES Modules to match the properties of the CommonJS exports. + * It does not add or remove exported names from the ES Modules. + */ + function syncBuiltinESMExports(): void; + + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + + class SourceMap { + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + + /** + * @deprecated Deprecated since: v12.2.0. Please use createRequire() instead. + */ + static createRequireFromPath(path: string): NodeRequire; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + + static Module: typeof Module; + + constructor(id: string, parent?: Module); + } + export = Module; +} diff --git a/tests/node_modules/@types/node/net.d.ts b/tests/node_modules/@types/node/net.d.ts new file mode 100755 index 0000000..81be6ba --- /dev/null +++ b/tests/node_modules/@types/node/net.d.ts @@ -0,0 +1,326 @@ +declare module 'net' { + import * as stream from 'stream'; + import { Abortable, EventEmitter } from 'events'; + import * as dns from 'dns'; + + type LookupFunction = ( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts; + } + + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + + setEncoding(encoding?: BufferEncoding): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | {}; + unref(): this; + ref(): this; + + /** @deprecated since v14.6.0 - Use `writableLength` instead. */ + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(cb?: () => void): void; + end(buffer: Uint8Array | string, cb?: () => void): void; + end(str: Uint8Array | string, encoding?: BufferEncoding, cb?: () => void): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions extends Abortable { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + } + + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean; + + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + close(callback?: (err?: Error) => void): this; + address(): AddressInfo | string | null; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + type IPVersion = 'ipv4' | 'ipv6'; + + class BlockList { + /** + * Adds a rule to block the given IP address. + * + * @param address An IPv4 or IPv6 address. + * @param type Either 'ipv4' or 'ipv6'. Default: 'ipv4'. + */ + addAddress(address: string, type?: IPVersion): void; + + /** + * Adds a rule to block a range of IP addresses from start (inclusive) to end (inclusive). + * + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param type Either 'ipv4' or 'ipv6'. Default: 'ipv4'. + */ + addRange(start: string, end: string, type?: IPVersion): void; + + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. + * For IPv4, this must be a value between 0 and 32. For IPv6, this must be between 0 and 128. + * @param type Either 'ipv4' or 'ipv6'. Default: 'ipv4'. + */ + addSubnet(net: string, prefix: number, type?: IPVersion): void; + + /** + * Returns `true` if the given IP address matches any of the rules added to the `BlockList`. + * + * @param address The IP address to check + * @param type Either 'ipv4' or 'ipv6'. Default: 'ipv4'. + */ + check(address: string, type?: IPVersion): boolean; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} diff --git a/tests/node_modules/@types/node/os.d.ts b/tests/node_modules/@types/node/os.d.ts new file mode 100755 index 0000000..b49949a --- /dev/null +++ b/tests/node_modules/@types/node/os.d.ts @@ -0,0 +1,239 @@ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): NodeJS.Dict; + function homedir(): string; + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + + function arch(): string; + /** + * Returns a string identifying the kernel version. + * On POSIX systems, the operating system release is determined by calling + * uname(3). On Windows, `pRtlGetVersion` is used, and if it is not available, + * `GetVersionExW()` will be used. See + * https://en.wikipedia.org/wiki/Uname#Examples for more information. + */ + function version(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} diff --git a/tests/node_modules/@types/node/package.json b/tests/node_modules/@types/node/package.json new file mode 100755 index 0000000..3dff091 --- /dev/null +++ b/tests/node_modules/@types/node/package.json @@ -0,0 +1,222 @@ +{ + "_from": "@types/node@*", + "_id": "@types/node@15.12.4", + "_inBundle": false, + "_integrity": "sha512-zrNj1+yqYF4WskCMOHwN+w9iuD12+dGm0rQ35HLl9/Ouuq52cEtd0CH9qMgrdNmi5ejC1/V7vKEXYubB+65DkA==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/node@*", + "name": "@types/node", + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "/@types/cacheable-request", + "/@types/keyv", + "/@types/responselike" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-15.12.4.tgz", + "_shasum": "e1cf817d70a1e118e81922c4ff6683ce9d422e26", + "_spec": "@types/node@*", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/@types/cacheable-request", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Hoàng Văn Khải", + "url": "https://github.com/KSXGitHub" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr" + }, + { + "name": "Minh Son Nguyen", + "url": "https://github.com/nguymin4" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Surasak Chaisurin", + "url": "https://github.com/Ryan-Willpower" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax" + }, + { + "name": "Jason Kwok", + "url": "https://github.com/JasonHK" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "typeScriptVersion": "3.6", + "types": "index.d.ts", + "typesPublisherContentHash": "4015e73b317c1729ff4d886338909c254c7ee7b4dd58073d03ac030b42a807cf", + "typesVersions": { + "<=3.6": { + "*": [ + "ts3.6/*" + ] + } + }, + "version": "15.12.4" +} diff --git a/tests/node_modules/@types/node/path.d.ts b/tests/node_modules/@types/node/path.d.ts new file mode 100755 index 0000000..4ca1c50 --- /dev/null +++ b/tests/node_modules/@types/node/path.d.ts @@ -0,0 +1,163 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} + +declare module 'path/win32' { + import path = require('path'); + export = path; +} + +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} diff --git a/tests/node_modules/@types/node/perf_hooks.d.ts b/tests/node_modules/@types/node/perf_hooks.d.ts new file mode 100755 index 0000000..4545f91 --- /dev/null +++ b/tests/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,310 @@ +declare module 'perf_hooks' { + import { AsyncResource } from 'async_hooks'; + + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: EntryType; + + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number; + + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number; + } + + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. + * If bootstrapping has not yet finished, the property has the value of -1. + */ + readonly environment: number; + + /** + * The high resolution millisecond timestamp at which the Node.js environment was initialized. + */ + readonly idleTime: number; + + /** + * The high resolution millisecond timestamp of the amount of time the event loop has been idle + * within the event loop's event provider (e.g. `epoll_wait`). This does not take CPU usage + * into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), + * the property has the value of 0. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + * If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: EventLoopUtilization, + ) => EventLoopUtilization; + + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark?: string, endMark?: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: ReadonlyArray; buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + + const performance: Performance; + + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number; + } + + interface Histogram { + /** + * A `Map` object detailing the accumulated percentile distribution. + */ + readonly percentiles: Map; + + /** + * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. + */ + readonly exceeds: number; + + /** + * The minimum recorded event loop delay. + */ + readonly min: number; + + /** + * The maximum recorded event loop delay. + */ + readonly max: number; + + /** + * The mean of the recorded event loop delays. + */ + readonly mean: number; + + /** + * The standard deviation of the recorded event loop delays. + */ + readonly stddev: number; + + /** + * Resets the collected histogram data. + */ + reset(): void; + + /** + * Returns the value at the given percentile. + * @param percentile A percentile value between 1 and 100. + */ + percentile(percentile: number): number; + } + + interface IntervalHistogram extends Histogram { + /** + * Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. + */ + enable(): boolean; + /** + * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. + */ + disable(): boolean; + } + + interface RecordableHistogram extends Histogram { + record(val: number | bigint): void; + + /** + * Calculates the amount of time (in nanoseconds) that has passed since the previous call to recordDelta() and records that amount in the histogram. + */ + recordDelta(): void; + } + + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint; + + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number; + } + + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} diff --git a/tests/node_modules/@types/node/process.d.ts b/tests/node_modules/@types/node/process.d.ts new file mode 100755 index 0000000..02778bb --- /dev/null +++ b/tests/node_modules/@types/node/process.d.ts @@ -0,0 +1,461 @@ +declare module 'process' { + import * as tty from 'tty'; + + global { + var process: NodeJS.Process; + + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin' + | 'netbsd'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + // Alias for compatibility + interface ProcessEnv extends Dict {} + + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string; + + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string; + + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function; + + /** + * Additional text to include with the error. + */ + detail?: string; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitations. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * Can also be a tty.WriteStream, not typed due to limitations. + */ + stderr: WriteStream & { + fd: 2; + }; + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): never; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + + /** + * The `process.emitWarning()` method can be used to emit custom or application specific process warnings. + * + * These can be listened for by adding a handler to the `'warning'` event. + * + * @param warning The warning to emit. + * @param type When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. Default: `'Warning'`. + * @param code A unique identifier for the warning instance being emitted. + * @param ctor When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. Default: `process.emitWarning`. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: ReadonlyArray): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): true; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + /** @deprecated since v14.0.0 - use `require.main` instead. */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * @deprecated since v14.0.0 - Calling process.umask() with no argument causes + * the process-wide umask to be written twice. This introduces a race condition between threads, + * and is a potential security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + resourceUsage(): ResourceUsage; + + traceDeprecation: boolean; + + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + process: Process; + } + } + } + + export = process; +} diff --git a/tests/node_modules/@types/node/punycode.d.ts b/tests/node_modules/@types/node/punycode.d.ts new file mode 100755 index 0000000..b21ee8e --- /dev/null +++ b/tests/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,75 @@ +/** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ +declare module 'punycode' { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function decode(string: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function encode(string: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function toUnicode(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} diff --git a/tests/node_modules/@types/node/querystring.d.ts b/tests/node_modules/@types/node/querystring.d.ts new file mode 100755 index 0000000..1065118 --- /dev/null +++ b/tests/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,28 @@ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: (str: string) => string; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: (str: string) => string; + } + + interface ParsedUrlQuery extends NodeJS.Dict { } + + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> { + } + + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + function escape(str: string): string; + function unescape(str: string): string; +} diff --git a/tests/node_modules/@types/node/readline.d.ts b/tests/node_modules/@types/node/readline.d.ts new file mode 100755 index 0000000..988d216 --- /dev/null +++ b/tests/node_modules/@types/node/readline.d.ts @@ -0,0 +1,192 @@ +declare module 'readline' { + import { Abortable, EventEmitter } from 'events'; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends EventEmitter { + readonly terminal: boolean; + + // Need direct access to line/cursor data, for use in external processes + // see: https://github.com/nodejs/node/issues/30347 + /** The current input data */ + readonly line: string; + /** The current cursor position in the input line */ + readonly cursor: number; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + getPrompt(): string; + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + */ + getCursorPos(): CursorPos; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + type ReadLine = Interface; // type forwarded for backwards compatibility + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[]; + historySize?: number; + prompt?: string; + crlfDelay?: number; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean; + escapeCodeTimeout?: number; + tabSize?: number; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + + type Direction = -1 | 0 | 1; + + interface CursorPos { + rows: number; + cols: number; + } + + /** + * Clears the current line of this WriteStream in a direction identified by `dir`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * Clears this `WriteStream` from the current cursor down. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * Moves this WriteStream's cursor to the specified position. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * Moves this WriteStream's cursor relative to its current position. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} diff --git a/tests/node_modules/@types/node/repl.d.ts b/tests/node_modules/@types/node/repl.d.ts new file mode 100755 index 0000000..45901e9 --- /dev/null +++ b/tests/node_modules/@types/node/repl.d.ts @@ -0,0 +1,395 @@ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'readline'; + import { Context } from 'vm'; + import { InspectOptions } from 'util'; + + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @param path The path to the history file + */ + setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} diff --git a/tests/node_modules/@types/node/stream.d.ts b/tests/node_modules/@types/node/stream.d.ts new file mode 100755 index 0000000..e471cba --- /dev/null +++ b/tests/node_modules/@types/node/stream.d.ts @@ -0,0 +1,471 @@ +declare module 'stream' { + import { EventEmitter, Abortable } from 'events'; + import * as streamPromises from "stream/promises"; + + class internal extends EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + + interface StreamOptions extends Abortable { + emitClose?: boolean; + highWaterMark?: number; + objectMode?: boolean; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; + } + + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding; + read?(this: Readable, size: number): void; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + + readable: boolean; + readonly readableEncoding: BufferEncoding | null; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any, encoding?: BufferEncoding): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean; + defaultEncoding?: BufferEncoding; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + class Writable extends Stream implements NodeJS.WritableStream { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + destroyed: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + readableHighWaterMark?: number; + writableHighWaterMark?: number; + writableCorked?: number; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error | null, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed + * `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` + * on the stream. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + + interface FinishedOptions extends Abortable { + error?: boolean; + readable?: boolean; + writable?: boolean; + } + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + NodeJS.ReadWriteStream | + ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? + AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + + type PipelineDestination, P> = + S extends PipelineTransformSource ? + (NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction) : never; + type PipelineCallback> = + S extends PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void : + (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = + S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + + function pipeline, + B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, + T1 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, + B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, + T1 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; + } + + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + + const promises: typeof streamPromises; + } + + export = internal; +} diff --git a/tests/node_modules/@types/node/stream/promises.d.ts b/tests/node_modules/@types/node/stream/promises.d.ts new file mode 100755 index 0000000..7c70423 --- /dev/null +++ b/tests/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,67 @@ +declare module "stream/promises" { + import { FinishedOptions, PipelineSource, PipelineTransform, + PipelineDestination, PipelinePromise, PipelineOptions } from "stream"; + + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + + function pipeline, + B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, + T1 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; +} diff --git a/tests/node_modules/@types/node/string_decoder.d.ts b/tests/node_modules/@types/node/string_decoder.d.ts new file mode 100755 index 0000000..c7ace1c --- /dev/null +++ b/tests/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,7 @@ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } +} diff --git a/tests/node_modules/@types/node/timers.d.ts b/tests/node_modules/@types/node/timers.d.ts new file mode 100755 index 0000000..d0a933b --- /dev/null +++ b/tests/node_modules/@types/node/timers.d.ts @@ -0,0 +1,27 @@ +declare module 'timers' { + import { Abortable } from 'events'; + + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean; + } + + function setTimeout(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T, options?: TimerOptions): Promise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T, options?: TimerOptions): Promise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} diff --git a/tests/node_modules/@types/node/timers/promises.d.ts b/tests/node_modules/@types/node/timers/promises.d.ts new file mode 100755 index 0000000..dbd4c99 --- /dev/null +++ b/tests/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,21 @@ +declare module 'timers/promises' { + import { TimerOptions } from 'timers'; + + /** + * Returns a promise that resolves after the specified delay in milliseconds. + * @param delay defaults to 1 + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + + /** + * Returns a promise that resolves in the next tick. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + + /** + * + * Returns an async iterator that generates values in an interval of delay ms. + * @param delay defaults to 1 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} diff --git a/tests/node_modules/@types/node/tls.d.ts b/tests/node_modules/@types/node/tls.d.ts new file mode 100755 index 0000000..7a0647c --- /dev/null +++ b/tests/node_modules/@types/node/tls.d.ts @@ -0,0 +1,793 @@ +declare module 'tls' { + import { X509Certificate } from 'crypto'; + import * as net from 'net'; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string; + } + + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string; + } + + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean; + /** + * An optional net.Server instance. + */ + server?: net.Server; + + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the local certificate. The returned + * object has some properties corresponding to the fields of the + * certificate. + * + * See tls.TLSSocket.getPeerCertificate() for an example of the + * certificate structure. + * + * If there is no local certificate, an empty object will be returned. + * If the socket has been destroyed, null will be returned. + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter + * of an ephemeral key exchange in Perfect Forward Secrecy on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; null is + * returned if called on a server socket. The supported types are 'DH' + * and 'ECDH'. The name property is available only when type is 'ECDH'. + * + * For example: { type: 'ECDH', name: 'prime256v1', size: 256 }. + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * Returns the latest Finished message that has + * been sent to the socket as part of a SSL/TLS handshake, or undefined + * if no Finished message has been sent yet. + * + * As the Finished messages are message digests of the complete + * handshake (with a total of 192 bits for TLS 1.0 and more for SSL + * 3.0), they can be used for external authentication procedures when + * the authentication provided by SSL/TLS is not desired or is not + * enough. + * + * Corresponds to the SSL_get_finished routine in OpenSSL and may be + * used to implement the tls-unique channel binding from RFC 5929. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns the latest Finished message that is expected or has actually + * been received from the socket as part of a SSL/TLS handshake, or + * undefined if there is no Finished message so far. + * + * As the Finished messages are message digests of the complete + * handshake (with a total of 192 bits for TLS 1.0 and more for SSL + * 3.0), they can be used for external authentication procedures when + * the authentication provided by SSL/TLS is not desired or is not + * enough. + * + * Corresponds to the SSL_get_peer_finished routine in OpenSSL and may + * be used to implement the tls-unique channel binding from RFC 5929. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): Buffer | undefined; + /** + * Returns a list of signature algorithms shared between the server and + * the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): Buffer | undefined; + /** + * Returns true if the session was reused, false otherwise. + */ + isSessionReused(): boolean; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + * @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): undefined | boolean; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * Disables TLS renegotiation for this TLSSocket instance. Once called, + * attempts to renegotiate will trigger an 'error' event on the + * TLSSocket. + */ + disableRenegotiation(): void; + + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * Note: The format of the output is identical to the output of `openssl s_client + * -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's + * `SSL_trace()` function, the format is undocumented, can change without notice, + * and should not be relied on. + */ + enableTrace(): void; + + /** + * If there is no peer certificate, or the socket has been destroyed, `undefined` will be returned. + */ + getPeerX509Certificate(): X509Certificate | undefined; + + /** + * If there is no local certificate, or the socket has been destroyed, `undefined` will be returned. + */ + getX509Certificate(): X509Certificate | undefined; + + /** + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the + * [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context optionally provide a context. + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext; + + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean; + } + + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer; + + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string; + } + + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + lookup?: net.LookupFunction; + timeout?: number; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + + /** + * The server.addContext() method adds a secure context that will be + * used if the client request's SNI name matches the supplied hostname + * (or wildcard). + */ + addContext(hostName: string, credentials: SecureContextOptions): void; + /** + * Returns the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * + * The server.setSecureContext() method replaces the + * secure context of an existing server. Existing connections to the + * server are not interrupted. + */ + setSecureContext(details: SecureContextOptions): void; + /** + * The server.setSecureContext() method replaces the secure context of + * an existing server. Existing connections to the server are not + * interrupted. + */ + setTicketKeys(keys: Buffer): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(options?: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} diff --git a/tests/node_modules/@types/node/trace_events.d.ts b/tests/node_modules/@types/node/trace_events.d.ts new file mode 100755 index 0000000..1bf6534 --- /dev/null +++ b/tests/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,61 @@ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + function getEnabledCategories(): string | undefined; +} diff --git a/tests/node_modules/@types/node/ts3.6/assert.d.ts b/tests/node_modules/@types/node/ts3.6/assert.d.ts new file mode 100755 index 0000000..37e24f5 --- /dev/null +++ b/tests/node_modules/@types/node/ts3.6/assert.d.ts @@ -0,0 +1,98 @@ +declare module 'assert' { + /** An alias of `assert.ok()`. */ + function assert(value: any, message?: string | Error): void; + namespace assert { + class AssertionError extends Error { + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string; + /** The `actual` property on the error instance. */ + actual?: any; + /** The `expected` property on the error instance. */ + expected?: any; + /** The `operator` property on the error instance. */ + operator?: string; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function; + }); + } + + class CallTracker { + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + report(): CallTrackerReportInformation[]; + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + + type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error; + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: any, + expected: any, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function, + ): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: () => any, message?: string | Error): void; + function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; + function doesNotThrow(block: () => any, message?: string | Error): void; + function doesNotThrow(block: () => any, error: AssertPredicate, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + + function match(value: string, regExp: RegExp, message?: string | Error): void; + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + + const strict: typeof assert; + } + + export = assert; +} diff --git a/tests/node_modules/@types/node/ts3.6/base.d.ts b/tests/node_modules/@types/node/ts3.6/base.d.ts new file mode 100755 index 0000000..0c67093 --- /dev/null +++ b/tests/node_modules/@types/node/ts3.6/base.d.ts @@ -0,0 +1,68 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.6 and earlier. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 3.7 and above +// - ~/ts3.6/base.d.ts - Definitions specific to TypeScript 3.6 and earlier +// - ~/ts3.6/index.d.ts - Definitions specific to TypeScript 3.6 and earlier with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +// TypeScript 3.6-specific augmentations: +/// + +// TypeScript 3.6-specific augmentations: +/// diff --git a/tests/node_modules/@types/node/ts3.6/index.d.ts b/tests/node_modules/@types/node/ts3.6/index.d.ts new file mode 100755 index 0000000..1a7d360 --- /dev/null +++ b/tests/node_modules/@types/node/ts3.6/index.d.ts @@ -0,0 +1,7 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.6. +// This is required to enable typing assert in ts3.7 without causing errors +// Typically type modifications should be made in base.d.ts instead of here + +/// + +/// diff --git a/tests/node_modules/@types/node/tty.d.ts b/tests/node_modules/@types/node/tty.d.ts new file mode 100755 index 0000000..0935524 --- /dev/null +++ b/tests/node_modules/@types/node/tty.d.ts @@ -0,0 +1,66 @@ +declare module 'tty' { + import * as net from 'net'; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + isRaw: boolean; + setRawMode(mode: boolean): this; + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + + /** + * Clears the current line of this WriteStream in a direction identified by `dir`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * Clears this `WriteStream` from the current cursor down. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * Moves this WriteStream's cursor to the specified position. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * Moves this WriteStream's cursor relative to its current position. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * @default `process.env` + */ + getColorDepth(env?: {}): number; + hasColors(depth?: number): boolean; + hasColors(env?: {}): boolean; + hasColors(depth: number, env?: {}): boolean; + getWindowSize(): [number, number]; + columns: number; + rows: number; + isTTY: boolean; + } +} diff --git a/tests/node_modules/@types/node/url.d.ts b/tests/node_modules/@types/node/url.d.ts new file mode 100755 index 0000000..f8da6e5 --- /dev/null +++ b/tests/node_modules/@types/node/url.d.ts @@ -0,0 +1,116 @@ +declare module 'url' { + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring'; + + // Input to `url.format` + interface UrlObject { + auth?: string | null; + hash?: string | null; + host?: string | null; + hostname?: string | null; + href?: string | null; + pathname?: string | null; + protocol?: string | null; + search?: string | null; + slashes?: boolean | null; + port?: string | number | null; + query?: string | null | ParsedUrlQueryInput; + } + + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function parse(urlStr: string): UrlWithStringQuery; + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function format(urlObject: UrlObject | string): string; + /** @deprecated since v11.0.0 - Use the WHATWG URL API. */ + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | NodeJS.Dict> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} diff --git a/tests/node_modules/@types/node/util.d.ts b/tests/node_modules/@types/node/util.d.ts new file mode 100755 index 0000000..f1c0794 --- /dev/null +++ b/tests/node_modules/@types/node/util.d.ts @@ -0,0 +1,156 @@ +declare module 'util' { + import * as types from 'util/types'; + + export interface InspectOptions extends NodeJS.InspectOptions { } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export function format(format?: any, ...param: any[]): string; + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** @deprecated since v0.11.3 - use a third party module instead. */ + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + const custom: unique symbol; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + export function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + export function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + export function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + export function isError(object: any): object is Error; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + export function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + export function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + export function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + export function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + export function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + export function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + export function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + export function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + export function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + export function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + export function isUndefined(object: any): object is undefined; + export function deprecate(fn: T, message: string, code?: string): T; + export function isDeepStrictEqual(val1: any, val2: any): boolean; + + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): + (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): + (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + const custom: unique symbol; + } + export class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + + export { types }; + + export class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + encodeInto(input: string, output: Uint8Array): EncodeIntoResult; + } +} diff --git a/tests/node_modules/@types/node/util/types.d.ts b/tests/node_modules/@types/node/util/types.d.ts new file mode 100755 index 0000000..ad4c0db --- /dev/null +++ b/tests/node_modules/@types/node/util/types.d.ts @@ -0,0 +1,53 @@ +declare module 'util/types' { + function isAnyArrayBuffer(object: any): object is ArrayBufferLike; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is NodeJS.ArrayBufferView; + function isAsyncFunction(object: any): boolean; + function isBigInt64Array(value: any): value is BigInt64Array; + function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is String | Number | BigInt | Boolean | Symbol; + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): object is GeneratorFunction; + function isGeneratorObject(object: any): object is Generator; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap + ? unknown extends T + ? never + : ReadonlyMap + : Map; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): object is Promise; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet( + object: T | {}, + ): object is T extends ReadonlySet + ? unknown extends T + ? never + : ReadonlySet + : Set; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): object is SharedArrayBuffer; + function isStringObject(object: any): object is String; + function isSymbolObject(object: any): object is Symbol; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): object is WeakMap; + function isWeakSet(object: any): object is WeakSet; +} diff --git a/tests/node_modules/@types/node/v8.d.ts b/tests/node_modules/@types/node/v8.d.ts new file mode 100755 index 0000000..c0f286b --- /dev/null +++ b/tests/node_modules/@types/node/v8.d.ts @@ -0,0 +1,198 @@ +declare module 'v8' { + import { Readable } from 'stream'; + + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + + /** + * Returns an integer representing a "version tag" derived from the V8 version, command line flags and detected CPU features. + * This is useful for determining whether a vm.Script cachedData buffer is compatible with this instance of V8. + */ + function cachedDataVersionTag(): number; + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This conversation was marked as resolved by joyeecheung + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine, and may change from one version of V8 to the next. + */ + function getHeapSnapshot(): Readable; + + /** + * + * @param fileName The file path where the V8 heap snapshot is to be + * saved. If not specified, a file name with the pattern + * `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, + * `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from + * the main Node.js thread or the id of a worker thread. + */ + function writeHeapSnapshot(fileName?: string): string; + + function getHeapCodeStatistics(): HeapCodeStatistics; + + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + + /** + * Serializes a JavaScript value and adds the serialized representation to the internal buffer. + * This throws an error if value cannot be serialized. + */ + writeValue(val: any): boolean; + + /** + * Returns the stored internal buffer. + * This serializer should not be used once the buffer is released. + * Calling this method results in undefined behavior if a previous write has failed. + */ + releaseBuffer(): Buffer; + + /** + * Marks an ArrayBuffer as having its contents transferred out of band.\ + * Pass the corresponding ArrayBuffer in the deserializing context to deserializer.transferArrayBuffer(). + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + + /** + * Write a raw 32-bit unsigned integer. + */ + writeUint32(value: number): void; + + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + */ + writeUint64(hi: number, lo: number): void; + + /** + * Write a JS number value. + */ + writeDouble(value: number): void; + + /** + * Write raw bytes into the serializer’s internal buffer. + * The deserializer will require a way to compute the length of the buffer. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + + /** + * A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, + * and only stores the part of their underlying `ArrayBuffers` that they are referring to. + */ + class DefaultSerializer extends Serializer { + } + + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. + * In that case, an Error is thrown. + */ + readHeader(): boolean; + + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + + /** + * Marks an ArrayBuffer as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to serializer.transferArrayBuffer() + * (or return the id from serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers). + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + + /** + * Reads the underlying wire format version. + * Likely mostly to be useful to legacy code reading old wire format versions. + * May not be called before .readHeader(). + */ + getWireFormatVersion(): number; + + /** + * Read a raw 32-bit unsigned integer and return it. + */ + readUint32(): number; + + /** + * Read a raw 64-bit unsigned integer and return it as an array [hi, lo] with two 32-bit unsigned integer entries. + */ + readUint64(): [number, number]; + + /** + * Read a JS number value. + */ + readDouble(): number; + + /** + * Read raw bytes from the deserializer’s internal buffer. + * The length parameter must correspond to the length of the buffer that was passed to serializer.writeRawBytes(). + */ + readRawBytes(length: number): Buffer; + } + + /** + * A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, + * and only stores the part of their underlying `ArrayBuffers` that they are referring to. + */ + class DefaultDeserializer extends Deserializer { + } + + /** + * Uses a `DefaultSerializer` to serialize value into a buffer. + */ + function serialize(value: any): Buffer; + + /** + * Uses a `DefaultDeserializer` with default options to read a JS value from a buffer. + */ + function deserialize(data: NodeJS.TypedArray): any; + + /** + * Begins writing coverage report based on the `NODE_V8_COVERAGE` env var. + * Noop is the env var is not set. + */ + function takeCoverage(): void; + + /** + * Stops writing coverage report. + */ + function stopCoverage(): void; +} diff --git a/tests/node_modules/@types/node/vm.d.ts b/tests/node_modules/@types/node/vm.d.ts new file mode 100755 index 0000000..0d54323 --- /dev/null +++ b/tests/node_modules/@types/node/vm.d.ts @@ -0,0 +1,152 @@ +declare module 'vm' { + interface Context extends NodeJS.Dict { } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate'; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string; + codeGeneration?: { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean; + }; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate'; + } + + type MeasureMemoryMode = 'summary' | 'detailed'; + + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode; + context?: Context; + } + + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + createCachedData(): Buffer; + cachedDataRejected?: boolean; + } + function createContext(sandbox?: Context, options?: CreateContextOptions): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params?: ReadonlyArray, options?: CompileFunctionOptions): Function; + + /** + * Measure the memory known to V8 and used by the current execution context or a specified context. + * + * The format of the object that the returned Promise may resolve with is + * specific to the V8 engine and may change from one version of V8 to the next. + * + * The returned result is different from the statistics returned by + * `v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measures + * the memory reachable by V8 from a specific context, while + * `v8.getHeapSpaceStatistics()` measures the memory used by an instance + * of V8 engine, which can switch among multiple contexts that reference + * objects in the heap of one engine. + * + * @experimental + */ + function measureMemory(options?: MeasureMemoryOptions): Promise; +} diff --git a/tests/node_modules/@types/node/wasi.d.ts b/tests/node_modules/@types/node/wasi.d.ts new file mode 100755 index 0000000..895572c --- /dev/null +++ b/tests/node_modules/@types/node/wasi.d.ts @@ -0,0 +1,86 @@ +declare module 'wasi' { + interface WASIOptions { + /** + * An array of strings that the WebAssembly application will + * see as command line arguments. The first argument is the virtual path to the + * WASI command itself. + */ + args?: string[]; + + /** + * An object similar to `process.env` that the WebAssembly + * application will see as its environment. + */ + env?: object; + + /** + * This object represents the WebAssembly application's + * sandbox directory structure. The string keys of `preopens` are treated as + * directories within the sandbox. The corresponding values in `preopens` are + * the real paths to those directories on the host machine. + */ + preopens?: NodeJS.Dict; + + /** + * By default, WASI applications terminate the Node.js + * process via the `__wasi_proc_exit()` function. Setting this option to `true` + * causes `wasi.start()` to return the exit code rather than terminate the + * process. + * @default false + */ + returnOnExit?: boolean; + + /** + * The file descriptor used as standard input in the WebAssembly application. + * @default 0 + */ + stdin?: number; + + /** + * The file descriptor used as standard output in the WebAssembly application. + * @default 1 + */ + stdout?: number; + + /** + * The file descriptor used as standard error in the WebAssembly application. + * @default 2 + */ + stderr?: number; + } + + class WASI { + constructor(options?: WASIOptions); + /** + * + * Attempt to begin execution of `instance` by invoking its `_start()` export. + * If `instance` does not contain a `_start()` export, then `start()` attempts to + * invoke the `__wasi_unstable_reactor_start()` export. If neither of those exports + * is present on `instance`, then `start()` does nothing. + * + * `start()` requires that `instance` exports a `WebAssembly.Memory` named + * `memory`. If `instance` does not have a `memory` export an exception is thrown. + * + * If `start()` is called more than once, an exception is thrown. + */ + start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. + + /** + * Attempt to initialize `instance` as a WASI reactor by invoking its `_initialize()` export, if it is present. + * If `instance` contains a `_start()` export, then an exception is thrown. + * + * `start()` requires that `instance` exports a `WebAssembly.Memory` named + * `memory`. If `instance` does not have a `memory` export an exception is thrown. + * + * If `initialize()` is called more than once, an exception is thrown. + */ + initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. + + /** + * Is an object that implements the WASI system call API. This object + * should be passed as the `wasi_snapshot_preview1` import during the instantiation of a + * `WebAssembly.Instance`. + */ + readonly wasiImport: NodeJS.Dict; // TODO: Narrow to DOM types + } +} diff --git a/tests/node_modules/@types/node/worker_threads.d.ts b/tests/node_modules/@types/node/worker_threads.d.ts new file mode 100755 index 0000000..86015d3 --- /dev/null +++ b/tests/node_modules/@types/node/worker_threads.d.ts @@ -0,0 +1,282 @@ +declare module 'worker_threads' { + import { Blob } from 'node:buffer'; + import { Context } from 'vm'; + import { EventEmitter } from 'events'; + import { EventLoopUtilityFunction } from 'perf_hooks'; + import { FileHandle } from 'fs/promises'; + import { Readable, Writable } from 'stream'; + import { URL } from 'url'; + import { X509Certificate } from 'crypto'; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const resourceLimits: ResourceLimits; + const SHARE_ENV: unique symbol; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + interface WorkerPerformance { + eventLoopUtilization: EventLoopUtilityFunction; + } + + type TransferListItem = ArrayBuffer | MessagePort | FileHandle | X509Certificate | Blob; + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: ReadonlyArray): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "messageerror", listener: (error: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: "messageerror", error: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "messageerror", listener: (error: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "messageerror", listener: (error: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "messageerror", listener: (error: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "messageerror", listener: (error: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "messageerror", listener: (error: Error) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + /** + * List of arguments which would be stringified and appended to + * `process.argv` in the worker. This is mostly similar to the `workerData` + * but the values will be available on the global `process.argv` as if they + * were passed as CLI options to the script. + */ + argv?: any[]; + env?: NodeJS.Dict | typeof SHARE_ENV; + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + execArgv?: string[]; + resourceLimits?: ResourceLimits; + /** + * Additional data to send in the first worker message. + */ + transferList?: TransferListItem[]; + /** + * @default true + */ + trackUnmanagedFds?: boolean; + } + + interface ResourceLimits { + /** + * The maximum size of a heap space for recently created objects. + */ + maxYoungGenerationSizeMb?: number; + /** + * The maximum size of the main heap in MB. + */ + maxOldGenerationSizeMb?: number; + /** + * The size of a pre-allocated memory range used for generated code. + */ + codeRangeSizeMb?: number; + /** + * The default maximum stack size for the thread. Small values may lead to unusable Worker instances. + * @default 4 + */ + stackSizeMb?: number; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + readonly resourceLimits?: ResourceLimits; + readonly performance: WorkerPerformance; + + /** + * @param filename The path to the Worker’s main script or module. + * Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../, + * or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path. + */ + constructor(filename: string | URL, options?: WorkerOptions); + + postMessage(value: any, transferList?: ReadonlyArray): void; + ref(): void; + unref(): void; + /** + * Stop all JavaScript execution in the worker thread as soon as possible. + * Returns a Promise for the exit code that is fulfilled when the `exit` event is emitted. + */ + terminate(): Promise; + + /** + * Returns a readable stream for a V8 snapshot of the current state of the Worker. + * See `v8.getHeapSnapshot()` for more details. + * + * If the Worker thread is no longer running, which may occur before the + * `'exit'` event is emitted, the returned `Promise` will be rejected + * immediately with an `ERR_WORKER_NOT_RUNNING` error + */ + getHeapSnapshot(): Promise; + + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "messageerror", listener: (error: Error) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: Error): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "messageerror", error: Error): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "messageerror", listener: (error: Error) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "messageerror", listener: (error: Error) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "messageerror", listener: (error: Error) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "messageerror", listener: (error: Error) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: Error) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "messageerror", listener: (error: Error) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface BroadcastChannel extends NodeJS.RefCounted {} + + /** + * See https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel + */ + class BroadcastChannel { + readonly name: string; + onmessage: (message: unknown) => void; + onmessageerror: (message: unknown) => void; + + constructor(name: string); + + close(): void; + postMessage(message: unknown): void; + } + + /** + * Mark an object as not transferable. + * If `object` occurs in the transfer list of a `port.postMessage()` call, it will be ignored. + * + * In particular, this makes sense for objects that can be cloned, rather than transferred, + * and which are used by other objects on the sending side. For example, Node.js marks + * the `ArrayBuffer`s it uses for its Buffer pool with this. + * + * This operation cannot be undone. + */ + function markAsUntransferable(object: object): void; + + /** + * Transfer a `MessagePort` to a different `vm` Context. The original `port` + * object will be rendered unusable, and the returned `MessagePort` instance will + * take its place. + * + * The returned `MessagePort` will be an object in the target context, and will + * inherit from its global `Object` class. Objects passed to the + * `port.onmessage()` listener will also be created in the target context + * and inherit from its global `Object` class. + * + * However, the created `MessagePort` will no longer inherit from + * `EventEmitter`, and only `port.onmessage()` can be used to receive + * events using it. + */ + function moveMessagePortToContext(port: MessagePort, context: Context): MessagePort; + + /** + * Receive a single message from a given `MessagePort`. If no message is available, + * `undefined` is returned, otherwise an object with a single `message` property + * that contains the message payload, corresponding to the oldest message in the + * `MessagePort`’s queue. + */ + function receiveMessageOnPort(port: MessagePort): { message: any } | undefined; + + type Serializable = string | object | number | boolean | bigint; + + /** + * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. + * @experimental + */ + function getEnvironmentData(key: Serializable): Serializable; + + /** + * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. + * @param value Any arbitrary, cloneable JavaScript value that will be cloned + * and passed automatically to all new `Worker` instances. If `value` is passed + * as `undefined`, any previously set value for the `key` will be deleted. + * @experimental + */ + function setEnvironmentData(key: Serializable, value: Serializable): void; +} diff --git a/tests/node_modules/@types/node/zlib.d.ts b/tests/node_modules/@types/node/zlib.d.ts new file mode 100755 index 0000000..eafc91b --- /dev/null +++ b/tests/node_modules/@types/node/zlib.d.ts @@ -0,0 +1,361 @@ +declare module 'zlib' { + import * as stream from 'stream'; + + interface ZlibOptions { + /** + * @default constants.Z_NO_FLUSH + */ + flush?: number; + /** + * @default constants.Z_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: NodeJS.ArrayBufferView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + info?: boolean; + maxOutputLength?: number; + } + + interface BrotliOptions { + /** + * @default constants.BROTLI_OPERATION_PROCESS + */ + flush?: number; + /** + * @default constants.BROTLI_OPERATION_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + params?: { + /** + * Each key is a `constants.BROTLI_*` constant. + */ + [key: number]: boolean | number; + }; + maxOutputLength?: number; + } + + interface Zlib { + /** @deprecated Use bytesWritten instead. */ + readonly bytesRead: number; + readonly bytesWritten: number; + shell?: boolean | string; + close(callback?: () => void): void; + flush(kind?: number, callback?: () => void): void; + flush(callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface BrotliCompress extends stream.Transform, Zlib { } + interface BrotliDecompress extends stream.Transform, Zlib { } + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createBrotliCompress(options?: BrotliOptions): BrotliCompress; + function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView; + + type CompressCallback = (error: Error | null, result: Buffer) => void; + + function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliCompress(buf: InputType, callback: CompressCallback): void; + namespace brotliCompress { + function __promisify__(buffer: InputType, options?: BrotliOptions): Promise; + } + + function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; + + function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliDecompress(buf: InputType, callback: CompressCallback): void; + namespace brotliDecompress { + function __promisify__(buffer: InputType, options?: BrotliOptions): Promise; + } + + function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; + + function deflate(buf: InputType, callback: CompressCallback): void; + function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace deflate { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + + function deflateRaw(buf: InputType, callback: CompressCallback): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace deflateRaw { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + + function gzip(buf: InputType, callback: CompressCallback): void; + function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace gzip { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + function gunzip(buf: InputType, callback: CompressCallback): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace gunzip { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + function inflate(buf: InputType, callback: CompressCallback): void; + function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace inflate { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + + function inflateRaw(buf: InputType, callback: CompressCallback): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace inflateRaw { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + + function unzip(buf: InputType, callback: CompressCallback): void; + function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + namespace unzip { + function __promisify__(buffer: InputType, options?: ZlibOptions): Promise; + } + + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + const BROTLI_DECODE: number; + const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; + const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; + const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; + const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; + const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; + const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; + const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; + const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; + const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; + const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; + const BROTLI_DECODER_ERROR_UNREACHABLE: number; + const BROTLI_DECODER_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_NO_ERROR: number; + const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; + const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; + const BROTLI_DECODER_RESULT_ERROR: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_RESULT_SUCCESS: number; + const BROTLI_DECODER_SUCCESS: number; + + const BROTLI_DEFAULT_MODE: number; + const BROTLI_DEFAULT_QUALITY: number; + const BROTLI_DEFAULT_WINDOW: number; + const BROTLI_ENCODE: number; + const BROTLI_LARGE_MAX_WINDOW_BITS: number; + const BROTLI_MAX_INPUT_BLOCK_BITS: number; + const BROTLI_MAX_QUALITY: number; + const BROTLI_MAX_WINDOW_BITS: number; + const BROTLI_MIN_INPUT_BLOCK_BITS: number; + const BROTLI_MIN_QUALITY: number; + const BROTLI_MIN_WINDOW_BITS: number; + + const BROTLI_MODE_FONT: number; + const BROTLI_MODE_GENERIC: number; + const BROTLI_MODE_TEXT: number; + + const BROTLI_OPERATION_EMIT_METADATA: number; + const BROTLI_OPERATION_FINISH: number; + const BROTLI_OPERATION_FLUSH: number; + const BROTLI_OPERATION_PROCESS: number; + + const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; + const BROTLI_PARAM_LARGE_WINDOW: number; + const BROTLI_PARAM_LGBLOCK: number; + const BROTLI_PARAM_LGWIN: number; + const BROTLI_PARAM_MODE: number; + const BROTLI_PARAM_NDIRECT: number; + const BROTLI_PARAM_NPOSTFIX: number; + const BROTLI_PARAM_QUALITY: number; + const BROTLI_PARAM_SIZE_HINT: number; + + const DEFLATE: number; + const DEFLATERAW: number; + const GUNZIP: number; + const GZIP: number; + const INFLATE: number; + const INFLATERAW: number; + const UNZIP: number; + + // Allowed flush values. + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + // Return codes for the compression/decompression functions. + // Negative values are errors, positive values are used for special but normal events. + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + // Compression levels. + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + + const Z_DEFAULT_WINDOWBITS: number; + const Z_MIN_WINDOWBITS: number; + const Z_MAX_WINDOWBITS: number; + + const Z_MIN_CHUNK: number; + const Z_MAX_CHUNK: number; + const Z_DEFAULT_CHUNK: number; + + const Z_MIN_MEMLEVEL: number; + const Z_MAX_MEMLEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; + + const Z_MIN_LEVEL: number; + const Z_MAX_LEVEL: number; + const Z_DEFAULT_LEVEL: number; + + const ZLIB_VERNUM: number; + } + + // Allowed flush values. + /** @deprecated Use `constants.Z_NO_FLUSH` */ + const Z_NO_FLUSH: number; + /** @deprecated Use `constants.Z_PARTIAL_FLUSH` */ + const Z_PARTIAL_FLUSH: number; + /** @deprecated Use `constants.Z_SYNC_FLUSH` */ + const Z_SYNC_FLUSH: number; + /** @deprecated Use `constants.Z_FULL_FLUSH` */ + const Z_FULL_FLUSH: number; + /** @deprecated Use `constants.Z_FINISH` */ + const Z_FINISH: number; + /** @deprecated Use `constants.Z_BLOCK` */ + const Z_BLOCK: number; + /** @deprecated Use `constants.Z_TREES` */ + const Z_TREES: number; + + // Return codes for the compression/decompression functions. + // Negative values are errors, positive values are used for special but normal events. + /** @deprecated Use `constants.Z_OK` */ + const Z_OK: number; + /** @deprecated Use `constants.Z_STREAM_END` */ + const Z_STREAM_END: number; + /** @deprecated Use `constants.Z_NEED_DICT` */ + const Z_NEED_DICT: number; + /** @deprecated Use `constants.Z_ERRNO` */ + const Z_ERRNO: number; + /** @deprecated Use `constants.Z_STREAM_ERROR` */ + const Z_STREAM_ERROR: number; + /** @deprecated Use `constants.Z_DATA_ERROR` */ + const Z_DATA_ERROR: number; + /** @deprecated Use `constants.Z_MEM_ERROR` */ + const Z_MEM_ERROR: number; + /** @deprecated Use `constants.Z_BUF_ERROR` */ + const Z_BUF_ERROR: number; + /** @deprecated Use `constants.Z_VERSION_ERROR` */ + const Z_VERSION_ERROR: number; + + // Compression levels. + /** @deprecated Use `constants.Z_NO_COMPRESSION` */ + const Z_NO_COMPRESSION: number; + /** @deprecated Use `constants.Z_BEST_SPEED` */ + const Z_BEST_SPEED: number; + /** @deprecated Use `constants.Z_BEST_COMPRESSION` */ + const Z_BEST_COMPRESSION: number; + /** @deprecated Use `constants.Z_DEFAULT_COMPRESSION` */ + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + /** @deprecated Use `constants.Z_FILTERED` */ + const Z_FILTERED: number; + /** @deprecated Use `constants.Z_HUFFMAN_ONLY` */ + const Z_HUFFMAN_ONLY: number; + /** @deprecated Use `constants.Z_RLE` */ + const Z_RLE: number; + /** @deprecated Use `constants.Z_FIXED` */ + const Z_FIXED: number; + /** @deprecated Use `constants.Z_DEFAULT_STRATEGY` */ + const Z_DEFAULT_STRATEGY: number; + + /** @deprecated */ + const Z_BINARY: number; + /** @deprecated */ + const Z_TEXT: number; + /** @deprecated */ + const Z_ASCII: number; + /** @deprecated */ + const Z_UNKNOWN: number; + /** @deprecated */ + const Z_DEFLATED: number; +} diff --git a/tests/node_modules/@types/responselike/LICENSE b/tests/node_modules/@types/responselike/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/tests/node_modules/@types/responselike/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/node_modules/@types/responselike/README.md b/tests/node_modules/@types/responselike/README.md new file mode 100644 index 0000000..4523ff9 --- /dev/null +++ b/tests/node_modules/@types/responselike/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/responselike` + +# Summary +This package contains type definitions for responselike ( https://github.com/lukechilds/responselike#readme ). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike + +Additional Details + * Last updated: Wed, 30 Jan 2019 18:47:32 GMT + * Dependencies: @types/node + * Global values: none + +# Credits +These definitions were written by BendingBender . diff --git a/tests/node_modules/@types/responselike/index.d.ts b/tests/node_modules/@types/responselike/index.d.ts new file mode 100644 index 0000000..7152388 --- /dev/null +++ b/tests/node_modules/@types/responselike/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for responselike 1.0 +// Project: https://github.com/lukechilds/responselike#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { IncomingMessage } from 'http'; +import { Stream } from 'stream'; + +export = ResponseLike; + +/** + * Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + */ +declare class ResponseLike extends Stream.Readable { + statusCode: number; + headers: { [header: string]: string | string[] | undefined }; + body: Buffer; + url: string; + + /** + * @param statusCode HTTP response status code. + * @param headers HTTP headers object. Keys will be automatically lowercased. + * @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + * @param url Request URL string. + */ + constructor( + statusCode: number, + headers: { [header: string]: string | string[] | undefined }, + body: Buffer, + url: string + ); +} diff --git a/tests/node_modules/@types/responselike/package.json b/tests/node_modules/@types/responselike/package.json new file mode 100644 index 0000000..06aa78a --- /dev/null +++ b/tests/node_modules/@types/responselike/package.json @@ -0,0 +1,55 @@ +{ + "_from": "@types/responselike@^1.0.0", + "_id": "@types/responselike@1.0.0", + "_inBundle": false, + "_integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", + "_location": "/@types/responselike", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/responselike@^1.0.0", + "name": "@types/responselike", + "escapedName": "@types%2fresponselike", + "scope": "@types", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/@types/cacheable-request", + "/got" + ], + "_resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", + "_shasum": "251f4fe7d154d2bad125abe1b429b23afd262e29", + "_spec": "@types/responselike@^1.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "dependencies": { + "@types/node": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for responselike", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/responselike", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "types": "index", + "typesPublisherContentHash": "38ee8db1511cdb4a9133ff67b8bc16901de733aa4dc1efffdb5064b7daaa3f21", + "version": "1.0.0" +} diff --git a/tests/node_modules/ansi-regex/index.js b/tests/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..b9574ed --- /dev/null +++ b/tests/node_modules/ansi-regex/index.js @@ -0,0 +1,4 @@ +'use strict'; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +}; diff --git a/tests/node_modules/ansi-regex/license b/tests/node_modules/ansi-regex/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/tests/node_modules/ansi-regex/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/ansi-regex/package.json b/tests/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..0a49a39 --- /dev/null +++ b/tests/node_modules/ansi-regex/package.json @@ -0,0 +1,109 @@ +{ + "_from": "ansi-regex@^2.0.0", + "_id": "ansi-regex@2.1.1", + "_inBundle": false, + "_integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "_location": "/ansi-regex", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-regex@^2.0.0", + "name": "ansi-regex", + "escapedName": "ansi-regex", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/has-ansi", + "/strip-ansi" + ], + "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df", + "_spec": "ansi-regex@^2.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/has-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-regex/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Regular expression for matching ANSI escape codes", + "devDependencies": { + "ava": "0.17.0", + "xo": "0.16.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/chalk/ansi-regex#readme", + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "license": "MIT", + "maintainers": [ + { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + { + "name": "Joshua Appelman", + "email": "jappelman@xebia.com", + "url": "jbnicolai.com" + }, + { + "name": "JD Ballard", + "email": "i.am.qix@gmail.com", + "url": "github.com/qix-" + } + ], + "name": "ansi-regex", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/ansi-regex.git" + }, + "scripts": { + "test": "xo && ava --verbose", + "view-supported": "node fixtures/view-codes.js" + }, + "version": "2.1.1", + "xo": { + "rules": { + "guard-for-in": 0, + "no-loop-func": 0 + } + } +} diff --git a/tests/node_modules/ansi-regex/readme.md b/tests/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..6a928ed --- /dev/null +++ b/tests/node_modules/ansi-regex/readme.md @@ -0,0 +1,39 @@ +# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) + +> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +``` +$ npm install --save ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001b[4mcake\u001b[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001b[4mcake\u001b[0m'.match(ansiRegex()); +//=> ['\u001b[4m', '\u001b[0m'] +``` + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tests/node_modules/ansi-styles/index.js b/tests/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..7894527 --- /dev/null +++ b/tests/node_modules/ansi-styles/index.js @@ -0,0 +1,65 @@ +'use strict'; + +function assembleStyles () { + var styles = { + modifiers: { + reset: [0, 0], + bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + colors: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39] + }, + bgColors: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49] + } + }; + + // fix humans + styles.colors.grey = styles.colors.gray; + + Object.keys(styles).forEach(function (groupName) { + var group = styles[groupName]; + + Object.keys(group).forEach(function (styleName) { + var style = group[styleName]; + + styles[styleName] = group[styleName] = { + open: '\u001b[' + style[0] + 'm', + close: '\u001b[' + style[1] + 'm' + }; + }); + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + }); + + return styles; +} + +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/tests/node_modules/ansi-styles/license b/tests/node_modules/ansi-styles/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/tests/node_modules/ansi-styles/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/ansi-styles/package.json b/tests/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..721aa47 --- /dev/null +++ b/tests/node_modules/ansi-styles/package.json @@ -0,0 +1,90 @@ +{ + "_from": "ansi-styles@^2.2.1", + "_id": "ansi-styles@2.2.1", + "_inBundle": false, + "_integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "_location": "/ansi-styles", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-styles@^2.2.1", + "name": "ansi-styles", + "escapedName": "ansi-styles", + "rawSpec": "^2.2.1", + "saveSpec": null, + "fetchSpec": "^2.2.1" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "_shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe", + "_spec": "ansi-styles@^2.2.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-styles/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "ANSI escape codes for styling strings in the terminal", + "devDependencies": { + "mocha": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/chalk/ansi-styles#readme", + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "maintainers": [ + { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + { + "name": "Joshua Appelman", + "email": "jappelman@xebia.com", + "url": "jbnicolai.com" + } + ], + "name": "ansi-styles", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/ansi-styles.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "2.2.1" +} diff --git a/tests/node_modules/ansi-styles/readme.md b/tests/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..3f933f6 --- /dev/null +++ b/tests/node_modules/ansi-styles/readme.md @@ -0,0 +1,86 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + +![](screenshot.png) + + +## Install + +``` +$ npm install --save ansi-styles +``` + + +## Usage + +```js +var ansi = require('ansi-styles'); + +console.log(ansi.green.open + 'Hello world!' + ansi.green.close); +``` + + +## API + +Each style has an `open` and `close` property. + + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `gray` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` + + +## Advanced usage + +By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `ansi.modifiers` +- `ansi.colors` +- `ansi.bgColors` + + +###### Example + +```js +console.log(ansi.colors.green.open); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tests/node_modules/anymatch/LICENSE b/tests/node_modules/anymatch/LICENSE new file mode 100644 index 0000000..491766c --- /dev/null +++ b/tests/node_modules/anymatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/tests/node_modules/anymatch/README.md b/tests/node_modules/anymatch/README.md new file mode 100644 index 0000000..1dd67f5 --- /dev/null +++ b/tests/node_modules/anymatch/README.md @@ -0,0 +1,87 @@ +anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) +====== +Javascript module to match a string against a regular expression, glob, string, +or function that takes the string as an argument and returns a truthy or falsy +value. The matcher can also be an array of any or all of these. Useful for +allowing a very flexible user-defined config to define things like file paths. + +__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ + + +Usage +----- +```sh +npm install anymatch +``` + +#### anymatch(matchers, testString, [returnIndex], [options]) +* __matchers__: (_Array|String|RegExp|Function_) +String to be directly matched, string with glob patterns, regular expression +test, function that takes the testString as an argument and returns a truthy +value if it should be matched, or an array of any number and mix of these types. +* __testString__: (_String|Array_) The string to test against the matchers. If +passed as an array, the first element of the array will be used as the +`testString` for non-function matchers, while the entire array will be applied +as the arguments for function matchers. +* __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. + * __returnIndex__: (_Boolean [optional]_) If true, return the array index of +the first matcher that that testString matched, or -1 if no match, instead of a +boolean result. + +```js +const anymatch = require('anymatch'); + +const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; + +anymatch(matchers, 'path/to/file.js'); // true +anymatch(matchers, 'path/anyjs/baz.js'); // true +anymatch(matchers, 'path/to/foo.js'); // true +anymatch(matchers, 'path/to/bar.js'); // true +anymatch(matchers, 'bar.js'); // false + +// returnIndex = true +anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 +anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 + +// any picomatc + +// using globs to match directories and their children +anymatch('node_modules', 'node_modules'); // true +anymatch('node_modules', 'node_modules/somelib/index.js'); // false +anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true +anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false +anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true + +const matcher = anymatch(matchers); +['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] +anymatch master* ❯ + +``` + +#### anymatch(matchers) +You can also pass in only your matcher(s) to get a curried function that has +already been bound to the provided matching criteria. This can be used as an +`Array#filter` callback. + +```js +var matcher = anymatch(matchers); + +matcher('path/to/file.js'); // true +matcher('path/anyjs/baz.js', true); // 1 + +['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] +``` + +Changelog +---------- +[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) + +- **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. +- **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). +- **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) +for glob pattern matching. Issues with glob pattern matching should be +reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). + +License +------- +[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) diff --git a/tests/node_modules/anymatch/index.d.ts b/tests/node_modules/anymatch/index.d.ts new file mode 100644 index 0000000..196d061 --- /dev/null +++ b/tests/node_modules/anymatch/index.d.ts @@ -0,0 +1,19 @@ +type AnymatchFn = (testString: string) => boolean; +type AnymatchPattern = string|RegExp|AnymatchFn; +type AnymatchMatcher = AnymatchPattern|AnymatchPattern[] +type AnymatchTester = { + (testString: string|any[], returnIndex: true): number; + (testString: string|any[]): boolean; +} + +type PicomatchOptions = {dot: boolean}; + +declare const anymatch: { + (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; + (matchers: AnymatchMatcher, testString: string|any[]): boolean; +} + +export {AnymatchMatcher as Matcher} +export {AnymatchTester as Tester} +export default anymatch diff --git a/tests/node_modules/anymatch/index.js b/tests/node_modules/anymatch/index.js new file mode 100644 index 0000000..9fb3ebb --- /dev/null +++ b/tests/node_modules/anymatch/index.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); + +const picomatch = require('picomatch'); +const normalizePath = require('normalize-path'); + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; diff --git a/tests/node_modules/anymatch/package.json b/tests/node_modules/anymatch/package.json new file mode 100644 index 0000000..c45df3e --- /dev/null +++ b/tests/node_modules/anymatch/package.json @@ -0,0 +1,76 @@ +{ + "_from": "anymatch@~3.1.2", + "_id": "anymatch@3.1.2", + "_inBundle": false, + "_integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "_location": "/anymatch", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "anymatch@~3.1.2", + "name": "anymatch", + "escapedName": "anymatch", + "rawSpec": "~3.1.2", + "saveSpec": null, + "fetchSpec": "~3.1.2" + }, + "_requiredBy": [ + "/chokidar" + ], + "_resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "_shasum": "c0557c096af32f106198f4f4e2a383537e378716", + "_spec": "anymatch@~3.1.2", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/chokidar", + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "bugs": { + "url": "https://github.com/micromatch/anymatch/issues" + }, + "bundleDependencies": false, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "deprecated": false, + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" + }, + "engines": { + "node": ">= 8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/micromatch/anymatch", + "keywords": [ + "match", + "any", + "string", + "file", + "fs", + "list", + "glob", + "regex", + "regexp", + "regular", + "expression", + "function" + ], + "license": "ISC", + "name": "anymatch", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/anymatch.git" + }, + "scripts": { + "mocha": "mocha", + "test": "nyc mocha" + }, + "version": "3.1.2" +} diff --git a/tests/node_modules/available-typed-arrays/.eslintignore b/tests/node_modules/available-typed-arrays/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/available-typed-arrays/.eslintrc b/tests/node_modules/available-typed-arrays/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/tests/node_modules/available-typed-arrays/.github/FUNDING.yml b/tests/node_modules/available-typed-arrays/.github/FUNDING.yml new file mode 100644 index 0000000..14abc72 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/available-typed-arrays +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/available-typed-arrays/.nycrc b/tests/node_modules/available-typed-arrays/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/tests/node_modules/available-typed-arrays/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/available-typed-arrays/CHANGELOG.md b/tests/node_modules/available-typed-arrays/CHANGELOG.md new file mode 100644 index 0000000..642bc3a --- /dev/null +++ b/tests/node_modules/available-typed-arrays/CHANGELOG.md @@ -0,0 +1,69 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.3...v1.0.4) - 2021-05-25 + +### Commits + +- [Refactor] Remove `array.prototype.filter` dependency [`f39c90e`](https://github.com/inspect-js/available-typed-arrays/commit/f39c90ecb1907de28ee2d3577b7da37ae12aac56) +- [Dev Deps] update `eslint`, `auto-changelog` [`b2e3a03`](https://github.com/inspect-js/available-typed-arrays/commit/b2e3a035e8cd3ddfd7b565249e1651c6419a34d0) +- [meta] create `FUNDING.yml` [`8c0e758`](https://github.com/inspect-js/available-typed-arrays/commit/8c0e758c6ec80adbb3770554653cdc3aa16beb55) +- [Tests] fix harmony test matrix [`ef96549`](https://github.com/inspect-js/available-typed-arrays/commit/ef96549df171776267529413240a2219cb59d5ce) +- [meta] add `sideEffects` flag [`288cca0`](https://github.com/inspect-js/available-typed-arrays/commit/288cca0fbd214bec706447851bb8bccc4b899a48) + +## [v1.0.3](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.2...v1.0.3) - 2021-05-19 + +### Commits + +- [Tests] migrate tests to Github Actions [`3ef082c`](https://github.com/inspect-js/available-typed-arrays/commit/3ef082caaa153b49f4c37c85bbd5c4b13fe4f638) +- [meta] do not publish github action workflow files [`fd95ffd`](https://github.com/inspect-js/available-typed-arrays/commit/fd95ffdaca759eca81cb4c5d5772ee863dfea501) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`eb6bd65`](https://github.com/inspect-js/available-typed-arrays/commit/eb6bd659a31c92a6a178c71a89fe0d5261413e6c) +- [Tests] run `nyc` on all tests [`636c946`](https://github.com/inspect-js/available-typed-arrays/commit/636c94657b532599ef90a214aaa12639d11b0161) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`70a3b61`](https://github.com/inspect-js/available-typed-arrays/commit/70a3b61367b318fb883c2f35b8f2d539849a23b6) +- [actions] add "Allow Edits" workflow [`bd09c45`](https://github.com/inspect-js/available-typed-arrays/commit/bd09c45299e396fa5bbd5be4c58b1aedcb372a82) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `array.prototype.every`, `aud`, `tape` [`8f97523`](https://github.com/inspect-js/available-typed-arrays/commit/8f9752308390a79068cd431436bbfd77bca15647) +- [readme] fix URLs [`75418e2`](https://github.com/inspect-js/available-typed-arrays/commit/75418e20b57f4ad5e65d8c2e1864efd14eaa2e65) +- [readme] add actions and codecov badges [`4a8bc30`](https://github.com/inspect-js/available-typed-arrays/commit/4a8bc30af2ce1f48e2b28ab3db5be9589bd6f2d0) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`65198ac`](https://github.com/inspect-js/available-typed-arrays/commit/65198ace335a013ef49b6bd722bc80bbbc6be784) +- [actions] update workflows [`7f816eb`](https://github.com/inspect-js/available-typed-arrays/commit/7f816eb231131e53ced2572ba6c6c6a00f975789) +- [Refactor] use `array.prototype.filter` instead of `array-filter` [`2dd1038`](https://github.com/inspect-js/available-typed-arrays/commit/2dd1038d71ce48b5650687691cf8fe09795a6d30) +- [actions] switch Automatic Rease workflow to `pull_request_target` event [`9b45e91`](https://github.com/inspect-js/available-typed-arrays/commit/9b45e914fcb08bdaaaa0166b41716e51f400d1c6) +- [Dev Deps] update `auto-changelog`, `tape` [`0003a5b`](https://github.com/inspect-js/available-typed-arrays/commit/0003a5b122a0724db5499c114104eeeb396b2f67) +- [meta] use `prepublishOnly` script for npm 7+ [`d884dd1`](https://github.com/inspect-js/available-typed-arrays/commit/d884dd1c1117411f35d9fbc07f513a1a85ccdead) +- [readme] remove travis badge [`9da2b3c`](https://github.com/inspect-js/available-typed-arrays/commit/9da2b3c29706340fada995137aba12cfae4d6f37) +- [Dev Deps] update `auto-changelog`; add `aud` [`41b1336`](https://github.com/inspect-js/available-typed-arrays/commit/41b13369c71b0e3e57b9de0f4fb1e4d67950d74a) +- [Tests] only audit prod deps [`2571826`](https://github.com/inspect-js/available-typed-arrays/commit/2571826a5d121eeeeccf4c711e3f9e4616685d50) + +## [v1.0.2](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.1...v1.0.2) - 2020-01-26 + +### Commits + +- [actions] add automatic rebasing / merge commit blocking [`3229a74`](https://github.com/inspect-js/available-typed-arrays/commit/3229a74bda60f24e2257efc40ddff9a3ce98de76) +- [Dev Deps] update `@ljharb/eslint-config` [`9579abe`](https://github.com/inspect-js/available-typed-arrays/commit/9579abecc196088561d3aedf27cad45b56f8e18b) +- [Fix] remove `require` condition to avoid experimental warning [`2cade6b`](https://github.com/inspect-js/available-typed-arrays/commit/2cade6b56d6a508a950c7da27d038bee496e716b) + +## [v1.0.1](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.0...v1.0.1) - 2020-01-24 + +### Commits + +- [meta] add "exports" [`5942917`](https://github.com/inspect-js/available-typed-arrays/commit/5942917aafb56c6bce80f01b7ae6a9b46bc72c69) + +## v1.0.0 - 2020-01-24 + +### Commits + +- Initial commit [`2bc5144`](https://github.com/inspect-js/available-typed-arrays/commit/2bc514459c9f65756adfbd9964abf433183d78f6) +- readme [`31e4796`](https://github.com/inspect-js/available-typed-arrays/commit/31e4796379eba4a16d3c6a8e9baf6eb3f39e33d1) +- npm init [`9194266`](https://github.com/inspect-js/available-typed-arrays/commit/9194266b471a2a2dd5e6969bc40358ceb346e21e) +- Tests [`b539830`](https://github.com/inspect-js/available-typed-arrays/commit/b539830c3213f90de42b4d6e62803f52daf61a6d) +- Implementation [`6577df2`](https://github.com/inspect-js/available-typed-arrays/commit/6577df244ea146ef5ec16858044c8955e0fc445c) +- [meta] add `auto-changelog` [`7b43310`](https://github.com/inspect-js/available-typed-arrays/commit/7b43310be76f00fe60b74a2fd6d0e46ac1d01f3e) +- [Tests] add `npm run lint` [`dedfbc1`](https://github.com/inspect-js/available-typed-arrays/commit/dedfbc1592f86ac1636267d3965f2345df43815b) +- [Tests] use shared travis-ci configs [`c459d78`](https://github.com/inspect-js/available-typed-arrays/commit/c459d78bf2efa9d777f88599ae71a796dbfcb70f) +- Only apps should have lockfiles [`d294668`](https://github.com/inspect-js/available-typed-arrays/commit/d294668422cf35f5e7716a85bfd204e62b01c056) +- [meta] add `funding` field [`6e70bc1`](https://github.com/inspect-js/available-typed-arrays/commit/6e70bc1fb199c7898165aaf05c25bb49f4062e53) +- [meta] add `safe-publish-latest` [`dd89ca2`](https://github.com/inspect-js/available-typed-arrays/commit/dd89ca2c6842f0f3e82958df2b2bd0fc0c929c51) diff --git a/tests/node_modules/available-typed-arrays/LICENSE b/tests/node_modules/available-typed-arrays/LICENSE new file mode 100644 index 0000000..707437b --- /dev/null +++ b/tests/node_modules/available-typed-arrays/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/available-typed-arrays/README.md b/tests/node_modules/available-typed-arrays/README.md new file mode 100644 index 0000000..16838f4 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/README.md @@ -0,0 +1,52 @@ +# available-typed-arrays [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Returns an array of Typed Array names that are available in the current environment. + +## Example + +```js +var availableTypedArrays = require('available-typed-arrays'); +var assert = require('assert'); + +assert.deepStrictEqual(availableTypedArrays(), [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +].sort()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/available-typed-arrays +[2]: https://versionbadg.es/inspect-js/available-typed-arrays.svg +[5]: https://david-dm.org/inspect-js/available-typed-arrays.svg +[6]: https://david-dm.org/inspect-js/available-typed-arrays +[7]: https://david-dm.org/inspect-js/available-typed-arrays/dev-status.svg +[8]: https://david-dm.org/inspect-js/available-typed-arrays#info=devDependencies +[11]: https://nodei.co/npm/available-typed-arrays.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/available-typed-arrays.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/available-typed-arrays.svg +[downloads-url]: https://npm-stat.com/charts.html?package=available-typed-arrays +[codecov-image]: https://codecov.io/gh/inspect-js/available-typed-arrays/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/available-typed-arrays/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/available-typed-arrays +[actions-url]: https://github.com/inspect-js/available-typed-arrays/actions diff --git a/tests/node_modules/available-typed-arrays/index.js b/tests/node_modules/available-typed-arrays/index.js new file mode 100644 index 0000000..00cb9c1 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/index.js @@ -0,0 +1,25 @@ +'use strict'; + +var possibleNames = [ + 'BigInt64Array', + 'BigUint64Array', + 'Float32Array', + 'Float64Array', + 'Int16Array', + 'Int32Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Uint8Array', + 'Uint8ClampedArray' +]; + +module.exports = function availableTypedArrays() { + var out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof global[possibleNames[i]] === 'function') { + out[out.length] = possibleNames[i]; + } + } + return out; +}; diff --git a/tests/node_modules/available-typed-arrays/package.json b/tests/node_modules/available-typed-arrays/package.json new file mode 100644 index 0000000..0f05dd9 --- /dev/null +++ b/tests/node_modules/available-typed-arrays/package.json @@ -0,0 +1,111 @@ +{ + "_from": "available-typed-arrays@^1.0.2", + "_id": "available-typed-arrays@1.0.4", + "_inBundle": false, + "_integrity": "sha512-SA5mXJWrId1TaQjfxUYghbqQ/hYioKmLJvPJyDuYRtXXenFNMjj4hSSt1Cf1xsuXSXrtxrVC5Ot4eU6cOtBDdA==", + "_location": "/available-typed-arrays", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "available-typed-arrays@^1.0.2", + "name": "available-typed-arrays", + "escapedName": "available-typed-arrays", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/is-typed-array", + "/which-typed-array" + ], + "_resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.4.tgz", + "_shasum": "9e0ae84ecff20caae6a94a1c3bc39b955649b7a9", + "_spec": "available-typed-arrays@^1.0.2", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/which-typed-array", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/inspect-js/available-typed-arrays/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Returns an array of Typed Array names that are available in the current environment", + "devDependencies": { + "@ljharb/eslint-config": "^17.6.0", + "array.prototype.every": "^1.1.2", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^7.27.0", + "evalmd": "^0.0.19", + "isarray": "^2.0.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package": "./package.json", + "./package.json": "./package.json" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/inspect-js/available-typed-arrays#readme", + "keywords": [ + "typed", + "arrays", + "Float32Array", + "Float64Array", + "Int8Array", + "Int16Array", + "Int32Array", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "BigInt64Array", + "BigUint64Array" + ], + "license": "MIT", + "main": "index.js", + "name": "available-typed-arrays", + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/available-typed-arrays.git" + }, + "scripts": { + "lint": "eslint --ext=js,mjs .", + "posttest": "aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prelint": "evalmd README.md", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only && npm run test:harmony", + "test:harmony": "nyc node --harmony --es-staging test", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "sideEffects": false, + "type": "commonjs", + "version": "1.0.4" +} diff --git a/tests/node_modules/available-typed-arrays/test/index.js b/tests/node_modules/available-typed-arrays/test/index.js new file mode 100644 index 0000000..21c986d --- /dev/null +++ b/tests/node_modules/available-typed-arrays/test/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var test = require('tape'); +var isArray = require('isarray'); +var every = require('array.prototype.every'); + +var availableTypedArrays = require('../'); + +test('available typed arrays', function (t) { + t.equal(typeof availableTypedArrays, 'function', 'is a function'); + + var arrays = availableTypedArrays(); + t.equal(isArray(arrays), true, 'returns an array'); + + t.equal(every(arrays, function (array) { return typeof array === 'string'; }), true, 'contains only strings'); + + t.end(); +}); diff --git a/tests/node_modules/balanced-match/.github/FUNDING.yml b/tests/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/tests/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/tests/node_modules/balanced-match/LICENSE.md b/tests/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/tests/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/balanced-match/README.md b/tests/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/tests/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/balanced-match/index.js b/tests/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/tests/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/tests/node_modules/balanced-match/package.json b/tests/node_modules/balanced-match/package.json new file mode 100644 index 0000000..25c68a5 --- /dev/null +++ b/tests/node_modules/balanced-match/package.json @@ -0,0 +1,76 @@ +{ + "_from": "balanced-match@^1.0.0", + "_id": "balanced-match@1.0.2", + "_inBundle": false, + "_integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "_location": "/balanced-match", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "balanced-match@^1.0.0", + "name": "balanced-match", + "escapedName": "balanced-match", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "_shasum": "e83e3a7e3f300b34cb9d87f615fa0cbf357690ee", + "_spec": "balanced-match@^1.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/brace-expansion", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "main": "index.js", + "name": "balanced-match", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "scripts": { + "bench": "matcha test/bench.js", + "test": "tape test/test.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.2" +} diff --git a/tests/node_modules/binary-extensions/binary-extensions.json b/tests/node_modules/binary-extensions/binary-extensions.json new file mode 100644 index 0000000..4aab383 --- /dev/null +++ b/tests/node_modules/binary-extensions/binary-extensions.json @@ -0,0 +1,260 @@ +[ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +] diff --git a/tests/node_modules/binary-extensions/binary-extensions.json.d.ts b/tests/node_modules/binary-extensions/binary-extensions.json.d.ts new file mode 100644 index 0000000..94a248c --- /dev/null +++ b/tests/node_modules/binary-extensions/binary-extensions.json.d.ts @@ -0,0 +1,3 @@ +declare const binaryExtensionsJson: readonly string[]; + +export = binaryExtensionsJson; diff --git a/tests/node_modules/binary-extensions/index.d.ts b/tests/node_modules/binary-extensions/index.d.ts new file mode 100644 index 0000000..f469ac5 --- /dev/null +++ b/tests/node_modules/binary-extensions/index.d.ts @@ -0,0 +1,14 @@ +/** +List of binary file extensions. + +@example +``` +import binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` +*/ +declare const binaryExtensions: readonly string[]; + +export = binaryExtensions; diff --git a/tests/node_modules/binary-extensions/index.js b/tests/node_modules/binary-extensions/index.js new file mode 100644 index 0000000..d46e468 --- /dev/null +++ b/tests/node_modules/binary-extensions/index.js @@ -0,0 +1 @@ +module.exports = require('./binary-extensions.json'); diff --git a/tests/node_modules/binary-extensions/license b/tests/node_modules/binary-extensions/license new file mode 100644 index 0000000..401b1c7 --- /dev/null +++ b/tests/node_modules/binary-extensions/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/binary-extensions/package.json b/tests/node_modules/binary-extensions/package.json new file mode 100644 index 0000000..e9ae55b --- /dev/null +++ b/tests/node_modules/binary-extensions/package.json @@ -0,0 +1,70 @@ +{ + "_from": "binary-extensions@^2.0.0", + "_id": "binary-extensions@2.2.0", + "_inBundle": false, + "_integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "_location": "/binary-extensions", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "binary-extensions@^2.0.0", + "name": "binary-extensions", + "escapedName": "binary-extensions", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/is-binary-path" + ], + "_resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "_shasum": "75f502eeaf9ffde42fc98829645be4ea76bd9e2d", + "_spec": "binary-extensions@^2.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/is-binary-path", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/binary-extensions/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "List of binary file extensions", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts", + "binary-extensions.json", + "binary-extensions.json.d.ts" + ], + "homepage": "https://github.com/sindresorhus/binary-extensions#readme", + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "json", + "list", + "array" + ], + "license": "MIT", + "name": "binary-extensions", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/binary-extensions.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.2.0" +} diff --git a/tests/node_modules/binary-extensions/readme.md b/tests/node_modules/binary-extensions/readme.md new file mode 100644 index 0000000..3e25dd8 --- /dev/null +++ b/tests/node_modules/binary-extensions/readme.md @@ -0,0 +1,41 @@ +# binary-extensions + +> List of binary file extensions + +The list is just a [JSON file](binary-extensions.json) and can be used anywhere. + + +## Install + +``` +$ npm install binary-extensions +``` + + +## Usage + +```js +const binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` + + +## Related + +- [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file +- [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions + + +--- + +

+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/tests/node_modules/brace-expansion/LICENSE b/tests/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/tests/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/brace-expansion/README.md b/tests/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/tests/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/brace-expansion/index.js b/tests/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/tests/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/tests/node_modules/brace-expansion/package.json b/tests/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..9761f56 --- /dev/null +++ b/tests/node_modules/brace-expansion/package.json @@ -0,0 +1,75 @@ +{ + "_from": "brace-expansion@^1.1.7", + "_id": "brace-expansion@1.1.11", + "_inBundle": false, + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "_location": "/brace-expansion", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "brace-expansion@^1.1.7", + "name": "brace-expansion", + "escapedName": "brace-expansion", + "rawSpec": "^1.1.7", + "saveSpec": null, + "fetchSpec": "^1.1.7" + }, + "_requiredBy": [ + "/minimatch" + ], + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "_shasum": "3c7fcbf529d87226f3d2f52b966ff5271eb441dd", + "_spec": "brace-expansion@^1.1.7", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/minimatch", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "bundleDependencies": false, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "deprecated": false, + "description": "Brace expansion as known from sh/bash", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "keywords": [], + "license": "MIT", + "main": "index.js", + "name": "brace-expansion", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "scripts": { + "bench": "matcha test/perf/bench.js", + "gentest": "bash test/generate.sh", + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.11" +} diff --git a/tests/node_modules/braces/CHANGELOG.md b/tests/node_modules/braces/CHANGELOG.md new file mode 100644 index 0000000..36f798b --- /dev/null +++ b/tests/node_modules/braces/CHANGELOG.md @@ -0,0 +1,184 @@ +# Release history + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ +## [3.0.0] - 2018-04-08 + +v3.0 is a complete refactor, resulting in a faster, smaller codebase, with fewer deps, and a more accurate parser and compiler. + +**Breaking Changes** + +- The undocumented `.makeRe` method was removed + +**Non-breaking changes** + +- Caching was removed + +## [2.3.2] - 2018-04-08 + +- start refactoring +- cover sets +- better range handling + +## [2.3.1] - 2018-02-17 + +- Remove unnecessary escape in Regex. (#14) + +## [2.3.0] - 2017-10-19 + +- minor code reorganization +- optimize regex +- expose `maxLength` option + +## [2.2.1] - 2017-05-30 + +- don't condense when braces contain extglobs + +## [2.2.0] - 2017-05-28 + +- ensure word boundaries are preserved +- fixes edge case where extglob characters precede a brace pattern + +## [2.1.1] - 2017-04-27 + +- use snapdragon-node +- handle edge case +- optimizations, lint + +## [2.0.4] - 2017-04-11 + +- pass opts to compiler +- minor optimization in create method +- re-write parser handlers to remove negation regex + +## [2.0.3] - 2016-12-10 + +- use split-string +- clear queue at the end +- adds sequences example +- add unit tests + +## [2.0.2] - 2016-10-21 + +- fix comma handling in nested extglobs + +## [2.0.1] - 2016-10-20 + +- add comments +- more tests, ensure quotes are stripped + +## [2.0.0] - 2016-10-19 + +- don't expand braces inside character classes +- add quantifier pattern + +## [1.8.5] - 2016-05-21 + +- Refactor (#10) + +## [1.8.4] - 2016-04-20 + +- fixes https://github.com/jonschlinkert/micromatch/issues/66 + +## [1.8.0] - 2015-03-18 + +- adds exponent examples, tests +- fixes the first example in https://github.com/jonschlinkert/micromatch/issues/38 + +## [1.6.0] - 2015-01-30 + +- optimizations, `bash` mode: +- improve path escaping + +## [1.5.0] - 2015-01-28 + +- Merge pull request #5 from eush77/lib-files + +## [1.4.0] - 2015-01-24 + +- add extglob tests +- externalize exponent function +- better whitespace handling + +## [1.3.0] - 2015-01-24 + +- make regex patterns explicity + +## [1.1.0] - 2015-01-11 + +- don't create a match group with `makeRe` + +## [1.0.0] - 2014-12-23 + +- Merge commit '97b05f5544f8348736a8efaecf5c32bbe3e2ad6e' +- support empty brace syntax +- better bash coverage +- better support for regex strings + +## [0.1.4] - 2014-11-14 + +- improve recognition of bad args, recognize mismatched argument types +- support escaping +- remove pathname-expansion +- support whitespace in patterns + +## [0.1.0] + +- first commit + +[2.3.2]: https://github.com/micromatch/braces/compare/2.3.1...2.3.2 +[2.3.1]: https://github.com/micromatch/braces/compare/2.3.0...2.3.1 +[2.3.0]: https://github.com/micromatch/braces/compare/2.2.1...2.3.0 +[2.2.1]: https://github.com/micromatch/braces/compare/2.2.0...2.2.1 +[2.2.0]: https://github.com/micromatch/braces/compare/2.1.1...2.2.0 +[2.1.1]: https://github.com/micromatch/braces/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/micromatch/braces/compare/2.0.4...2.1.0 +[2.0.4]: https://github.com/micromatch/braces/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/micromatch/braces/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/micromatch/braces/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/micromatch/braces/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/micromatch/braces/compare/1.8.5...2.0.0 +[1.8.5]: https://github.com/micromatch/braces/compare/1.8.4...1.8.5 +[1.8.4]: https://github.com/micromatch/braces/compare/1.8.0...1.8.4 +[1.8.0]: https://github.com/micromatch/braces/compare/1.6.0...1.8.0 +[1.6.0]: https://github.com/micromatch/braces/compare/1.5.0...1.6.0 +[1.5.0]: https://github.com/micromatch/braces/compare/1.4.0...1.5.0 +[1.4.0]: https://github.com/micromatch/braces/compare/1.3.0...1.4.0 +[1.3.0]: https://github.com/micromatch/braces/compare/1.2.0...1.3.0 +[1.2.0]: https://github.com/micromatch/braces/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/micromatch/braces/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/micromatch/braces/compare/0.1.4...1.0.0 +[0.1.4]: https://github.com/micromatch/braces/compare/0.1.0...0.1.4 + +[Unreleased]: https://github.com/micromatch/braces/compare/0.1.0...HEAD +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog \ No newline at end of file diff --git a/tests/node_modules/braces/LICENSE b/tests/node_modules/braces/LICENSE new file mode 100644 index 0000000..d32ab44 --- /dev/null +++ b/tests/node_modules/braces/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2018, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/braces/README.md b/tests/node_modules/braces/README.md new file mode 100644 index 0000000..cba2f60 --- /dev/null +++ b/tests/node_modules/braces/README.md @@ -0,0 +1,593 @@ +# braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) + +> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save braces +``` + +## v3.0.0 Released!! + +See the [changelog](CHANGELOG.md) for details. + +## Why use braces? + +Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. + +* **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) +* **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. +* **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. +* **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). +* **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). +* [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` +* [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` +* [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` +* [Supports escaping](#escaping) - To prevent evaluation of special characters. + +## Usage + +The main export is a function that takes one or more brace `patterns` and `options`. + +```js +const braces = require('braces'); +// braces(patterns[, options]); + +console.log(braces(['{01..05}', '{a..e}'])); +//=> ['(0[1-5])', '([a-e])'] + +console.log(braces(['{01..05}', '{a..e}'], { expand: true })); +//=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] +``` + +### Brace Expansion vs. Compilation + +By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. + +**Compiled** + +```js +console.log(braces('a/{x,y,z}/b')); +//=> ['a/(x|y|z)/b'] +console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); +//=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] +``` + +**Expanded** + +Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): + +```js +console.log(braces('a/{x,y,z}/b', { expand: true })); +//=> ['a/x/b', 'a/y/b', 'a/z/b'] + +console.log(braces.expand('{01..10}')); +//=> ['01','02','03','04','05','06','07','08','09','10'] +``` + +### Lists + +Expand lists (like Bash "sets"): + +```js +console.log(braces('a/{foo,bar,baz}/*.js')); +//=> ['a/(foo|bar|baz)/*.js'] + +console.log(braces.expand('a/{foo,bar,baz}/*.js')); +//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] +``` + +### Sequences + +Expand ranges of characters (like Bash "sequences"): + +```js +console.log(braces.expand('{1..3}')); // ['1', '2', '3'] +console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] +console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] +console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] + +// supports zero-padded ranges +console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] +console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] +``` + +See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. + +### Steppped ranges + +Steps, or increments, may be used with ranges: + +```js +console.log(braces.expand('{2..10..2}')); +//=> ['2', '4', '6', '8', '10'] + +console.log(braces('{2..10..2}')); +//=> ['(2|4|6|8|10)'] +``` + +When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. + +### Nesting + +Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. + +**"Expanded" braces** + +```js +console.log(braces.expand('a{b,c,/{x,y}}/e')); +//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] + +console.log(braces.expand('a/{x,{1..5},y}/c')); +//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] +``` + +**"Optimized" braces** + +```js +console.log(braces('a{b,c,/{x,y}}/e')); +//=> ['a(b|c|/(x|y))/e'] + +console.log(braces('a/{x,{1..5},y}/c')); +//=> ['a/(x|([1-5])|y)/c'] +``` + +### Escaping + +**Escaping braces** + +A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: + +```js +console.log(braces.expand('a\\{d,c,b}e')); +//=> ['a{d,c,b}e'] + +console.log(braces.expand('a{d,c,b\\}e')); +//=> ['a{d,c,b}e'] +``` + +**Escaping commas** + +Commas inside braces may also be escaped: + +```js +console.log(braces.expand('a{b\\,c}d')); +//=> ['a{b,c}d'] + +console.log(braces.expand('a{d\\,c,b}e')); +//=> ['ad,ce', 'abe'] +``` + +**Single items** + +Following bash conventions, a brace pattern is also not expanded when it contains a single character: + +```js +console.log(braces.expand('a{b}c')); +//=> ['a{b}c'] +``` + +## Options + +### options.maxLength + +**Type**: `Number` + +**Default**: `65,536` + +**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. + +```js +console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error +``` + +### options.expand + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). + +```js +console.log(braces('a/{b,c}/d', { expand: true })); +//=> [ 'a/b/d', 'a/c/d' ] +``` + +### options.nodupes + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Remove duplicates from the returned array. + +### options.rangeLimit + +**Type**: `Number` + +**Default**: `1000` + +**Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. + +You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. + +**Examples** + +```js +// pattern exceeds the "rangeLimit", so it's optimized automatically +console.log(braces.expand('{1..1000}')); +//=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] + +// pattern does not exceed "rangeLimit", so it's NOT optimized +console.log(braces.expand('{1..100}')); +//=> ['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'] +``` + +### options.transform + +**Type**: `Function` + +**Default**: `undefined` + +**Description**: Customize range expansion. + +**Example: Transforming non-numeric values** + +```js +const alpha = braces.expand('x/{a..e}/y', { + transform(value, index) { + // When non-numeric values are passed, "value" is a character code. + return 'foo/' + String.fromCharCode(value) + '-' + index; + } +}); +console.log(alpha); +//=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] +``` + +**Example: Transforming numeric values** + +```js +const numeric = braces.expand('{1..5}', { + transform(value) { + // when numeric values are passed, "value" is a number + return 'foo/' + value * 2; + } +}); +console.log(numeric); +//=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] +``` + +### options.quantifiers + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. + +Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) + +The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists. + +**Examples** + +```js +const braces = require('braces'); +console.log(braces('a/b{1,3}/{x,y,z}')); +//=> [ 'a/b(1|3)/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); +//=> [ 'a/b{1,3}/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); +//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] +``` + +### options.unescape + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Strip backslashes that were used for escaping from the result. + +## What is "brace expansion"? + +Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). + +In addition to "expansion", braces are also used for matching. In other words: + +* [brace expansion](#brace-expansion) is for generating new lists +* [brace matching](#brace-matching) is for filtering existing lists + +
+More about brace expansion (click to expand) + +There are two main types of brace expansion: + +1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` +2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". + +Here are some example brace patterns to illustrate how they work: + +**Sets** + +``` +{a,b,c} => a b c +{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 +``` + +**Sequences** + +``` +{1..9} => 1 2 3 4 5 6 7 8 9 +{4..-4} => 4 3 2 1 0 -1 -2 -3 -4 +{1..20..3} => 1 4 7 10 13 16 19 +{a..j} => a b c d e f g h i j +{j..a} => j i h g f e d c b a +{a..z..3} => a d g j m p s v y +``` + +**Combination** + +Sets and sequences can be mixed together or used along with any other strings. + +``` +{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 +foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar +``` + +The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. + +## Brace matching + +In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. + +For example, the pattern `foo/{1..3}/bar` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +``` + +But not: + +``` +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +## Brace matching pitfalls + +Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. + +### tldr + +**"brace bombs"** + +* brace expansion can eat up a huge amount of processing resources +* as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially +* users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) + +For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. + +### The solution + +Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. + +### Geometric complexity + +At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. + +For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: + +``` +{1,2}{3,4} => (2X2) => 13 14 23 24 +{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 +``` + +But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: + +``` +{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 + 249 257 258 259 267 268 269 347 348 349 357 + 358 359 367 368 369 +``` + +Now, imagine how this complexity grows given that each element is a n-tuple: + +``` +{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) +{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) +``` + +Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. + +**More information** + +Interested in learning more about brace expansion? + +* [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) +* [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) +* [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) + +
+ +## Performance + +Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. + +### Better algorithms + +Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. + +Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. + +**The proof is in the numbers** + +Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. + +| **Pattern** | **braces** | **[minimatch][]** | +| --- | --- | --- | +| `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs)| N/A (freezes) | +| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | +| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | +| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | +| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | +| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | +| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | +| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | +| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | +| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | +| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | +| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | +| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | +| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | +| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | +| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | +| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | + +### Faster algorithms + +When you need expansion, braces is still much faster. + +_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ + +| **Pattern** | **braces** | **[minimatch][]** | +| --- | --- | --- | +| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | +| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | +| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | +| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | +| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | +| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | +| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | +| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | + +If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). + +## Benchmarks + +### Running benchmarks + +Install dev dependencies: + +```bash +npm i -d && npm benchmark +``` + +### Latest results + +Braces is more accurate, without sacrificing performance. + +```bash +# range (expanded) + braces x 29,040 ops/sec ±3.69% (91 runs sampled)) + minimatch x 4,735 ops/sec ±1.28% (90 runs sampled) + +# range (optimized for regex) + braces x 382,878 ops/sec ±0.56% (94 runs sampled) + minimatch x 1,040 ops/sec ±0.44% (93 runs sampled) + +# nested ranges (expanded) + braces x 19,744 ops/sec ±2.27% (92 runs sampled)) + minimatch x 4,579 ops/sec ±0.50% (93 runs sampled) + +# nested ranges (optimized for regex) + braces x 246,019 ops/sec ±2.02% (93 runs sampled) + minimatch x 1,028 ops/sec ±0.39% (94 runs sampled) + +# set (expanded) + braces x 138,641 ops/sec ±0.53% (95 runs sampled) + minimatch x 219,582 ops/sec ±0.98% (94 runs sampled) + +# set (optimized for regex) + braces x 388,408 ops/sec ±0.41% (95 runs sampled) + minimatch x 44,724 ops/sec ±0.91% (89 runs sampled) + +# nested sets (expanded) + braces x 84,966 ops/sec ±0.48% (94 runs sampled) + minimatch x 140,720 ops/sec ±0.37% (95 runs sampled) + +# nested sets (optimized for regex) + braces x 263,340 ops/sec ±2.06% (92 runs sampled) + minimatch x 28,714 ops/sec ±0.40% (90 runs sampled) +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 197 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [doowb](https://github.com/doowb) | +| 1 | [es128](https://github.com/es128) | +| 1 | [eush77](https://github.com/eush77) | +| 1 | [hemanth](https://github.com/hemanth) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ \ No newline at end of file diff --git a/tests/node_modules/braces/index.js b/tests/node_modules/braces/index.js new file mode 100644 index 0000000..0eee0f5 --- /dev/null +++ b/tests/node_modules/braces/index.js @@ -0,0 +1,170 @@ +'use strict'; + +const stringify = require('./lib/stringify'); +const compile = require('./lib/compile'); +const expand = require('./lib/expand'); +const parse = require('./lib/parse'); + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +module.exports = braces; diff --git a/tests/node_modules/braces/lib/compile.js b/tests/node_modules/braces/lib/compile.js new file mode 100644 index 0000000..3e984a4 --- /dev/null +++ b/tests/node_modules/braces/lib/compile.js @@ -0,0 +1,57 @@ +'use strict'; + +const fill = require('fill-range'); +const utils = require('./utils'); + +const compile = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + let range = fill(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +module.exports = compile; diff --git a/tests/node_modules/braces/lib/constants.js b/tests/node_modules/braces/lib/constants.js new file mode 100644 index 0000000..a937943 --- /dev/null +++ b/tests/node_modules/braces/lib/constants.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; diff --git a/tests/node_modules/braces/lib/expand.js b/tests/node_modules/braces/lib/expand.js new file mode 100644 index 0000000..376c748 --- /dev/null +++ b/tests/node_modules/braces/lib/expand.js @@ -0,0 +1,113 @@ +'use strict'; + +const fill = require('fill-range'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + } + } + } + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +module.exports = expand; diff --git a/tests/node_modules/braces/lib/parse.js b/tests/node_modules/braces/lib/parse.js new file mode 100644 index 0000000..145ea26 --- /dev/null +++ b/tests/node_modules/braces/lib/parse.js @@ -0,0 +1,333 @@ +'use strict'; + +const stringify = require('./stringify'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = require('./constants'); + +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + let memo = {}; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + + let closed = true; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; diff --git a/tests/node_modules/braces/lib/stringify.js b/tests/node_modules/braces/lib/stringify.js new file mode 100644 index 0000000..414b7bc --- /dev/null +++ b/tests/node_modules/braces/lib/stringify.js @@ -0,0 +1,32 @@ +'use strict'; + +const utils = require('./utils'); + +module.exports = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + diff --git a/tests/node_modules/braces/lib/utils.js b/tests/node_modules/braces/lib/utils.js new file mode 100644 index 0000000..e3551a6 --- /dev/null +++ b/tests/node_modules/braces/lib/utils.js @@ -0,0 +1,112 @@ +'use strict'; + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; +}; diff --git a/tests/node_modules/braces/package.json b/tests/node_modules/braces/package.json new file mode 100644 index 0000000..c22622d --- /dev/null +++ b/tests/node_modules/braces/package.json @@ -0,0 +1,123 @@ +{ + "_from": "braces@~3.0.2", + "_id": "braces@3.0.2", + "_inBundle": false, + "_integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "_location": "/braces", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "braces@~3.0.2", + "name": "braces", + "escapedName": "braces", + "rawSpec": "~3.0.2", + "saveSpec": null, + "fetchSpec": "~3.0.2" + }, + "_requiredBy": [ + "/chokidar" + ], + "_resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "_shasum": "3454e1a462ee8d599e236df336cd9ea4f8afe107", + "_spec": "braces@~3.0.2", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/chokidar", + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/micromatch/braces/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Brian Woodward", + "url": "https://twitter.com/doowb" + }, + { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + { + "name": "Eugene Sharygin", + "url": "https://github.com/eush77" + }, + { + "name": "hemanth.hm", + "url": "http://h3manth.com" + }, + { + "name": "Jon Schlinkert", + "url": "http://twitter.com/jonschlinkert" + } + ], + "dependencies": { + "fill-range": "^7.0.1" + }, + "deprecated": false, + "description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.", + "devDependencies": { + "ansi-colors": "^3.2.4", + "bash-path": "^2.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/micromatch/braces", + "keywords": [ + "alpha", + "alphabetical", + "bash", + "brace", + "braces", + "expand", + "expansion", + "filepath", + "fill", + "fs", + "glob", + "globbing", + "letter", + "match", + "matches", + "matching", + "number", + "numerical", + "path", + "range", + "ranges", + "sh" + ], + "license": "MIT", + "main": "index.js", + "name": "braces", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/braces.git" + }, + "scripts": { + "benchmark": "node benchmark", + "test": "mocha" + }, + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "lint": { + "reflinks": true + }, + "plugins": [ + "gulp-format-md" + ] + }, + "version": "3.0.2" +} diff --git a/tests/node_modules/buffer-equal-constant-time/.npmignore b/tests/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/tests/node_modules/buffer-equal-constant-time/.travis.yml b/tests/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/tests/node_modules/buffer-equal-constant-time/LICENSE.txt b/tests/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tests/node_modules/buffer-equal-constant-time/README.md b/tests/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/tests/node_modules/buffer-equal-constant-time/index.js b/tests/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/tests/node_modules/buffer-equal-constant-time/package.json b/tests/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..8b59aa9 --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,55 @@ +{ + "_from": "buffer-equal-constant-time@1.0.1", + "_id": "buffer-equal-constant-time@1.0.1", + "_inBundle": false, + "_integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=", + "_location": "/buffer-equal-constant-time", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "buffer-equal-constant-time@1.0.1", + "name": "buffer-equal-constant-time", + "escapedName": "buffer-equal-constant-time", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/jwa" + ], + "_resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "_shasum": "f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819", + "_spec": "buffer-equal-constant-time@1.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/jwa", + "author": { + "name": "GoInstant Inc., a salesforce.com company" + }, + "bugs": { + "url": "https://github.com/goinstant/buffer-equal-constant-time/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Constant-time comparison of Buffers", + "devDependencies": { + "mocha": "~1.15.1" + }, + "homepage": "https://github.com/goinstant/buffer-equal-constant-time#readme", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "name": "buffer-equal-constant-time", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/goinstant/buffer-equal-constant-time.git" + }, + "scripts": { + "test": "mocha test.js" + }, + "version": "1.0.1" +} diff --git a/tests/node_modules/buffer-equal-constant-time/test.js b/tests/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/tests/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/tests/node_modules/buffer-shims/index.js b/tests/node_modules/buffer-shims/index.js new file mode 100644 index 0000000..1cab4c0 --- /dev/null +++ b/tests/node_modules/buffer-shims/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} diff --git a/tests/node_modules/buffer-shims/license.md b/tests/node_modules/buffer-shims/license.md new file mode 100644 index 0000000..01cfaef --- /dev/null +++ b/tests/node_modules/buffer-shims/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2016 Calvin Metcalf + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.** diff --git a/tests/node_modules/buffer-shims/package.json b/tests/node_modules/buffer-shims/package.json new file mode 100644 index 0000000..f21453a --- /dev/null +++ b/tests/node_modules/buffer-shims/package.json @@ -0,0 +1,49 @@ +{ + "_from": "buffer-shims@~1.0.0", + "_id": "buffer-shims@1.0.0", + "_inBundle": false, + "_integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=", + "_location": "/buffer-shims", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "buffer-shims@~1.0.0", + "name": "buffer-shims", + "escapedName": "buffer-shims", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", + "_shasum": "9978ce317388c649ad8793028c3477ef044a8b51", + "_spec": "buffer-shims@~1.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/readable-stream", + "bugs": { + "url": "https://github.com/calvinmetcalf/buffer-shims/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "some shims for node buffers", + "devDependencies": { + "tape": "^4.5.1" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/calvinmetcalf/buffer-shims#readme", + "license": "MIT", + "main": "index.js", + "name": "buffer-shims", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/calvinmetcalf/buffer-shims.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "version": "1.0.0" +} diff --git a/tests/node_modules/buffer-shims/readme.md b/tests/node_modules/buffer-shims/readme.md new file mode 100644 index 0000000..7ea6475 --- /dev/null +++ b/tests/node_modules/buffer-shims/readme.md @@ -0,0 +1,21 @@ +buffer-shims +=== + +functions to make sure the new buffer methods work in older browsers. + +```js +var bufferShim = require('buffer-shims'); +bufferShim.from('foo'); +bufferShim.alloc(9, 'cafeface', 'hex'); +bufferShim.allocUnsafe(15); +bufferShim.allocUnsafeSlow(21); +``` + +should just use the original in newer nodes and on older nodes uses fallbacks. + +Known Issues +=== +- this does not patch the buffer object, only the constructor stuff +- it's actually a polyfill + +![](https://i.imgur.com/zxII3jJ.gif) diff --git a/tests/node_modules/cacheable-lookup/LICENSE b/tests/node_modules/cacheable-lookup/LICENSE new file mode 100755 index 0000000..92498ed --- /dev/null +++ b/tests/node_modules/cacheable-lookup/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Szymon Marczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/cacheable-lookup/README.md b/tests/node_modules/cacheable-lookup/README.md new file mode 100755 index 0000000..2507155 --- /dev/null +++ b/tests/node_modules/cacheable-lookup/README.md @@ -0,0 +1,240 @@ +# cacheable-lookup + +> A cacheable [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) that respects TTL :tada: + +[![Node CI](https://github.com/szmarczak/cacheable-lookup/workflows/Node%20CI/badge.svg)](https://github.com/szmarczak/cacheable-lookup/actions) +[![Coverage Status](https://coveralls.io/repos/github/szmarczak/cacheable-lookup/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/cacheable-lookup?branch=master) +[![npm](https://img.shields.io/npm/dm/cacheable-lookup.svg)](https://www.npmjs.com/package/cacheable-lookup) +[![install size](https://packagephobia.now.sh/badge?p=cacheable-lookup)](https://packagephobia.now.sh/result?p=cacheable-lookup) + +Making lots of HTTP requests? You can save some time by caching DNS lookups :zap: + +## Usage + +### Using the `lookup` option + +```js +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); + +const cacheable = new CacheableLookup(); + +http.get('http://example.com', {lookup: cacheable.lookup}, response => { + // Handle the response here +}); +``` + +### Attaching CacheableLookup to an Agent + +```js +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); + +const cacheable = new CacheableLookup(); +cacheable.install(http.globalAgent); + +http.get('http://example.com', response => { + // Handle the response here +}); +``` + +## API + +### new CacheableLookup(options) + +Returns a new instance of `CacheableLookup`. + +#### options + +Type: `object`
+Default: `{}` + +Options used to cache the DNS lookups. + +##### cache + +Type: `Map` | [`Keyv`](https://github.com/lukechilds/keyv/)
+Default: `new Map()` + +Custom cache instance. If `undefined`, it will create a new one. + +**Note**: If you decide to use Keyv instead of the native implementation, the performance will drop by 10x. Memory leaks may occur as it doesn't provide any way to remove all the deprecated values at once. + +**Tip**: [`QuickLRU`](https://github.com/sindresorhus/quick-lru) is fully compatible with the Map API, you can use it to limit the amount of cached entries. Example: + +```js +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); +const QuickLRU = require('quick-lru'); + +const cacheable = new CacheableLookup({ + cache: new QuickLRU({maxSize: 1000}) +}); + +http.get('http://example.com', {lookup: cacheable.lookup}, response => { + // Handle the response here +}); +``` + +##### options.maxTtl + +Type: `number`
+Default: `Infinity` + +The maximum lifetime of the entries received from the specifed DNS server (TTL in seconds). + +If set to `0`, it will make a new DNS query each time. + +**Pro Tip**: This shouldn't be lower than your DNS server response time in order to prevent bottlenecks. For example, if you use Cloudflare, this value should be greater than `0.01`. + +##### options.fallbackDuration + +Type: `number`
+Default: `3600` (1 hour) + +When the DNS server responds with `ENOTFOUND` or `ENODATA` and the OS reports that the entry is available, it will use `dns.lookup(...)` directly for the requested hostnames for the specified amount of time (in seconds). + +If you don't query internal hostnames (such as `localhost`, `database.local` etc.), it is strongly recommended to set this value to `0`. + +##### options.errorTtl + +Type: `number`
+Default: `0.15` + +The time how long it needs to remember queries that threw `ENOTFOUND` or `ENODATA` (TTL in seconds). + +**Note**: This option is independent, `options.maxTtl` does not affect this. + +**Pro Tip**: This shouldn't be lower than your DNS server response time in order to prevent bottlenecks. For example, if you use Cloudflare, this value should be greater than `0.01`. + +##### options.resolver + +Type: `dns.Resolver | dns.promises.Resolver`
+Default: [`new dns.promises.Resolver()`](https://nodejs.org/api/dns.html#dns_class_dns_resolver) + +An instance of [DNS Resolver](https://nodejs.org/api/dns.html#dns_class_dns_resolver) used to make DNS queries. + +##### options.lookup + +Type: `Function`
+Default: [`dns.lookup`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) + +The fallback function to use when the DNS server responds with `ENOTFOUND` or `ENODATA`. + +**Note**: This has no effect if the `fallbackDuration` option is less than `1`. + +### Entry object + +Type: `object` + +#### address + +Type: `string` + +The IP address (can be an IPv4 or IPv6 address). + +#### family + +Type: `number` + +The IP family (`4` or `6`). + +##### expires + +Type: `number` + +**Note**: This is not present when falling back to `dns.lookup(...)`! + +The timestamp (`Date.now() + ttl * 1000`) when the entry expires. + +#### ttl + +**Note**: This is not present when falling back to `dns.lookup(...)`! + +The time in seconds for its lifetime. + +### Entry object (callback-style) + +When `options.all` is `false`, then `callback(error, address, family, expires, ttl)` is called.
+When `options.all` is `true`, then `callback(error, entries)` is called. + +### CacheableLookup instance + +#### servers + +Type: `Array` + +The DNS servers used to make queries. Can be overridden - doing so will clear the cache. + +#### [lookup(hostname, options, callback)](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) + +#### lookupAsync(hostname, options) + +The asynchronous version of `dns.lookup(…)`. + +Returns an [entry object](#entry-object).
+If `options.all` is true, returns an array of entry objects. + +##### hostname + +Type: `string` + +##### options + +Type: `object` + +The same as the [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) options. + +#### query(hostname) + +An asynchronous function which returns cached DNS lookup entries.
+This is the base for `lookupAsync(hostname, options)` and `lookup(hostname, options, callback)`. + +**Note**: This function has no options. + +Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. + +#### queryAndCache(hostname) + +An asynchronous function which makes two DNS queries: A and AAAA. The result is cached.
+This is used by `query(hostname)` if no entry in the database is present. + +Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. + +#### updateInterfaceInfo() + +Updates interface info. For example, you need to run this when you plug or unplug your WiFi driver. + +**Note:** Running `updateInterfaceInfo()` will trigger `clear()` only on network interface removal. + +#### clear(hostname?) + +Clears the cache for the given hostname. If the hostname argument is not present, the entire cache will be emptied. + +## High performance + +Performed on: +- Query: `example.com` +- CPU: i7-7700k +- CPU governor: performance + +``` +CacheableLookup#lookupAsync x 2,896,251 ops/sec ±1.07% (85 runs sampled) +CacheableLookup#lookupAsync.all x 2,842,664 ops/sec ±1.11% (88 runs sampled) +CacheableLookup#lookupAsync.all.ADDRCONFIG x 2,598,283 ops/sec ±1.21% (88 runs sampled) +CacheableLookup#lookup x 2,565,913 ops/sec ±1.56% (85 runs sampled) +CacheableLookup#lookup.all x 2,609,039 ops/sec ±1.01% (86 runs sampled) +CacheableLookup#lookup.all.ADDRCONFIG x 2,416,242 ops/sec ±0.89% (85 runs sampled) +dns#lookup x 7,272 ops/sec ±0.36% (86 runs sampled) +dns#lookup.all x 7,249 ops/sec ±0.40% (86 runs sampled) +dns#lookup.all.ADDRCONFIG x 5,693 ops/sec ±0.28% (85 runs sampled) +Fastest is CacheableLookup#lookupAsync.all +``` + +## Related + + - [cacheable-request](https://github.com/lukechilds/cacheable-request) - Wrap native HTTP requests with RFC compliant cache support + +## License + +MIT diff --git a/tests/node_modules/cacheable-lookup/index.d.ts b/tests/node_modules/cacheable-lookup/index.d.ts new file mode 100755 index 0000000..528b1e2 --- /dev/null +++ b/tests/node_modules/cacheable-lookup/index.d.ts @@ -0,0 +1,139 @@ +import {Resolver, promises as dnsPromises, lookup} from 'dns'; +import {Agent} from 'http'; + +type AsyncResolver = dnsPromises.Resolver; + +export type IPFamily = 4 | 6; + +type TPromise = T | Promise; + +export interface CacheInstance { + set(hostname: string, entries: EntryObject[], ttl: number): TPromise; + get(hostname: string): TPromise; + delete(hostname: string): TPromise; + clear(): TPromise; +} + +export interface Options { + /** + * Custom cache instance. If `undefined`, it will create a new one. + * @default undefined + */ + cache?: CacheInstance; + /** + * Limits the cache time (TTL). If set to `0`, it will make a new DNS query each time. + * @default Infinity + */ + maxTtl?: number; + /** + * DNS Resolver used to make DNS queries. + * @default new dns.promises.Resolver() + */ + resolver?: Resolver | AsyncResolver; + /** + * When the DNS server responds with `ENOTFOUND` or `ENODATA` and the OS reports that the entry is available, + * it will use `dns.lookup(...)` directly for the requested hostnames for the specified amount of time (in seconds). + * + * If you don't query internal hostnames (such as `localhost`, `database.local` etc.), + * it is strongly recommended to set this value to `0`. + * @default 3600 + */ + fallbackDuration?: number; + /** + * The time how long it needs to remember failed queries (TTL in seconds). + * + * **Note**: This option is independent, `options.maxTtl` does not affect this. + * @default 0.15 + */ + errorTtl?: number; + /** + * The fallback function to use when the DNS server responds with `ENOTFOUND` or `ENODATA`. + * + * **Note**: This has no effect if the `fallbackDuration` option is less than `1`. + * @default dns.lookup + */ + lookup?: typeof lookup; +} + +export interface EntryObject { + /** + * The IP address (can be an IPv4 or IPv5 address). + */ + readonly address: string; + /** + * The IP family. + */ + readonly family: IPFamily; + /** + * The original TTL. + */ + readonly ttl?: number; + /** + * The expiration timestamp. + */ + readonly expires?: number; +} + +export interface LookupOptions { + /** + * One or more supported getaddrinfo flags. Multiple flags may be passed by bitwise ORing their values. + */ + hints?: number; + /** + * The record family. Must be `4` or `6`. IPv4 and IPv6 addresses are both returned by default. + */ + family?: IPFamily; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean; +} + +export default class CacheableLookup { + constructor(options?: Options); + /** + * The DNS servers used to make queries. Can be overridden - doing so will clear the cache. + */ + servers: string[]; + /** + * @see https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback + */ + lookup(hostname: string, family: IPFamily, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; + lookup(hostname: string, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; + lookup(hostname: string, options: LookupOptions & {all: true}, callback: (error: NodeJS.ErrnoException, result: ReadonlyArray) => void): void; + lookup(hostname: string, options: LookupOptions, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; + /** + * The asynchronous version of `dns.lookup(…)`. + */ + lookupAsync(hostname: string, options: LookupOptions & {all: true}): Promise>; + lookupAsync(hostname: string, options: LookupOptions): Promise; + lookupAsync(hostname: string): Promise; + lookupAsync(hostname: string, family: IPFamily): Promise; + /** + * An asynchronous function which returns cached DNS lookup entries. This is the base for `lookupAsync(hostname, options)` and `lookup(hostname, options, callback)`. + */ + query(hostname: string): Promise>; + /** + * An asynchronous function which makes a new DNS lookup query and updates the database. This is used by `query(hostname, family)` if no entry in the database is present. Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. + */ + queryAndCache(hostname: string): Promise>; + /** + * Attaches itself to an Agent instance. + */ + install(agent: Agent): void; + /** + * Removes itself from an Agent instance. + */ + uninstall(agent: Agent): void; + /** + * Updates interface info. For example, you need to run this when you plug or unplug your WiFi driver. + * + * **Note:** Running `updateInterfaceInfo()` will trigger `clear()` only on network interface removal. + */ + updateInterfaceInfo(): void; + /** + * Clears the cache for the given hostname. If the hostname argument is not present, the entire cache will be emptied. + */ + clear(hostname?: string): void; +} diff --git a/tests/node_modules/cacheable-lookup/package.json b/tests/node_modules/cacheable-lookup/package.json new file mode 100755 index 0000000..7bcc224 --- /dev/null +++ b/tests/node_modules/cacheable-lookup/package.json @@ -0,0 +1,72 @@ +{ + "_from": "cacheable-lookup@^5.0.3", + "_id": "cacheable-lookup@5.0.4", + "_inBundle": false, + "_integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==", + "_location": "/cacheable-lookup", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cacheable-lookup@^5.0.3", + "name": "cacheable-lookup", + "escapedName": "cacheable-lookup", + "rawSpec": "^5.0.3", + "saveSpec": null, + "fetchSpec": "^5.0.3" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "_shasum": "5a6b865b2c44357be3d5ebc2a467b032719a7005", + "_spec": "cacheable-lookup@^5.0.3", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "author": { + "name": "Szymon Marczak" + }, + "bugs": { + "url": "https://github.com/szmarczak/cacheable-lookup/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A cacheable dns.lookup(…) that respects the TTL", + "devDependencies": { + "@types/keyv": "^3.1.1", + "ava": "^3.8.2", + "benchmark": "^2.1.4", + "coveralls": "^3.0.9", + "keyv": "^4.0.0", + "nyc": "^15.0.0", + "proxyquire": "^2.1.3", + "quick-lru": "^5.1.0", + "tsd": "^0.11.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=10.6.0" + }, + "files": [ + "source", + "index.d.ts" + ], + "homepage": "https://github.com/szmarczak/cacheable-lookup#readme", + "keywords": [ + "dns", + "lookup", + "cacheable", + "ttl" + ], + "license": "MIT", + "main": "source/index.js", + "name": "cacheable-lookup", + "repository": { + "type": "git", + "url": "git+https://github.com/szmarczak/cacheable-lookup.git" + }, + "scripts": { + "test": "xo && nyc --reporter=lcovonly --reporter=text ava && tsd" + }, + "types": "index.d.ts", + "version": "5.0.4" +} diff --git a/tests/node_modules/cacheable-lookup/source/index.js b/tests/node_modules/cacheable-lookup/source/index.js new file mode 100755 index 0000000..21f731e --- /dev/null +++ b/tests/node_modules/cacheable-lookup/source/index.js @@ -0,0 +1,436 @@ +'use strict'; +const { + V4MAPPED, + ADDRCONFIG, + ALL, + promises: { + Resolver: AsyncResolver + }, + lookup: dnsLookup +} = require('dns'); +const {promisify} = require('util'); +const os = require('os'); + +const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); +const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); +const kExpires = Symbol('expires'); + +const supportsALL = typeof ALL === 'number'; + +const verifyAgent = agent => { + if (!(agent && typeof agent.createConnection === 'function')) { + throw new Error('Expected an Agent instance as the first argument'); + } +}; + +const map4to6 = entries => { + for (const entry of entries) { + if (entry.family === 6) { + continue; + } + + entry.address = `::ffff:${entry.address}`; + entry.family = 6; + } +}; + +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; + + for (const device of Object.values(os.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } + + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } + + if (has4 && has6) { + return {has4, has6}; + } + } + } + + return {has4, has6}; +}; + +const isIterable = map => { + return Symbol.iterator in map; +}; + +const ttl = {ttl: true}; +const all = {all: true}; + +class CacheableLookup { + constructor({ + cache = new Map(), + maxTtl = Infinity, + fallbackDuration = 3600, + errorTtl = 0.15, + resolver = new AsyncResolver(), + lookup = dnsLookup + } = {}) { + this.maxTtl = maxTtl; + this.errorTtl = errorTtl; + + this._cache = cache; + this._resolver = resolver; + this._dnsLookup = promisify(lookup); + + if (this._resolver instanceof AsyncResolver) { + this._resolve4 = this._resolver.resolve4.bind(this._resolver); + this._resolve6 = this._resolver.resolve6.bind(this._resolver); + } else { + this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); + } + + this._iface = getIfaceInfo(); + + this._pending = {}; + this._nextRemovalTime = false; + this._hostnamesToFallback = new Set(); + + if (fallbackDuration < 1) { + this._fallback = false; + } else { + this._fallback = true; + + const interval = setInterval(() => { + this._hostnamesToFallback.clear(); + }, fallbackDuration * 1000); + + /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ + if (interval.unref) { + interval.unref(); + } + } + + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); + } + + set servers(servers) { + this.clear(); + + this._resolver.setServers(servers); + } + + get servers() { + return this._resolver.getServers(); + } + + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else if (typeof options === 'number') { + options = { + family: options + }; + } + + if (!callback) { + throw new Error('Callback must be a function.'); + } + + // eslint-disable-next-line promise/prefer-await-to-then + this.lookupAsync(hostname, options).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family, result.expires, result.ttl); + } + }, callback); + } + + async lookupAsync(hostname, options = {}) { + if (typeof options === 'number') { + options = { + family: options + }; + } + + let cached = await this.query(hostname); + + if (options.family === 6) { + const filtered = cached.filter(entry => entry.family === 6); + + if (options.hints & V4MAPPED) { + if ((supportsALL && options.hints & ALL) || filtered.length === 0) { + map4to6(cached); + } else { + cached = filtered; + } + } else { + cached = filtered; + } + } else if (options.family === 4) { + cached = cached.filter(entry => entry.family === 4); + } + + if (options.hints & ADDRCONFIG) { + const {_iface} = this; + cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); + } + + if (cached.length === 0) { + const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; + + throw error; + } + + if (options.all) { + return cached; + } + + return cached[0]; + } + + async query(hostname) { + let cached = await this._cache.get(hostname); + + if (!cached) { + const pending = this._pending[hostname]; + + if (pending) { + cached = await pending; + } else { + const newPromise = this.queryAndCache(hostname); + this._pending[hostname] = newPromise; + + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } + } + } + + cached = cached.map(entry => { + return {...entry}; + }); + + return cached; + } + + async _resolve(hostname) { + const wrap = async promise => { + try { + return await promise; + } catch (error) { + if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { + return []; + } + + throw error; + } + }; + + // ANY is unsafe as it doesn't trigger new queries in the underlying server. + const [A, AAAA] = await Promise.all([ + this._resolve4(hostname, ttl), + this._resolve6(hostname, ttl) + ].map(promise => wrap(promise))); + + let aTtl = 0; + let aaaaTtl = 0; + let cacheTtl = 0; + + const now = Date.now(); + + for (const entry of A) { + entry.family = 4; + entry.expires = now + (entry.ttl * 1000); + + aTtl = Math.max(aTtl, entry.ttl); + } + + for (const entry of AAAA) { + entry.family = 6; + entry.expires = now + (entry.ttl * 1000); + + aaaaTtl = Math.max(aaaaTtl, entry.ttl); + } + + if (A.length > 0) { + if (AAAA.length > 0) { + cacheTtl = Math.min(aTtl, aaaaTtl); + } else { + cacheTtl = aTtl; + } + } else { + cacheTtl = aaaaTtl; + } + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl + }; + } + + async _lookup(hostname) { + try { + const entries = await this._dnsLookup(hostname, { + all: true + }); + + return { + entries, + cacheTtl: 0 + }; + } catch (_) { + return { + entries: [], + cacheTtl: 0 + }; + } + } + + async _set(hostname, data, cacheTtl) { + if (this.maxTtl > 0 && cacheTtl > 0) { + cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; + data[kExpires] = Date.now() + cacheTtl; + + try { + await this._cache.set(hostname, data, cacheTtl); + } catch (error) { + this.lookupAsync = async () => { + const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); + cacheError.cause = error; + + throw cacheError; + }; + } + + if (isIterable(this._cache)) { + this._tick(cacheTtl); + } + } + } + + async queryAndCache(hostname) { + if (this._hostnamesToFallback.has(hostname)) { + return this._dnsLookup(hostname, all); + } + + let query = await this._resolve(hostname); + + if (query.entries.length === 0 && this._fallback) { + query = await this._lookup(hostname); + + if (query.entries.length !== 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); + } + } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; + } + + _tick(ms) { + const nextRemovalTime = this._nextRemovalTime; + + if (!nextRemovalTime || ms < nextRemovalTime) { + clearTimeout(this._removalTimeout); + + this._nextRemovalTime = ms; + + this._removalTimeout = setTimeout(() => { + this._nextRemovalTime = false; + + let nextExpiry = Infinity; + + const now = Date.now(); + + for (const [hostname, entries] of this._cache) { + const expires = entries[kExpires]; + + if (now >= expires) { + this._cache.delete(hostname); + } else if (expires < nextExpiry) { + nextExpiry = expires; + } + } + + if (nextExpiry !== Infinity) { + this._tick(nextExpiry - now); + } + }, ms); + + /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ + if (this._removalTimeout.unref) { + this._removalTimeout.unref(); + } + } + } + + install(agent) { + verifyAgent(agent); + + if (kCacheableLookupCreateConnection in agent) { + throw new Error('CacheableLookup has been already installed'); + } + + agent[kCacheableLookupCreateConnection] = agent.createConnection; + agent[kCacheableLookupInstance] = this; + + agent.createConnection = (options, callback) => { + if (!('lookup' in options)) { + options.lookup = this.lookup; + } + + return agent[kCacheableLookupCreateConnection](options, callback); + }; + } + + uninstall(agent) { + verifyAgent(agent); + + if (agent[kCacheableLookupCreateConnection]) { + if (agent[kCacheableLookupInstance] !== this) { + throw new Error('The agent is not owned by this CacheableLookup instance'); + } + + agent.createConnection = agent[kCacheableLookupCreateConnection]; + + delete agent[kCacheableLookupCreateConnection]; + delete agent[kCacheableLookupInstance]; + } + } + + updateInterfaceInfo() { + const {_iface} = this; + + this._iface = getIfaceInfo(); + + if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { + this._cache.clear(); + } + } + + clear(hostname) { + if (hostname) { + this._cache.delete(hostname); + return; + } + + this._cache.clear(); + } +} + +module.exports = CacheableLookup; +module.exports.default = CacheableLookup; diff --git a/tests/node_modules/cacheable-request/LICENSE b/tests/node_modules/cacheable-request/LICENSE new file mode 100644 index 0000000..f27ee9b --- /dev/null +++ b/tests/node_modules/cacheable-request/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Luke Childs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/cacheable-request/README.md b/tests/node_modules/cacheable-request/README.md new file mode 100644 index 0000000..725e7e0 --- /dev/null +++ b/tests/node_modules/cacheable-request/README.md @@ -0,0 +1,206 @@ +# cacheable-request + +> Wrap native HTTP requests with RFC compliant cache support + +[![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) +[![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) +[![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) + +[RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters. + +**Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. + +## Features + +- Only stores cacheable responses as defined by RFC 7234 +- Fresh cache entries are served directly from cache +- Stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers +- 304 responses from revalidation requests use cached body +- Updates `Age` header on cached responses +- Can completely bypass cache on a per request basis +- In memory cache by default +- Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters +- Easily plug in your own or third-party storage adapters +- If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) +- Adds cache support to any existing HTTP code with minimal changes +- Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance + +## Install + +```shell +npm install cacheable-request +``` + +## Usage + +```js +const http = require('http'); +const CacheableRequest = require('cacheable-request'); + +// Then instead of +const req = http.request('http://example.com', cb); +req.end(); + +// You can do +const cacheableRequest = new CacheableRequest(http.request); +const cacheReq = cacheableRequest('http://example.com', cb); +cacheReq.on('request', req => req.end()); +// Future requests to 'example.com' will be returned from cache if still valid + +// You pass in any other http.request API compatible method to be wrapped with cache support: +const cacheableRequest = new CacheableRequest(https.request); +const cacheableRequest = new CacheableRequest(electron.net); +``` + +## Storage Adapters + +`cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. + +For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: + +``` +npm install @keyv/redis +``` + +And then you can pass `CacheableRequest` your connection string: + +```js +const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); +``` + +[View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) + +Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. + +e.g The following are all valid storage adapters + +```js +const storageAdapter = new Map(); +// or +const storageAdapter = require('./my-storage-adapter'); +// or +const QuickLRU = require('quick-lru'); +const storageAdapter = new QuickLRU({ maxSize: 1000 }); + +const cacheableRequest = new CacheableRequest(http.request, storageAdapter); +``` + +View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. + +## API + +### new cacheableRequest(request, [storageAdapter]) + +Returns the provided request function wrapped with cache support. + +#### request + +Type: `function` + +Request function to wrap with cache support. Should be [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) or a similar API compatible request function. + +#### storageAdapter + +Type: `Keyv storage adapter`
+Default: `new Map()` + +A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. + +### Instance + +#### cacheableRequest(opts, [cb]) + +Returns an event emitter. + +##### opts + +Type: `object`, `string` + +- Any of the default request functions options. +- Any [`http-cache-semantics`](https://github.com/kornelski/http-cache-semantics#constructor-options) options. +- Any of the following: + +###### opts.cache + +Type: `boolean`
+Default: `true` + +If the cache should be used. Setting this to false will completely bypass the cache for the current request. + +###### opts.strictTtl + +Type: `boolean`
+Default: `false` + +If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + +If set to `false` (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with `If-None-Match`/`If-Modified-Since` headers. + +###### opts.maxTtl + +Type: `number`
+Default: `undefined` + +Limits TTL. The `number` represents milliseconds. + +###### opts.automaticFailover + +Type: `boolean`
+Default: `false` + +When set to `true`, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + +###### opts.forceRefresh + +Type: `boolean`
+Default: `false` + +Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead. + +##### cb + +Type: `function` + +The callback function which will receive the response as an argument. + +The response can be either a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) or a [responselike object](https://github.com/lukechilds/responselike). The response will also have a `fromCache` property set with a boolean value. + +##### .on('request', request) + +`request` event to get the request object of the request. + +**Note:** This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the `request` event to end the request and handle any potential request errors. + +##### .on('response', response) + +`response` event to get the response object from the HTTP request or cache. + +##### .on('error', error) + +`error` event emitted in case of an error with the cache. + +Errors emitted here will be an instance of `CacheableRequest.RequestError` or `CacheableRequest.CacheError`. You will only ever receive a `RequestError` if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the `request` event. + +To properly handle all error scenarios you should use the following pattern: + +```js +cacheableRequest('example.com', cb) + .on('error', err => { + if (err instanceof CacheableRequest.CacheError) { + handleCacheError(err); // Cache error + } else if (err instanceof CacheableRequest.RequestError) { + handleRequestError(err); // Request function thrown + } + }) + .on('request', req => { + req.on('error', handleRequestError); // Request error emitted + req.end(); + }); +``` + +**Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. + +## License + +MIT © Luke Childs diff --git a/tests/node_modules/cacheable-request/package.json b/tests/node_modules/cacheable-request/package.json new file mode 100644 index 0000000..eb006f1 --- /dev/null +++ b/tests/node_modules/cacheable-request/package.json @@ -0,0 +1,92 @@ +{ + "_from": "cacheable-request@^7.0.1", + "_id": "cacheable-request@7.0.2", + "_inBundle": false, + "_integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", + "_location": "/cacheable-request", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cacheable-request@^7.0.1", + "name": "cacheable-request", + "escapedName": "cacheable-request", + "rawSpec": "^7.0.1", + "saveSpec": null, + "fetchSpec": "^7.0.1" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", + "_shasum": "ea0d0b889364a25854757301ca12b2da77f91d27", + "_spec": "cacheable-request@^7.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/got", + "author": { + "name": "Luke Childs", + "email": "lukechilds123@gmail.com", + "url": "http://lukechilds.co.uk" + }, + "bugs": { + "url": "https://github.com/lukechilds/cacheable-request/issues" + }, + "bundleDependencies": false, + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" + }, + "deprecated": false, + "description": "Wrap native HTTP requests with RFC compliant cache support", + "devDependencies": { + "@keyv/sqlite": "^2.0.0", + "ava": "^1.1.0", + "coveralls": "^3.0.0", + "create-test-server": "3.0.0", + "delay": "^4.0.0", + "eslint-config-xo-lukechilds": "^1.0.0", + "nyc": "^14.1.1", + "pify": "^4.0.0", + "sqlite3": "^4.0.2", + "this": "^1.0.2", + "xo": "^0.23.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "src" + ], + "homepage": "https://github.com/lukechilds/cacheable-request#readme", + "keywords": [ + "HTTP", + "HTTPS", + "cache", + "caching", + "layer", + "cacheable", + "RFC 7234", + "RFC", + "7234", + "compliant" + ], + "license": "MIT", + "main": "src/index.js", + "name": "cacheable-request", + "repository": { + "type": "git", + "url": "git+https://github.com/lukechilds/cacheable-request.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov | coveralls", + "test": "xo && nyc ava" + }, + "version": "7.0.2", + "xo": { + "extends": "xo-lukechilds" + } +} diff --git a/tests/node_modules/cacheable-request/src/index.js b/tests/node_modules/cacheable-request/src/index.js new file mode 100644 index 0000000..3fcea3f --- /dev/null +++ b/tests/node_modules/cacheable-request/src/index.js @@ -0,0 +1,251 @@ +'use strict'; + +const EventEmitter = require('events'); +const urlLib = require('url'); +const normalizeUrl = require('normalize-url'); +const getStream = require('get-stream'); +const CachePolicy = require('http-cache-semantics'); +const Response = require('responselike'); +const lowercaseKeys = require('lowercase-keys'); +const cloneResponse = require('clone-response'); +const Keyv = require('keyv'); + +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } + + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); + + return this.createCacheableRequest(request); + } + + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } + + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); + + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; + + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; + + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + + (async () => { + try { + const bodyPromise = getStream.buffer(response); + + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); + + if (requestErrored) { + return; + } + + const body = await bodyPromise; + + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } + + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; + + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + + (async () => { + const get = async opts => { + await Promise.resolve(); + + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } + + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; + + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; + + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); + + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } + + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + + return ee; + }; + } +} + +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} + +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} + +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } +}; + +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; + +module.exports = CacheableRequest; diff --git a/tests/node_modules/call-bind/.eslintignore b/tests/node_modules/call-bind/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/call-bind/.eslintrc b/tests/node_modules/call-bind/.eslintrc new file mode 100644 index 0000000..e5d3c9a --- /dev/null +++ b/tests/node_modules/call-bind/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + "operator-linebreak": [2, "before"], + }, +} diff --git a/tests/node_modules/call-bind/.github/FUNDING.yml b/tests/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 0000000..c70c2ec --- /dev/null +++ b/tests/node_modules/call-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/call-bind/.nycrc b/tests/node_modules/call-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/tests/node_modules/call-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/call-bind/CHANGELOG.md b/tests/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 0000000..62a3727 --- /dev/null +++ b/tests/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/tests/node_modules/call-bind/LICENSE b/tests/node_modules/call-bind/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/tests/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/call-bind/README.md b/tests/node_modules/call-bind/README.md new file mode 100644 index 0000000..53649eb --- /dev/null +++ b/tests/node_modules/call-bind/README.md @@ -0,0 +1,2 @@ +# call-bind +Robustly `.call.bind()` a function. diff --git a/tests/node_modules/call-bind/callBound.js b/tests/node_modules/call-bind/callBound.js new file mode 100644 index 0000000..8374adf --- /dev/null +++ b/tests/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/tests/node_modules/call-bind/index.js b/tests/node_modules/call-bind/index.js new file mode 100644 index 0000000..6fa3e4a --- /dev/null +++ b/tests/node_modules/call-bind/index.js @@ -0,0 +1,47 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/tests/node_modules/call-bind/package.json b/tests/node_modules/call-bind/package.json new file mode 100644 index 0000000..48bf50b --- /dev/null +++ b/tests/node_modules/call-bind/package.json @@ -0,0 +1,123 @@ +{ + "_from": "call-bind@^1.0.2", + "_id": "call-bind@1.0.2", + "_inBundle": false, + "_integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "_location": "/call-bind", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "call-bind@^1.0.2", + "name": "call-bind", + "escapedName": "call-bind", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/deep-equal", + "/es-abstract", + "/es-get-iterator", + "/is-arguments", + "/is-boolean-object", + "/is-regex", + "/is-typed-array", + "/object-is", + "/object.assign", + "/regexp.prototype.flags", + "/side-channel", + "/string.prototype.trim", + "/string.prototype.trimend", + "/string.prototype.trimstart", + "/tape", + "/which-typed-array" + ], + "_resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "_shasum": "b1d4e89e688119c3c9a903ad30abb2f6a919be3c", + "_spec": "call-bind@^1.0.2", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tape", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "bundleDependencies": false, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "deprecated": false, + "description": "Robustly `.call.bind()` a function", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.17.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.1.1" + }, + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./callBound": [ + { + "default": "./callBound.js" + }, + "./callBound.js" + ], + "./package.json": "./package.json" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "license": "MIT", + "main": "index.js", + "name": "call-bind", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind.git" + }, + "scripts": { + "lint": "eslint --ext=.js,.mjs .", + "posttest": "aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/*'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "version": "1.0.2" +} diff --git a/tests/node_modules/call-bind/test/callBound.js b/tests/node_modules/call-bind/test/callBound.js new file mode 100644 index 0000000..209ce3c --- /dev/null +++ b/tests/node_modules/call-bind/test/callBound.js @@ -0,0 +1,55 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + /* globals WeakRef: false */ + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/tests/node_modules/call-bind/test/index.js b/tests/node_modules/call-bind/test/index.js new file mode 100644 index 0000000..bf6769c --- /dev/null +++ b/tests/node_modules/call-bind/test/index.js @@ -0,0 +1,66 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); + +var test = require('tape'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + var sentinel = { sentinel: true }; + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [1, 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [1, 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/tests/node_modules/chalk/index.js b/tests/node_modules/chalk/index.js new file mode 100644 index 0000000..2d85a91 --- /dev/null +++ b/tests/node_modules/chalk/index.js @@ -0,0 +1,116 @@ +'use strict'; +var escapeStringRegexp = require('escape-string-regexp'); +var ansiStyles = require('ansi-styles'); +var stripAnsi = require('strip-ansi'); +var hasAnsi = require('has-ansi'); +var supportsColor = require('supports-color'); +var defineProps = Object.defineProperties; +var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); + +function Chalk(options) { + // detect mode if not set manually + this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; +} + +// use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001b[94m'; +} + +var styles = (function () { + var ret = {}; + + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + ret[key] = { + get: function () { + return build.call(this, this._styles.concat(key)); + } + }; + }); + + return ret; +})(); + +var proto = defineProps(function chalk() {}, styles); + +function build(_styles) { + var builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder.enabled = this.enabled; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + /* eslint-disable no-proto */ + builder.__proto__ = proto; + + return builder; +} + +function applyStyle() { + // support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + + if (argsLen > 1) { + // don't slice `arguments`, it prevents v8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || !str) { + return str; + } + + var nestedStyles = this._styles; + var i = nestedStyles.length; + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + var originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { + ansiStyles.dim.open = ''; + } + + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. + ansiStyles.dim.open = originalDim; + + return str; +} + +function init() { + var ret = {}; + + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build.call(this, [name]); + } + }; + }); + + return ret; +} + +defineProps(Chalk.prototype, init()); + +module.exports = new Chalk(); +module.exports.styles = ansiStyles; +module.exports.hasColor = hasAnsi; +module.exports.stripColor = stripAnsi; +module.exports.supportsColor = supportsColor; diff --git a/tests/node_modules/chalk/license b/tests/node_modules/chalk/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/tests/node_modules/chalk/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/chalk/package.json b/tests/node_modules/chalk/package.json new file mode 100644 index 0000000..d8eb0a9 --- /dev/null +++ b/tests/node_modules/chalk/package.json @@ -0,0 +1,114 @@ +{ + "_from": "chalk@^1.0.0", + "_id": "chalk@1.1.3", + "_inBundle": false, + "_integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "_location": "/chalk", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "chalk@^1.0.0", + "name": "chalk", + "escapedName": "chalk", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/tap-spec" + ], + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "_shasum": "a8115c55e4a702fe4d150abd3872822a7e09fc98", + "_spec": "chalk@^1.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tap-spec", + "bugs": { + "url": "https://github.com/chalk/chalk/issues" + }, + "bundleDependencies": false, + "dependencies": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + }, + "deprecated": false, + "description": "Terminal string styling done right. Much color.", + "devDependencies": { + "coveralls": "^2.11.2", + "matcha": "^0.6.0", + "mocha": "*", + "nyc": "^3.0.0", + "require-uncached": "^1.0.2", + "resolve-from": "^1.0.0", + "semver": "^4.3.3", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/chalk/chalk#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "maintainers": [ + { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + { + "name": "Joshua Appelman", + "email": "jappelman@xebia.com", + "url": "jbnicolai.com" + }, + { + "name": "JD Ballard", + "email": "i.am.qix@gmail.com", + "url": "github.com/qix-" + } + ], + "name": "chalk", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/chalk.git" + }, + "scripts": { + "bench": "matcha benchmark.js", + "coverage": "nyc npm test && nyc report", + "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls", + "test": "xo && mocha" + }, + "version": "1.1.3", + "xo": { + "envs": [ + "node", + "mocha" + ] + } +} diff --git a/tests/node_modules/chalk/readme.md b/tests/node_modules/chalk/readme.md new file mode 100644 index 0000000..5cf111e --- /dev/null +++ b/tests/node_modules/chalk/readme.md @@ -0,0 +1,213 @@ +

+
+
+ chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) +[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master) +[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) + + +[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough. + +**Chalk is a clean and focused alternative.** + +![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png) + + +## Why + +- Highly performant +- Doesn't extend `String.prototype` +- Expressive API +- Ability to nest styles +- Clean and focused +- Auto-detects color support +- Actively maintained +- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015 + + +## Install + +``` +$ npm install --save chalk +``` + + +## Usage + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +var chalk = require('chalk'); + +// style a string +chalk.blue('Hello world!'); + +// combine styled and normal strings +chalk.blue('Hello') + 'World' + chalk.red('!'); + +// compose multiple styles using the chainable API +chalk.blue.bgRed.bold('Hello world!'); + +// pass in multiple arguments +chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'); + +// nest styles +chalk.red('Hello', chalk.underline.bgBlue('world') + '!'); + +// nest styles of the same type even (color, underline, background) +chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +); +``` + +Easily define your own themes. + +```js +var chalk = require('chalk'); +var error = chalk.bold.red; +console.log(error('Error!')); +``` + +Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data). + +```js +var name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> Hello Sindre +``` + + +## API + +### chalk.` + + + + + + diff --git a/tests/node_modules/tape-es/node_modules/tape/example/static/server.js b/tests/node_modules/tape-es/node_modules/tape/example/static/server.js new file mode 100644 index 0000000..80cea43 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/static/server.js @@ -0,0 +1,4 @@ +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(ecstatic); +server.listen(8000); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/stream/object.js b/tests/node_modules/tape-es/node_modules/tape/example/stream/object.js new file mode 100644 index 0000000..20f0819 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/stream/object.js @@ -0,0 +1,10 @@ +var test = require('../../'); +var path = require('path'); + +test.createStream({ objectMode: true }).on('data', function (row) { + console.log(JSON.stringify(row)); +}); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/stream/tap.js b/tests/node_modules/tape-es/node_modules/tape/example/stream/tap.js new file mode 100644 index 0000000..9ea9ff7 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/stream/tap.js @@ -0,0 +1,8 @@ +var test = require('../../'); +var path = require('path'); + +test.createStream().pipe(process.stdout); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/stream/test/x.js b/tests/node_modules/tape-es/node_modules/tape/example/stream/test/x.js new file mode 100644 index 0000000..7dbb98a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/stream/test/x.js @@ -0,0 +1,5 @@ +var test = require('../../../'); +test(function (t) { + t.plan(1); + t.equal('beep', 'boop'); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/stream/test/y.js b/tests/node_modules/tape-es/node_modules/tape/example/stream/test/y.js new file mode 100644 index 0000000..28606d5 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/stream/test/y.js @@ -0,0 +1,11 @@ +var test = require('../../../'); +test(function (t) { + t.plan(2); + t.equal(1+1, 2); + t.ok(true); +}); + +test('wheee', function (t) { + t.ok(true); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/throw.js b/tests/node_modules/tape-es/node_modules/tape/example/throw.js new file mode 100644 index 0000000..ef82c3a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/throw.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = require('../'); + +test('throw', function (t) { + t.plan(2); + + setTimeout(function () { + throw new Error('doom'); + }, 100); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/timing.js b/tests/node_modules/tape-es/node_modules/tape/example/timing.js new file mode 100644 index 0000000..614c144 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/timing.js @@ -0,0 +1,12 @@ +var test = require('../'); + +test('timing test', function (t) { + t.plan(2); + + t.equal(typeof Date.now, 'function'); + var start = new Date; + + setTimeout(function () { + t.equal(new Date - start, 100); + }, 100); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/too_many.js b/tests/node_modules/tape-es/node_modules/tape/example/too_many.js new file mode 100644 index 0000000..cdcb5ee --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/too_many.js @@ -0,0 +1,35 @@ +var falafel = require('falafel'); +var test = require('../'); + +test('array', function (t) { + t.plan(3); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/example/two.js b/tests/node_modules/tape-es/node_modules/tape/example/two.js new file mode 100644 index 0000000..78e49c3 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/example/two.js @@ -0,0 +1,18 @@ +var test = require('../'); + +test('one', function (t) { + t.plan(2); + t.ok(true); + setTimeout(function () { + t.equal(1+3, 4); + }, 100); +}); + +test('two', function (t) { + t.plan(3); + t.equal(5, 2+3); + setTimeout(function () { + t.equal('a'.charCodeAt(0), 97); + t.ok(true); + }, 50); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/index.js b/tests/node_modules/tape-es/node_modules/tape/index.js new file mode 100644 index 0000000..7ab2951 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/index.js @@ -0,0 +1,150 @@ +var defined = require('defined'); +var createDefaultStream = require('./lib/default_stream'); +var Test = require('./lib/test'); +var createResult = require('./lib/results'); +var through = require('through'); + +var canEmitExit = typeof process !== 'undefined' && process + && typeof process.on === 'function' && process.browser !== true +; +var canExit = typeof process !== 'undefined' && process + && typeof process.exit === 'function' +; + +exports = module.exports = (function () { + var harness; + var lazyLoad = function () { + return getHarness().apply(this, arguments); + }; + + lazyLoad.only = function () { + return getHarness().only.apply(this, arguments); + }; + + lazyLoad.createStream = function (opts) { + if (!opts) opts = {}; + if (!harness) { + var output = through(); + getHarness({ stream: output, objectMode: opts.objectMode }); + return output; + } + return harness.createStream(opts); + }; + + lazyLoad.onFinish = function () { + return getHarness().onFinish.apply(this, arguments); + }; + + lazyLoad.onFailure = function () { + return getHarness().onFailure.apply(this, arguments); + }; + + lazyLoad.getHarness = getHarness; + + return lazyLoad; + + function getHarness(opts) { + if (!opts) opts = {}; + opts.autoclose = !canEmitExit; + if (!harness) harness = createExitHarness(opts); + return harness; + } +})(); + +function createExitHarness(conf) { + if (!conf) conf = {}; + var harness = createHarness({ + autoclose: defined(conf.autoclose, false) + }); + + var stream = harness.createStream({ objectMode: conf.objectMode }); + var es = stream.pipe(conf.stream || createDefaultStream()); + if (canEmitExit) { + es.on('error', function (err) { harness._exitCode = 1; }); + } + + var ended = false; + stream.on('end', function () { ended = true; }); + + if (conf.exit === false) return harness; + if (!canEmitExit || !canExit) return harness; + + process.on('exit', function (code) { + // let the process exit cleanly. + if (code !== 0) { + return; + } + + if (!ended) { + var only = harness._results._only; + for (var i = 0; i < harness._tests.length; i++) { + var t = harness._tests[i]; + if (only && t !== only) continue; + t._exit(); + } + } + harness.close(); + process.exit(code || harness._exitCode); + }); + + return harness; +} + +exports.createHarness = createHarness; +exports.Test = Test; +exports.test = exports; // tap compat +exports.test.skip = Test.skip; + +function createHarness(conf_) { + if (!conf_) conf_ = {}; + var results = createResult(); + if (conf_.autoclose !== false) { + results.once('done', function () { results.close(); }); + } + + var test = function (name, conf, cb) { + var t = new Test(name, conf, cb); + test._tests.push(t); + + (function inspectCode(st) { + st.on('test', function sub(st_) { + inspectCode(st_); + }); + st.on('result', function (r) { + if (!r.todo && !r.ok && typeof r !== 'string') test._exitCode = 1; + }); + })(t); + + results.push(t); + return t; + }; + test._results = results; + + test._tests = []; + + test.createStream = function (opts) { + return results.createStream(opts); + }; + + test.onFinish = function (cb) { + results.on('done', cb); + }; + + test.onFailure = function (cb) { + results.on('fail', cb); + }; + + var only = false; + test.only = function () { + if (only) throw new Error('there can only be one only test'); + only = true; + var t = test.apply(null, arguments); + results.only(t); + return t; + }; + test._exitCode = 0; + + test.close = function () { results.close(); }; + + return test; +} diff --git a/tests/node_modules/tape-es/node_modules/tape/lib/default_stream.js b/tests/node_modules/tape-es/node_modules/tape/lib/default_stream.js new file mode 100644 index 0000000..2744258 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/lib/default_stream.js @@ -0,0 +1,30 @@ +var through = require('through'); +var fs = require('fs'); + +module.exports = function () { + var line = ''; + var stream = through(write, flush); + return stream; + + function write(buf) { + for (var i = 0; i < buf.length; i++) { + var c = typeof buf === 'string' + ? buf.charAt(i) + : String.fromCharCode(buf[i]) + ; + if (c === '\n') flush(); + else line += c; + } + } + + function flush() { + if (fs.writeSync && /^win/.test(process.platform)) { + try { fs.writeSync(1, line + '\n'); } + catch (e) { stream.emit('error', e); } + } else { + try { console.log(line); } + catch (e) { stream.emit('error', e); } + } + line = ''; + } +}; diff --git a/tests/node_modules/tape-es/node_modules/tape/lib/results.js b/tests/node_modules/tape-es/node_modules/tape/lib/results.js new file mode 100644 index 0000000..89da4b0 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/lib/results.js @@ -0,0 +1,214 @@ +var defined = require('defined'); +var EventEmitter = require('events').EventEmitter; +var inherits = require('inherits'); +var through = require('through'); +var resumer = require('resumer'); +var inspect = require('object-inspect'); +var bind = require('function-bind'); +var has = require('has'); +var regexpTest = bind.call(Function.call, RegExp.prototype.test); +var yamlIndicators = /\:|\-|\?/; +var nextTick = typeof setImmediate !== 'undefined' + ? setImmediate + : process.nextTick +; + +module.exports = Results; +inherits(Results, EventEmitter); + +function coalesceWhiteSpaces(str) { + return String(str).replace(/\s+/g, ' '); +} + +function Results() { + if (!(this instanceof Results)) return new Results; + this.count = 0; + this.fail = 0; + this.pass = 0; + this.todo = 0; + this._stream = through(); + this.tests = []; + this._only = null; + this._isRunning = false; +} + +Results.prototype.createStream = function (opts) { + if (!opts) opts = {}; + var self = this; + var output, testId = 0; + if (opts.objectMode) { + output = through(); + self.on('_push', function ontest(t, extra) { + if (!extra) extra = {}; + var id = testId++; + t.once('prerun', function () { + var row = { + type: 'test', + name: t.name, + id: id, + skip: t._skip, + todo: t._todo + }; + if (has(extra, 'parent')) { + row.parent = extra.parent; + } + output.queue(row); + }); + t.on('test', function (st) { + ontest(st, { parent: id }); + }); + t.on('result', function (res) { + if (res && typeof res === 'object') { + res.test = id; + res.type = 'assert'; + } + output.queue(res); + }); + t.on('end', function () { + output.queue({ type: 'end', test: id }); + }); + }); + self.on('done', function () { output.queue(null); }); + } else { + output = resumer(); + output.queue('TAP version 13\n'); + self._stream.pipe(output); + } + + if (!this._isRunning) { + this._isRunning = true; + nextTick(function next() { + var t; + while (t = getNextTest(self)) { + t.run(); + if (!t.ended) return t.once('end', function () { nextTick(next); }); + } + self.emit('done'); + }); + } + + return output; +}; + +Results.prototype.push = function (t) { + var self = this; + self.tests.push(t); + self._watch(t); + self.emit('_push', t); +}; + +Results.prototype.only = function (t) { + this._only = t; +}; + +Results.prototype._watch = function (t) { + var self = this; + var write = function (s) { self._stream.queue(s); }; + t.once('prerun', function () { + var premsg = ''; + if (t._skip) premsg = 'SKIP '; + else if (t._todo) premsg = 'TODO '; + write('# ' + premsg + coalesceWhiteSpaces(t.name) + '\n'); + }); + + t.on('result', function (res) { + if (typeof res === 'string') { + write('# ' + res + '\n'); + return; + } + write(encodeResult(res, self.count + 1)); + self.count ++; + + if (res.ok || res.todo) self.pass ++; + else { + self.fail ++; + self.emit('fail'); + } + }); + + t.on('test', function (st) { self._watch(st); }); +}; + +Results.prototype.close = function () { + var self = this; + if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED')); + self.closed = true; + var write = function (s) { self._stream.queue(s); }; + + write('\n1..' + self.count + '\n'); + write('# tests ' + self.count + '\n'); + write('# pass ' + (self.pass + self.todo) + '\n'); + if (self.todo) write('# todo ' + self.todo + '\n'); + if (self.fail) write('# fail ' + self.fail + '\n'); + else write('\n# ok\n'); + + self._stream.queue(null); +}; + +function encodeResult(res, count) { + var output = ''; + output += (res.ok ? 'ok ' : 'not ok ') + count; + output += res.name ? ' ' + coalesceWhiteSpaces(res.name) : ''; + + if (res.skip) { + output += ' # SKIP' + ((typeof res.skip === 'string') ? ' ' + coalesceWhiteSpaces(res.skip) : ''); + } else if (res.todo) { + output += ' # TODO' + ((typeof res.todo === 'string') ? ' ' + coalesceWhiteSpaces(res.todo) : ''); + }; + + output += '\n'; + if (res.ok) return output; + + var outer = ' '; + var inner = outer + ' '; + output += outer + '---\n'; + output += inner + 'operator: ' + res.operator + '\n'; + + if (has(res, 'expected') || has(res, 'actual')) { + var ex = inspect(res.expected, {depth: res.objectPrintDepth}); + var ac = inspect(res.actual, {depth: res.objectPrintDepth}); + + if (Math.max(ex.length, ac.length) > 65 || invalidYaml(ex) || invalidYaml(ac)) { + output += inner + 'expected: |-\n' + inner + ' ' + ex + '\n'; + output += inner + 'actual: |-\n' + inner + ' ' + ac + '\n'; + } else { + output += inner + 'expected: ' + ex + '\n'; + output += inner + 'actual: ' + ac + '\n'; + } + } + if (res.at) { + output += inner + 'at: ' + res.at + '\n'; + } + + var actualStack = res.actual && (typeof res.actual === 'object' || typeof res.actual === 'function') ? res.actual.stack : undefined; + var errorStack = res.error && res.error.stack; + var stack = defined(actualStack, errorStack); + if (stack) { + var lines = String(stack).split('\n'); + output += inner + 'stack: |-\n'; + for (var i = 0; i < lines.length; i++) { + output += inner + ' ' + lines[i] + '\n'; + } + } + + output += outer + '...\n'; + return output; +} + +function getNextTest(results) { + if (!results._only) { + return results.tests.shift(); + } + + do { + var t = results.tests.shift(); + if (!t) continue; + if (results._only === t) { + return t; + } + } while (results.tests.length !== 0); +} + +function invalidYaml(str) { + return regexpTest(yamlIndicators, str); +} diff --git a/tests/node_modules/tape-es/node_modules/tape/lib/test.js b/tests/node_modules/tape-es/node_modules/tape/lib/test.js new file mode 100644 index 0000000..3e75ee2 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/lib/test.js @@ -0,0 +1,599 @@ +var deepEqual = require('deep-equal'); +var defined = require('defined'); +var path = require('path'); +var inherits = require('inherits'); +var EventEmitter = require('events').EventEmitter; +var has = require('has'); +var isRegExp = require('is-regex'); +var trim = require('string.prototype.trim'); +var bind = require('function-bind'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); +var toLowerCase = bind.call(Function.call, String.prototype.toLowerCase); +var $test = bind.call(Function.call, RegExp.prototype.test); + +module.exports = Test; + +var nextTick = typeof setImmediate !== 'undefined' + ? setImmediate + : process.nextTick; +var safeSetTimeout = setTimeout; +var safeClearTimeout = clearTimeout; + +inherits(Test, EventEmitter); + +var getTestArgs = function (name_, opts_, cb_) { + var name = '(anonymous)'; + var opts = {}; + var cb; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + var t = typeof arg; + if (t === 'string') { + name = arg; + } else if (t === 'object') { + opts = arg || opts; + } else if (t === 'function') { + cb = arg; + } + } + return { name: name, opts: opts, cb: cb }; +}; + +function Test(name_, opts_, cb_) { + if (! (this instanceof Test)) { + return new Test(name_, opts_, cb_); + } + + var args = getTestArgs(name_, opts_, cb_); + + this.readable = true; + this.name = args.name || '(anonymous)'; + this.assertCount = 0; + this.pendingCount = 0; + this._skip = args.opts.skip || false; + this._todo = args.opts.todo || false; + this._timeout = args.opts.timeout; + this._plan = undefined; + this._cb = args.cb; + this._progeny = []; + this._ok = true; + var depthEnvVar = process.env.NODE_TAPE_OBJECT_PRINT_DEPTH; + if (args.opts.objectPrintDepth) { + this._objectPrintDepth = args.opts.objectPrintDepth; + } else if (depthEnvVar) { + if (toLowerCase(depthEnvVar) === 'infinity') { + this._objectPrintDepth = Infinity; + } else { + this._objectPrintDepth = depthEnvVar; + } + } else { + this._objectPrintDepth = 5; + } + + for (var prop in this) { + this[prop] = (function bind(self, val) { + if (typeof val === 'function') { + return function bound() { + return val.apply(self, arguments); + }; + } + return val; + })(this, this[prop]); + } +} + +Test.prototype.run = function () { + this.emit('prerun'); + if (!this._cb || this._skip) { + return this._end(); + } + if (this._timeout != null) { + this.timeoutAfter(this._timeout); + } + this._cb(this); + this.emit('run'); +}; + +Test.prototype.test = function (name, opts, cb) { + var self = this; + var t = new Test(name, opts, cb); + this._progeny.push(t); + this.pendingCount++; + this.emit('test', t); + t.on('prerun', function () { + self.assertCount++; + }); + + if (!self._pendingAsserts()) { + nextTick(function () { + self._end(); + }); + } + + nextTick(function () { + if (!self._plan && self.pendingCount == self._progeny.length) { + self._end(); + } + }); +}; + +Test.prototype.comment = function (msg) { + var that = this; + forEach(trim(msg).split('\n'), function (aMsg) { + that.emit('result', trim(aMsg).replace(/^#\s*/, '')); + }); +}; + +Test.prototype.plan = function (n) { + this._plan = n; + this.emit('plan', n); +}; + +Test.prototype.timeoutAfter = function (ms) { + if (!ms) throw new Error('timeoutAfter requires a timespan'); + var self = this; + var timeout = safeSetTimeout(function () { + self.fail('test timed out after ' + ms + 'ms'); + self.end(); + }, ms); + this.once('end', function () { + safeClearTimeout(timeout); + }); +}; + +Test.prototype.end = function (err) { + var self = this; + if (arguments.length >= 1 && !!err) { + this.ifError(err); + } + + if (this.calledEnd) { + this.fail('.end() called twice'); + } + this.calledEnd = true; + this._end(); +}; + +Test.prototype._end = function (err) { + var self = this; + if (this._progeny.length) { + var t = this._progeny.shift(); + t.on('end', function () { self._end(); }); + t.run(); + return; + } + + if (!this.ended) this.emit('end'); + var pendingAsserts = this._pendingAsserts(); + if (!this._planError && this._plan !== undefined && pendingAsserts) { + this._planError = true; + this.fail('plan != count', { + expected: this._plan, + actual: this.assertCount + }); + } + this.ended = true; +}; + +Test.prototype._exit = function () { + if (this._plan !== undefined && + !this._planError && this.assertCount !== this._plan) { + this._planError = true; + this.fail('plan != count', { + expected: this._plan, + actual: this.assertCount, + exiting: true + }); + } else if (!this.ended) { + this.fail('test exited without ending: ' + this.name, { + exiting: true + }); + } +}; + +Test.prototype._pendingAsserts = function () { + if (this._plan === undefined) { + return 1; + } + return this._plan - (this._progeny.length + this.assertCount); +}; + +Test.prototype._assert = function assert(ok, opts) { + var self = this; + var extra = opts.extra || {}; + + ok = !!ok || !!extra.skip; + + var res = { + id: self.assertCount++, + ok: ok, + skip: defined(extra.skip, opts.skip), + todo: defined(extra.todo, opts.todo, self._todo), + name: defined(extra.message, opts.message, '(unnamed assert)'), + operator: defined(extra.operator, opts.operator), + objectPrintDepth: self._objectPrintDepth + }; + if (has(opts, 'actual') || has(extra, 'actual')) { + res.actual = defined(extra.actual, opts.actual); + } + if (has(opts, 'expected') || has(extra, 'expected')) { + res.expected = defined(extra.expected, opts.expected); + } + this._ok = !!(this._ok && ok); + + if (!ok && !res.todo) { + res.error = defined(extra.error, opts.error, new Error(res.name)); + } + + if (!ok) { + var e = new Error('exception'); + var err = (e.stack || '').split('\n'); + var dir = __dirname + path.sep; + + for (var i = 0; i < err.length; i++) { + /* + Stack trace lines may resemble one of the following. We need + to correctly extract a function name (if any) and path / line + number for each line. + + at myFunction (/path/to/file.js:123:45) + at myFunction (/path/to/file.other-ext:123:45) + at myFunction (/path to/file.js:123:45) + at myFunction (C:\path\to\file.js:123:45) + at myFunction (/path/to/file.js:123) + at Test. (/path/to/file.js:123:45) + at Test.bound [as run] (/path/to/file.js:123:45) + at /path/to/file.js:123:45 + + Regex has three parts. First is non-capturing group for 'at ' + (plus anything preceding it). + + /^(?:[^\s]*\s*\bat\s+)/ + + Second captures function call description (optional). This is + not necessarily a valid JS function name, but just what the + stack trace is using to represent a function call. It may look + like `` or 'Test.bound [as run]'. + + For our purposes, we assume that, if there is a function + name, it's everything leading up to the first open + parentheses (trimmed) before our pathname. + + /(?:(.*)\s+\()?/ + + Last part captures file path plus line no (and optional + column no). + + /((?:\/|[a-zA-Z]:\\)[^:\)]+:(\d+)(?::(\d+))?)\)?/ + */ + var re = /^(?:[^\s]*\s*\bat\s+)(?:(.*)\s+\()?((?:\/|[a-zA-Z]:\\)[^:\)]+:(\d+)(?::(\d+))?)\)?$/; + var lineWithTokens = err[i].replace(process.cwd(), '/\$CWD').replace(__dirname, '/\$TEST'); + var m = re.exec(lineWithTokens); + + if (!m) { + continue; + } + + var callDescription = m[1] || ''; + var filePath = m[2].replace('/$CWD', process.cwd()).replace('/$TEST', __dirname); + + if (filePath.slice(0, dir.length) === dir) { + continue; + } + + // Function call description may not (just) be a function name. + // Try to extract function name by looking at first "word" only. + res.functionName = callDescription.split(/\s+/)[0]; + res.file = filePath; + res.line = Number(m[3]); + if (m[4]) res.column = Number(m[4]); + + res.at = callDescription + ' (' + filePath + ')'; + break; + } + } + + self.emit('result', res); + + var pendingAsserts = self._pendingAsserts(); + if (!pendingAsserts) { + if (extra.exiting) { + self._end(); + } else { + nextTick(function () { + self._end(); + }); + } + } + + if (!self._planError && pendingAsserts < 0) { + self._planError = true; + self.fail('plan != count', { + expected: self._plan, + actual: self._plan - pendingAsserts + }); + } +}; + +Test.prototype.fail = function (msg, extra) { + this._assert(false, { + message: msg, + operator: 'fail', + extra: extra + }); +}; + +Test.prototype.pass = function (msg, extra) { + this._assert(true, { + message: msg, + operator: 'pass', + extra: extra + }); +}; + +Test.prototype.skip = function (msg, extra) { + this._assert(true, { + message: msg, + operator: 'skip', + skip: true, + extra: extra + }); +}; + +function assert(value, msg, extra) { + this._assert(value, { + message: defined(msg, 'should be truthy'), + operator: 'ok', + expected: true, + actual: value, + extra: extra + }); +} +Test.prototype.ok += Test.prototype['true'] += Test.prototype.assert += assert; + +function notOK(value, msg, extra) { + this._assert(!value, { + message: defined(msg, 'should be falsy'), + operator: 'notOk', + expected: false, + actual: value, + extra: extra + }); +} +Test.prototype.notOk += Test.prototype['false'] += Test.prototype.notok += notOK; + +function error(err, msg, extra) { + this._assert(!err, { + message: defined(msg, String(err)), + operator: 'error', + actual: err, + extra: extra + }); +} +Test.prototype.error += Test.prototype.ifError += Test.prototype.ifErr += Test.prototype.iferror += error; + +function equal(a, b, msg, extra) { + this._assert(a === b, { + message: defined(msg, 'should be equal'), + operator: 'equal', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.equal += Test.prototype.equals += Test.prototype.isEqual += Test.prototype.is += Test.prototype.strictEqual += Test.prototype.strictEquals += equal; + +function notEqual(a, b, msg, extra) { + this._assert(a !== b, { + message: defined(msg, 'should not be equal'), + operator: 'notEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notEqual += Test.prototype.notEquals += Test.prototype.notStrictEqual += Test.prototype.notStrictEquals += Test.prototype.isNotEqual += Test.prototype.isNot += Test.prototype.not += Test.prototype.doesNotEqual += Test.prototype.isInequal += notEqual; + +function tapeDeepEqual(a, b, msg, extra) { + this._assert(deepEqual(a, b, { strict: true }), { + message: defined(msg, 'should be equivalent'), + operator: 'deepEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.deepEqual += Test.prototype.deepEquals += Test.prototype.isEquivalent += Test.prototype.same += tapeDeepEqual; + +function deepLooseEqual(a, b, msg, extra) { + this._assert(deepEqual(a, b), { + message: defined(msg, 'should be equivalent'), + operator: 'deepLooseEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.deepLooseEqual += Test.prototype.looseEqual += Test.prototype.looseEquals += deepLooseEqual; + +function notDeepEqual(a, b, msg, extra) { + this._assert(!deepEqual(a, b, { strict: true }), { + message: defined(msg, 'should not be equivalent'), + operator: 'notDeepEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notDeepEqual += Test.prototype.notDeepEquals += Test.prototype.notEquivalent += Test.prototype.notDeeply += Test.prototype.notSame += Test.prototype.isNotDeepEqual += Test.prototype.isNotDeeply += Test.prototype.isNotEquivalent += Test.prototype.isInequivalent += notDeepEqual; + +function notDeepLooseEqual(a, b, msg, extra) { + this._assert(!deepEqual(a, b), { + message: defined(msg, 'should be equivalent'), + operator: 'notDeepLooseEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notDeepLooseEqual += Test.prototype.notLooseEqual += Test.prototype.notLooseEquals += notDeepLooseEqual; + +Test.prototype['throws'] = function (fn, expected, msg, extra) { + if (typeof expected === 'string') { + msg = expected; + expected = undefined; + } + + var caught = undefined; + + try { + fn(); + } catch (err) { + caught = { error: err }; + if ((err != null) && (!isEnumerable(err, 'message') || !has(err, 'message'))) { + var message = err.message; + delete err.message; + err.message = message; + } + } + + var passed = caught; + + if (isRegExp(expected)) { + passed = expected.test(caught && caught.error); + expected = String(expected); + } + + if (typeof expected === 'function' && caught) { + passed = caught.error instanceof expected; + } + + this._assert(typeof fn === 'function' && passed, { + message: defined(msg, 'should throw'), + operator: 'throws', + actual: caught && caught.error, + expected: expected, + error: !passed && caught && caught.error, + extra: extra + }); +}; + +Test.prototype.doesNotThrow = function (fn, expected, msg, extra) { + if (typeof expected === 'string') { + msg = expected; + expected = undefined; + } + var caught = undefined; + try { + fn(); + } + catch (err) { + caught = { error: err }; + } + this._assert(!caught, { + message: defined(msg, 'should not throw'), + operator: 'throws', + actual: caught && caught.error, + expected: expected, + error: caught && caught.error, + extra: extra + }); +}; + +Test.prototype.match = function match(string, regexp, msg, extra) { + if (!isRegExp(regexp)) { + throw new TypeError('The "regexp" argument must be an instance of RegExp. Received type ' + typeof regexp + ' (' + inspect(regexp) + ')'); + } + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be of type string. Received type ' + typeof string + ' (' + inspect(string) + ')'); + } + + var matches = $test(regexp, string); + var message = defined( + msg, + 'The input ' + (matches ? 'matched' : 'did not match') + ' the regular expression ' + inspect(regexp) + '. Input: ' + inspect(string) + ); + this._assert(matches, { + message: message, + operator: 'match', + actual: string, + expected: regexp, + extra: extra + }); +}; + +Test.prototype.doesNotMatch = function doesNotMatch(string, regexp, msg, extra) { + if (!isRegExp(regexp)) { + throw new TypeError('The "regexp" argument must be an instance of RegExp. Received type ' + typeof regexp + ' (' + inspect(regexp) + ')'); + } + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be of type string. Received type ' + typeof string + ' (' + inspect(string) + ')'); + } + var matches = $test(regexp, string); + var message = defined( + msg, + 'The input ' + (matches ? 'was expected to not match' : 'did not match') + ' the regular expression ' + inspect(regexp) + '. Input: ' + inspect(string) + ); + this._assert(!matches, { + message: message, + operator: 'doesNotMatch', + actual: string, + expected: regexp, + extra: extra + }); +}; + +Test.skip = function (name_, _opts, _cb) { + var args = getTestArgs.apply(null, arguments); + args.opts.skip = true; + return Test(args.name, args.opts, args.cb); +}; + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape-es/node_modules/tape/package.json b/tests/node_modules/tape-es/node_modules/tape/package.json new file mode 100644 index 0000000..0ba3b85 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/package.json @@ -0,0 +1,105 @@ +{ + "_from": "tape@^4.13.3", + "_id": "tape@4.13.3", + "_inBundle": false, + "_integrity": "sha512-0/Y20PwRIUkQcTCSi4AASs+OANZZwqPKaipGCEwp10dQMipVvSZwUUCi01Y/OklIGyHKFhIcjock+DKnBfLAFw==", + "_location": "/tape-es/tape", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "tape@^4.13.3", + "name": "tape", + "escapedName": "tape", + "rawSpec": "^4.13.3", + "saveSpec": null, + "fetchSpec": "^4.13.3" + }, + "_requiredBy": [ + "/tape-es" + ], + "_resolved": "https://registry.npmjs.org/tape/-/tape-4.13.3.tgz", + "_shasum": "51b3d91c83668c7a45b1a594b607dee0a0b46278", + "_spec": "tape@^4.13.3", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tape-es", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bin": { + "tape": "bin/tape" + }, + "bugs": { + "url": "https://github.com/substack/tape/issues" + }, + "bundleDependencies": false, + "dependencies": { + "deep-equal": "~1.1.1", + "defined": "~1.0.0", + "dotignore": "~0.1.2", + "for-each": "~0.3.3", + "function-bind": "~1.1.1", + "glob": "~7.1.6", + "has": "~1.0.3", + "inherits": "~2.0.4", + "is-regex": "~1.0.5", + "minimist": "~1.2.5", + "object-inspect": "~1.7.0", + "resolve": "~1.17.0", + "resumer": "~0.0.0", + "string.prototype.trim": "~1.2.1", + "through": "~2.3.8" + }, + "deprecated": false, + "description": "tap-producing test harness for node and browsers", + "devDependencies": { + "concat-stream": "^1.6.2", + "eclint": "^2.8.1", + "ecstatic": "^4.1.4", + "eslint": "^7.1.0", + "falafel": "^2.2.4", + "js-yaml": "^3.14.0", + "tap": "^8.0.1", + "tap-parser": "^3.0.5" + }, + "directories": { + "example": "example", + "test": "test" + }, + "homepage": "https://github.com/substack/tape", + "keywords": [ + "tap", + "test", + "harness", + "assert", + "browser" + ], + "license": "MIT", + "main": "index.js", + "name": "tape", + "repository": { + "type": "git", + "url": "git://github.com/substack/tape.git" + }, + "scripts": { + "lint": "eslint .", + "prelint": "eclint check", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "tap test/*.js" + }, + "testling": { + "files": "test/browser/*.js", + "browsers": [ + "ie/6..latest", + "chrome/20..latest", + "firefox/10..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6" + ] + }, + "version": "4.13.3" +} diff --git a/tests/node_modules/tape-es/node_modules/tape/readme.markdown b/tests/node_modules/tape-es/node_modules/tape/readme.markdown new file mode 100644 index 0000000..4676bce --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/readme.markdown @@ -0,0 +1,406 @@ +# tape + +tap-producing test harness for node and browsers + +[![browser support](https://ci.testling.com/substack/tape.png)](http://ci.testling.com/substack/tape) + +[![build status](https://secure.travis-ci.org/substack/tape.svg?branch=master)](http://travis-ci.org/substack/tape) + +![tape](https://web.archive.org/web/20170612184731if_/http://substack.net/images/tape_drive.png) + +# example + +``` js +var test = require('tape'); + +test('timing test', function (t) { + t.plan(2); + + t.equal(typeof Date.now, 'function'); + var start = Date.now(); + + setTimeout(function () { + t.equal(Date.now() - start, 100); + }, 100); +}); +``` + +``` +$ node example/timing.js +TAP version 13 +# timing test +ok 1 should be equal +not ok 2 should be equal + --- + operator: equal + expected: 100 + actual: 107 + ... + +1..2 +# tests 2 +# pass 1 +# fail 1 +``` + +# usage + +You always need to `require('tape')` in test files. You can run the tests by +usual node means (`require('test-file.js')` or `node test-file.js`). You can +also run tests using the `tape` binary to utilize globbing, on Windows for +example: + +```sh +$ tape tests/**/*.js +``` + +`tape`'s arguments are passed to the +[`glob`](https://www.npmjs.com/package/glob) module. If you want `glob` to +perform the expansion on a system where the shell performs such expansion, quote +the arguments as necessary: + +```sh +$ tape 'tests/**/*.js' +$ tape "tests/**/*.js" +``` + +## Preloading modules + +Additionally, it is possible to make `tape` load one or more modules before running any tests, by using the `-r` or `--require` flag. Here's an example that loads [babel-register](http://babeljs.io/docs/usage/require/) before running any tests, to allow for JIT compilation: + +```sh +$ tape -r babel-register tests/**/*.js +``` + +Depending on the module you're loading, you may be able to parameterize it using environment variables or auxiliary files. Babel, for instance, will load options from [`.babelrc`](http://babeljs.io/docs/usage/babelrc/) at runtime. + +The `-r` flag behaves exactly like node's `require`, and uses the same module resolution algorithm. This means that if you need to load local modules, you have to prepend their path with `./` or `../` accordingly. + +For example: + +```sh +$ tape -r ./my/local/module tests/**/*.js +``` + +Please note that all modules loaded using the `-r` flag will run *before* any tests, regardless of when they are specified. For example, `tape -r a b -r c` will actually load `a` and `c` *before* loading `b`, since they are flagged as required modules. + +# things that go well with tape + +`tape` maintains a fairly minimal core. Additional features are usually added by using another module alongside `tape`. + +## pretty reporters + +The default TAP output is good for machines and humans that are robots. + +If you want a more colorful / pretty output there are lots of modules on npm +that will output something pretty if you pipe TAP into them: + +- [tap-spec](https://github.com/scottcorgan/tap-spec) +- [tap-dot](https://github.com/scottcorgan/tap-dot) +- [faucet](https://github.com/substack/faucet) +- [tap-bail](https://github.com/juliangruber/tap-bail) +- [tap-browser-color](https://github.com/kirbysayshi/tap-browser-color) +- [tap-json](https://github.com/gummesson/tap-json) +- [tap-min](https://github.com/derhuerst/tap-min) +- [tap-nyan](https://github.com/calvinmetcalf/tap-nyan) +- [tap-pessimist](https://www.npmjs.org/package/tap-pessimist) +- [tap-prettify](https://github.com/toolness/tap-prettify) +- [colortape](https://github.com/shuhei/colortape) +- [tap-xunit](https://github.com/aghassemi/tap-xunit) +- [tap-difflet](https://github.com/namuol/tap-difflet) +- [tape-dom](https://github.com/gritzko/tape-dom) +- [tap-diff](https://github.com/axross/tap-diff) +- [tap-notify](https://github.com/axross/tap-notify) +- [tap-summary](https://github.com/zoubin/tap-summary) +- [tap-markdown](https://github.com/Hypercubed/tap-markdown) +- [tap-html](https://github.com/gabrielcsapo/tap-html) +- [tap-react-browser](https://github.com/mcnuttandrew/tap-react-browser) +- [tap-junit](https://github.com/dhershman1/tap-junit) +- [tap-nyc](https://github.com/MegaArman/tap-nyc) +- [tap-spec (emoji patch)](https://github.com/Sceat/tap-spec-emoji) +- [tape-repeater](https://github.com/rgruesbeck/tape-repeater) + +To use them, try `node test/index.js | tap-spec` or pipe it into one +of the modules of your choice! + +## uncaught exceptions + +By default, uncaught exceptions in your tests will not be intercepted, and will cause `tape` to crash. If you find this behavior undesirable, use [`tape-catch`](https://github.com/michaelrhodes/tape-catch) to report any exceptions as TAP errors. + +## other + +- CoffeeScript support with https://www.npmjs.com/package/coffeetape +- Promise support with https://www.npmjs.com/package/blue-tape or https://www.npmjs.com/package/tape-promise +- ES6 support with https://www.npmjs.com/package/babel-tape-runner or https://www.npmjs.com/package/buble-tape-runner +- Different test syntax with https://github.com/pguth/flip-tape (warning: mutates String.prototype) +- Electron test runner with https://github.com/tundrax/electron-tap +- Concurrency support with https://github.com/imsnif/mixed-tape +- In-process reporting with https://github.com/DavidAnson/tape-player + +# methods + +The assertion methods in `tape` are heavily influenced or copied from the methods +in [node-tap](https://github.com/isaacs/node-tap). + +```js +var test = require('tape') +``` + +## test([name], [opts], cb) + +Create a new test with an optional `name` string and optional `opts` object. +`cb(t)` fires with the new test object `t` once all preceding tests have +finished. Tests execute serially. + +Available `opts` options are: +- opts.skip = true/false. See test.skip. +- opts.timeout = 500. Set a timeout for the test, after which it will fail. See test.timeoutAfter. +- opts.objectPrintDepth = 5. Configure max depth of expected / actual object printing. Environmental variable `NODE_TAPE_OBJECT_PRINT_DEPTH` can set the desired default depth for all tests; locally-set values will take precedence. +- opts.todo = true/false. Test will be allowed to fail. + +If you forget to `t.plan()` out how many assertions you are going to run and you +don't call `t.end()` explicitly, your test will hang. + +## test.skip([name], [opts], cb) + +Generate a new test that will be skipped over. + +## test.onFinish(fn) + +The onFinish hook will get invoked when ALL `tape` tests have finished +right before `tape` is about to print the test summary. + +## test.onFailure(fn) + +The onFailure hook will get invoked whenever any `tape` tests has failed. + +## t.plan(n) + +Declare that `n` assertions should be run. `t.end()` will be called +automatically after the `n`th assertion. If there are any more assertions after +the `n`th, or after `t.end()` is called, they will generate errors. + +## t.end(err) + +Declare the end of a test explicitly. If `err` is passed in `t.end` will assert +that it is falsey. + +## t.fail(msg) + +Generate a failing assertion with a message `msg`. + +## t.pass(msg) + +Generate a passing assertion with a message `msg`. + +## t.timeoutAfter(ms) + +Automatically timeout the test after X ms. + +## t.skip(msg) + +Generate an assertion that will be skipped over. + +## t.ok(value, msg) + +Assert that `value` is truthy with an optional description of the assertion `msg`. + +Aliases: `t.true()`, `t.assert()` + +## t.notOk(value, msg) + +Assert that `value` is falsy with an optional description of the assertion `msg`. + +Aliases: `t.false()`, `t.notok()` + +## t.error(err, msg) + +Assert that `err` is falsy. If `err` is non-falsy, use its `err.message` as the +description message. + +Aliases: `t.ifError()`, `t.ifErr()`, `t.iferror()` + +## t.equal(actual, expected, msg) + +Assert that `actual === expected` with an optional description of the assertion `msg`. + +Aliases: `t.equals()`, `t.isEqual()`, `t.is()`, `t.strictEqual()`, +`t.strictEquals()` + +## t.notEqual(actual, expected, msg) + +Assert that `actual !== expected` with an optional description of the assertion `msg`. + +Aliases: `t.notEquals()`, `t.notStrictEqual()`, `t.notStrictEquals()`, +`t.isNotEqual()`, `t.isNot()`, `t.not()`, `t.doesNotEqual()`, `t.isInequal()` + +## t.deepEqual(actual, expected, msg) + +Assert that `actual` and `expected` have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with strict comparisons (`===`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.deepEquals()`, `t.isEquivalent()`, `t.same()` + +## t.notDeepEqual(actual, expected, msg) + +Assert that `actual` and `expected` do not have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with strict comparisons (`===`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.notDeepEquals`, `t.notEquivalent()`, `t.notDeeply()`, `t.notSame()`, +`t.isNotDeepEqual()`, `t.isNotDeeply()`, `t.isNotEquivalent()`, +`t.isInequivalent()` + +## t.deepLooseEqual(actual, expected, msg) + +Assert that `actual` and `expected` have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with loose comparisons (`==`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.looseEqual()`, `t.looseEquals()` + +## t.notDeepLooseEqual(actual, expected, msg) + +Assert that `actual` and `expected` do not have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with loose comparisons (`==`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.notLooseEqual()`, `t.notLooseEquals()` + +## t.throws(fn, expected, msg) + +Assert that the function call `fn()` throws an exception. `expected`, if present, must be a `RegExp` or `Function`. The `RegExp` matches the string representation of the exception, as generated by `err.toString()`. The `Function` is the exception thrown (e.g. `Error`). `msg` is an optional description of the assertion. + +## t.doesNotThrow(fn, expected, msg) + +Assert that the function call `fn()` does not throw an exception. `expected`, if present, limits what should not be thrown. For example, set `expected` to `/user/` to fail the test only if the string representation of the exception contains the word `user`. Any other exception would pass the test. If `expected` is omitted, any exception will fail the test. `msg` is an optional description of the assertion. + +## t.test(name, [opts], cb) + +Create a subtest with a new test handle `st` from `cb(st)` inside the current +test `t`. `cb(st)` will only fire when `t` finishes. Additional tests queued up +after `t` will not be run until all subtests finish. + +You may pass the same options that [`test()`](#testname-opts-cb) accepts. + +## t.comment(message) + +Print a message without breaking the tap output. (Useful when using e.g. `tap-colorize` where output is buffered & `console.log` will print in incorrect order vis-a-vis tap output.) + +## t.match(string, regexp, message) + +Assert that `string` matches the RegExp `regexp`. Will throw (not just fail) when the first two arguments are the wrong type. + +## t.doesNotMatch(string, regexp, message) + +Assert that `string` does not match the RegExp `regexp`. Will throw (not just fail) when the first two arguments are the wrong type. + +## var htest = test.createHarness() + +Create a new test harness instance, which is a function like `test()`, but with +a new pending stack and test state. + +By default the TAP output goes to `console.log()`. You can pipe the output to +someplace else if you `htest.createStream().pipe()` to a destination stream on +the first tick. + +## test.only([name], [opts], cb) + +Like `test([name], [opts], cb)` except if you use `.only` this is the only test case +that will run for the entire process, all other test cases using `tape` will +be ignored. + +## var stream = test.createStream(opts) + +Create a stream of output, bypassing the default output stream that writes +messages to `console.log()`. By default `stream` will be a text stream of TAP +output, but you can get an object stream instead by setting `opts.objectMode` to +`true`. + +### tap stream reporter + +You can create your own custom test reporter using this `createStream()` api: + +``` js +var test = require('tape'); +var path = require('path'); + +test.createStream().pipe(process.stdout); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); +``` + +You could substitute `process.stdout` for whatever other output stream you want, +like a network connection or a file. + +Pass in test files to run as arguments: + +```sh +$ node tap.js test/x.js test/y.js +TAP version 13 +# (anonymous) +not ok 1 should be equal + --- + operator: equal + expected: "boop" + actual: "beep" + ... +# (anonymous) +ok 2 should be equal +ok 3 (unnamed assert) +# wheee +ok 4 (unnamed assert) + +1..4 +# tests 4 +# pass 3 +# fail 1 +``` + +### object stream reporter + +Here's how you can render an object stream instead of TAP: + +``` js +var test = require('tape'); +var path = require('path'); + +test.createStream({ objectMode: true }).on('data', function (row) { + console.log(JSON.stringify(row)) +}); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); +``` + +The output for this runner is: + +```sh +$ node object.js test/x.js test/y.js +{"type":"test","name":"(anonymous)","id":0} +{"id":0,"ok":false,"name":"should be equal","operator":"equal","actual":"beep","expected":"boop","error":{},"test":0,"type":"assert"} +{"type":"end","test":0} +{"type":"test","name":"(anonymous)","id":1} +{"id":0,"ok":true,"name":"should be equal","operator":"equal","actual":2,"expected":2,"test":1,"type":"assert"} +{"id":1,"ok":true,"name":"(unnamed assert)","operator":"ok","actual":true,"expected":true,"test":1,"type":"assert"} +{"type":"end","test":1} +{"type":"test","name":"wheee","id":2} +{"id":0,"ok":true,"name":"(unnamed assert)","operator":"ok","actual":true,"expected":true,"test":2,"type":"assert"} +{"type":"end","test":2} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install tape --save-dev +``` + +# license + +MIT diff --git a/tests/node_modules/tape-es/node_modules/tape/test/add-subtest-async.js b/tests/node_modules/tape-es/node_modules/tape/test/add-subtest-async.js new file mode 100644 index 0000000..12b2e2d --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/add-subtest-async.js @@ -0,0 +1,11 @@ +var test = require('../'); + +test('parent', function (t) { + t.pass('parent'); + setTimeout(function () { + t.test('child', function (st) { + st.pass('child'); + st.end(); + }); + }, 100); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn.js b/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn.js new file mode 100644 index 0000000..a402eb9 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn.js @@ -0,0 +1,43 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; +var testWrapper = require('./anonymous-fn/test-wrapper'); + +tap.test('inside anonymous functions', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + var body = stripFullStack(rows.toString('utf8')); + + tt.same(body, [ + 'TAP version 13', + '# wrapped test failure', + 'not ok 1 fail', + ' ---', + ' operator: fail', + ' at: ($TEST/anonymous-fn.js:$LINE:$COL)', + ' stack: |-', + ' Error: fail', + ' [... stack stripped ...]', + ' at $TEST/anonymous-fn.js:$LINE:$COL', + ' at Test. ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('wrapped test failure', testWrapper(function (t) { + t.fail('fail'); + t.end(); + })); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn/test-wrapper.js b/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn/test-wrapper.js new file mode 100644 index 0000000..38e8ba1 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/anonymous-fn/test-wrapper.js @@ -0,0 +1,16 @@ +// Example of wrapper function that would invoke tape +module.exports = function (testCase) { + return function (t) { + setUp(); + testCase(t); + tearDown(); + }; +}; + +function setUp() { + // ... example ... +} + +function tearDown() { + // ... example ... +} diff --git a/tests/node_modules/tape-es/node_modules/tape/test/array.js b/tests/node_modules/tape-es/node_modules/tape/test/array.js new file mode 100644 index 0000000..dc4a4a4 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/array.js @@ -0,0 +1,61 @@ +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + + test.createStream().pipe(concat(function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# array', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'ok 5 should be equivalent', + '', + '1..5', + '# tests 5', + '# pass 5', + '', + '# ok' + ].join('\n') + '\n'); + })); + + test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/bound.js b/tests/node_modules/tape-es/node_modules/tape/test/bound.js new file mode 100644 index 0000000..58f2692 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/bound.js @@ -0,0 +1,10 @@ +var test = require('../'); + +test('bind works', function (t) { + t.plan(2); + var equal = t.equal; + var deepEqual = t.deepEqual; + equal(3, 3); + deepEqual([4], [4]); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/browser/asserts.js b/tests/node_modules/tape-es/node_modules/tape/test/browser/asserts.js new file mode 100644 index 0000000..a1b24f6 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/browser/asserts.js @@ -0,0 +1,9 @@ +var test = require('../../'); + +test(function (t) { + t.plan(4); + t.ok(true); + t.equal(3, 1+2); + t.deepEqual([1,2,[3,4]], [1,2,[3,4]]); + t.notDeepEqual([1,2,[3,4,5]], [1,2,[3,4]]); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/child_ordering.js b/tests/node_modules/tape-es/node_modules/tape/test/child_ordering.js new file mode 100644 index 0000000..08d3c76 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/child_ordering.js @@ -0,0 +1,54 @@ +var test = require('../'); + +var childRan = false; + +test('parent', function (t) { + t.test('child', function (t) { + childRan = true; + t.pass('child ran'); + t.end(); + }); + t.end(); +}); + +test('uncle', function (t) { + t.ok(childRan, 'Child should run before next top-level test'); + t.end(); +}); + +var grandParentRan = false; +var parentRan = false; +var grandChildRan = false; +test('grandparent', function (t) { + t.ok(!grandParentRan, 'grand parent ran twice'); + grandParentRan = true; + t.test('parent', function (t) { + t.ok(!parentRan, 'parent ran twice'); + parentRan = true; + t.test('grandchild', function (t) { + t.ok(!grandChildRan, 'grand child ran twice'); + grandChildRan = true; + t.pass('grand child ran'); + t.end(); + }); + t.pass('parent ran'); + t.end(); + }); + t.test('other parent', function (t) { + t.ok(parentRan, 'first parent runs before second parent'); + t.ok(grandChildRan, 'grandchild runs before second parent'); + t.end(); + }); + t.pass('grandparent ran'); + t.end(); +}); + +test('second grandparent', function (t) { + t.ok(grandParentRan, 'grandparent ran'); + t.ok(parentRan, 'parent ran'); + t.ok(grandChildRan, 'grandchild ran'); + t.pass('other grandparent ran'); + t.end(); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape-es/node_modules/tape/test/circular-things.js b/tests/node_modules/tape-es/node_modules/tape/test/circular-things.js new file mode 100644 index 0000000..dcab2b1 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/circular-things.js @@ -0,0 +1,44 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('circular test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# circular\n' + + 'not ok 1 should be equal\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: |-\n' + + ' {}\n' + + ' actual: |-\n' + + ' { circular: [Circular] }\n' + + ' at: Test. ($TEST/circular-things.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should be equal\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/circular-things.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + })); + + test('circular', function (t) { + t.plan(1); + var circular = {}; + circular.circular = circular; + t.equal(circular, {}); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/comment.js b/tests/node_modules/tape-es/node_modules/tape/test/comment.js new file mode 100644 index 0000000..007d457 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/comment.js @@ -0,0 +1,175 @@ +var concat = require('concat-stream'); +var tap = require('tap'); +var tape = require('../'); + +// Exploratory test to ascertain proper output when no t.comment() call +// is made. +tap.test('no comment', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# no comment', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('no comment', function (t) { + t.end(); + }); +}); + +// Exploratory test, can we call t.comment() passing nothing? +tap.test('missing argument', function (assert) { + assert.plan(1); + var test = tape.createHarness(); + test.createStream(); + test('missing argument', function (t) { + try { + t.comment(); + t.end(); + } catch (err) { + assert.equal(err.constructor, TypeError); + } finally { + assert.end(); + } + }); +}); + +// Exploratory test, can we call t.comment() passing nothing? +tap.test('null argument', function (assert) { + assert.plan(1); + var test = tape.createHarness(); + test.createStream(); + test('null argument', function (t) { + try { + t.comment(null); + t.end(); + } catch (err) { + assert.equal(err.constructor, TypeError); + } finally { + assert.end(); + } + }); +}); + + +// Exploratory test, how is whitespace treated? +tap.test('whitespace', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# whitespace', + '# ', + '# a', + '# a', + '# a', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('whitespace', function (t) { + t.comment(' '); + t.comment(' a'); + t.comment('a '); + t.comment(' a '); + t.end(); + }); +}); + +// Exploratory test, how about passing types other than strings? +tap.test('non-string types', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# non-string types', + '# true', + '# false', + '# 42', + '# 6.66', + '# [object Object]', + '# [object Object]', + '# [object Object]', + '# function ConstructorFunction() {}', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('non-string types', function (t) { + t.comment(true); + t.comment(false); + t.comment(42); + t.comment(6.66); + t.comment({}); + t.comment({'answer': 42}); + function ConstructorFunction() {} + t.comment(new ConstructorFunction()); + t.comment(ConstructorFunction); + t.end(); + }); +}); + +tap.test('multiline string', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# multiline strings', + '# a', + '# b', + '# c', + '# d', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('multiline strings', function (t) { + t.comment([ + 'a', + 'b', + ].join('\n')); + t.comment([ + 'c', + 'd', + ].join('\r\n')); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/common.js b/tests/node_modules/tape-es/node_modules/tape/test/common.js new file mode 100644 index 0000000..e7df7d1 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/common.js @@ -0,0 +1,65 @@ +var path = require('path'); +var yaml = require('js-yaml'); + +module.exports.getDiag = function (body) { + var yamlStart = body.indexOf(' ---'); + var yamlEnd = body.indexOf(' ...\n'); + var diag = body.slice(yamlStart, yamlEnd).split('\n').map(function (line) { + return line.slice(2); + }).join('\n'); + + // The stack trace and at variable will vary depending on where the code + // is run, so just strip it out. + var withStack = yaml.safeLoad(diag); + delete withStack.stack; + delete withStack.at; + return withStack; +}; + +// There are three challenges associated with checking the stack traces included +// in errors: +// 1) The base checkout directory of tape might change. Because stack traces +// include absolute paths, the stack traces will change depending on the +// checkout path. We handle this by replacing the base test directory with a +// placeholder $TEST variable and the package root with a placeholder +// $TAPE variable. +// 2) Line positions within the file might change. We handle this by replacing +// line and column markers with placeholder $LINE and $COL "variables" +// a) node 0.8 does not provide nested eval line numbers, so we remove them +// 3) Stacks themselves change frequently with refactoring. We've even run into +// issues with node library refactorings "breaking" stack traces. Most of +// these changes are irrelevant to the tests themselves. To counter this, we +// strip out all stack frames that aren't directly under our test directory, +// and replace them with placeholders. + +var stripChangingData = function (line) { + var withoutTestDir = line.replace(__dirname, '$TEST'); + var withoutPackageDir = withoutTestDir.replace(path.dirname(__dirname), '$TAPE'); + var withoutPathSep = withoutPackageDir.replace(new RegExp('\\' + path.sep, 'g'), '/'); + var withoutLineNumbers = withoutPathSep.replace(/:\d+:\d+/g, ':$LINE:$COL'); + var withoutNestedLineNumbers = withoutLineNumbers.replace(/, \:\$LINE:\$COL\)$/, ')'); + return withoutNestedLineNumbers; +}; + +module.exports.stripFullStack = function (output) { + var stripped = ' [... stack stripped ...]'; + var withDuplicates = output.split('\n').map(stripChangingData).map(function (line) { + var m = line.match(/[ ]{8}at .*\((.*)\)/); + + if (m && m[1].slice(0, 5) !== '$TEST') { + return stripped; + } + return line; + }); + + var deduped = withDuplicates.filter(function (line, ix) { + var hasPrior = line === stripped && withDuplicates[ix - 1] === stripped; + return !hasPrior; + }); + + return deduped.join('\n').replace( + // Handle stack trace variation in Node v0.8 + /at(:?) Test\.(?:module\.exports|tap\.test\.err\.code)/g, + 'at$1 Test.' + ); +}; diff --git a/tests/node_modules/tape-es/node_modules/tape/test/create_multiple_streams.js b/tests/node_modules/tape-es/node_modules/tape/test/create_multiple_streams.js new file mode 100644 index 0000000..8ecac49 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/create_multiple_streams.js @@ -0,0 +1,31 @@ +var tape = require('../'); + +tape.test('createMultipleStreams', function (tt) { + tt.plan(2); + + var th = tape.createHarness(); + th.createStream(); + th.createStream(); + + var testOneComplete = false; + + th('test one', function (tht) { + tht.plan(1); + setTimeout( function () { + tht.pass(); + testOneComplete = true; + }, 100); + }); + + th('test two', function (tht) { + tht.ok(testOneComplete, 'test 1 completed before test 2'); + tht.end(); + }); + + th.onFinish(function () { + tt.equal(th._results.count, 2, 'harness test ran'); + tt.equal(th._results.fail, 0, "harness test didn't fail"); + }); +}); + + diff --git a/tests/node_modules/tape-es/node_modules/tape/test/deep-equal-failure.js b/tests/node_modules/tape-es/node_modules/tape/test/deep-equal-failure.js new file mode 100644 index 0000000..e1f2659 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/deep-equal-failure.js @@ -0,0 +1,191 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('deep equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# deep equal\n' + + 'not ok 1 should be equal\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: |-\n' + + ' { b: 2 }\n' + + ' actual: |-\n' + + ' { a: 1 }\n' + + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should be equal\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ b: 2 }', + actual: '{ a: 1 }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be equal', + diag: { + operator: 'equal', + expected: '{ b: 2 }', + actual: '{ a: 1 }' + } + }); + }); + + test('deep equal', function (t) { + t.plan(1); + t.equal({a: 1}, {b: 2}); + }); +}); + +tap.test('deep equal failure, depth 6, with option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# deep equal\n' + + 'not ok 1 should be equal\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: |-\n' + + ' { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }\n' + + ' actual: |-\n' + + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }\n' + + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should be equal\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be equal', + diag: { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + } + }); + }); + + test('deep equal', {objectPrintDepth: 6}, function (t) { + t.plan(1); + t.equal({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }); + }); +}); + +tap.test('deep equal failure, depth 6, without option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# deep equal\n' + + 'not ok 1 should be equal\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: |-\n' + + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }\n' + + ' actual: |-\n' + + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }\n' + + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should be equal\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be equal', + diag: { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + } + }); + }); + + test('deep equal', function (t) { + t.plan(1); + t.equal({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/deep.js b/tests/node_modules/tape-es/node_modules/tape/test/deep.js new file mode 100644 index 0000000..909ebe1 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/deep.js @@ -0,0 +1,17 @@ +var test = require('../'); + +test('deep strict equal', function (t) { + t.notDeepEqual( + [ { a: '3' } ], + [ { a: 3 } ] + ); + t.end(); +}); + +test('deep loose equal', function (t) { + t.deepLooseEqual( + [ { a: '3' } ], + [ { a: 3 } ] + ); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/default-messages.js b/tests/node_modules/tape-es/node_modules/tape/test/default-messages.js new file mode 100644 index 0000000..5651a8e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/default-messages.js @@ -0,0 +1,50 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('default messages', function (t) { + t.plan(1); + + var ps = spawn(process.execPath, [path.join(__dirname, 'messages', 'defaults.js')]); + + ps.stdout.pipe(concat(function (rows) { + + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# default messages', + 'ok 1 should be truthy', + 'ok 2 should be falsy', + 'ok 3 should be equal', + 'ok 4 should not be equal', + 'ok 5 should be equivalent', + 'ok 6 should be equivalent', + 'ok 7 should be equal', + 'ok 8 should not be equal', + 'ok 9 should be equivalent', + 'not ok 10 should not be equivalent', + ' ---', + ' operator: notDeepEqual', + ' expected: true', + ' actual: true', + ' at: Test. ($TEST/messages/defaults.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/messages/defaults.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 11 should be equivalent', + 'ok 12 should be equivalent', + '', + '1..12', + '# tests 12', + '# pass 11', + '# fail 1' + ].join('\n') + '\n\n'); + })); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/double_end.js b/tests/node_modules/tape-es/node_modules/tape/test/double_end.js new file mode 100644 index 0000000..b2fbc5b --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/double_end.js @@ -0,0 +1,60 @@ +var test = require('tap').test; +var path = require('path'); +var concat = require('concat-stream'); +var spawn = require('child_process').spawn; + +var stripFullStack = require('./common').stripFullStack; + +test(function (t) { + t.plan(2); + var ps = spawn(process.execPath, [path.join(__dirname, 'double_end', 'double.js')]); + ps.on('exit', function (code) { + t.equal(code, 1); + }); + ps.stdout.pipe(concat(function (body) { + // The implementation of node's timer library has changed over time. We + // need to reverse engineer the error we expect to see. + + // This code is unfortunately by necessity highly coupled to node + // versions, and may require tweaking with future versions of the timers + // library. + function doEnd() { throw new Error(); }; + var to = setTimeout(doEnd, 5000); + clearTimeout(to); + to._onTimeout = doEnd; + + var stackExpected; + var atExpected; + try { + to._onTimeout(); + } + catch (e) { + stackExpected = stripFullStack(e.stack).split('\n')[1]; + stackExpected = stackExpected.replace('double_end.js', 'double_end/double.js'); + stackExpected = stackExpected.trim(); + atExpected = stackExpected.replace(/^at\s+/, 'at: '); + } + + var stripped = stripFullStack(body.toString('utf8')); + t.equal(stripped, [ + 'TAP version 13', + '# double end', + 'ok 1 should be equal', + 'not ok 2 .end() called twice', + ' ---', + ' operator: fail', + ' ' + atExpected, + ' stack: |-', + ' Error: .end() called twice', + ' [... stack stripped ...]', + ' ' + stackExpected, + ' [... stack stripped ...]', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + ].join('\n') + '\n\n'); + })); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/double_end/double.js b/tests/node_modules/tape-es/node_modules/tape/test/double_end/double.js new file mode 100644 index 0000000..43929e5 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/double_end/double.js @@ -0,0 +1,11 @@ +var test = require('../../'); + +test('double end', function (t) { + function doEnd() { + t.end(); + } + + t.equal(1 + 1, 2); + t.end(); + setTimeout(doEnd, 5); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/edge-cases.js b/tests/node_modules/tape-es/node_modules/tape/test/edge-cases.js new file mode 100644 index 0000000..96da854 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/edge-cases.js @@ -0,0 +1,288 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('edge cases', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# zeroes\n' + + 'ok 1 0 equal to -0\n' + + 'ok 2 -0 equal to 0\n' + + 'not ok 3 0 notEqual to -0\n' + + ' ---\n' + + ' operator: notEqual\n' + + ' expected: |-\n' + + ' -0\n' + + ' actual: |-\n' + + ' 0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: 0 notEqual to -0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 4 -0 notEqual to 0\n' + + ' ---\n' + + ' operator: notEqual\n' + + ' expected: |-\n' + + ' 0\n' + + ' actual: |-\n' + + ' -0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: -0 notEqual to 0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 5 0 looseEqual to -0\n' + + 'ok 6 -0 looseEqual to 0\n' + + 'not ok 7 0 notLooseEqual to -0\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: |-\n' + + ' -0\n' + + ' actual: |-\n' + + ' 0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: 0 notLooseEqual to -0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 8 -0 notLooseEqual to 0\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: |-\n' + + ' 0\n' + + ' actual: |-\n' + + ' -0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: -0 notLooseEqual to 0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 9 0 strictEqual to -0\n' + + 'ok 10 -0 strictEqual to 0\n' + + 'not ok 11 0 notStrictEqual to -0\n' + + ' ---\n' + + ' operator: notEqual\n' + + ' expected: |-\n' + + ' -0\n' + + ' actual: |-\n' + + ' 0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: 0 notStrictEqual to -0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 12 -0 notStrictEqual to 0\n' + + ' ---\n' + + ' operator: notEqual\n' + + ' expected: |-\n' + + ' 0\n' + + ' actual: |-\n' + + ' -0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: -0 notStrictEqual to 0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 13 0 deepLooseEqual to -0\n' + + 'ok 14 -0 deepLooseEqual to 0\n' + + 'not ok 15 0 notDeepLooseEqual to -0\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: |-\n' + + ' -0\n' + + ' actual: |-\n' + + ' 0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: 0 notDeepLooseEqual to -0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 16 -0 notDeepLooseEqual to 0\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: |-\n' + + ' 0\n' + + ' actual: |-\n' + + ' -0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: -0 notDeepLooseEqual to 0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 17 0 deepEqual to -0\n' + + ' ---\n' + + ' operator: deepEqual\n' + + ' expected: |-\n' + + ' -0\n' + + ' actual: |-\n' + + ' 0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: 0 deepEqual to -0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 18 -0 deepEqual to 0\n' + + ' ---\n' + + ' operator: deepEqual\n' + + ' expected: |-\n' + + ' 0\n' + + ' actual: |-\n' + + ' -0\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: -0 deepEqual to 0\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 19 0 notDeepEqual to -0\n' + + 'ok 20 -0 notDeepEqual to 0\n' + + '# NaNs\n' + + 'not ok 21 NaN equal to NaN\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: NaN\n' + + ' actual: NaN\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: NaN equal to NaN\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 22 NaN notEqual to NaN\n' + + 'not ok 23 NaN looseEqual to NaN\n' + + ' ---\n' + + ' operator: deepLooseEqual\n' + + ' expected: NaN\n' + + ' actual: NaN\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: NaN looseEqual to NaN\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 24 NaN notLooseEqual to NaN\n' + + 'not ok 25 NaN strictEqual to NaN\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: NaN\n' + + ' actual: NaN\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: NaN strictEqual to NaN\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 26 NaN notStrictEqual to NaN\n' + + 'not ok 27 NaN deepLooseEqual to NaN\n' + + ' ---\n' + + ' operator: deepLooseEqual\n' + + ' expected: NaN\n' + + ' actual: NaN\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: NaN deepLooseEqual to NaN\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 28 NaN notDeepLooseEqual to NaN\n' + + 'ok 29 NaN deepEqual to NaN\n' + + 'not ok 30 NaN notDeepEqual to NaN\n' + + ' ---\n' + + ' operator: notDeepEqual\n' + + ' expected: NaN\n' + + ' actual: NaN\n' + + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: NaN notDeepEqual to NaN\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n1..30\n' + + '# tests 30\n' + + '# pass 15\n' + + '# fail 15\n' + ); + })); + + test('zeroes', function (t) { + t.equal(0, -0, '0 equal to -0'); + t.equal(-0, 0, '-0 equal to 0'); + t.notEqual(0, -0, '0 notEqual to -0'); + t.notEqual(-0, 0, '-0 notEqual to 0'); + + t.looseEqual(0, -0, '0 looseEqual to -0'); + t.looseEqual(-0, 0, '-0 looseEqual to 0'); + t.notLooseEqual(0, -0, '0 notLooseEqual to -0'); + t.notLooseEqual(-0, 0, '-0 notLooseEqual to 0'); + + t.strictEqual(0, -0, '0 strictEqual to -0'); + t.strictEqual(-0, 0, '-0 strictEqual to 0'); + t.notStrictEqual(0, -0, '0 notStrictEqual to -0'); + t.notStrictEqual(-0, 0, '-0 notStrictEqual to 0'); + + t.deepLooseEqual(0, -0, '0 deepLooseEqual to -0'); + t.deepLooseEqual(-0, 0, '-0 deepLooseEqual to 0'); + t.notDeepLooseEqual(0, -0, '0 notDeepLooseEqual to -0'); + t.notDeepLooseEqual(-0, 0, '-0 notDeepLooseEqual to 0'); + + t.deepEqual(0, -0, '0 deepEqual to -0'); + t.deepEqual(-0, 0, '-0 deepEqual to 0'); + t.notDeepEqual(0, -0, '0 notDeepEqual to -0'); + t.notDeepEqual(-0, 0, '-0 notDeepEqual to 0'); + + t.end(); + }); + + test('NaNs', function (t) { + t.equal(NaN, NaN, 'NaN equal to NaN'); + t.notEqual(NaN, NaN, 'NaN notEqual to NaN'); + + t.looseEqual(NaN, NaN, 'NaN looseEqual to NaN'); + t.notLooseEqual(NaN, NaN, 'NaN notLooseEqual to NaN'); + + t.strictEqual(NaN, NaN, 'NaN strictEqual to NaN'); + t.notStrictEqual(NaN, NaN, 'NaN notStrictEqual to NaN'); + + t.deepLooseEqual(NaN, NaN, 'NaN deepLooseEqual to NaN'); + t.notDeepLooseEqual(NaN, NaN, 'NaN notDeepLooseEqual to NaN'); + + t.deepEqual(NaN, NaN, 'NaN deepEqual to NaN'); + t.notDeepEqual(NaN, NaN, 'NaN notDeepEqual to NaN'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/end-as-callback.js b/tests/node_modules/tape-es/node_modules/tape/test/end-as-callback.js new file mode 100644 index 0000000..a8c7094 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/end-as-callback.js @@ -0,0 +1,88 @@ +var tap = require('tap'); +var forEach = require('for-each'); +var tape = require('../'); +var concat = require('concat-stream'); + +tap.test('tape assert.end as callback', function (tt) { + var test = tape.createHarness({ exit: false }); + + test.createStream().pipe(concat(function (rows) { + tt.equal(rows.toString('utf8'), [ + 'TAP version 13', + '# do a task and write', + 'ok 1 null', + 'ok 2 should be equal', + '# do a task and write fail', + 'ok 3 null', + 'ok 4 should be equal', + 'not ok 5 Error: fail', + getStackTrace(rows), // tap error stack + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1' + ].join('\n') + '\n'); + tt.end(); + })); + + test('do a task and write', function (assert) { + fakeAsyncTask('foo', function (err, value) { + assert.ifError(err); + assert.equal(value, 'taskfoo'); + + fakeAsyncWrite('bar', assert.end); + }); + }); + + test('do a task and write fail', function (assert) { + fakeAsyncTask('bar', function (err, value) { + assert.ifError(err); + assert.equal(value, 'taskbar'); + + fakeAsyncWriteFail('baz', assert.end); + }); + }); +}); + +function fakeAsyncTask(name, cb) { + cb(null, 'task' + name); +} + +function fakeAsyncWrite(name, cb) { + cb(null); +} + +function fakeAsyncWriteFail(name, cb) { + cb(new Error('fail')); +} + +/** + * extract the stack trace for the failed test. + * this will change dependent on the environment + * so no point hard-coding it in the test assertion + * see: https://git.io/v6hGG for example + * @param String rows - the tap output lines + * @returns String stacktrace - just the error stack part + */ +function getStackTrace(rows) { + var stacktrace = ' ---\n'; + var extract = false; + forEach(rows.toString('utf8').split('\n'), function (row) { + if (!extract) { + if (row.indexOf('---') > -1) { // start of stack trace + extract = true; + } + } else { + if (row.indexOf('...') > -1) { // end of stack trace + extract = false; + stacktrace += ' ...'; + } else { + stacktrace += row + '\n'; + } + + } + }); + // console.log(stacktrace); + return stacktrace; +} diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit.js b/tests/node_modules/tape-es/node_modules/tape/test/exit.js new file mode 100644 index 0000000..4ba1f9a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit.js @@ -0,0 +1,237 @@ +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('exit ok', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# array', + '# hi', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'ok 5 should be equivalent', + '', + '1..5', + '# tests 5', + '# pass 5', + '', + '# ok', + '', // yes, these double-blank-lines at the end are required. + '' // if you can figure out how to remove them, please do! + ].join('\n')); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, 'exit', 'ok.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('exit fail', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'not ok 5 should be equivalent', + ' ---', + ' operator: deepEqual', + ' expected: [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]', + ' actual: [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]', + ' at: ($TEST/exit/fail.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be equivalent', + ' [... stack stripped ...]', + ' at $TEST/exit/fail.js:$LINE:$COL', + ' at eval (eval at ($TEST/exit/fail.js:$LINE:$COL))', + ' at eval (eval at ($TEST/exit/fail.js:$LINE:$COL))', + ' at Test. ($TEST/exit/fail.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, 'exit', 'fail.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('too few exit', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'ok 5 should be equivalent', + 'not ok 6 plan != count', + ' ---', + ' operator: fail', + ' expected: 6', + ' actual: 5', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' ...', + '', + '1..6', + '# tests 6', + '# pass 5', + '# fail 1' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/too_few.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('more planned in a second test', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# first', + 'ok 1 should be truthy', + '# second', + 'ok 2 should be truthy', + 'not ok 3 plan != count', + ' ---', + ' operator: fail', + ' expected: 2', + ' actual: 1', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' ...', + '', + '1..3', + '# tests 3', + '# pass 2', + '# fail 1' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/second.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('todo passing', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# TODO todo pass', + 'ok 1 should be truthy # TODO', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/todo.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('todo failing', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# TODO todo fail', + 'not ok 1 should be truthy # TODO', + ' ---', + ' operator: ok', + ' expected: true', + ' actual: false', + ' at: Test. ($TEST/exit/todo_fail.js:$LINE:$COL)', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/todo_fail.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('forgot to call t.end()', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# first', + 'ok 1 should be truthy', + '# oops forgot end', + 'ok 2 should be truthy', + 'not ok 3 test exited without ending: oops forgot end', + ' ---', + ' operator: fail', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: test exited without ending: oops forgot end', + ' [... stack stripped ...]', + ' ...', + '', + '1..3', + '# tests 3', + '# pass 2', + '# fail 1' + ].join('\n') + '\n\n'); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/missing_end.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/fail.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/fail.js new file mode 100644 index 0000000..07a65ca --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/fail.js @@ -0,0 +1,35 @@ +var test = require('../../'); +var falafel = require('falafel'); + +test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/missing_end.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/missing_end.js new file mode 100644 index 0000000..7616fec --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/missing_end.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../../'); + +test('first', function (t) { + t.ok(true); + t.end(); +}); + +test('oops forgot end', function (t) { + t.ok(true); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/ok.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/ok.js new file mode 100644 index 0000000..6d405c7 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/ok.js @@ -0,0 +1,36 @@ +var falafel = require('falafel'); +var test = require('../../'); + +test('array', function (t) { + t.comment('hi'); + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/second.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/second.js new file mode 100644 index 0000000..8a206bb --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/second.js @@ -0,0 +1,11 @@ +var test = require('../../'); + +test('first', function (t) { + t.plan(1); + t.ok(true); +}); + +test('second', function (t) { + t.plan(2); + t.ok(true); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/todo.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/todo.js new file mode 100644 index 0000000..acbf960 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/todo.js @@ -0,0 +1,6 @@ +var test = require('../../'); + +test('todo pass', { todo: true }, function (t) { + t.plan(1); + t.ok(true); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/todo_fail.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/todo_fail.js new file mode 100644 index 0000000..f8ffa67 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/todo_fail.js @@ -0,0 +1,6 @@ +var test = require('../../'); + +test('todo fail', { todo: true }, function (t) { + t.plan(1); + t.ok(false); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exit/too_few.js b/tests/node_modules/tape-es/node_modules/tape/test/exit/too_few.js new file mode 100644 index 0000000..68ba71d --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exit/too_few.js @@ -0,0 +1,35 @@ +var falafel = require('falafel'); +var test = require('../../'); + +test('array', function (t) { + t.plan(6); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/exposed-harness.js b/tests/node_modules/tape-es/node_modules/tape/test/exposed-harness.js new file mode 100644 index 0000000..1056ddb --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/exposed-harness.js @@ -0,0 +1,12 @@ +var tape = require('../'); +var tap = require('tap'); + +tap.test('main harness object is exposed', function (assert) { + + assert.equal(typeof tape.getHarness, 'function', 'tape.getHarness is a function'); + + assert.equal(tape.getHarness()._results.pass, 0); + + assert.end(); + +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/fail.js b/tests/node_modules/tape-es/node_modules/tape/test/fail.js new file mode 100644 index 0000000..580e40a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/fail.js @@ -0,0 +1,78 @@ +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'not ok 5 should be equivalent', + ' ---', + ' operator: deepEqual', + ' expected: [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]', + ' actual: [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]', + ' at: ($TEST/fail.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be equivalent', + ' [... stack stripped ...]', + ' at $TEST/fail.js:$LINE:$COL', + ' at eval (eval at ($TEST/fail.js:$LINE:$COL))', + ' at eval (eval at ($TEST/fail.js:$LINE:$COL))', + ' at Test. ($TEST/fail.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1', + '' + ].join('\n')); + }; + + test.createStream().pipe(concat(tc)); + + test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/has spaces.js b/tests/node_modules/tape-es/node_modules/tape/test/has spaces.js new file mode 100644 index 0000000..f8630de --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/has spaces.js @@ -0,0 +1,40 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# fail', + 'not ok 1 this should fail', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/has spaces.js:$LINE:$COL)', + ' stack: |-', + ' Error: this should fail', + ' [... stack stripped ...]', + ' at Test. ($TEST/has spaces.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ].join('\n')); + }; + + test.createStream().pipe(concat(tc)); + + test('fail', function (t) { + t.fail('this should fail'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/.ignore b/tests/node_modules/tape-es/node_modules/tape/test/ignore/.ignore new file mode 100644 index 0000000..ec1cc29 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/.ignore @@ -0,0 +1 @@ +fake_node_modules diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub1.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub1.js new file mode 100644 index 0000000..6ef0b71 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.plan(1); + t.fail('Should not print'); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub2.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub2.js new file mode 100644 index 0000000..27bebd8 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/fake_node_modules/stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.fail('Should not print'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test.js new file mode 100644 index 0000000..f2d6f57 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../'); + +tape.test(function (t) { + t.plan(1); + t.ok('Okay'); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub1.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub1.js new file mode 100644 index 0000000..e91244e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.plan(1); + t.pass('test/stub1'); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub2.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub2.js new file mode 100644 index 0000000..f4661b8 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.pass('test/stub2'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub1.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub1.js new file mode 100644 index 0000000..0f39cfe --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../../'); + +tape.test(function (t) { + t.plan(1); + t.pass('test/sub/stub1'); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub2.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub2.js new file mode 100644 index 0000000..bec910d --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test/sub/sub.stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../../'); + +tape.test(function (t) { + t.pass('test/sub/stub2'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore/test2.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test2.js new file mode 100644 index 0000000..a2ceecc --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore/test2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../'); + +tape.test(function (t) { + t.pass('Should print'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/ignore_from_gitignore.js b/tests/node_modules/tape-es/node_modules/tape/test/ignore_from_gitignore.js new file mode 100644 index 0000000..16b076a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/ignore_from_gitignore.js @@ -0,0 +1,122 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +var tapeBin = path.join(process.cwd(), 'bin/tape'); + +tap.test('Should pass with ignoring', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(2); + + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# (anonymous)', + 'ok 1 should be truthy', + '# (anonymous)', + 'ok 2 test/stub1', + '# (anonymous)', + 'ok 3 test/stub2', + '# (anonymous)', + 'ok 4 test/sub/stub1', + '# (anonymous)', + 'ok 5 test/sub/stub2', + '# (anonymous)', + 'ok 6 Should print', + '', + '1..6', + '# tests 6', + '# pass 6', + '', + '# ok', + '', + '' + ].join('\n')); + }; + + var ps = spawn(tapeBin, ['**/*.js', '-i', '.ignore'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + tt.equal(code, 0); // code 0 + }); +}); + +tap.test('Should pass', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(2); + + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# (anonymous)', + 'not ok 1 Should not print', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/ignore/fake_node_modules/stub1.js:$LINE:$COL)', + ' stack: |-', + ' Error: Should not print', + ' [... stack stripped ...]', + ' at Test. ($TEST/ignore/fake_node_modules/stub1.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# (anonymous)', + 'not ok 2 Should not print', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/ignore/fake_node_modules/stub2.js:$LINE:$COL)', + ' stack: |-', + ' Error: Should not print', + ' [... stack stripped ...]', + ' at Test. ($TEST/ignore/fake_node_modules/stub2.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# (anonymous)', + 'ok 3 should be truthy', + '# (anonymous)', + 'ok 4 test/stub1', + '# (anonymous)', + 'ok 5 test/stub2', + '# (anonymous)', + 'ok 6 test/sub/stub1', + '# (anonymous)', + 'ok 7 test/sub/stub2', + '# (anonymous)', + 'ok 8 Should print', + '', + '1..8', + '# tests 8', + '# pass 6', + '# fail 2', + '', + '' + ].join('\n')); + }; + + var ps = spawn(tapeBin, ['**/*.js'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + tt.equal(code, 1); + }); +}); + +tap.test('Should fail when ignore file does not exist', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(3); + + var testStdout = function (rows) { + tt.same(rows.toString('utf8'), ''); + }; + + var testStderr = function (rows) { + tt.ok(/^ENOENT[:,] no such file or directory,? (?:open )?'\$TEST\/ignore\/.gitignore'\n$/m.test(stripFullStack(rows.toString('utf8')))); + }; + + var ps = spawn(tapeBin, ['**/*.js', '-i'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(testStdout)); + ps.stderr.pipe(concat(testStderr)); + ps.on('exit', function (code) { + tt.equal(code, 2); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/many.js b/tests/node_modules/tape-es/node_modules/tape/test/many.js new file mode 100644 index 0000000..d6e8515 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/many.js @@ -0,0 +1,8 @@ +var test = require('../'); + +test('many tests', function (t) { + t.plan(100); + for (var i = 0; i < 100; i++) { + setTimeout(function () { t.pass(); }, Math.random() * 50); + } +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/match.js b/tests/node_modules/tape-es/node_modules/tape/test/match.js new file mode 100644 index 0000000..09ccd34 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/match.js @@ -0,0 +1,173 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('match', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# match', + 'ok 1 regex arg must be a regex', + 'ok 2 string arg must be a string', + 'not ok 3 The input did not match the regular expression /abc/. Input: \'string\'', + ' ---', + ' operator: match', + ' expected: /abc/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input did not match the regular expression /abc/. Input: \'string\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 4 "string" does not match /abc/', + ' ---', + ' operator: match', + ' expected: /abc/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "string" does not match /abc/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 5 The input matched the regular expression /pass$/. Input: \'I will pass\'', + 'ok 6 "I will pass" matches /pass$/', + '', + '1..6', + '# tests 6', + '# pass 4', + '# fail 2', + '' + ].join('\n')); + }; + + test.createStream().pipe(concat(tc)); + + test('match', function (t) { + t.plan(6); + + t.throws( + function () { t.match(/abc/, 'string'); }, + TypeError, + 'regex arg must be a regex' + ); + + t.throws( + function () { t.match({ abc: 123 }, /abc/); }, + TypeError, + 'string arg must be a string' + ); + + t.match('string', /abc/); + t.match('string', /abc/, '"string" does not match /abc/'); + + t.match('I will pass', /pass$/); + t.match('I will pass', /pass$/, '"I will pass" matches /pass$/'); + + t.end(); + }); +}); + +tap.test('doesNotMatch', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# doesNotMatch', + 'ok 1 regex arg must be a regex', + 'ok 2 string arg must be a string', + 'not ok 3 The input was expected to not match the regular expression /string/. Input: \'string\'', + ' ---', + ' operator: doesNotMatch', + ' expected: /string/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input was expected to not match the regular expression /string/. Input: \'string\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 4 "string" should not match /string/', + ' ---', + ' operator: doesNotMatch', + ' expected: /string/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "string" should not match /string/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 5 The input was expected to not match the regular expression /pass$/. Input: \'I will pass\'', + ' ---', + ' operator: doesNotMatch', + ' expected: /pass$/', + ' actual: \'I will pass\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input was expected to not match the regular expression /pass$/. Input: \'I will pass\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 6 "I will pass" should not match /pass$/', + ' ---', + ' operator: doesNotMatch', + ' expected: /pass$/', + ' actual: \'I will pass\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "I will pass" should not match /pass$/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..6', + '# tests 6', + '# pass 2', + '# fail 4', + '' + ].join('\n')); + }; + + test.createStream().pipe(concat(tc)); + + test('doesNotMatch', function (t) { + t.plan(6); + + t.throws( + function () { t.doesNotMatch(/abc/, 'string'); }, + TypeError, + 'regex arg must be a regex' + ); + + t.throws( + function () { t.doesNotMatch({ abc: 123 }, /abc/); }, + TypeError, + 'string arg must be a string' + ); + + t.doesNotMatch('string', /string/); + t.doesNotMatch('string', /string/, '"string" should not match /string/'); + + t.doesNotMatch('I will pass', /pass$/); + t.doesNotMatch('I will pass', /pass$/, '"I will pass" should not match /pass$/'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/max_listeners.js b/tests/node_modules/tape-es/node_modules/tape/test/max_listeners.js new file mode 100644 index 0000000..23ebea8 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/max_listeners.js @@ -0,0 +1,10 @@ +var spawn = require('child_process').spawn; +var path = require('path'); + +var ps = spawn(process.execPath, [path.join(__dirname, 'max_listeners', 'source.js')]); + +ps.stdout.pipe(process.stdout, { end: false }); + +ps.stderr.on('data', function (buf) { + console.log('not ok ' + buf); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/max_listeners/source.js b/tests/node_modules/tape-es/node_modules/tape/test/max_listeners/source.js new file mode 100644 index 0000000..2179f97 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/max_listeners/source.js @@ -0,0 +1,5 @@ +var test = require('../../'); + +for (var i = 0; i < 11; i ++) { + test(function (t) { t.ok(true, 'true is truthy'); t.end(); }); +} diff --git a/tests/node_modules/tape-es/node_modules/tape/test/messages/defaults.js b/tests/node_modules/tape-es/node_modules/tape/test/messages/defaults.js new file mode 100644 index 0000000..e967214 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/messages/defaults.js @@ -0,0 +1,25 @@ +'use strict'; + +var test = require('../../'); + +test('default messages', function (t) { + t.plan(12); + + t.ok(true); + t.notOk(false); + + t.equal(true, true); + t.notEqual(true, false); + + t.looseEqual(true, true); + t.notLooseEqual(true, false); + + t.strictEqual(true, true); + t.notStrictEqual(true, false); + + t.deepEqual(true, true); + t.notDeepEqual(true, true); + + t.deepLooseEqual(true, true); + t.notDeepLooseEqual(true, false); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/nested-async-plan-noend.js b/tests/node_modules/tape-es/node_modules/tape/test/nested-async-plan-noend.js new file mode 100644 index 0000000..1acc141 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/nested-async-plan-noend.js @@ -0,0 +1,36 @@ +var test = require('../'); + +test('Harness async test support', function (t) { + t.plan(3); + + t.ok(true, 'sync child A'); + + t.test('sync child B', function (tt) { + tt.plan(2); + + setTimeout(function () { + tt.test('async grandchild A', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }, 50); + + setTimeout(function () { + tt.test('async grandchild B', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }, 100); + }); + + setTimeout(function () { + t.test('async child', function (tt) { + tt.plan(2); + tt.ok(true, 'sync grandchild in async child A'); + tt.test('sync grandchild in async child B', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }); + }, 200); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/nested-sync-noplan-noend.js b/tests/node_modules/tape-es/node_modules/tape/test/nested-sync-noplan-noend.js new file mode 100644 index 0000000..c0e5d4a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/nested-sync-noplan-noend.js @@ -0,0 +1,43 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('nested sync test without plan or end', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# nested without plan or end', + '# first', + 'ok 1 should be truthy', + '# second', + 'ok 2 should be truthy', + '', + '1..2', + '# tests 2', + '# pass 2', + '', + '# ok' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('nested without plan or end', function (t) { + t.test('first', function (q) { + setTimeout(function first() { + q.ok(true); + q.end(); + }, 10); + }); + t.test('second', function (q) { + setTimeout(function second() { + q.ok(true); + q.end(); + }, 10); + }); + }); + +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/nested.js b/tests/node_modules/tape-es/node_modules/tape/test/nested.js new file mode 100644 index 0000000..4682259 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/nested.js @@ -0,0 +1,83 @@ +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# nested array test', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'ok 5 should be equivalent', + '# inside test', + 'ok 6 should be truthy', + 'ok 7 should be truthy', + '# another', + 'ok 8 should be truthy', + '', + '1..8', + '# tests 8', + '# pass 8', + '', + '# ok' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('nested array test', function (t) { + t.plan(6); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + t.test('inside test', function (q) { + q.plan(2); + q.ok(true); + + setTimeout(function () { + q.ok(true); + }, 100); + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); + + test('another', function (t) { + t.plan(1); + setTimeout(function () { + t.ok(true); + }, 50); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/nested2.js b/tests/node_modules/tape-es/node_modules/tape/test/nested2.js new file mode 100644 index 0000000..1612b9b --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/nested2.js @@ -0,0 +1,19 @@ +var test = require('../'); + +test(function (t) { + var i = 0; + t.test('setup', function (t) { + process.nextTick(function () { + t.equal(i, 0, 'called once'); + i++; + t.end(); + }); + }); + + + t.test('teardown', function (t) { + t.end(); + }); + + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/no_callback.js b/tests/node_modules/tape-es/node_modules/tape/test/no_callback.js new file mode 100644 index 0000000..760ff26 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/no_callback.js @@ -0,0 +1,3 @@ +var test = require('../'); + +test('No callback.'); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/not-deep-equal-failure.js b/tests/node_modules/tape-es/node_modules/tape/test/not-deep-equal-failure.js new file mode 100644 index 0000000..63fbd61 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/not-deep-equal-failure.js @@ -0,0 +1,191 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('deep equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# not deep equal\n' + + 'not ok 1 should not be equivalent\n' + + ' ---\n' + + ' operator: notDeepEqual\n' + + ' expected: |-\n' + + ' { b: 2 }\n' + + ' actual: |-\n' + + ' { b: 2 }\n' + + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should not be equivalent\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ b: 2 }', + actual: '{ b: 2 }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ b: 2 }', + actual: '{ b: 2 }' + } + }); + }); + + test('not deep equal', function (t) { + t.plan(1); + t.notDeepEqual({b: 2}, {b: 2}); + }); +}); + +tap.test('not deep equal failure, depth 6, with option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# not deep equal\n' + + 'not ok 1 should not be equivalent\n' + + ' ---\n' + + ' operator: notDeepEqual\n' + + ' expected: |-\n' + + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }\n' + + ' actual: |-\n' + + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }\n' + + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should not be equivalent\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + } + }); + }); + + test('not deep equal', {objectPrintDepth: 6}, function (t) { + t.plan(1); + t.notDeepEqual({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }); + }); +}); + +tap.test('not deep equal failure, depth 6, without option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# not deep equal\n' + + 'not ok 1 should not be equivalent\n' + + ' ---\n' + + ' operator: notDeepEqual\n' + + ' expected: |-\n' + + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }\n' + + ' actual: |-\n' + + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }\n' + + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should not be equivalent\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + } + }); + }); + + test('not deep equal', function (t) { + t.plan(1); + t.notDeepEqual({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/not-equal-failure.js b/tests/node_modules/tape-es/node_modules/tape/test/not-equal-failure.js new file mode 100644 index 0000000..28e31a6 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/not-equal-failure.js @@ -0,0 +1,67 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('not equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# not equal\n' + + 'not ok 1 should not be equal\n' + + ' ---\n' + + ' operator: notEqual\n' + + ' expected: 2\n' + + ' actual: 2\n' + + ' at: Test. ($TEST/not-equal-failure.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should not be equal\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/not-equal-failure.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + assert.deepEqual(getDiag(body), { + operator: 'notEqual', + expected: '2', + actual: '2' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be equal', + diag: { + operator: 'notEqual', + expected: '2', + actual: '2' + } + }); + }); + + test('not equal', function (t) { + t.plan(1); + t.notEqual(2, 2); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/numerics.js b/tests/node_modules/tape-es/node_modules/tape/test/numerics.js new file mode 100644 index 0000000..a425de4 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/numerics.js @@ -0,0 +1,183 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('numerics', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# numeric strings\n' + + 'not ok 1 number equal to string\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: \'3\'\n' + + ' actual: 3\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: number equal to string\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 2 string equal to number\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: 3\n' + + ' actual: \'3\'\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: string equal to number\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 3 number notEqual to string\n' + + 'ok 4 string notEqual to number\n' + + 'ok 5 number looseEqual to string\n' + + 'ok 6 string looseEqual to number\n' + + 'not ok 7 number notLooseEqual to string\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: \'3\'\n' + + ' actual: 3\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: number notLooseEqual to string\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 8 string notLooseEqual to number\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: 3\n' + + ' actual: \'3\'\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: string notLooseEqual to number\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 9 number strictEqual to string\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: \'3\'\n' + + ' actual: 3\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: number strictEqual to string\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 10 string strictEqual to number\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: 3\n' + + ' actual: \'3\'\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: string strictEqual to number\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 11 number notStrictEqual to string\n' + + 'ok 12 string notStrictEqual to number\n' + + 'ok 13 number deepLooseEqual to string\n' + + 'ok 14 string deepLooseEqual to number\n' + + 'not ok 15 number notDeepLooseEqual to string\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: \'3\'\n' + + ' actual: 3\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: number notDeepLooseEqual to string\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 16 string notDeepLooseEqual to number\n' + + ' ---\n' + + ' operator: notDeepLooseEqual\n' + + ' expected: 3\n' + + ' actual: \'3\'\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: string notDeepLooseEqual to number\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 17 number deepEqual to string\n' + + ' ---\n' + + ' operator: deepEqual\n' + + ' expected: \'3\'\n' + + ' actual: 3\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: number deepEqual to string\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 18 string deepEqual to number\n' + + ' ---\n' + + ' operator: deepEqual\n' + + ' expected: 3\n' + + ' actual: \'3\'\n' + + ' at: Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: string deepEqual to number\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/numerics.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'ok 19 number notDeepEqual to string\n' + + 'ok 20 string notDeepEqual to number\n' + + '\n1..20\n' + + '# tests 20\n' + + '# pass 10\n' + + '# fail 10\n' + ); + })); + + test('numeric strings', function (t) { + t.equal(3, '3', 'number equal to string'); + t.equal('3', 3, 'string equal to number'); + t.notEqual(3, '3', 'number notEqual to string'); + t.notEqual('3', 3, 'string notEqual to number'); + + t.looseEqual(3, '3', 'number looseEqual to string'); + t.looseEqual('3', 3, 'string looseEqual to number'); + t.notLooseEqual(3, '3', 'number notLooseEqual to string'); + t.notLooseEqual('3', 3, 'string notLooseEqual to number'); + + t.strictEqual(3, '3', 'number strictEqual to string'); + t.strictEqual('3', 3, 'string strictEqual to number'); + t.notStrictEqual(3, '3', 'number notStrictEqual to string'); + t.notStrictEqual('3', 3, 'string notStrictEqual to number'); + + t.deepLooseEqual(3, '3', 'number deepLooseEqual to string'); + t.deepLooseEqual('3', 3, 'string deepLooseEqual to number'); + t.notDeepLooseEqual(3, '3', 'number notDeepLooseEqual to string'); + t.notDeepLooseEqual('3', 3, 'string notDeepLooseEqual to number'); + + t.deepEqual(3, '3', 'number deepEqual to string'); + t.deepEqual('3', 3, 'string deepEqual to number'); + t.notDeepEqual(3, '3', 'number notDeepEqual to string'); + t.notDeepEqual('3', 3, 'string notDeepEqual to number'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/objectMode.js b/tests/node_modules/tape-es/node_modules/tape/test/objectMode.js new file mode 100644 index 0000000..33df466 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/objectMode.js @@ -0,0 +1,69 @@ +var tap = require('tap'); +var tape = require('../'); +var forEach = require('for-each'); +var through = require('through'); + +tap.test('object results', function (assert) { + var printer = through({ objectMode: true }); + var objects = []; + + printer.write = function (obj) { + objects.push(obj); + }; + + printer.end = function (obj) { + if (obj) objects.push(obj); + + var todos = 0; + var skips = 0; + var testIds = []; + var endIds = []; + var asserts = 0; + + assert.equal(objects.length, 13); + + forEach(objects, function (obj) { + if (obj.type === 'assert') { + asserts++; + } else if (obj.type === 'test') { + testIds.push(obj.id); + + if (obj.skip) { + skips++; + } else if (obj.todo) { + todos++; + } + } else if (obj.type === 'end') { + endIds.push(obj.text); + // test object should exist + assert.notEqual(testIds.indexOf(obj.test), -1); + } + }); + + assert.equal(asserts, 5); + assert.equal(skips, 1); + assert.equal(todos, 2); + assert.equal(testIds.length, endIds.length); + assert.end(); + }; + + tape.createStream({ objectMode: true }).pipe(printer); + + tape('parent', function (t1) { + t1.equal(true, true); + t1.test('child1', {skip: true}, function (t2) { + t2.equal(true, true); + t2.equal(true, false); + t2.end(); + }); + t1.test('child2', {todo: true}, function (t3) { + t3.equal(true, false); + t3.equal(true, true); + t3.end(); + }); + t1.test('child3', {todo: true}); + t1.equal(true, true); + t1.equal(true, true); + t1.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/objectModeWithComment.js b/tests/node_modules/tape-es/node_modules/tape/test/objectModeWithComment.js new file mode 100644 index 0000000..9a34f27 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/objectModeWithComment.js @@ -0,0 +1,41 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var through = require('through'); + +tap.test('test.comment() in objectMode', function (assert) { + var printer = through({ objectMode: true }); + var objects = []; + printer.on('error', function (e) { + assert.fail(e); + }); + + printer.write = function (obj) { + objects.push(obj); + }; + printer.end = function (obj) { + if (obj) { objects.push(obj); } + + assert.equal(objects.length, 3); + assert.deepEqual(objects, [ + { + type: 'test', + name: 'test.comment', + id: 0, + skip: false, + todo: false + }, + 'message', + { type: 'end', test: 0 } + ]); + assert.end(); + }; + + tape.createStream({ objectMode: true }).pipe(printer); + + tape('test.comment', function (test) { + test.comment('message'); + test.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/onFailure.js b/tests/node_modules/tape-es/node_modules/tape/test/onFailure.js new file mode 100644 index 0000000..666227d --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/onFailure.js @@ -0,0 +1,21 @@ +var tap = require('tap'); +var tape = require('../').createHarness(); + +//Because this test passing depends on a failure, +//we must direct the failing output of the inner test +var noop = function () {}; +var mockSink = {on: noop, removeListener: noop, emit: noop, end: noop}; +tape.createStream().pipe(mockSink); + +tap.test('on failure', { timeout: 1000 }, function (tt) { + tt.plan(1); + + tape('dummy test', function (t) { + t.fail(); + t.end(); + }); + + tape.onFailure(function () { + tt.pass('tape ended'); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/onFinish.js b/tests/node_modules/tape-es/node_modules/tape/test/onFinish.js new file mode 100644 index 0000000..7881273 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/onFinish.js @@ -0,0 +1,12 @@ +var tap = require('tap'); +var tape = require('../'); + +tap.test('on finish', {timeout: 1000}, function (tt) { + tt.plan(1); + tape.onFinish(function () { + tt.pass('tape ended'); + }); + tape('dummy test', function (t) { + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only-twice.js b/tests/node_modules/tape-es/node_modules/tape/test/only-twice.js new file mode 100644 index 0000000..cca7c75 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only-twice.js @@ -0,0 +1,20 @@ +var tape = require('../'); +var tap = require('tap'); + +tap.test('only twice error', function (assert) { + var test = tape.createHarness({ exit: false }); + + test.only('first only', function (t) { + t.end(); + }); + + assert.throws(function () { + test.only('second only', function (t) { + t.end(); + }); + }, { + name: 'Error', + message: 'there can only be one only test' + }); + assert.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only.js b/tests/node_modules/tape-es/node_modules/tape/test/only.js new file mode 100644 index 0000000..41f2f83 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only.js @@ -0,0 +1,45 @@ +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +tap.test('tape only test', function (tt) { + var test = tape.createHarness({ exit: false }); + var ran = []; + + var tc = function (rows) { + tt.deepEqual(rows.toString('utf8'), [ + 'TAP version 13', + '# run success', + 'ok 1 assert name', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok' + ].join('\n') + '\n'); + tt.deepEqual(ran, [ 3 ]); + + tt.end(); + }; + + test.createStream().pipe(concat(tc)); + + test('never run fail', function (t) { + ran.push(1); + t.equal(true, false); + t.end(); + }); + + test('never run success', function (t) { + ran.push(2); + t.equal(true, true); + t.end(); + }); + + test.only('run success', function (t) { + ran.push(3); + t.ok(true, 'assert name'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only2.js b/tests/node_modules/tape-es/node_modules/tape/test/only2.js new file mode 100644 index 0000000..fcf4f43 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only2.js @@ -0,0 +1,9 @@ +var test = require('../'); + +test('only2 test 1', function (t) { + t.end(); +}); + +test.only('only2 test 2', function (t) { + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only3.js b/tests/node_modules/tape-es/node_modules/tape/test/only3.js new file mode 100644 index 0000000..b192a4e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only3.js @@ -0,0 +1,15 @@ +var test = require('../'); + +test('only3 test 1', function (t) { + t.fail('not 1'); + t.end(); +}); + +test.only('only3 test 2', function (t) { + t.end(); +}); + +test('only3 test 3', function (t) { + t.fail('not 3'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only4.js b/tests/node_modules/tape-es/node_modules/tape/test/only4.js new file mode 100644 index 0000000..d570b5b --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only4.js @@ -0,0 +1,10 @@ +var test = require('../'); + +test('only4 duplicate test name', function (t) { + t.fail('not 1'); + t.end(); +}); + +test.only('only4 duplicate test name', function (t) { + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/only5.js b/tests/node_modules/tape-es/node_modules/tape/test/only5.js new file mode 100644 index 0000000..0e15887 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/only5.js @@ -0,0 +1,10 @@ +var test = require('../'); + +test.only('only5 duplicate test name', function (t) { + t.end(); +}); + +test('only5 duplicate test name', function (t) { + t.fail('not 2'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/order.js b/tests/node_modules/tape-es/node_modules/tape/test/order.js new file mode 100644 index 0000000..02aaa05 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/order.js @@ -0,0 +1,17 @@ +var test = require('../'); +var current = 0; + +test(function (t) { + t.equal(current++, 0); + t.end(); +}); +test(function (t) { + t.plan(1); + setTimeout(function () { + t.equal(current++, 1); + }, 100); +}); +test(function (t) { + t.equal(current++, 2); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/plan_optional.js b/tests/node_modules/tape-es/node_modules/tape/test/plan_optional.js new file mode 100644 index 0000000..680dbcb --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/plan_optional.js @@ -0,0 +1,15 @@ +var test = require('../'); + +test('plan should be optional', function (t) { + t.pass('no plan here'); + t.end(); +}); + +test('no plan async', function (t) { + setTimeout(function () { + t.pass('ok'); + t.end(); + }, 100); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape-es/node_modules/tape/test/require.js b/tests/node_modules/tape-es/node_modules/tape/test/require.js new file mode 100644 index 0000000..7420bb7 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/require.js @@ -0,0 +1,69 @@ +var tap = require('tap'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +tap.test('requiring a single module', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# module-a', + 'ok 1 loaded module a', + '# test-a', + 'ok 2 module-a loaded in same context', + 'ok 3 test ran after module-a was loaded', + '', + '1..3', + '# tests 3', + '# pass 3', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = tape('-r ./require/a require/test-a.js'); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('requiring multiple modules', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# module-a', + 'ok 1 loaded module a', + '# module-b', + 'ok 2 loaded module b', + '# test-a', + 'ok 3 module-a loaded in same context', + 'ok 4 test ran after module-a was loaded', + '# test-b', + 'ok 5 module-b loaded in same context', + 'ok 6 test ran after module-b was loaded', + '', + '1..6', + '# tests 6', + '# pass 6', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = tape('-r ./require/a -r ./require/b require/test-a.js require/test-b.js'); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +function tape(args) { + var proc = require('child_process'); + var bin = __dirname + '/../bin/tape'; + + return proc.spawn('node', [bin].concat(args.split(' ')), { cwd: __dirname }); +} diff --git a/tests/node_modules/tape-es/node_modules/tape/test/require/a.js b/tests/node_modules/tape-es/node_modules/tape/test/require/a.js new file mode 100644 index 0000000..86e0296 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/require/a.js @@ -0,0 +1,8 @@ +var tape = require('../..'); + +tape.test('module-a', function (t) { + t.plan(1); + t.pass('loaded module a'); +}); + +global.module_a = true; diff --git a/tests/node_modules/tape-es/node_modules/tape/test/require/b.js b/tests/node_modules/tape-es/node_modules/tape/test/require/b.js new file mode 100644 index 0000000..808fc9e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/require/b.js @@ -0,0 +1,8 @@ +var tape = require('../..'); + +tape.test('module-b', function (t) { + t.plan(1); + t.pass('loaded module b'); +}); + +global.module_b = true; diff --git a/tests/node_modules/tape-es/node_modules/tape/test/require/test-a.js b/tests/node_modules/tape-es/node_modules/tape/test/require/test-a.js new file mode 100644 index 0000000..03d5a84 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/require/test-a.js @@ -0,0 +1,7 @@ +var tape = require('../..'); + +tape.test('test-a', function (t) { + t.ok(global.module_a, 'module-a loaded in same context'); + t.pass('test ran after module-a was loaded'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/require/test-b.js b/tests/node_modules/tape-es/node_modules/tape/test/require/test-b.js new file mode 100644 index 0000000..5069b55 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/require/test-b.js @@ -0,0 +1,7 @@ +var tape = require('../..'); + +tape.test('test-b', function (t) { + t.ok(global.module_b, 'module-b loaded in same context'); + t.pass('test ran after module-b was loaded'); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/skip.js b/tests/node_modules/tape-es/node_modules/tape/test/skip.js new file mode 100644 index 0000000..234c75a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/skip.js @@ -0,0 +1,52 @@ +var test = require('../'); +var ran = 0; + +var concat = require('concat-stream'); +var tap = require('tap'); + +tap.test('test SKIP comment', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# SKIP skipped', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var tapeTest = test.createHarness(); + tapeTest.createStream().pipe(concat(verify)); + tapeTest('skipped', { skip: true }, function (t) { + t.end(); + }); +}); + +test('skip this', { skip: true }, function (t) { + t.fail('this should not even run'); + ran++; + t.end(); +}); + +test.skip('skip this too', function (t) { + t.fail('this should not even run'); + ran++; + t.end(); +}); + +test('skip subtest', function (t) { + ran++; + t.test('skip this', { skip: true }, function (t) { + t.fail('this should not even run'); + t.end(); + }); + t.end(); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape-es/node_modules/tape/test/skip_explanation.js b/tests/node_modules/tape-es/node_modules/tape/test/skip_explanation.js new file mode 100644 index 0000000..09928ff --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/skip_explanation.js @@ -0,0 +1,82 @@ +var tap = require('tap'); +var test = require('../'); +var concat = require('concat-stream'); +var stripFullStack = require('./common').stripFullStack; + +tap.test('test skip explanations', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(stripFullStack(output.toString('utf8')), [ + 'TAP version 13', + '# SKIP (this skips)', + '# some tests might skip', + 'ok 1 this runs', + 'ok 2 failing assert is skipped # SKIP', + 'ok 3 this runs', + '# incomplete test', + 'ok 4 run sh', + 'ok 5 run openssl # SKIP', + '# incomplete test with explanation', + 'ok 6 run sh (conditional skip) # SKIP', + 'ok 7 run openssl # SKIP can\'t run on windows platforms', + 'ok 8 this runs', + '# too much explanation', + 'ok 9 run openssl # SKIP Installer cannot work on windows and fails to add to PATH Err: (2401) denied', + '', + '1..9', + '# tests 9', + '# pass 9', + '', + '# ok', + '' + ].join('\n')); + }; + + var tapeTest = test.createHarness(); + tapeTest.createStream().pipe(concat(verify)); + + tapeTest('(this skips)', { skip: true }, function (t) { + t.fail('doesn\'t run'); + t.fail('this doesn\'t run too', { skip: false }); + t.end(); + }); + + tapeTest('some tests might skip', function (t) { + t.pass('this runs'); + t.fail('failing assert is skipped', { skip: true }); + t.pass('this runs'); + t.end(); + }); + + tapeTest('incomplete test', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.pass('run sh', { skip: platform !== 'win32' }); + t.pass('run openssl', { skip: platform === 'win32' }); + t.end(); + }); + + tapeTest('incomplete test with explanation', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.fail('run sh (conditional skip)', { skip: platform === 'win32' }); + t.fail('run openssl', { skip: platform === 'win32' && 'can\'t run on windows platforms' }); + t.pass('this runs'); + t.end(); + }); + + tapeTest('too much explanation', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.fail('run openssl', + { skip: platform === 'win32' && 'Installer cannot work on windows\nand fails to add to PATH\n\n Err: (2401) denied' } + ); + t.end(); + }); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape-es/node_modules/tape/test/stackTrace.js b/tests/node_modules/tape-es/node_modules/tape/test/stackTrace.js new file mode 100644 index 0000000..f2e4b4e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/stackTrace.js @@ -0,0 +1,313 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var yaml = require('js-yaml'); + +tap.test('preserves stack trace with newlines', function (tt) { + tt.plan(3); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + var stackTrace = 'foo\n bar'; + + parser.once('assert', function (data) { + delete data.diag.at; + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'Error: Preserve stack', + diag: { + stack: stackTrace, + operator: 'error', + expected: 'undefined', + actual: '[Error: Preserve stack]' + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# multiline stack trace\n' + + 'not ok 1 Error: Preserve stack\n' + + ' ---\n' + + ' operator: error\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' [Error: Preserve stack]\n' + + ' stack: |-\n' + + ' foo\n' + + ' bar\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stackTrace, + operator: 'error', + expected: 'undefined', + actual: '[Error: Preserve stack]' + }); + })); + + test('multiline stack trace', function (t) { + t.plan(1); + var err = new Error('Preserve stack'); + err.stack = stackTrace; + t.error(err); + }); +}); + +tap.test('parses function info from original stack', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('Test.testFunctionNameParsing', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + t.equal(true, false, 'true should be false'); + t.end(); + }); +}); + +tap.test('parses function info from original stack for anonymous function', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('Test.', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function (t) { + t.equal(true, false, 'true should be false'); + t.end(); + }); +}); + +if (typeof Promise === 'function' && typeof Promise.resolve === 'function') { + + tap.test('parses function info from original stack for Promise scenario', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('onfulfilled', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + new Promise(function (resolve) { + resolve(); + }).then(function onfulfilled() { + t.equal(true, false, 'true should be false'); + t.end(); + }); + }); + }); + + tap.test('parses function info from original stack for Promise scenario with anonymous function', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + new Promise(function (resolve) { + resolve(); + }).then(function () { + t.equal(true, false, 'true should be false'); + t.end(); + }); + }); + }); + +} + +tap.test('preserves stack trace for failed assertions', function (tt) { + tt.plan(6); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + + var stack = ''; + parser.once('assert', function (data) { + tt.equal(typeof data.diag.at, 'string'); + tt.equal(typeof data.diag.stack, 'string'); + at = data.diag.at || ''; + stack = data.diag.stack || ''; + tt.ok(/^Error: true should be false(\n at .+)+/.exec(stack), 'stack should be a stack'); + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'true should be false', + diag: { + at: at, + stack: stack, + operator: 'equal', + expected: false, + actual: true + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# t.equal stack trace\n' + + 'not ok 1 true should be false\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: false\n' + + ' actual: true\n' + + ' stack: |-\n' + + ' ' + + stack.replace(/\n/g, '\n ') + '\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stack, + operator: 'equal', + expected: false, + actual: true + }); + })); + + test('t.equal stack trace', function (t) { + t.plan(1); + t.equal(true, false, 'true should be false'); + }); +}); + +tap.test('preserves stack trace for failed assertions where actual===falsy', function (tt) { + tt.plan(6); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + + var stack = ''; + parser.once('assert', function (data) { + tt.equal(typeof data.diag.at, 'string'); + tt.equal(typeof data.diag.stack, 'string'); + at = data.diag.at || ''; + stack = data.diag.stack || ''; + tt.ok(/^Error: false should be true(\n at .+)+/.exec(stack), 'stack should be a stack'); + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'false should be true', + diag: { + at: at, + stack: stack, + operator: 'equal', + expected: true, + actual: false + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# t.equal stack trace\n' + + 'not ok 1 false should be true\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: true\n' + + ' actual: false\n' + + ' stack: |-\n' + + ' ' + + stack.replace(/\n/g, '\n ') + '\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stack, + operator: 'equal', + expected: true, + actual: false + }); + })); + + test('t.equal stack trace', function (t) { + t.plan(1); + t.equal(false, true, 'false should be true'); + }); +}); + +function getDiag(body) { + var yamlStart = body.indexOf(' ---'); + var yamlEnd = body.indexOf(' ...\n'); + var diag = body.slice(yamlStart, yamlEnd).split('\n').map(function (line) { + return line.slice(2); + }).join('\n'); + + // Get rid of 'at' variable (which has a line number / path of its own that's + // difficult to check). + var withStack = yaml.safeLoad(diag); + delete withStack.at; + return withStack; +} + +function stripAt(body) { + return body.replace(/^\s*at:\s+Test.*$\n/m, ''); +} diff --git a/tests/node_modules/tape-es/node_modules/tape/test/subcount.js b/tests/node_modules/tape-es/node_modules/tape/test/subcount.js new file mode 100644 index 0000000..8985e6d --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/subcount.js @@ -0,0 +1,14 @@ +var test = require('../'); + +test('parent test', function (t) { + t.plan(2); + t.test('first child', function (t) { + t.plan(1); + t.pass('pass first child'); + }); + + t.test(function (t) { + t.plan(1); + t.pass('pass second child'); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/subtest_and_async.js b/tests/node_modules/tape-es/node_modules/tape/test/subtest_and_async.js new file mode 100644 index 0000000..5d92285 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/subtest_and_async.js @@ -0,0 +1,25 @@ +var test = require('../'); + +var asyncFunction = function (callback) { + setTimeout(callback, Math.random * 50); +}; + +test('master test', function (t) { + t.test('subtest 1', function (st) { + st.pass('subtest 1 before async call'); + asyncFunction(function () { + st.pass('subtest 1 in async callback'); + st.end(); + }); + }); + + t.test('subtest 2', function (st) { + st.pass('subtest 2 before async call'); + asyncFunction(function () { + st.pass('subtest 2 in async callback'); + st.end(); + }); + }); + + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/subtest_plan.js b/tests/node_modules/tape-es/node_modules/tape/test/subtest_plan.js new file mode 100644 index 0000000..e0f906e --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/subtest_plan.js @@ -0,0 +1,21 @@ +var test = require('../'); + +test('parent', function (t) { + t.plan(3); + + var firstChildRan = false; + + t.pass('assertion in parent'); + + t.test('first child', function (t) { + t.plan(1); + t.pass('pass first child'); + firstChildRan = true; + }); + + t.test('second child', function (t) { + t.plan(2); + t.ok(firstChildRan, 'first child ran first'); + t.pass('pass second child'); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/throws.js b/tests/node_modules/tape-es/node_modules/tape/test/throws.js new file mode 100644 index 0000000..1628d82 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/throws.js @@ -0,0 +1,224 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +function fn() { + throw new TypeError('RegExp'); +} + +function getNonFunctionMessage(fn) { + try { + fn(); + } catch (e) { + return e.message; + } +} + +var getter = function () { return 'message'; }; +var messageGetterError = Object.defineProperty( + { custom: 'error' }, + 'message', + { configurable: true, enumerable: true, get: getter } +); +var thrower = function () { throw messageGetterError; }; + +tap.test('failures', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# non functions\n' + + 'not ok 1 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage() + "] message: '" + getNonFunctionMessage() + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage(undefined) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 2 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage(null) + "] message: '" + getNonFunctionMessage(null) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage(null) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 3 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage(true) + "] message: '" + getNonFunctionMessage(true) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage(true) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 4 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage(false) + "] message: '" + getNonFunctionMessage(false) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage(false) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 5 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage('abc') + "] message: '" + getNonFunctionMessage('abc') + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage('abc') + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 6 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage(/a/g) + "] message: '" + getNonFunctionMessage(/a/g) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage(/a/g) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 7 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage([]) + "] message: '" + getNonFunctionMessage([]) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage([]) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + 'not ok 8 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' undefined\n' + + ' actual: |-\n' + + ' { [TypeError: ' + getNonFunctionMessage({}) + "] message: '" + getNonFunctionMessage({}) + "' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' TypeError: ' + getNonFunctionMessage({}) + '\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '# function\n' + + 'not ok 9 should throw\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: undefined\n' + + ' actual: undefined\n' + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should throw\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '# custom error messages\n' + + 'ok 10 "message" is enumerable\n' + + "ok 11 { custom: 'error', message: 'message' }\n" + + 'ok 12 getter is still the same\n' + + '# throws null\n' + + 'ok 13 throws null\n' + + '# wrong type of error\n' + + 'not ok 14 throws actual\n' + + ' ---\n' + + ' operator: throws\n' + + ' expected: |-\n' + + ' [Function: TypeError]\n' + + ' actual: |-\n' + + " { [RangeError: actual!] message: 'actual!' }\n" + + ' at: Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' RangeError: actual!\n' + + ' at Test. ($TEST/throws.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n1..14\n' + + '# tests 14\n' + + '# pass 4\n' + + '# fail 10\n' + ); + })); + + test('non functions', function (t) { + t.plan(8); + t.throws(); + t.throws(null); + t.throws(true); + t.throws(false); + t.throws('abc'); + t.throws(/a/g); + t.throws([]); + t.throws({}); + }); + + test('function', function (t) { + t.plan(1); + t.throws(function () {}); + }); + + test('custom error messages', function (t) { + t.plan(3); + t.equal(Object.prototype.propertyIsEnumerable.call(messageGetterError, 'message'), true, '"message" is enumerable'); + t.throws(thrower, "{ custom: 'error', message: 'message' }"); + t.equal(Object.getOwnPropertyDescriptor(messageGetterError, 'message').get, getter, 'getter is still the same'); + }); + + test('throws null', function (t) { + t.plan(1); + t.throws(function () { throw null; }, 'throws null'); + t.end(); + }); + + test('wrong type of error', function (t) { + t.plan(1); + var actual = new RangeError('actual!'); + t.throws(function () { throw actual; }, TypeError, 'throws actual'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/timeout.js b/tests/node_modules/tape-es/node_modules/tape/test/timeout.js new file mode 100644 index 0000000..b74b11a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/timeout.js @@ -0,0 +1,15 @@ +var test = require('../'); +var ran = 0; + +test('timeout', function (t) { + t.pass('this should run'); + ran++; + setTimeout(function () { + t.end(); + }, 100); +}); + +test('should still run', { timeout: 50 }, function (t) { + t.equal(ran, 1); + t.end(); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/timeoutAfter.js b/tests/node_modules/tape-es/node_modules/tape/test/timeoutAfter.js new file mode 100644 index 0000000..80752d2 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/timeoutAfter.js @@ -0,0 +1,36 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('timeoutAfter test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# timeoutAfter', + 'not ok 1 test timed out after 1ms', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: test timed out after 1ms', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('timeoutAfter', function (t) { + t.plan(1); + t.timeoutAfter(1); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/todo.js b/tests/node_modules/tape-es/node_modules/tape/test/todo.js new file mode 100644 index 0000000..73a8f6a --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/todo.js @@ -0,0 +1,42 @@ +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# success\n' + + 'ok 1 this test runs\n' + + '# TODO failure\n' + + 'not ok 2 should never happen # TODO\n' + + ' ---\n' + + ' operator: fail\n' + + ' at: Test. ($TEST/todo.js:$LINE:$COL)\n' + + ' ...\n' + + '\n' + + '1..2\n' + + '# tests 2\n' + + '# pass 2\n' + + '\n' + + '# ok\n' + ); + })); + + test('success', function (t) { + t.equal(true, true, 'this test runs'); + t.end(); + }); + + test('failure', { todo: true }, function (t) { + t.fail('should never happen'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/todo_explanation.js b/tests/node_modules/tape-es/node_modules/tape/test/todo_explanation.js new file mode 100644 index 0000000..5269b08 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/todo_explanation.js @@ -0,0 +1,70 @@ +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', { todo: process.versions.node.match(/0\.8\.\d+/) ? 'Fails on node 0.8': false }, function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# success', + 'ok 1 this test runs', + '# TODO incomplete test1', + 'not ok 2 check output # TODO', + ' ---', + ' operator: equal', + ' expected: false', + ' actual: true', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + 'not ok 3 check vars output # TODO name conflict', + ' ---', + ' operator: equal', + ' expected: 0', + ' actual: 1', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + '# incomplete test2', + 'not ok 4 run openssl # TODO installer needs fix', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + '# TODO passing test', + '', + '1..4', + '# tests 4', + '# pass 4', + '', + '# ok', + '' + ].join('\n') + ); + })); + + test('success', function (t) { + t.equal(true, true, 'this test runs'); + t.end(); + }); + + test('incomplete test1', { todo: true }, function (t) { + t.equal(true, false, 'check output'); + t.equal(1, 0, 'check vars output', { todo: 'name conflict' }); + t.end(); + }); + + test('incomplete test2', function (t) { + t.fail('run openssl', { todo: 'installer needs fix' }); + t.end(); + }); + + test('passing test', { todo: 'yet incomplete' }, function (t) { + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/todo_single.js b/tests/node_modules/tape-es/node_modules/tape/test/todo_single.js new file mode 100644 index 0000000..48cd287 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/todo_single.js @@ -0,0 +1,37 @@ +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# TODO failure\n' + + 'not ok 1 should be equal # TODO\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: false\n' + + ' actual: true\n' + + ' at: Test. ($TEST/todo_single.js:$LINE:$COL)\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 1\n' + + '\n' + + '# ok\n' + ); + })); + + test('failure', { todo: true }, function (t) { + t.equal(true, false); + t.end(); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/too_many.js b/tests/node_modules/tape-es/node_modules/tape/test/too_many.js new file mode 100644 index 0000000..946ceb8 --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/too_many.js @@ -0,0 +1,78 @@ +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be equivalent', + 'ok 2 should be equivalent', + 'ok 3 should be equivalent', + 'ok 4 should be equivalent', + 'not ok 5 plan != count', + ' ---', + ' operator: fail', + ' expected: 3', + ' actual: 4', + ' at: ($TEST/too_many.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' at $TEST/too_many.js:$LINE:$COL', + ' at eval (eval at ($TEST/too_many.js:$LINE:$COL))', + ' at eval (eval at ($TEST/too_many.js:$LINE:$COL))', + ' at Test. ($TEST/too_many.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 6 should be equivalent', + '', + '1..6', + '# tests 6', + '# pass 5', + '# fail 1' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('array', function (t) { + t.plan(3); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape-es/node_modules/tape/test/undef.js b/tests/node_modules/tape-es/node_modules/tape/test/undef.js new file mode 100644 index 0000000..52759ac --- /dev/null +++ b/tests/node_modules/tape-es/node_modules/tape/test/undef.js @@ -0,0 +1,42 @@ +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.equal( + stripFullStack(body.toString('utf8')), + 'TAP version 13\n' + + '# undef\n' + + 'not ok 1 should be equivalent\n' + + ' ---\n' + + ' operator: deepEqual\n' + + ' expected: |-\n' + + ' { beep: undefined }\n' + + ' actual: |-\n' + + ' {}\n' + + ' at: Test. ($TEST/undef.js:$LINE:$COL)\n' + + ' stack: |-\n' + + ' Error: should be equivalent\n' + + ' [... stack stripped ...]\n' + + ' at Test. ($TEST/undef.js:$LINE:$COL)\n' + + ' [... stack stripped ...]\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + })); + + test('undef', function (t) { + t.plan(1); + t.deepEqual({}, { beep: undefined }); + }); +}); diff --git a/tests/node_modules/tape-es/package.json b/tests/node_modules/tape-es/package.json new file mode 100644 index 0000000..2d703c3 --- /dev/null +++ b/tests/node_modules/tape-es/package.json @@ -0,0 +1,94 @@ +{ + "_from": "tape-es", + "_id": "tape-es@1.2.15", + "_inBundle": false, + "_integrity": "sha512-b8saVSzLFvxPro394o718mAN37iMvHrOt9XLx+caZIewBeA2Q4LobUtW2Gjv5JMsrm9VrZ4L9+4xRVUyUokmpQ==", + "_location": "/tape-es", + "_phantomChildren": { + "defined": "1.0.0", + "dotignore": "0.1.2", + "for-each": "0.3.3", + "function-bind": "1.1.1", + "glob": "7.1.7", + "has": "1.0.3", + "inherits": "2.0.4", + "is-arguments": "1.1.0", + "is-date-object": "1.0.4", + "minimist": "1.2.5", + "object-is": "1.1.5", + "object-keys": "1.1.1", + "path-parse": "1.0.7", + "regexp.prototype.flags": "1.3.1", + "resumer": "0.0.0", + "string.prototype.trim": "1.2.4", + "through": "2.3.8" + }, + "_requested": { + "type": "tag", + "registry": true, + "raw": "tape-es", + "name": "tape-es", + "escapedName": "tape-es", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/tape-es/-/tape-es-1.2.15.tgz", + "_shasum": "b50a8c0aff65a9f0bd7c6084738c302a499abba0", + "_spec": "tape-es", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests", + "author": { + "name": "Evan Plaice", + "email": "evanplaice@gmail.com", + "url": "http://evanplaice.com/" + }, + "bin": { + "tape-es": "bin/tape-es.js", + "tape-watch-es": "bin/tape-watch-es.js" + }, + "bugs": { + "url": "https://github.com/vanillaes/tape-es/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chokidar": "^3.5.1", + "commander": "^4.1.1", + "glob": "^7.1.6", + "tape": "^4.13.3" + }, + "deprecated": false, + "description": "ESM-compatible Tape.js test runner", + "devDependencies": { + "esmtk": "^0.5.3" + }, + "engines": { + "node": ">=14" + }, + "homepage": "https://github.com/vanillaes/tape-es#readme", + "keywords": [ + "testing", + "esm", + "esmodules", + "tape", + "nodejs", + "cli" + ], + "license": "MIT", + "name": "tape-es", + "repository": { + "type": "git", + "url": "git+https://github.com/vanillaes/tape-es.git" + }, + "scripts": { + "lint": "esmtk lint", + "package": "npx rimraf package && npm pack | tail -n 1 | xargs tar -xf", + "postversion": "git push --follow-tags", + "preversion": "npm run lint" + }, + "type": "module", + "version": "1.2.15" +} diff --git a/tests/node_modules/tape-es/src/runners.js b/tests/node_modules/tape-es/src/runners.js new file mode 100644 index 0000000..2e1c75e --- /dev/null +++ b/tests/node_modules/tape-es/src/runners.js @@ -0,0 +1,26 @@ +import { spawn } from 'child_process' +import { eachLimit } from './util/index.js' + +export async function run (test, root) { + spawn('node', [test], { + cwd: root, + stdio: ['pipe', process.stdout, process.stderr] + }).on('close', msg => { + if (msg === 1) { console.error('\x1b[31m%s\x1b[0m %s', 'ERR', 'Test failed!') } + }).on('error', err => { + console.error(err) + }) +} + +export async function runAll (tests, max, root) { + await eachLimit(tests, max, function (test) { + spawn('node', [test], { + cwd: root, + stdio: ['pipe', process.stdout, process.stderr] + }).on('close', msg => { + if (msg === 1) { process.exitCode = 1 } + }).on('error', err => { + console.error(err) + }) + }) +} diff --git a/tests/node_modules/tape-es/src/util/eachLimit.js b/tests/node_modules/tape-es/src/util/eachLimit.js new file mode 100644 index 0000000..3c777b3 --- /dev/null +++ b/tests/node_modules/tape-es/src/util/eachLimit.js @@ -0,0 +1,7 @@ +export async function eachLimit (items, limit, fn) { + Promise.all([...Array(limit)].map(async () => { + while (items.length > 0) { + await fn(items.pop()) + } + })) +} diff --git a/tests/node_modules/tape-es/src/util/index.js b/tests/node_modules/tape-es/src/util/index.js new file mode 100644 index 0000000..f363c42 --- /dev/null +++ b/tests/node_modules/tape-es/src/util/index.js @@ -0,0 +1,3 @@ +export { eachLimit } from './eachLimit.js' +export { match } from './match.js' +export { readPkg } from './readPkg.js' diff --git a/tests/node_modules/tape-es/src/util/match.js b/tests/node_modules/tape-es/src/util/match.js new file mode 100644 index 0000000..fd58432 --- /dev/null +++ b/tests/node_modules/tape-es/src/util/match.js @@ -0,0 +1,11 @@ +import glob from 'glob' +import { promisify } from 'util' +const globAsync = promisify(glob) + +export async function match (pattern, ignore, root) { + // multiple ignore patterns + if (ignore.includes(',')) { + ignore = ignore.split(',') + } + return globAsync(pattern, { cwd: root, ignore }) +} diff --git a/tests/node_modules/tape-es/src/util/readPkg.js b/tests/node_modules/tape-es/src/util/readPkg.js new file mode 100644 index 0000000..d98e2db --- /dev/null +++ b/tests/node_modules/tape-es/src/util/readPkg.js @@ -0,0 +1,14 @@ +import { promises as fs } from 'fs' + +export async function readPkg () { + const PKG_PATH = new URL('../../package.json', import.meta.url) + if (!await fs.stat(PKG_PATH)) { + throw Error('package.json not found, is this a package?') + } + + try { + return JSON.parse(await fs.readFile(PKG_PATH, 'utf-8')) + } catch { + throw Error('Failed to read package.json') + } +} diff --git a/tests/node_modules/tape/.editorconfig b/tests/node_modules/tape/.editorconfig new file mode 100644 index 0000000..32f9d03 --- /dev/null +++ b/tests/node_modules/tape/.editorconfig @@ -0,0 +1,40 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 180 +block_comment_start = /* +block_comment = * +block_comment_end = */ + +[.nycrc] +indent_style = tab + +[*.md] +indent_style = space +indent_size = 4 + +[*.yml] +indent_style = space +indent_size = 2 + +[readme.markdown] +indent_size = off +max_line_length = off + +[*.json] +max_line_length = off + +[*.yml] +max_line_length = off + +[Makefile] +max_line_length = off + +[.travis.yml] +indent_size = 1 diff --git a/tests/node_modules/tape/.eslintignore b/tests/node_modules/tape/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/tape/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/tape/.eslintrc b/tests/node_modules/tape/.eslintrc new file mode 100644 index 0000000..6a6eed2 --- /dev/null +++ b/tests/node_modules/tape/.eslintrc @@ -0,0 +1,45 @@ +{ + "root": true, + "env": { + "browser": true, + "node": true, + }, + "globals": { + "Promise": false, + }, + "rules": { + "comma-dangle": ["error", "never"], + "indent": ["error", 4], + "key-spacing": "error", + "quotes": ["error", "single", { + "avoidEscape": true, + }], + "semi": ["error", "always"], + "space-before-function-paren": ["error", { + "anonymous": "always", + "named": "never", + }], + "no-undef": "error", + "no-useless-escape": "error", + "operator-linebreak": ["error", "before"], + "space-unary-ops": ["error", { + "words": false, + "nonwords": false, + }], + "strict": "error", + }, + "overrides": [ + { + "files": ["test/async-await/*"], + "parserOptions": { + "ecmaVersion": 2017, + }, + }, + { + "files": ["example/**", "test/**"], + "globals": { + "g": false, + }, + }, + ], +} diff --git a/tests/node_modules/tape/.nycrc b/tests/node_modules/tape/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/tests/node_modules/tape/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/tape/LICENSE b/tests/node_modules/tape/LICENSE new file mode 100644 index 0000000..ff4fce2 --- /dev/null +++ b/tests/node_modules/tape/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/tape/bin/tape b/tests/node_modules/tape/bin/tape new file mode 100755 index 0000000..771fd01 --- /dev/null +++ b/tests/node_modules/tape/bin/tape @@ -0,0 +1,58 @@ +#!/usr/bin/env node + +'use strict'; + +var resolveModule = require('resolve').sync; +var resolvePath = require('path').resolve; +var readFileSync = require('fs').readFileSync; +var parseOpts = require('minimist'); +var glob = require('glob'); +var ignore = require('dotignore'); + +var opts = parseOpts(process.argv.slice(2), { + alias: { r: 'require', i: 'ignore' }, + string: ['require', 'ignore'], + default: { r: [], i: null } +}); + +var cwd = process.cwd(); + +if (typeof opts.require === 'string') { + opts.require = [opts.require]; +} + +opts.require.forEach(function (module) { + var options = { basedir: cwd, extensions: Object.keys(require.extensions) }; + if (module) { + /* This check ensures we ignore `-r ""`, trailing `-r`, or + * other silly things the user might (inadvertently) be doing. + */ + require(resolveModule(module, options)); + } +}); + +if (typeof opts.ignore === 'string') { + try { + var ignoreStr = readFileSync(resolvePath(cwd, opts.ignore || '.gitignore'), 'utf-8'); + } catch (e) { + console.error(e.message); + process.exit(2); + } + var matcher = ignore.createMatcher(ignoreStr); +} + +opts._.forEach(function (arg) { + // If glob does not match, `files` will be an empty array. + // Note: `glob.sync` may throw an error and crash the node process. + var files = glob.sync(arg); + + if (!Array.isArray(files)) { + throw new TypeError('unknown error: glob.sync did not return an array or throw. Please report this.'); + } + + files.filter(function (file) { return !matcher || !matcher.shouldIgnore(file); }).forEach(function (file) { + require(resolvePath(cwd, file)); + }); +}); + +// vim: ft=javascript diff --git a/tests/node_modules/tape/example/array.js b/tests/node_modules/tape/example/array.js new file mode 100644 index 0000000..8b99804 --- /dev/null +++ b/tests/node_modules/tape/example/array.js @@ -0,0 +1,37 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/example/fail.js b/tests/node_modules/tape/example/fail.js new file mode 100644 index 0000000..28c6ac7 --- /dev/null +++ b/tests/node_modules/tape/example/fail.js @@ -0,0 +1,37 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/example/nested.js b/tests/node_modules/tape/example/nested.js new file mode 100644 index 0000000..0e4e1cb --- /dev/null +++ b/tests/node_modules/tape/example/nested.js @@ -0,0 +1,53 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('nested array test', function (t) { + t.plan(6); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + t.test('inside test', function (q) { + q.plan(2); + q.ok(true, 'inside ok'); + + setTimeout(function () { + q.ok(true, 'inside delayed'); + }, 3000); + }); + + var arrays = [ + [3, 4], + [1, 2, [3, 4]], + [5, 6], + [[1, 2, [3, 4]], [5, 6]] + ]; + + Function(['fn', 'g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [[1, 2, [3, 4]], [5, 6]]); + } + ); +}); + +test('another', function (t) { + t.plan(1); + setTimeout(function () { + t.ok(true); + }, 100); +}); diff --git a/tests/node_modules/tape/example/nested_fail.js b/tests/node_modules/tape/example/nested_fail.js new file mode 100644 index 0000000..8013a48 --- /dev/null +++ b/tests/node_modules/tape/example/nested_fail.js @@ -0,0 +1,53 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('nested array test', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + t.test('inside test', function (q) { + q.plan(2); + q.ok(true); + + setTimeout(function () { + q.equal(3, 4); + }, 3000); + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); + +test('another', function (t) { + t.plan(1); + setTimeout(function () { + t.ok(true); + }, 100); +}); diff --git a/tests/node_modules/tape/example/no_callback.js b/tests/node_modules/tape/example/no_callback.js new file mode 100644 index 0000000..698701f --- /dev/null +++ b/tests/node_modules/tape/example/no_callback.js @@ -0,0 +1,5 @@ +'use strict'; + +var test = require('../'); + +test('No cb test'); diff --git a/tests/node_modules/tape/example/not_enough_fail.js b/tests/node_modules/tape/example/not_enough_fail.js new file mode 100644 index 0000000..ecd2dce --- /dev/null +++ b/tests/node_modules/tape/example/not_enough_fail.js @@ -0,0 +1,37 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('array', function (t) { + t.plan(8); + + var src = '(' + function () { + var xs = [1, 2, [3, 4]]; + var ys = [5, 6]; + g([xs, ys]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [3, 4], + [1, 2, [3, 4]], + [5, 6], + [[1, 2, [3, 4]], [5, 6]] + ]; + + Function(['fn', 'g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [[1, 2, [3, 4]], [5, 6]]); + } + ); +}); diff --git a/tests/node_modules/tape/example/static/build.sh b/tests/node_modules/tape/example/static/build.sh new file mode 100755 index 0000000..c583640 --- /dev/null +++ b/tests/node_modules/tape/example/static/build.sh @@ -0,0 +1,2 @@ +#!/bin/bash +browserify ../timing.js -o bundle.js diff --git a/tests/node_modules/tape/example/static/index.html b/tests/node_modules/tape/example/static/index.html new file mode 100644 index 0000000..45ccf07 --- /dev/null +++ b/tests/node_modules/tape/example/static/index.html @@ -0,0 +1,21 @@ + + + + + + + + + + diff --git a/tests/node_modules/tape/example/static/server.js b/tests/node_modules/tape/example/static/server.js new file mode 100644 index 0000000..6b1e353 --- /dev/null +++ b/tests/node_modules/tape/example/static/server.js @@ -0,0 +1,6 @@ +'use strict'; + +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(ecstatic); +server.listen(8000); diff --git a/tests/node_modules/tape/example/stream/object.js b/tests/node_modules/tape/example/stream/object.js new file mode 100644 index 0000000..39c662c --- /dev/null +++ b/tests/node_modules/tape/example/stream/object.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../../'); +var path = require('path'); + +test.createStream({ objectMode: true }).on('data', function (row) { + console.log(JSON.stringify(row)); +}); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); diff --git a/tests/node_modules/tape/example/stream/tap.js b/tests/node_modules/tape/example/stream/tap.js new file mode 100644 index 0000000..53d7e23 --- /dev/null +++ b/tests/node_modules/tape/example/stream/tap.js @@ -0,0 +1,10 @@ +'use strict'; + +var test = require('../../'); +var path = require('path'); + +test.createStream().pipe(process.stdout); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); diff --git a/tests/node_modules/tape/example/stream/test/x_fail.js b/tests/node_modules/tape/example/stream/test/x_fail.js new file mode 100644 index 0000000..670baa5 --- /dev/null +++ b/tests/node_modules/tape/example/stream/test/x_fail.js @@ -0,0 +1,7 @@ +'use strict'; + +var test = require('../../../'); +test(function (t) { + t.plan(1); + t.equal('beep', 'boop'); +}); diff --git a/tests/node_modules/tape/example/stream/test/y.js b/tests/node_modules/tape/example/stream/test/y.js new file mode 100644 index 0000000..0a0928f --- /dev/null +++ b/tests/node_modules/tape/example/stream/test/y.js @@ -0,0 +1,13 @@ +'use strict'; + +var test = require('../../../'); +test(function (t) { + t.plan(2); + t.equal(1 + 1, 2); + t.ok(true); +}); + +test('wheee', function (t) { + t.ok(true); + t.end(); +}); diff --git a/tests/node_modules/tape/example/throw.js b/tests/node_modules/tape/example/throw.js new file mode 100644 index 0000000..ef82c3a --- /dev/null +++ b/tests/node_modules/tape/example/throw.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = require('../'); + +test('throw', function (t) { + t.plan(2); + + setTimeout(function () { + throw new Error('doom'); + }, 100); +}); diff --git a/tests/node_modules/tape/example/timing.js b/tests/node_modules/tape/example/timing.js new file mode 100644 index 0000000..ba97963 --- /dev/null +++ b/tests/node_modules/tape/example/timing.js @@ -0,0 +1,14 @@ +'use strict'; + +var test = require('../'); + +test('timing test', function (t) { + t.plan(2); + + t.equal(typeof Date.now, 'function'); + var start = Date.now(); + + setTimeout(function () { + t.ok(Date.now() - start > 100); + }, 100); +}); diff --git a/tests/node_modules/tape/example/too_many_fail.js b/tests/node_modules/tape/example/too_many_fail.js new file mode 100644 index 0000000..e5780be --- /dev/null +++ b/tests/node_modules/tape/example/too_many_fail.js @@ -0,0 +1,37 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../'); + +test('array', function (t) { + t.plan(3); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/example/two.js b/tests/node_modules/tape/example/two.js new file mode 100644 index 0000000..0e31516 --- /dev/null +++ b/tests/node_modules/tape/example/two.js @@ -0,0 +1,20 @@ +'use strict'; + +var test = require('../'); + +test('one', function (t) { + t.plan(2); + t.ok(true); + setTimeout(function () { + t.equal(1+3, 4); + }, 100); +}); + +test('two', function (t) { + t.plan(3); + t.equal(5, 2+3); + setTimeout(function () { + t.equal('a'.charCodeAt(0), 97); + t.ok(true); + }, 50); +}); diff --git a/tests/node_modules/tape/index.js b/tests/node_modules/tape/index.js new file mode 100644 index 0000000..19cacb3 --- /dev/null +++ b/tests/node_modules/tape/index.js @@ -0,0 +1,154 @@ +'use strict'; + +var defined = require('defined'); +var createDefaultStream = require('./lib/default_stream'); +var Test = require('./lib/test'); +var createResult = require('./lib/results'); +var through = require('through'); + +var canEmitExit = typeof process !== 'undefined' && process + && typeof process.on === 'function' && process.browser !== true +; +var canExit = typeof process !== 'undefined' && process + && typeof process.exit === 'function' +; + +exports = module.exports = (function () { + var harness; + var lazyLoad = function () { + return getHarness().apply(this, arguments); + }; + + lazyLoad.only = function () { + return getHarness().only.apply(this, arguments); + }; + + lazyLoad.createStream = function (opts) { + if (!opts) opts = {}; + if (!harness) { + var output = through(); + getHarness({ stream: output, objectMode: opts.objectMode }); + return output; + } + return harness.createStream(opts); + }; + + lazyLoad.onFinish = function () { + return getHarness().onFinish.apply(this, arguments); + }; + + lazyLoad.onFailure = function () { + return getHarness().onFailure.apply(this, arguments); + }; + + lazyLoad.getHarness = getHarness; + + return lazyLoad; + + function getHarness(opts) { + if (!opts) opts = {}; + opts.autoclose = !canEmitExit; + if (!harness) harness = createExitHarness(opts); + return harness; + } +})(); + +function createExitHarness(conf) { + if (!conf) conf = {}; + var harness = createHarness({ + autoclose: defined(conf.autoclose, false) + }); + + var stream = harness.createStream({ objectMode: conf.objectMode }); + var es = stream.pipe(conf.stream || createDefaultStream()); + if (canEmitExit) { + es.on('error', function (err) { harness._exitCode = 1; }); + } + + var ended = false; + stream.on('end', function () { ended = true; }); + + if (conf.exit === false) return harness; + if (!canEmitExit || !canExit) return harness; + + process.on('exit', function (code) { + // let the process exit cleanly. + if (typeof code === 'number' && code !== 0) { + return; + } + + if (!ended) { + var only = harness._results._only; + for (var i = 0; i < harness._tests.length; i++) { + var t = harness._tests[i]; + if (only && t !== only) continue; + t._exit(); + } + } + harness.close(); + + process.removeAllListeners('exit'); // necessary for node v0.6 + process.exit(code || harness._exitCode); + }); + + return harness; +} + +exports.createHarness = createHarness; +exports.Test = Test; +exports.test = exports; // tap compat +exports.test.skip = Test.skip; + +function createHarness(conf_) { + if (!conf_) conf_ = {}; + var results = createResult(); + if (conf_.autoclose !== false) { + results.once('done', function () { results.close(); }); + } + + var test = function (name, conf, cb) { + var t = new Test(name, conf, cb); + test._tests.push(t); + + (function inspectCode(st) { + st.on('test', function sub(st_) { + inspectCode(st_); + }); + st.on('result', function (r) { + if (!r.todo && !r.ok && typeof r !== 'string') test._exitCode = 1; + }); + })(t); + + results.push(t); + return t; + }; + test._results = results; + + test._tests = []; + + test.createStream = function (opts) { + return results.createStream(opts); + }; + + test.onFinish = function (cb) { + results.on('done', cb); + }; + + test.onFailure = function (cb) { + results.on('fail', cb); + }; + + var only = false; + test.only = function () { + if (only) throw new Error('there can only be one only test'); + only = true; + var t = test.apply(null, arguments); + results.only(t); + return t; + }; + test._exitCode = 0; + + test.close = function () { results.close(); }; + + return test; +} diff --git a/tests/node_modules/tape/lib/default_stream.js b/tests/node_modules/tape/lib/default_stream.js new file mode 100644 index 0000000..f8901ed --- /dev/null +++ b/tests/node_modules/tape/lib/default_stream.js @@ -0,0 +1,32 @@ +'use strict'; + +var through = require('through'); +var fs = require('fs'); + +module.exports = function () { + var line = ''; + var stream = through(write, flush); + return stream; + + function write(buf) { + for (var i = 0; i < buf.length; i++) { + var c = typeof buf === 'string' + ? buf.charAt(i) + : String.fromCharCode(buf[i]) + ; + if (c === '\n') flush(); + else line += c; + } + } + + function flush() { + if (fs.writeSync && /^win/.test(process.platform)) { + try { fs.writeSync(1, line + '\n'); } + catch (e) { stream.emit('error', e); } + } else { + try { console.log(line); } + catch (e) { stream.emit('error', e); } + } + line = ''; + } +}; diff --git a/tests/node_modules/tape/lib/results.js b/tests/node_modules/tape/lib/results.js new file mode 100644 index 0000000..37bb191 --- /dev/null +++ b/tests/node_modules/tape/lib/results.js @@ -0,0 +1,220 @@ +'use strict'; + +var defined = require('defined'); +var EventEmitter = require('events').EventEmitter; +var inherits = require('inherits'); +var through = require('through'); +var resumer = require('resumer'); +var inspect = require('object-inspect'); +var callBound = require('call-bind/callBound'); +var has = require('has'); +var regexpTest = callBound('RegExp.prototype.test'); +var $split = callBound('String.prototype.split'); +var $replace = callBound('String.prototype.replace'); +var $shift = callBound('Array.prototype.shift'); +var $push = callBound('Array.prototype.push'); +var yamlIndicators = /:|-|\?/; +var nextTick = typeof setImmediate !== 'undefined' + ? setImmediate + : process.nextTick +; + +module.exports = Results; +inherits(Results, EventEmitter); + +function coalesceWhiteSpaces(str) { + return $replace(String(str), /\s+/g, ' '); +} + +function Results() { + if (!(this instanceof Results)) return new Results; + this.count = 0; + this.fail = 0; + this.pass = 0; + this.todo = 0; + this._stream = through(); + this.tests = []; + this._only = null; + this._isRunning = false; +} + +Results.prototype.createStream = function (opts) { + if (!opts) opts = {}; + var self = this; + var output, testId = 0; + if (opts.objectMode) { + output = through(); + self.on('_push', function ontest(t, extra) { + if (!extra) extra = {}; + var id = testId++; + t.once('prerun', function () { + var row = { + type: 'test', + name: t.name, + id: id, + skip: t._skip, + todo: t._todo + }; + if (has(extra, 'parent')) { + row.parent = extra.parent; + } + output.queue(row); + }); + t.on('test', function (st) { + ontest(st, { parent: id }); + }); + t.on('result', function (res) { + if (res && typeof res === 'object') { + res.test = id; + res.type = 'assert'; + } + output.queue(res); + }); + t.on('end', function () { + output.queue({ type: 'end', test: id }); + }); + }); + self.on('done', function () { output.queue(null); }); + } else { + output = resumer(); + output.queue('TAP version 13\n'); + self._stream.pipe(output); + } + + if (!this._isRunning) { + this._isRunning = true; + nextTick(function next() { + var t; + while (t = getNextTest(self)) { + t.run(); + if (!t.ended) return t.once('end', function () { nextTick(next); }); + } + self.emit('done'); + }); + } + + return output; +}; + +Results.prototype.push = function (t) { + var self = this; + $push(self.tests, t); + self._watch(t); + self.emit('_push', t); +}; + +Results.prototype.only = function (t) { + this._only = t; +}; + +Results.prototype._watch = function (t) { + var self = this; + var write = function (s) { self._stream.queue(s); }; + t.once('prerun', function () { + var premsg = ''; + if (t._skip) premsg = 'SKIP '; + else if (t._todo) premsg = 'TODO '; + write('# ' + premsg + coalesceWhiteSpaces(t.name) + '\n'); + }); + + t.on('result', function (res) { + if (typeof res === 'string') { + write('# ' + res + '\n'); + return; + } + write(encodeResult(res, self.count + 1)); + self.count++; + + if (res.ok || res.todo) self.pass++; + else { + self.fail++; + self.emit('fail'); + } + }); + + t.on('test', function (st) { self._watch(st); }); +}; + +Results.prototype.close = function () { + var self = this; + if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED')); + self.closed = true; + var write = function (s) { self._stream.queue(s); }; + + write('\n1..' + self.count + '\n'); + write('# tests ' + self.count + '\n'); + write('# pass ' + (self.pass + self.todo) + '\n'); + if (self.todo) write('# todo ' + self.todo + '\n'); + if (self.fail) write('# fail ' + self.fail + '\n'); + else write('\n# ok\n'); + + self._stream.queue(null); +}; + +function encodeResult(res, count) { + var output = ''; + output += (res.ok ? 'ok ' : 'not ok ') + count; + output += res.name ? ' ' + coalesceWhiteSpaces(res.name) : ''; + + if (res.skip) { + output += ' # SKIP' + ((typeof res.skip === 'string') ? ' ' + coalesceWhiteSpaces(res.skip) : ''); + } else if (res.todo) { + output += ' # TODO' + ((typeof res.todo === 'string') ? ' ' + coalesceWhiteSpaces(res.todo) : ''); + }; + + output += '\n'; + if (res.ok) return output; + + var outer = ' '; + var inner = outer + ' '; + output += outer + '---\n'; + output += inner + 'operator: ' + res.operator + '\n'; + + if (has(res, 'expected') || has(res, 'actual')) { + var ex = inspect(res.expected, {depth: res.objectPrintDepth}); + var ac = inspect(res.actual, {depth: res.objectPrintDepth}); + + if (Math.max(ex.length, ac.length) > 65 || invalidYaml(ex) || invalidYaml(ac)) { + output += inner + 'expected: |-\n' + inner + ' ' + ex + '\n'; + output += inner + 'actual: |-\n' + inner + ' ' + ac + '\n'; + } else { + output += inner + 'expected: ' + ex + '\n'; + output += inner + 'actual: ' + ac + '\n'; + } + } + if (res.at) { + output += inner + 'at: ' + res.at + '\n'; + } + + var actualStack = res.actual && (typeof res.actual === 'object' || typeof res.actual === 'function') ? res.actual.stack : undefined; + var errorStack = res.error && res.error.stack; + var stack = defined(actualStack, errorStack); + if (stack) { + var lines = $split(String(stack), '\n'); + output += inner + 'stack: |-\n'; + for (var i = 0; i < lines.length; i++) { + output += inner + ' ' + lines[i] + '\n'; + } + } + + output += outer + '...\n'; + return output; +} + +function getNextTest(results) { + if (!results._only) { + return $shift(results.tests); + } + + do { + var t = $shift(results.tests); + if (!t) continue; + if (results._only === t) { + return t; + } + } while (results.tests.length !== 0); +} + +function invalidYaml(str) { + return regexpTest(yamlIndicators, str); +} diff --git a/tests/node_modules/tape/lib/test.js b/tests/node_modules/tape/lib/test.js new file mode 100644 index 0000000..f477cfa --- /dev/null +++ b/tests/node_modules/tape/lib/test.js @@ -0,0 +1,750 @@ +'use strict'; + +var deepEqual = require('deep-equal'); +var defined = require('defined'); +var path = require('path'); +var inherits = require('inherits'); +var EventEmitter = require('events').EventEmitter; +var has = require('has'); +var isRegExp = require('is-regex'); +var trim = require('string.prototype.trim'); +var callBound = require('call-bind/callBound'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var is = require('object-is'); +var isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var toLowerCase = callBound('String.prototype.toLowerCase'); +var isProto = callBound('Object.prototype.isPrototypeOf'); +var $test = callBound('RegExp.prototype.test'); +var objectToString = callBound('Object.prototype.toString'); +var $split = callBound('String.prototype.split'); +var $replace = callBound('String.prototype.replace'); +var $strSlice = callBound('String.prototype.slice'); +var $push = callBound('Array.prototype.push'); +var $shift = callBound('Array.prototype.shift'); + +module.exports = Test; + +var nextTick = typeof setImmediate !== 'undefined' + ? setImmediate + : process.nextTick; +var safeSetTimeout = setTimeout; +var safeClearTimeout = clearTimeout; + +inherits(Test, EventEmitter); + +var getTestArgs = function (name_, opts_, cb_) { + var name = '(anonymous)'; + var opts = {}; + var cb; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + var t = typeof arg; + if (t === 'string') { + name = arg; + } else if (t === 'object') { + opts = arg || opts; + } else if (t === 'function') { + cb = arg; + } + } + return { name: name, opts: opts, cb: cb }; +}; + +function Test(name_, opts_, cb_) { + if (!(this instanceof Test)) { + return new Test(name_, opts_, cb_); + } + + var args = getTestArgs(name_, opts_, cb_); + + this.readable = true; + this.name = args.name || '(anonymous)'; + this.assertCount = 0; + this.pendingCount = 0; + this._skip = args.opts.skip || false; + this._todo = args.opts.todo || false; + this._timeout = args.opts.timeout; + this._plan = undefined; + this._cb = args.cb; + this._progeny = []; + this._teardown = []; + this._ok = true; + var depthEnvVar = process.env.NODE_TAPE_OBJECT_PRINT_DEPTH; + if (args.opts.objectPrintDepth) { + this._objectPrintDepth = args.opts.objectPrintDepth; + } else if (depthEnvVar) { + if (toLowerCase(depthEnvVar) === 'infinity') { + this._objectPrintDepth = Infinity; + } else { + this._objectPrintDepth = depthEnvVar; + } + } else { + this._objectPrintDepth = 5; + } + + for (var prop in this) { + this[prop] = (function bind(self, val) { + if (typeof val === 'function') { + return function bound() { + return val.apply(self, arguments); + }; + } + return val; + })(this, this[prop]); + } +} + +Test.prototype.run = function () { + this.emit('prerun'); + if (!this._cb || this._skip) { + return this._end(); + } + if (this._timeout != null) { + this.timeoutAfter(this._timeout); + } + + var callbackReturn = this._cb(this); + + if ( + typeof Promise === 'function' + && callbackReturn + && typeof callbackReturn.then === 'function' + ) { + var self = this; + Promise.resolve(callbackReturn).then(function onResolve() { + if (!self.calledEnd) { + self.end(); + } + })['catch'](function onError(err) { + if (err instanceof Error || objectToString(err) === '[object Error]') { + self.ifError(err); + } else { + self.fail(err); + } + self.end(); + }); + return; + } + + this.emit('run'); +}; + +Test.prototype.test = function (name, opts, cb) { + var self = this; + var t = new Test(name, opts, cb); + $push(this._progeny, t); + this.pendingCount++; + this.emit('test', t); + t.on('prerun', function () { + self.assertCount++; + }); + + if (!self._pendingAsserts()) { + nextTick(function () { + self._end(); + }); + } + + nextTick(function () { + if (!self._plan && self.pendingCount == self._progeny.length) { + self._end(); + } + }); +}; + +Test.prototype.comment = function (msg) { + var that = this; + forEach($split(trim(msg), '\n'), function (aMsg) { + that.emit('result', $replace(trim(aMsg), /^#\s*/, '')); + }); +}; + +Test.prototype.plan = function (n) { + this._plan = n; + this.emit('plan', n); +}; + +Test.prototype.timeoutAfter = function (ms) { + if (!ms) throw new Error('timeoutAfter requires a timespan'); + var self = this; + var timeout = safeSetTimeout(function () { + self.fail(self.name + ' timed out after ' + ms + 'ms'); + self.end(); + }, ms); + this.once('end', function () { + safeClearTimeout(timeout); + }); +}; + +Test.prototype.end = function (err) { + var self = this; + if (arguments.length >= 1 && !!err) { + this.ifError(err); + } + + if (this.calledEnd) { + this.fail('.end() already called'); + } + this.calledEnd = true; + this._end(); +}; + +Test.prototype.teardown = function (fn) { + if (typeof fn !== 'function') { + this.fail('teardown: ' + inspect(fn) + ' is not a function'); + } else { + this._teardown.push(fn); + } +}; + +Test.prototype._end = function (err) { + var self = this; + + if (!this._cb && !this._todo && !this._skip) this.fail('# TODO ' + this.name); + + if (this._progeny.length) { + var t = $shift(this._progeny); + t.on('end', function () { self._end(); }); + t.run(); + return; + } + + + function next() { + if (self._teardown.length === 0) { + completeEnd(); + return; + } + var fn = self._teardown.shift(); + var res; + try { + res = fn(); + } catch (e) { + self.fail(e); + } + if (res && typeof res.then === 'function') { + res.then(next, function (_err) { + err = err || _err; + }); + } else { + next(); + } + } + + next(); + + function completeEnd() { + if (!self.ended) self.emit('end'); + var pendingAsserts = self._pendingAsserts(); + if (!self._planError && self._plan !== undefined && pendingAsserts) { + self._planError = true; + self.fail('plan != count', { + expected: self._plan, + actual: self.assertCount + }); + } + self.ended = true; + } +}; + +Test.prototype._exit = function () { + if (this._plan !== undefined && !this._planError && this.assertCount !== this._plan) { + this._planError = true; + this.fail('plan != count', { + expected: this._plan, + actual: this.assertCount, + exiting: true + }); + } else if (!this.ended) { + this.fail('test exited without ending: ' + this.name, { + exiting: true + }); + } +}; + +Test.prototype._pendingAsserts = function () { + if (this._plan === undefined) { + return 1; + } + return this._plan - (this._progeny.length + this.assertCount); +}; + +Test.prototype._assert = function assert(ok, opts) { + var self = this; + var extra = opts.extra || {}; + + ok = !!ok || !!extra.skip; + + var name = defined(extra.message, opts.message, '(unnamed assert)'); + if (this.calledEnd && opts.operator !== 'fail') { + this.fail('.end() already called: ' + name); + return; + } + + var res = { + id: self.assertCount++, + ok: ok, + skip: defined(extra.skip, opts.skip), + todo: defined(extra.todo, opts.todo, self._todo), + name: name, + operator: defined(extra.operator, opts.operator), + objectPrintDepth: self._objectPrintDepth + }; + if (has(opts, 'actual') || has(extra, 'actual')) { + res.actual = defined(extra.actual, opts.actual); + } + if (has(opts, 'expected') || has(extra, 'expected')) { + res.expected = defined(extra.expected, opts.expected); + } + this._ok = !!(this._ok && ok); + + if (!ok && !res.todo) { + res.error = defined(extra.error, opts.error, new Error(res.name)); + } + + if (!ok) { + var e = new Error('exception'); + var err = $split(e.stack || '', '\n'); + var dir = __dirname + path.sep; + + for (var i = 0; i < err.length; i++) { + /* + Stack trace lines may resemble one of the following. We need + to correctly extract a function name (if any) and path / line + number for each line. + + at myFunction (/path/to/file.js:123:45) + at myFunction (/path/to/file.other-ext:123:45) + at myFunction (/path to/file.js:123:45) + at myFunction (C:\path\to\file.js:123:45) + at myFunction (/path/to/file.js:123) + at Test. (/path/to/file.js:123:45) + at Test.bound [as run] (/path/to/file.js:123:45) + at /path/to/file.js:123:45 + + Regex has three parts. First is non-capturing group for 'at ' + (plus anything preceding it). + + /^(?:[^\s]*\s*\bat\s+)/ + + Second captures function call description (optional). This is + not necessarily a valid JS function name, but just what the + stack trace is using to represent a function call. It may look + like `` or 'Test.bound [as run]'. + + For our purposes, we assume that, if there is a function + name, it's everything leading up to the first open + parentheses (trimmed) before our pathname. + + /(?:(.*)\s+\()?/ + + Last part captures file path plus line no (and optional + column no). + + /((?:\/|[a-zA-Z]:\\)[^:\)]+:(\d+)(?::(\d+))?)\)?/ + */ + var re = /^(?:[^\s]*\s*\bat\s+)(?:(.*)\s+\()?((?:\/|[a-zA-Z]:\\)[^:)]+:(\d+)(?::(\d+))?)\)?$/; + var lineWithTokens = $replace($replace(err[i], process.cwd(), '/$CWD'), __dirname, '/$TEST'); + var m = re.exec(lineWithTokens); + + if (!m) { + continue; + } + + var callDescription = m[1] || ''; + var filePath = $replace($replace(m[2], '/$CWD', process.cwd()), '/$TEST', __dirname); + + if ($strSlice(filePath, 0, dir.length) === dir) { + continue; + } + + // Function call description may not (just) be a function name. + // Try to extract function name by looking at first "word" only. + res.functionName = $split(callDescription, /\s+/)[0]; + res.file = filePath; + res.line = Number(m[3]); + if (m[4]) res.column = Number(m[4]); + + res.at = callDescription + ' (' + filePath + ')'; + break; + } + } + + self.emit('result', res); + + var pendingAsserts = self._pendingAsserts(); + if (!pendingAsserts) { + if (extra.exiting) { + self._end(); + } else { + nextTick(function () { + self._end(); + }); + } + } + + if (!self._planError && pendingAsserts < 0) { + self._planError = true; + self.fail('plan != count', { + expected: self._plan, + actual: self._plan - pendingAsserts + }); + } +}; + +Test.prototype.fail = function (msg, extra) { + this._assert(false, { + message: msg, + operator: 'fail', + extra: extra + }); +}; + +Test.prototype.pass = function (msg, extra) { + this._assert(true, { + message: msg, + operator: 'pass', + extra: extra + }); +}; + +Test.prototype.skip = function (msg, extra) { + this._assert(true, { + message: msg, + operator: 'skip', + skip: true, + extra: extra + }); +}; + +function assert(value, msg, extra) { + this._assert(value, { + message: defined(msg, 'should be truthy'), + operator: 'ok', + expected: true, + actual: value, + extra: extra + }); +} +Test.prototype.ok += Test.prototype['true'] += Test.prototype.assert += assert; + +function notOK(value, msg, extra) { + this._assert(!value, { + message: defined(msg, 'should be falsy'), + operator: 'notOk', + expected: false, + actual: value, + extra: extra + }); +} +Test.prototype.notOk += Test.prototype['false'] += Test.prototype.notok += notOK; + +function error(err, msg, extra) { + this._assert(!err, { + message: defined(msg, String(err)), + operator: 'error', + error: err, + extra: extra + }); +} +Test.prototype.error += Test.prototype.ifError += Test.prototype.ifErr += Test.prototype.iferror += error; + +function strictEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(is(a, b), { + message: defined(msg, 'should be strictly equal'), + operator: 'equal', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.equal += Test.prototype.equals += Test.prototype.isEqual += Test.prototype.strictEqual += Test.prototype.strictEquals += Test.prototype.is += strictEqual; + +function notStrictEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(!is(a, b), { + message: defined(msg, 'should not be strictly equal'), + operator: 'notEqual', + actual: a, + expected: b, + extra: extra + }); +} + +Test.prototype.notEqual += Test.prototype.notEquals += Test.prototype.isNotEqual += Test.prototype.doesNotEqual += Test.prototype.isInequal += Test.prototype.notStrictEqual += Test.prototype.notStrictEquals += Test.prototype.isNot += Test.prototype.not += notStrictEqual; + +function looseEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(a == b, { + message: defined(msg, 'should be loosely equal'), + operator: 'looseEqual', + actual: a, + expected: b, + extra: extra + }); +} + +Test.prototype.looseEqual += Test.prototype.looseEquals += looseEqual; + +function notLooseEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(a != b, { + message: defined(msg, 'should not be loosely equal'), + operator: 'notLooseEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notLooseEqual += Test.prototype.notLooseEquals += notLooseEqual; + +function tapeDeepEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(deepEqual(a, b, { strict: true }), { + message: defined(msg, 'should be deeply equivalent'), + operator: 'deepEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.deepEqual += Test.prototype.deepEquals += Test.prototype.isEquivalent += Test.prototype.same += tapeDeepEqual; + +function notDeepEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(!deepEqual(a, b, { strict: true }), { + message: defined(msg, 'should not be deeply equivalent'), + operator: 'notDeepEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notDeepEqual += Test.prototype.notDeepEquals += Test.prototype.notEquivalent += Test.prototype.notDeeply += Test.prototype.notSame += Test.prototype.isNotDeepEqual += Test.prototype.isNotDeeply += Test.prototype.isNotEquivalent += Test.prototype.isInequivalent += notDeepEqual; + +function deepLooseEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(deepEqual(a, b), { + message: defined(msg, 'should be loosely deeply equivalent'), + operator: 'deepLooseEqual', + actual: a, + expected: b, + extra: extra + }); +} + +Test.prototype.deepLooseEqual += deepLooseEqual; + +function notDeepLooseEqual(a, b, msg, extra) { + if (arguments.length < 2) { + throw new TypeError('two arguments must be provided to compare'); + } + this._assert(!deepEqual(a, b), { + message: defined(msg, 'should not be loosely deeply equivalent'), + operator: 'notDeepLooseEqual', + actual: a, + expected: b, + extra: extra + }); +} +Test.prototype.notDeepLooseEqual += notDeepLooseEqual; + +Test.prototype['throws'] = function (fn, expected, msg, extra) { + if (typeof expected === 'string') { + msg = expected; + expected = undefined; + } + + var caught = undefined; + + try { + fn(); + } catch (err) { + caught = { error: err }; + if (Object(err) === err && (!isEnumerable(err, 'message') || !has(err, 'message'))) { + var message = err.message; + delete err.message; + err.message = message; + } + } + + var passed = caught; + + if (caught) { + if (typeof expected === 'string' && caught.error && caught.error.message === expected) { + throw new TypeError('The "error/message" argument is ambiguous. The error message ' + inspect(expected) + ' is identical to the message.'); + } + if (typeof expected === 'function') { + if (typeof expected.prototype !== 'undefined' && caught.error instanceof expected) { + passed = true; + } else if (isProto(Error, expected)) { + passed = false; + } else { + passed = expected.call({}, caught.error) === true; + } + } else if (isRegExp(expected)) { + passed = expected.test(caught.error); + expected = inspect(expected); + } else if (expected && typeof expected === 'object') { // Handle validation objects. + var keys = Object.keys(expected); + // Special handle errors to make sure the name and the message are compared as well. + if (expected instanceof Error) { + $push(keys, 'name', 'message'); + } else if (keys.length === 0) { + throw new TypeError('`throws` validation object must not be empty'); + } + passed = keys.every(function (key) { + if (typeof caught.error[key] === 'string' && isRegExp(expected[key]) && $test(expected[key], caught.error[key])) { + return true; + } + if (key in caught.error && deepEqual(caught.error[key], expected[key], { strict: true })) { + return true; + } + return false; + }); + } + } + + this._assert(!!passed, { + message: defined(msg, 'should throw'), + operator: 'throws', + actual: caught && caught.error, + expected: expected, + error: !passed && caught && caught.error, + extra: extra + }); +}; + +Test.prototype.doesNotThrow = function (fn, expected, msg, extra) { + if (typeof expected === 'string') { + msg = expected; + expected = undefined; + } + var caught = undefined; + try { + fn(); + } + catch (err) { + caught = { error: err }; + } + this._assert(!caught, { + message: defined(msg, 'should not throw'), + operator: 'throws', + actual: caught && caught.error, + expected: expected, + error: caught && caught.error, + extra: extra + }); +}; + +Test.prototype.match = function match(string, regexp, msg, extra) { + if (!isRegExp(regexp)) { + throw new TypeError('The "regexp" argument must be an instance of RegExp. Received type ' + typeof regexp + ' (' + inspect(regexp) + ')'); + } + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be of type string. Received type ' + typeof string + ' (' + inspect(string) + ')'); + } + + var matches = $test(regexp, string); + var message = defined( + msg, + 'The input ' + (matches ? 'matched' : 'did not match') + ' the regular expression ' + inspect(regexp) + '. Input: ' + inspect(string) + ); + this._assert(matches, { + message: message, + operator: 'match', + actual: string, + expected: regexp, + extra: extra + }); +}; + +Test.prototype.doesNotMatch = function doesNotMatch(string, regexp, msg, extra) { + if (!isRegExp(regexp)) { + throw new TypeError('The "regexp" argument must be an instance of RegExp. Received type ' + typeof regexp + ' (' + inspect(regexp) + ')'); + } + if (typeof string !== 'string') { + throw new TypeError('The "string" argument must be of type string. Received type ' + typeof string + ' (' + inspect(string) + ')'); + } + var matches = $test(regexp, string); + var message = defined( + msg, + 'The input ' + (matches ? 'was expected to not match' : 'did not match') + ' the regular expression ' + inspect(regexp) + '. Input: ' + inspect(string) + ); + this._assert(!matches, { + message: message, + operator: 'doesNotMatch', + actual: string, + expected: regexp, + extra: extra + }); +}; + +Test.skip = function (name_, _opts, _cb) { + var args = getTestArgs.apply(null, arguments); + args.opts.skip = true; + return Test(args.name, args.opts, args.cb); +}; + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape/package.json b/tests/node_modules/tape/package.json new file mode 100644 index 0000000..a19888d --- /dev/null +++ b/tests/node_modules/tape/package.json @@ -0,0 +1,126 @@ +{ + "_from": "tape", + "_id": "tape@5.2.2", + "_inBundle": false, + "_integrity": "sha512-grXrzPC1ly2kyTMKdqxh5GiLpb0BpNctCuecTB0psHX4Gu0nc+uxWR4xKjTh/4CfQlH4zhvTM2/EXmHXp6v/uA==", + "_location": "/tape", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "tape", + "name": "tape", + "escapedName": "tape", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/tape/-/tape-5.2.2.tgz", + "_shasum": "a98475ecf30aa0ed2a89c36439bb9438d24d2184", + "_spec": "tape", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bin": { + "tape": "bin/tape" + }, + "bugs": { + "url": "https://github.com/substack/tape/issues" + }, + "bundleDependencies": false, + "dependencies": { + "call-bind": "^1.0.2", + "deep-equal": "^2.0.5", + "defined": "^1.0.0", + "dotignore": "^0.1.2", + "for-each": "^0.3.3", + "glob": "^7.1.6", + "has": "^1.0.3", + "inherits": "^2.0.4", + "is-regex": "^1.1.2", + "minimist": "^1.2.5", + "object-inspect": "^1.9.0", + "object-is": "^1.1.5", + "object.assign": "^4.1.2", + "resolve": "^2.0.0-next.3", + "resumer": "^0.0.0", + "string.prototype.trim": "^1.2.4", + "through": "^2.3.8" + }, + "deprecated": false, + "description": "tap-producing test harness for node and browsers", + "devDependencies": { + "array.prototype.flatmap": "^1.2.4", + "aud": "^1.1.4", + "concat-stream": "^1.6.2", + "eclint": "^2.8.1", + "ecstatic": "^4.1.4", + "es-value-fixtures": "^1.2.1", + "eslint": "^7.20.0", + "falafel": "^2.2.4", + "js-yaml": "^3.14.0", + "tap": "^8.0.1", + "tap-parser": "^3.0.5" + }, + "directories": { + "example": "example", + "test": "test" + }, + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./lib/default_stream": "./lib/default_stream.js", + "./lib/results": "./lib/results.js", + "./lib/test": "./lib/test.js", + "./package": "./package.json", + "./package.json": "./package.json" + }, + "homepage": "https://github.com/substack/tape", + "keywords": [ + "tap", + "test", + "harness", + "assert", + "browser" + ], + "license": "MIT", + "main": "index.js", + "name": "tape", + "repository": { + "type": "git", + "url": "git://github.com/substack/tape.git" + }, + "scripts": { + "lint": "eslint . bin/*", + "posttest": "aud --production", + "prelint": "eclint check", + "pretest": "npm run lint", + "test": "npm run tests-only", + "test:example": "find example -name '*.js' | grep -v fail | grep -v static | xargs tap", + "tests-only": "nyc tap test/*.js" + }, + "testling": { + "files": "test/browser/*.js", + "browsers": [ + "ie/6..latest", + "chrome/20..latest", + "firefox/10..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6" + ] + }, + "version": "5.2.2" +} diff --git a/tests/node_modules/tape/readme.markdown b/tests/node_modules/tape/readme.markdown new file mode 100644 index 0000000..286e088 --- /dev/null +++ b/tests/node_modules/tape/readme.markdown @@ -0,0 +1,527 @@ +# tape + +tap-producing test harness for node and browsers + +[![build status](https://secure.travis-ci.org/substack/tape.svg?branch=master)](http://travis-ci.org/substack/tape) + +![tape](https://web.archive.org/web/20170612184731if_/http://substack.net/images/tape_drive.png) + +# example + +``` js +var test = require('tape'); + +test('timing test', function (t) { + t.plan(2); + + t.equal(typeof Date.now, 'function'); + var start = Date.now(); + + setTimeout(function () { + t.equal(Date.now() - start, 100); + }, 100); +}); + +test('test using promises', async function (t) { + const result = await someAsyncThing(); + t.ok(result); +}); +``` + +``` +$ node example/timing.js +TAP version 13 +# timing test +ok 1 should be strictly equal +not ok 2 should be strictly equal + --- + operator: equal + expected: 100 + actual: 107 + ... + +1..2 +# tests 2 +# pass 1 +# fail 1 +``` + +# usage + +You always need to `require('tape')` in test files. You can run the tests by +usual node means (`require('test-file.js')` or `node test-file.js`). You can +also run tests using the `tape` binary to utilize globbing, on Windows for +example: + +```sh +$ tape tests/**/*.js +``` + +`tape`'s arguments are passed to the +[`glob`](https://www.npmjs.com/package/glob) module. If you want `glob` to +perform the expansion on a system where the shell performs such expansion, quote +the arguments as necessary: + +```sh +$ tape 'tests/**/*.js' +$ tape "tests/**/*.js" +``` + +## Preloading modules + +Additionally, it is possible to make `tape` load one or more modules before running any tests, by using the `-r` or `--require` flag. Here's an example that loads [babel-register](http://babeljs.io/docs/usage/require/) before running any tests, to allow for JIT compilation: + +```sh +$ tape -r babel-register tests/**/*.js +``` + +Depending on the module you're loading, you may be able to parameterize it using environment variables or auxiliary files. Babel, for instance, will load options from [`.babelrc`](http://babeljs.io/docs/usage/babelrc/) at runtime. + +The `-r` flag behaves exactly like node's `require`, and uses the same module resolution algorithm. This means that if you need to load local modules, you have to prepend their path with `./` or `../` accordingly. + +For example: + +```sh +$ tape -r ./my/local/module tests/**/*.js +``` + +Please note that all modules loaded using the `-r` flag will run *before* any tests, regardless of when they are specified. For example, `tape -r a b -r c` will actually load `a` and `c` *before* loading `b`, since they are flagged as required modules. + +# things that go well with tape + +`tape` maintains a fairly minimal core. Additional features are usually added by using another module alongside `tape`. + +## pretty reporters + +The default TAP output is good for machines and humans that are robots. + +If you want a more colorful / pretty output there are lots of modules on npm +that will output something pretty if you pipe TAP into them: + +- [tap-spec](https://github.com/scottcorgan/tap-spec) +- [tap-dot](https://github.com/scottcorgan/tap-dot) +- [faucet](https://github.com/substack/faucet) +- [tap-bail](https://github.com/juliangruber/tap-bail) +- [tap-browser-color](https://github.com/kirbysayshi/tap-browser-color) +- [tap-json](https://github.com/gummesson/tap-json) +- [tap-min](https://github.com/derhuerst/tap-min) +- [tap-nyan](https://github.com/calvinmetcalf/tap-nyan) +- [tap-pessimist](https://www.npmjs.org/package/tap-pessimist) +- [tap-prettify](https://github.com/toolness/tap-prettify) +- [colortape](https://github.com/shuhei/colortape) +- [tap-xunit](https://github.com/aghassemi/tap-xunit) +- [tap-difflet](https://github.com/namuol/tap-difflet) +- [tape-dom](https://github.com/gritzko/tape-dom) +- [tap-diff](https://github.com/axross/tap-diff) +- [tap-notify](https://github.com/axross/tap-notify) +- [tap-summary](https://github.com/zoubin/tap-summary) +- [tap-markdown](https://github.com/Hypercubed/tap-markdown) +- [tap-html](https://github.com/gabrielcsapo/tap-html) +- [tap-react-browser](https://github.com/mcnuttandrew/tap-react-browser) +- [tap-junit](https://github.com/dhershman1/tap-junit) +- [tap-nyc](https://github.com/MegaArman/tap-nyc) +- [tap-spec (emoji patch)](https://github.com/Sceat/tap-spec-emoji) +- [tape-repeater](https://github.com/rgruesbeck/tape-repeater) +- [tabe](https://github.com/Josenzo/tabe) + +To use them, try `node test/index.js | tap-spec` or pipe it into one +of the modules of your choice! + +## uncaught exceptions + +By default, uncaught exceptions in your tests will not be intercepted, and will cause `tape` to crash. If you find this behavior undesirable, use [`tape-catch`](https://github.com/michaelrhodes/tape-catch) to report any exceptions as TAP errors. + +## other + +- CoffeeScript support with https://www.npmjs.com/package/coffeetape +- ES6 support with https://www.npmjs.com/package/babel-tape-runner or https://www.npmjs.com/package/buble-tape-runner +- Different test syntax with https://github.com/pguth/flip-tape (warning: mutates String.prototype) +- Electron test runner with https://github.com/tundrax/electron-tap +- Concurrency support with https://github.com/imsnif/mixed-tape +- In-process reporting with https://github.com/DavidAnson/tape-player +- Describe blocks with https://github.com/mattriley/tape-describe + +# methods + +The assertion methods in `tape` are heavily influenced or copied from the methods +in [node-tap](https://github.com/isaacs/node-tap). + +```js +var test = require('tape') +``` + +## test([name], [opts], cb) + +Create a new test with an optional `name` string and optional `opts` object. +`cb(t)` fires with the new test object `t` once all preceding tests have +finished. Tests execute serially. + +Available `opts` options are: +- opts.skip = true/false. See test.skip. +- opts.timeout = 500. Set a timeout for the test, after which it will fail. See test.timeoutAfter. +- opts.objectPrintDepth = 5. Configure max depth of expected / actual object printing. Environmental variable `NODE_TAPE_OBJECT_PRINT_DEPTH` can set the desired default depth for all tests; locally-set values will take precedence. +- opts.todo = true/false. Test will be allowed to fail. + +If you forget to `t.plan()` out how many assertions you are going to run and you don't call `t.end()` explicitly, or return a Promise that eventually settles, your test will hang. + +If `cb` returns a Promise, it will be implicitly awaited. If that promise rejects, the test will be failed; if it fulfills, the test will end. Explicitly calling `t.end()` while also returning a Promise that fulfills is an error. + +## test.skip([name], [opts], cb) + +Generate a new test that will be skipped over. + +## test.teardown(cb) + +Register a callback to run after the individual test has completed. Multiple registered teardown callbacks will run in order. Useful for undoing side effects, closing network connections, etc. + +## test.onFinish(fn) + +The onFinish hook will get invoked when ALL `tape` tests have finished right before `tape` is about to print the test summary. + +`fn` is called with no arguments, and its return value is ignored. + +## test.onFailure(fn) + +The onFailure hook will get invoked whenever any `tape` tests has failed. + +`fn` is called with no arguments, and its return value is ignored. + +## t.plan(n) + +Declare that `n` assertions should be run. `t.end()` will be called +automatically after the `n`th assertion. If there are any more assertions after +the `n`th, or after `t.end()` is called, they will generate errors. + +## t.end(err) + +Declare the end of a test explicitly. If `err` is passed in `t.end` will assert that it is falsy. + +Do not call `t.end()` if your test callback returns a Promise. + +## t.fail(msg) + +Generate a failing assertion with a message `msg`. + +## t.pass(msg) + +Generate a passing assertion with a message `msg`. + +## t.timeoutAfter(ms) + +Automatically timeout the test after X ms. + +## t.skip(msg) + +Generate an assertion that will be skipped over. + +## t.ok(value, msg) + +Assert that `value` is truthy with an optional description of the assertion `msg`. + +Aliases: `t.true()`, `t.assert()` + +## t.notOk(value, msg) + +Assert that `value` is falsy with an optional description of the assertion `msg`. + +Aliases: `t.false()`, `t.notok()` + +## t.error(err, msg) + +Assert that `err` is falsy. If `err` is non-falsy, use its `err.message` as the description message. + +Aliases: `t.ifError()`, `t.ifErr()`, `t.iferror()` + +## t.equal(actual, expected, msg) + +Assert that `Object.is(actual, expected)` with an optional description of the assertion `msg`. + +Aliases: `t.equals()`, `t.isEqual()`, `t.strictEqual()`, `t.strictEquals()`, `t.is()` + +## t.notEqual(actual, expected, msg) + +Assert that `!Object.is(actual, expected)` with an optional description of the assertion `msg`. + +Aliases: `t.notEquals()`, `t.isNotEqual()`, `t.doesNotEqual()`, `t.isInequal()`, `t.notStrictEqual()`, `t.notStrictEquals()`, `t.isNot()`, `t.not()` + +## t.looseEqual(actual, expected, msg) + +Assert that `actual == expected` with an optional description of the assertion `msg`. + +Aliases: `t.looseEquals()` + +## t.notLooseEqual(actual, expected, msg) + +Assert that `actual != expected` with an optional description of the assertion `msg`. + +Aliases: `t.notLooseEquals()` + +## t.deepEqual(actual, expected, msg) + +Assert that `actual` and `expected` have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with strict comparisons (`===`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.deepEquals()`, `t.isEquivalent()`, `t.same()` + +## t.notDeepEqual(actual, expected, msg) + +Assert that `actual` and `expected` do not have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with strict comparisons (`===`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.notDeepEquals`, `t.notEquivalent()`, `t.notDeeply()`, `t.notSame()`, +`t.isNotDeepEqual()`, `t.isNotDeeply()`, `t.isNotEquivalent()`, +`t.isInequivalent()` + +## t.deepLooseEqual(actual, expected, msg) + +Assert that `actual` and `expected` have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with loose comparisons (`==`) on leaf nodes and an optional description of the assertion `msg`. + +## t.notDeepLooseEqual(actual, expected, msg) + +Assert that `actual` and `expected` do not have the same structure and nested values using +[node's deepEqual() algorithm](https://github.com/substack/node-deep-equal) +with loose comparisons (`==`) on leaf nodes and an optional description of the assertion `msg`. + +Aliases: `t.notLooseEqual()`, `t.notLooseEquals()` + +## t.throws(fn, expected, msg) + +Assert that the function call `fn()` throws an exception. `expected`, if present, must be a `RegExp`, `Function`, or `Object`. The `RegExp` matches the string representation of the exception, as generated by `err.toString()`. For example, if you set `expected` to `/user/`, the test will pass only if the string representation of the exception contains the word `user`. Any other exception will result in a failed test. The `Function` is the exception thrown (e.g. `Error`). `Object` in this case corresponds to a so-called validation object, in which each property is tested for strict deep equality. As an example, see the following two tests--each passes a validation object to `t.throws()` as the second parameter. The first test will pass, because all property values in the actual error object are deeply strictly equal to the property values in the validation object. +``` + const err = new TypeError("Wrong value"); + err.code = 404; + err.check = true; + + // Passing test. + t.throws( + () => { + throw err; + }, + { + code: 404, + check: true + }, + "Test message." + ); +``` +This next test will fail, because all property values in the actual error object are _not_ deeply strictly equal to the property values in the validation object. +``` + const err = new TypeError("Wrong value"); + err.code = 404; + err.check = "true"; + + // Failing test. + t.throws( + () => { + throw err; + }, + { + code: 404, + check: true // This is not deeply strictly equal to err.check. + }, + "Test message." + ); +``` + +This is very similar to how Node's `assert.throws()` method tests validation objects (please see the [Node _assert.throws()_ documentation](https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message) for more information). + +If `expected` is not of type `RegExp`, `Function`, or `Object`, or omitted entirely, any exception will result in a passed test. `msg` is an optional description of the assertion. + +Please note that the second parameter, `expected`, cannot be of type `string`. If a value of type `string` is provided for `expected`, then `t.throws(fn, expected, msg)` will execute, but the value of `expected` will be set to `undefined`, and the specified string will be set as the value for the `msg` parameter (regardless of what _actually_ passed as the third parameter). This can cause unexpected results, so please be mindful. + +## t.doesNotThrow(fn, expected, msg) + +Assert that the function call `fn()` does not throw an exception. `expected`, if present, limits what should not be thrown, and must be a `RegExp` or `Function`. The `RegExp` matches the string representation of the exception, as generated by `err.toString()`. For example, if you set `expected` to `/user/`, the test will fail only if the string representation of the exception contains the word `user`. Any other exception will result in a passed test. The `Function` is the exception thrown (e.g. `Error`). If `expected` is not of type `RegExp` or `Function`, or omitted entirely, any exception will result in a failed test. `msg` is an optional description of the assertion. + +Please note that the second parameter, `expected`, cannot be of type `string`. If a value of type `string` is provided for `expected`, then `t.doesNotThrows(fn, expected, msg)` will execute, but the value of `expected` will be set to `undefined`, and the specified string will be set as the value for the `msg` parameter (regardless of what _actually_ passed as the third parameter). This can cause unexpected results, so please be mindful. +## t.test(name, [opts], cb) + +Create a subtest with a new test handle `st` from `cb(st)` inside the current test `t`. `cb(st)` will only fire when `t` finishes. Additional tests queued up after `t` will not be run until all subtests finish. + +You may pass the same options that [`test()`](#testname-opts-cb) accepts. + +## t.comment(message) + +Print a message without breaking the tap output. (Useful when using e.g. `tap-colorize` where output is buffered & `console.log` will print in incorrect order vis-a-vis tap output.) + +Multiline output will be split by `\n` characters, and each one printed as a comment. + +## t.match(string, regexp, message) + +Assert that `string` matches the RegExp `regexp`. Will throw (not just fail) when the first two arguments are the wrong type. + +## t.doesNotMatch(string, regexp, message) + +Assert that `string` does not match the RegExp `regexp`. Will throw (not just fail) when the first two arguments are the wrong type. + +## var htest = test.createHarness() + +Create a new test harness instance, which is a function like `test()`, but with a new pending stack and test state. + +By default the TAP output goes to `console.log()`. You can pipe the output to someplace else if you `htest.createStream().pipe()` to a destination stream on the first tick. + +## test.only([name], [opts], cb) + +Like `test([name], [opts], cb)` except if you use `.only` this is the only test case that will run for the entire process, all other test cases using `tape` will be ignored. + +## var stream = test.createStream(opts) + +Create a stream of output, bypassing the default output stream that writes messages to `console.log()`. By default `stream` will be a text stream of TAP output, but you can get an object stream instead by setting `opts.objectMode` to `true`. + +### tap stream reporter + +You can create your own custom test reporter using this `createStream()` api: + +``` js +var test = require('tape'); +var path = require('path'); + +test.createStream().pipe(process.stdout); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); +``` + +You could substitute `process.stdout` for whatever other output stream you want, like a network connection or a file. + +Pass in test files to run as arguments: + +```sh +$ node tap.js test/x.js test/y.js +TAP version 13 +# (anonymous) +not ok 1 should be strictly equal + --- + operator: equal + expected: "boop" + actual: "beep" + ... +# (anonymous) +ok 2 should be strictly equal +ok 3 (unnamed assert) +# wheee +ok 4 (unnamed assert) + +1..4 +# tests 4 +# pass 3 +# fail 1 +``` + +### object stream reporter + +Here's how you can render an object stream instead of TAP: + +``` js +var test = require('tape'); +var path = require('path'); + +test.createStream({ objectMode: true }).on('data', function (row) { + console.log(JSON.stringify(row)) +}); + +process.argv.slice(2).forEach(function (file) { + require(path.resolve(file)); +}); +``` + +The output for this runner is: + +```sh +$ node object.js test/x.js test/y.js +{"type":"test","name":"(anonymous)","id":0} +{"id":0,"ok":false,"name":"should be strictly equal","operator":"equal","actual":"beep","expected":"boop","error":{},"test":0,"type":"assert"} +{"type":"end","test":0} +{"type":"test","name":"(anonymous)","id":1} +{"id":0,"ok":true,"name":"should be strictly equal","operator":"equal","actual":2,"expected":2,"test":1,"type":"assert"} +{"id":1,"ok":true,"name":"(unnamed assert)","operator":"ok","actual":true,"expected":true,"test":1,"type":"assert"} +{"type":"end","test":1} +{"type":"test","name":"wheee","id":2} +{"id":0,"ok":true,"name":"(unnamed assert)","operator":"ok","actual":true,"expected":true,"test":2,"type":"assert"} +{"type":"end","test":2} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install tape --save-dev +``` + +# troubleshooting + +Sometimes `t.end()` doesn’t preserve the expected output ordering. + +For instance the following: + +```js +var test = require('tape'); + +test('first', function (t) { + + setTimeout(function () { + t.ok(1, 'first test'); + t.end(); + }, 200); + + t.test('second', function (t) { + t.ok(1, 'second test'); + t.end(); + }); +}); + +test('third', function (t) { + setTimeout(function () { + t.ok(1, 'third test'); + t.end(); + }, 100); +}); +``` + +will output: + +``` +ok 1 second test +ok 2 third test +ok 3 first test +``` + +because `second` and `third` assume `first` has ended before it actually does. + +Use `t.plan()` instead to let other tests know they should wait: + +```diff +var test = require('tape'); + +test('first', function (t) { + ++ t.plan(2); + + setTimeout(function () { + t.ok(1, 'first test'); +- t.end(); + }, 200); + + t.test('second', function (t) { + t.ok(1, 'second test'); + t.end(); + }); +}); + +test('third', function (t) { + setTimeout(function () { + t.ok(1, 'third test'); + t.end(); + }, 100); +}); +``` + +# license + +MIT diff --git a/tests/node_modules/tape/test/add-subtest-async.js b/tests/node_modules/tape/test/add-subtest-async.js new file mode 100644 index 0000000..9d13d44 --- /dev/null +++ b/tests/node_modules/tape/test/add-subtest-async.js @@ -0,0 +1,13 @@ +'use strict'; + +var test = require('../'); + +test('parent', function (t) { + t.pass('parent'); + setTimeout(function () { + t.test('child', function (st) { + st.pass('child'); + st.end(); + }); + }, 100); +}); diff --git a/tests/node_modules/tape/test/anonymous-fn.js b/tests/node_modules/tape/test/anonymous-fn.js new file mode 100644 index 0000000..9a73ed8 --- /dev/null +++ b/tests/node_modules/tape/test/anonymous-fn.js @@ -0,0 +1,46 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; +var testWrapper = require('./anonymous-fn/test-wrapper'); + +tap.test('inside anonymous functions', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + var body = stripFullStack(rows.toString('utf8')); + + tt.same(body, [ + 'TAP version 13', + '# wrapped test failure', + 'not ok 1 fail', + ' ---', + ' operator: fail', + ' at: ($TEST/anonymous-fn.js:$LINE:$COL)', + ' stack: |-', + ' Error: fail', + ' [... stack stripped ...]', + ' at $TEST/anonymous-fn.js:$LINE:$COL', + ' at Test. ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('wrapped test failure', testWrapper(function (t) { + t.fail('fail'); + t.end(); + })); +}); diff --git a/tests/node_modules/tape/test/anonymous-fn/test-wrapper.js b/tests/node_modules/tape/test/anonymous-fn/test-wrapper.js new file mode 100644 index 0000000..f79ef48 --- /dev/null +++ b/tests/node_modules/tape/test/anonymous-fn/test-wrapper.js @@ -0,0 +1,18 @@ +'use strict'; + +// Example of wrapper function that would invoke tape +module.exports = function (testCase) { + return function (t) { + setUp(); + testCase(t); + tearDown(); + }; +}; + +function setUp() { + // ... example ... +} + +function tearDown() { + // ... example ... +} diff --git a/tests/node_modules/tape/test/array.js b/tests/node_modules/tape/test/array.js new file mode 100644 index 0000000..7a27038 --- /dev/null +++ b/tests/node_modules/tape/test/array.js @@ -0,0 +1,63 @@ +'use strict'; + +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + + test.createStream().pipe(concat(function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# array', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'ok 5 should be deeply equivalent', + '', + '1..5', + '# tests 5', + '# pass 5', + '', + '# ok' + ].join('\n') + '\n'); + })); + + test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape/test/async-await.js b/tests/node_modules/tape/test/async-await.js new file mode 100644 index 0000000..ef88ff0 --- /dev/null +++ b/tests/node_modules/tape/test/async-await.js @@ -0,0 +1,291 @@ +'use strict'; + +var tap = require('tap'); + +var stripFullStack = require('./common').stripFullStack; +var runProgram = require('./common').runProgram; + +var nodeVersion = process.versions.node; +var majorVersion = nodeVersion.split('.')[0]; + +if (Number(majorVersion) < 8) { + process.exit(0); +} + +tap.test('async1', function (t) { + runProgram('async-await', 'async1.js', function (r) { + t.same(r.stdout.toString('utf8'), [ + 'TAP version 13', + '# async1', + 'ok 1 before await', + 'ok 2 after await', + '', + '1..2', + '# tests 2', + '# pass 2', + '', + '# ok' + ].join('\n') + '\n\n'); + t.same(r.exitCode, 0); + t.same(r.stderr.toString('utf8'), ''); + t.end(); + }); +}); + +tap.test('async2', function (t) { + runProgram('async-await', 'async2.js', function (r) { + var stdout = r.stdout.toString('utf8'); + var lines = stdout.split('\n').filter(function (line) { + return !/^(\s+)at(\s+)$/.test(line); + }); + + t.same(stripFullStack(lines.join('\n')), [ + 'TAP version 13', + '# async2', + 'ok 1 before await', + 'not ok 2 after await', + ' ---', + ' operator: ok', + ' expected: true', + ' actual: false', + ' at: Test.myTest ($TEST/async-await/async2.js:$LINE:$COL)', + ' stack: |-', + ' Error: after await', + ' [... stack stripped ...]', + ' at Test.myTest ($TEST/async-await/async2.js:$LINE:$COL)', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ]); + t.same(r.exitCode, 1); + t.same(r.stderr.toString('utf8'), ''); + t.end(); + }); +}); + +tap.test('async3', function (t) { + runProgram('async-await', 'async3.js', function (r) { + t.same(r.stdout.toString('utf8'), [ + 'TAP version 13', + '# async3', + 'ok 1 before await', + 'ok 2 after await', + '', + '1..2', + '# tests 2', + '# pass 2', + '', + '# ok' + ].join('\n') + '\n\n'); + t.same(r.exitCode, 0); + t.same(r.stderr.toString('utf8'), ''); + t.end(); + }); +}); + +tap.test('async4', function (t) { + runProgram('async-await', 'async4.js', function (r) { + t.same(stripFullStack(r.stdout.toString('utf8')), [ + 'TAP version 13', + '# async4', + 'ok 1 before await', + 'not ok 2 Error: oops', + ' ---', + ' operator: error', + ' at: Test.myTest ($TEST/async-await/async4.js:$LINE:$COL)', + ' stack: |-', + ' Error: oops', + ' at Timeout.myTimeout [as _onTimeout] ($TEST/async-await/async4.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ]); + t.same(r.exitCode, 1); + t.same(r.stderr.toString('utf8'), ''); + t.end(); + }); +}); + +tap.test('async5', function (t) { + runProgram('async-await', 'async5.js', function (r) { + t.same(stripFullStack(r.stdout.toString('utf8')), [ + 'TAP version 13', + '# async5', + 'ok 1 before server', + 'ok 2 after server', + 'ok 3 before request', + 'ok 4 after request', + 'ok 5 res.statusCode is 200', + 'not ok 6 .end() already called: mockDb.state is new', + ' ---', + ' operator: fail', + ' at: Timeout._onTimeout ($TEST/async-await/async5.js:$LINE:$COL)', + ' stack: |-', + ' Error: .end() already called: mockDb.state is new', + ' [... stack stripped ...]', + ' at Timeout._onTimeout ($TEST/async-await/async5.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 7 .end() already called: error on close', + ' ---', + ' operator: fail', + ' at: Server. ($TEST/async-await/async5.js:$LINE:$COL)', + ' stack: |-', + ' Error: .end() already called: error on close', + ' [... stack stripped ...]', + ' at Server. ($TEST/async-await/async5.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 8 .end() already called', + ' ---', + ' operator: fail', + ' at: Server. ($TEST/async-await/async5.js:$LINE:$COL)', + ' stack: |-', + ' Error: .end() already called', + ' [... stack stripped ...]', + ' at Server. ($TEST/async-await/async5.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..8', + '# tests 8', + '# pass 5', + '# fail 3', + '', + '' + ]); + t.same(r.exitCode, 1); + t.same(r.stderr.toString('utf8'), ''); + t.end(); + }); +}); + +tap.test('sync-error', function (t) { + runProgram('async-await', 'sync-error.js', function (r) { + t.same(stripFullStack(r.stdout.toString('utf8')), [ + 'TAP version 13', + '# sync-error', + 'ok 1 before throw', + '' + ]); + t.same(r.exitCode, 1); + + var stderr = r.stderr.toString('utf8'); + var lines = stderr.split('\n'); + lines = lines.filter(function (line) { + return !/\(timers.js:/.test(line) + && !/\(internal\/timers.js:/.test(line) + && !/Immediate\.next/.test(line); + }); + stderr = lines.join('\n'); + + t.same(stripFullStack(stderr), [ + '$TEST/async-await/sync-error.js:7', + ' throw new Error(\'oopsie\');', + ' ^', + '', + 'Error: oopsie', + ' at Test.myTest ($TEST/async-await/sync-error.js:$LINE:$COL)', + ' at Test.bound [as _cb] ($TAPE/lib/test.js:$LINE:$COL)', + ' at Test.run ($TAPE/lib/test.js:$LINE:$COL)', + ' at Test.bound [as run] ($TAPE/lib/test.js:$LINE:$COL)', + '' + ]); + t.end(); + }); +}); + +tap.test('async-error', function (t) { + runProgram('async-await', 'async-error.js', function (r) { + var stdout = r.stdout.toString('utf8'); + var lines = stdout.split('\n'); + lines = lines.filter(function (line) { + return !/^(\s+)at(\s+)$/.test(line); + }); + stdout = lines.join('\n'); + + t.same(stripFullStack(stdout), [ + 'TAP version 13', + '# async-error', + 'ok 1 before throw', + 'not ok 2 Error: oopsie', + ' ---', + ' operator: error', + ' stack: |-', + ' Error: oopsie', + ' at Test.myTest ($TEST/async-await/async-error.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ]); + t.same(r.exitCode, 1); + + var stderr = r.stderr.toString('utf8'); + var lines = stderr.split('\n'); + lines = lines.filter(function (line) { + return !/\(timers.js:/.test(line) + && !/\(internal\/timers.js:/.test(line) + && !/Immediate\.next/.test(line); + }); + stderr = lines.join('\n'); + + t.same(stderr, ''); + t.end(); + }); +}); + +tap.test('async-bug', function (t) { + runProgram('async-await', 'async-bug.js', function (r) { + var stdout = r.stdout.toString('utf8'); + var lines = stdout.split('\n'); + lines = lines.filter(function (line) { + return !/^(\s+)at(\s+)$/.test(line); + }); + stdout = lines.join('\n'); + + t.same(stripFullStack(stdout), [ + 'TAP version 13', + '# async-error', + 'ok 1 before throw', + 'ok 2 should be strictly equal', + 'not ok 3 TypeError: Cannot read property \'length\' of null', + ' ---', + ' operator: error', + ' stack: |-', + ' TypeError: Cannot read property \'length\' of null', + ' at myCode ($TEST/async-await/async-bug.js:$LINE:$COL)', + ' at Test.myTest ($TEST/async-await/async-bug.js:$LINE:$COL)', + ' ...', + '', + '1..3', + '# tests 3', + '# pass 2', + '# fail 1', + '', + '' + ]); + t.same(r.exitCode, 1); + + var stderr = r.stderr.toString('utf8'); + + t.same(stderr, ''); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/async-await/async-bug.js b/tests/node_modules/tape/test/async-await/async-bug.js new file mode 100644 index 0000000..219db58 --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async-bug.js @@ -0,0 +1,32 @@ +'use strict'; + +var test = require('../../'); + +function myCode(arr) { + let sum = 0; + // oops forgot to handle null + for (let i = 0; i < arr.length; i++) { + sum += arr[i]; + } + return sum; +} + +test('async-error', async function myTest(t) { + await sleep(100); + t.ok(true, 'before throw'); + + const sum = myCode([1, 2, 3]); + t.equal(sum, 6); + + const sum2 = myCode(null); + t.equal(sum2, 0); + + t.end(); +}); + + +function sleep(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} diff --git a/tests/node_modules/tape/test/async-await/async-error.js b/tests/node_modules/tape/test/async-await/async-error.js new file mode 100644 index 0000000..35fc27a --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async-error.js @@ -0,0 +1,9 @@ +'use strict'; + +var test = require('../../'); + +test('async-error', async function myTest(t) { + t.ok(true, 'before throw'); + throw new Error('oopsie'); + t.ok(true, 'after throw'); +}); diff --git a/tests/node_modules/tape/test/async-await/async1.js b/tests/node_modules/tape/test/async-await/async1.js new file mode 100644 index 0000000..ac40d19 --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async1.js @@ -0,0 +1,16 @@ +'use strict'; + +var test = require('../../'); + +test('async1', async function myTest(t) { + try { + t.ok(true, 'before await'); + await new Promise((resolve) => { + setTimeout(resolve, 10); + }); + t.ok(true, 'after await'); + t.end(); + } catch (err) { + t.ifError(err); + } +}); diff --git a/tests/node_modules/tape/test/async-await/async2.js b/tests/node_modules/tape/test/async-await/async2.js new file mode 100644 index 0000000..1f366b1 --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async2.js @@ -0,0 +1,15 @@ +'use strict'; + +var test = require('../../'); + +test('async2', async function myTest(t) { + try { + t.ok(true, 'before await'); + await new Promise((resolve) => { + setTimeout(resolve, 10); + }); + t.ok(false, 'after await'); + } catch (err) { + t.ifError(err); + } +}); diff --git a/tests/node_modules/tape/test/async-await/async3.js b/tests/node_modules/tape/test/async-await/async3.js new file mode 100644 index 0000000..25dd1bc --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async3.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = require('../../'); + +test('async3', async function myTest(t) { + t.ok(true, 'before await'); + await new Promise((resolve) => { + setTimeout(resolve, 10); + }); + t.ok(true, 'after await'); +}); diff --git a/tests/node_modules/tape/test/async-await/async4.js b/tests/node_modules/tape/test/async-await/async4.js new file mode 100644 index 0000000..67706a6 --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async4.js @@ -0,0 +1,17 @@ +'use strict'; + +var test = require('../../'); + +test('async4', async function myTest(t) { + try { + t.ok(true, 'before await'); + await new Promise((resolve, reject) => { + setTimeout(function myTimeout() { + reject(new Error('oops')); + }, 10); + }); + t.ok(true, 'after await'); + } catch (err) { + t.ifError(err); + } +}); diff --git a/tests/node_modules/tape/test/async-await/async5.js b/tests/node_modules/tape/test/async-await/async5.js new file mode 100644 index 0000000..a58930e --- /dev/null +++ b/tests/node_modules/tape/test/async-await/async5.js @@ -0,0 +1,59 @@ +'use strict'; + +var util = require('util'); +var http = require('http'); + +var test = require('../../'); + +test('async5', async function myTest(t) { + try { + t.ok(true, 'before server'); + + var mockDb = { state: 'old' }; + var server = http.createServer(function (req, res) { + res.end('OK'); + + // Pretend we write to the DB and it takes time. + setTimeout(function () { + mockDb.state = 'new'; + }, 10); + }); + + await util.promisify(function (cb) { + server.listen(0, cb); + })(); + + t.ok(true, 'after server'); + + t.ok(true, 'before request'); + + var res = await util.promisify(function (cb) { + var req = http.request({ + hostname: 'localhost', + port: server.address().port, + path: '/', + method: 'GET' + }, function (res) { + cb(null, res); + }); + req.end(); + })(); + + t.ok(true, 'after request'); + + res.resume(); + t.equal(res.statusCode, 200, 'res.statusCode is 200'); + + setTimeout(function () { + t.equal(mockDb.state, 'new', 'mockDb.state is new'); + + server.close(function (err) { + t.ifError(err, 'error on close'); + t.end(); + }); + }, 50); + } catch (err) { + t.ifError(err, 'error in catch'); + t.end(); + } +}); diff --git a/tests/node_modules/tape/test/async-await/sync-error.js b/tests/node_modules/tape/test/async-await/sync-error.js new file mode 100644 index 0000000..989f4f7 --- /dev/null +++ b/tests/node_modules/tape/test/async-await/sync-error.js @@ -0,0 +1,10 @@ +'use strict'; + +var test = require('../../'); + +test('sync-error', function myTest(t) { + t.ok(true, 'before throw'); + throw new Error('oopsie'); + t.ok(true, 'after throw'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/bound.js b/tests/node_modules/tape/test/bound.js new file mode 100644 index 0000000..cff296b --- /dev/null +++ b/tests/node_modules/tape/test/bound.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../'); + +test('bind works', function (t) { + t.plan(2); + var equal = t.equal; + var deepEqual = t.deepEqual; + equal(3, 3); + deepEqual([4], [4]); + t.end(); +}); diff --git a/tests/node_modules/tape/test/browser/asserts.js b/tests/node_modules/tape/test/browser/asserts.js new file mode 100644 index 0000000..77611f5 --- /dev/null +++ b/tests/node_modules/tape/test/browser/asserts.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = require('../../'); + +test(function (t) { + t.plan(4); + t.ok(true); + t.equal(3, 1+2); + t.deepEqual([1,2,[3,4]], [1,2,[3,4]]); + t.notDeepEqual([1,2,[3,4,5]], [1,2,[3,4]]); +}); diff --git a/tests/node_modules/tape/test/child_ordering.js b/tests/node_modules/tape/test/child_ordering.js new file mode 100644 index 0000000..c2cb2c2 --- /dev/null +++ b/tests/node_modules/tape/test/child_ordering.js @@ -0,0 +1,56 @@ +'use strict'; + +var test = require('../'); + +var childRan = false; + +test('parent', function (t) { + t.test('child', function (t) { + childRan = true; + t.pass('child ran'); + t.end(); + }); + t.end(); +}); + +test('uncle', function (t) { + t.ok(childRan, 'Child should run before next top-level test'); + t.end(); +}); + +var grandParentRan = false; +var parentRan = false; +var grandChildRan = false; +test('grandparent', function (t) { + t.ok(!grandParentRan, 'grand parent ran twice'); + grandParentRan = true; + t.test('parent', function (t) { + t.ok(!parentRan, 'parent ran twice'); + parentRan = true; + t.test('grandchild', function (t) { + t.ok(!grandChildRan, 'grand child ran twice'); + grandChildRan = true; + t.pass('grand child ran'); + t.end(); + }); + t.pass('parent ran'); + t.end(); + }); + t.test('other parent', function (t) { + t.ok(parentRan, 'first parent runs before second parent'); + t.ok(grandChildRan, 'grandchild runs before second parent'); + t.end(); + }); + t.pass('grandparent ran'); + t.end(); +}); + +test('second grandparent', function (t) { + t.ok(grandParentRan, 'grandparent ran'); + t.ok(parentRan, 'parent ran'); + t.ok(grandChildRan, 'grandchild ran'); + t.pass('other grandparent ran'); + t.end(); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape/test/circular-things.js b/tests/node_modules/tape/test/circular-things.js new file mode 100644 index 0000000..37786b5 --- /dev/null +++ b/tests/node_modules/tape/test/circular-things.js @@ -0,0 +1,46 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('circular test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# circular', + 'not ok 1 should be strictly equal', + ' ---', + ' operator: equal', + ' expected: |-', + ' {}', + ' actual: |-', + ' { circular: [Circular] }', + ' at: Test. ($TEST/circular-things.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be strictly equal', + ' [... stack stripped ...]', + ' at Test. ($TEST/circular-things.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + })); + + test('circular', function (t) { + t.plan(1); + var circular = {}; + circular.circular = circular; + t.equal(circular, {}); + }); +}); diff --git a/tests/node_modules/tape/test/comment.js b/tests/node_modules/tape/test/comment.js new file mode 100644 index 0000000..378db5a --- /dev/null +++ b/tests/node_modules/tape/test/comment.js @@ -0,0 +1,192 @@ +'use strict'; + +var concat = require('concat-stream'); +var tap = require('tap'); +var tape = require('../'); + +// Exploratory test to ascertain proper output when no t.comment() call +// is made. +tap.test('no comment', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# no comment', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('no comment', function (t) { + t.end(); + }); +}); + +// Exploratory test, can we call t.comment() passing nothing? +tap.test('missing argument', function (assert) { + assert.plan(1); + var test = tape.createHarness(); + test.createStream(); + test('missing argument', function (t) { + try { + t.comment(); + t.end(); + } catch (err) { + assert.equal(err.constructor, TypeError); + } finally { + assert.end(); + } + }); +}); + +// Exploratory test, can we call t.comment() passing nothing? +tap.test('null argument', function (assert) { + assert.plan(1); + var test = tape.createHarness(); + test.createStream(); + test('null argument', function (t) { + try { + t.comment(null); + t.end(); + } catch (err) { + assert.equal(err.constructor, TypeError); + } finally { + assert.end(); + } + }); +}); + + +// Exploratory test, how is whitespace treated? +tap.test('whitespace', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# whitespace', + '# ', + '# a', + '# a', + '# a', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('whitespace', function (t) { + t.comment(' '); + t.comment(' a'); + t.comment('a '); + t.comment(' a '); + t.end(); + }); +}); + +// Exploratory test, how about passing types other than strings? +tap.test('non-string types', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# non-string types', + '# true', + '# false', + '# 42', + '# 6.66', + '# [object Object]', + '# [object Object]', + '# [object Object]', + '# function ConstructorFunction() {}', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('non-string types', function (t) { + t.comment(true); + t.comment(false); + t.comment(42); + t.comment(6.66); + t.comment({}); + t.comment({'answer': 42}); + function ConstructorFunction() {} + t.comment(new ConstructorFunction()); + t.comment(ConstructorFunction); + t.end(); + }); +}); + +tap.test('multiline string', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# multiline strings', + '# a', + '# b', + '# c', + '# d', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var test = tape.createHarness(); + test.createStream().pipe(concat(verify)); + test('multiline strings', function (t) { + t.comment([ + 'a', + 'b' + ].join('\n')); + t.comment([ + 'c', + 'd' + ].join('\r\n')); + t.end(); + }); +}); + +tap.test('comment with createStream/objectMode', function (assert) { + assert.plan(1); + + var test = tape.createHarness(); + test.createStream({ objectMode: true }).on('data', function (row) { + if (typeof row === 'string') { + assert.equal(row, 'comment message'); + } + }); + test('t.comment', function (t) { + t.comment('comment message'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/common.js b/tests/node_modules/tape/test/common.js new file mode 100644 index 0000000..b4af7dc --- /dev/null +++ b/tests/node_modules/tape/test/common.js @@ -0,0 +1,104 @@ +'use strict'; + +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); +var yaml = require('js-yaml'); + +module.exports.getDiag = function (body) { + var yamlStart = body.indexOf(' ---'); + var yamlEnd = body.indexOf(' ...\n'); + var diag = body.slice(yamlStart, yamlEnd).split('\n').map(function (line) { + return line.slice(2); + }).join('\n'); + + // The stack trace and at variable will vary depending on where the code + // is run, so just strip it out. + var withStack = yaml.safeLoad(diag); + delete withStack.stack; + delete withStack.at; + return withStack; +}; + +// There are three challenges associated with checking the stack traces included +// in errors: +// 1) The base checkout directory of tape might change. Because stack traces +// include absolute paths, the stack traces will change depending on the +// checkout path. We handle this by replacing the base test directory with a +// placeholder $TEST variable and the package root with a placeholder +// $TAPE variable. +// 2) Line positions within the file might change. We handle this by replacing +// line and column markers with placeholder $LINE and $COL "variables" +// a) node 0.8 does not provide nested eval line numbers, so we remove them +// 3) Stacks themselves change frequently with refactoring. We've even run into +// issues with node library refactorings "breaking" stack traces. Most of +// these changes are irrelevant to the tests themselves. To counter this, we +// strip out all stack frames that aren't directly under our test directory, +// and replace them with placeholders. + +var stripChangingData = function (line) { + var withoutTestDir = line.replace(__dirname, '$TEST'); + var withoutPackageDir = withoutTestDir.replace(path.dirname(__dirname), '$TAPE'); + var withoutPathSep = withoutPackageDir.replace(new RegExp('\\' + path.sep, 'g'), '/'); + var withoutLineNumbers = withoutPathSep.replace(/:\d+:\d+/g, ':$LINE:$COL'); + var withoutNestedLineNumbers = withoutLineNumbers.replace(/, :\$LINE:\$COL\)$/, ')'); + return withoutNestedLineNumbers; +}; + +module.exports.stripFullStack = function (output) { + var stripped = ' [... stack stripped ...]'; + var withDuplicates = output.split('\n').map(stripChangingData).map(function (line) { + var m = line.match(/[ ]{8}at .*\((.*)\)/); + + if (m && m[1].slice(0, 5) !== '$TEST') { + return stripped; + } + return line; + }); + + var withoutInternals = withDuplicates.filter(function (line) { + return !line.match(/ \(node:[^)]+\)$/); + }); + + var deduped = withoutInternals.filter(function (line, ix) { + var hasPrior = line === stripped && withDuplicates[ix - 1] === stripped; + return !hasPrior; + }); + + return deduped.join('\n').replace( + // Handle stack trace variation in Node v0.8 + /at(:?) Test\.(?:module\.exports|tap\.test\.err\.code)/g, + 'at$1 Test.' + ).replace( + // Handle stack trace variation in Node v0.8 + /at(:?) (Test\.)?tap\.test\.test\.skip/g, + 'at$1 $2' + ).replace( + // Handle stack trace variation in Node v0.8 + /(\[\.\.\. stack stripped \.\.\.\]\n *at) \(([^)]+)\)/g, + '$1 $2' + ).split('\n'); +}; + +module.exports.runProgram = function (folderName, fileName, cb) { + var result = { + stdout: null, + stderr: null, + exitCode: 0 + }; + var ps = spawn(process.execPath, [ + path.join(__dirname, folderName, fileName) + ]); + + ps.stdout.pipe(concat(function (stdoutRows) { + result.stdout = stdoutRows; + })); + ps.stderr.pipe(concat(function (stderrRows) { + result.stderr = stderrRows; + })); + + ps.on('exit', function (code) { + result.exitCode = code; + cb(result); + }); +}; diff --git a/tests/node_modules/tape/test/create_multiple_streams.js b/tests/node_modules/tape/test/create_multiple_streams.js new file mode 100644 index 0000000..19cd5f9 --- /dev/null +++ b/tests/node_modules/tape/test/create_multiple_streams.js @@ -0,0 +1,33 @@ +'use strict'; + +var tape = require('../'); + +tape.test('createMultipleStreams', function (tt) { + tt.plan(2); + + var th = tape.createHarness(); + th.createStream(); + th.createStream(); + + var testOneComplete = false; + + th('test one', function (tht) { + tht.plan(1); + setTimeout( function () { + tht.pass(); + testOneComplete = true; + }, 100); + }); + + th('test two', function (tht) { + tht.ok(testOneComplete, 'test 1 completed before test 2'); + tht.end(); + }); + + th.onFinish(function () { + tt.equal(th._results.count, 2, 'harness test ran'); + tt.equal(th._results.fail, 0, "harness test didn't fail"); + }); +}); + + diff --git a/tests/node_modules/tape/test/deep-equal-failure.js b/tests/node_modules/tape/test/deep-equal-failure.js new file mode 100644 index 0000000..d5f1bc7 --- /dev/null +++ b/tests/node_modules/tape/test/deep-equal-failure.js @@ -0,0 +1,193 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('deep equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# deep equal', + 'not ok 1 should be strictly equal', + ' ---', + ' operator: equal', + ' expected: |-', + ' { b: 2 }', + ' actual: |-', + ' { a: 1 }', + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be strictly equal', + ' [... stack stripped ...]', + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ b: 2 }', + actual: '{ a: 1 }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be strictly equal', + diag: { + operator: 'equal', + expected: '{ b: 2 }', + actual: '{ a: 1 }' + } + }); + }); + + test('deep equal', function (t) { + t.plan(1); + t.equal({a: 1}, {b: 2}); + }); +}); + +tap.test('deep equal failure, depth 6, with option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# deep equal', + 'not ok 1 should be strictly equal', + ' ---', + ' operator: equal', + ' expected: |-', + ' { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }', + ' actual: |-', + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be strictly equal', + ' [... stack stripped ...]', + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be strictly equal', + diag: { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + } + }); + }); + + test('deep equal', {objectPrintDepth: 6}, function (t) { + t.plan(1); + t.equal({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }); + }); +}); + +tap.test('deep equal failure, depth 6, without option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# deep equal', + 'not ok 1 should be strictly equal', + ' ---', + ' operator: equal', + ' expected: |-', + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }', + ' actual: |-', + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }', + ' at: Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be strictly equal', + ' [... stack stripped ...]', + ' at Test. ($TEST/deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should be strictly equal', + diag: { + operator: 'equal', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + } + }); + }); + + test('deep equal', function (t) { + t.plan(1); + t.equal({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 2 } } } } } }); + }); +}); diff --git a/tests/node_modules/tape/test/deep.js b/tests/node_modules/tape/test/deep.js new file mode 100644 index 0000000..8f8862b --- /dev/null +++ b/tests/node_modules/tape/test/deep.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('../'); + +test('deep strict equal', function (t) { + t.notDeepEqual( + [ { a: '3' } ], + [ { a: 3 } ] + ); + t.end(); +}); + +test('deep loose equal', function (t) { + t.deepLooseEqual( + [ { a: '3' } ], + [ { a: 3 } ] + ); + t.end(); +}); + +test('requires 2 arguments', function (t) { + var err = /^TypeError: two arguments must be provided/; + t.throws(function () { t.deepEqual(); }, err, 'deepEqual: no args'); + t.throws(function () { t.deepEqual(undefined); }, err, 'deepEqual: one arg'); + t.throws(function () { t.deepLooseEqual(); }, err, 'deepLooseEqual: no args'); + t.throws(function () { t.deepLooseEqual(undefined); }, err, 'deepLooseEqual: one arg'); + t.throws(function () { t.notDeepEqual(); }, err, 'notDeepEqual: no args'); + t.throws(function () { t.notDeepEqual(undefined); }, err, 'notDeepEqual: one arg'); + t.throws(function () { t.notDeepLooseEqual(); }, err, 'notDeepLooseEqual: no args'); + t.throws(function () { t.notDeepLooseEqual(undefined); }, err, 'notDeepLooseEqual: one arg'); + t.throws(function () { t.equal(); }, err, 'equal: no args'); + t.throws(function () { t.equal(undefined); }, err, 'equal: one arg'); + t.throws(function () { t.notEqual(); }, err, 'notEqual: no args'); + t.throws(function () { t.notEqual(undefined); }, err, 'notEqual: one arg'); + + t.end(); +}); diff --git a/tests/node_modules/tape/test/default-messages.js b/tests/node_modules/tape/test/default-messages.js new file mode 100644 index 0000000..70d113b --- /dev/null +++ b/tests/node_modules/tape/test/default-messages.js @@ -0,0 +1,51 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('default messages', function (t) { + t.plan(1); + + var ps = spawn(process.execPath, [path.join(__dirname, 'messages', 'defaults.js')]); + + ps.stdout.pipe(concat(function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# default messages', + 'ok 1 should be truthy', + 'ok 2 should be falsy', + 'ok 3 should be strictly equal', + 'ok 4 should not be strictly equal', + 'ok 5 should be loosely equal', + 'ok 6 should not be loosely equal', + 'ok 7 should be strictly equal', + 'ok 8 should not be strictly equal', + 'ok 9 should be deeply equivalent', + 'not ok 10 should not be deeply equivalent', + ' ---', + ' operator: notDeepEqual', + ' expected: true', + ' actual: true', + ' at: Test. ($TEST/messages/defaults.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be deeply equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/messages/defaults.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 11 should be loosely deeply equivalent', + 'ok 12 should not be loosely deeply equivalent', + '', + '1..12', + '# tests 12', + '# pass 11', + '# fail 1', + '', + '' + ]); + })); +}); diff --git a/tests/node_modules/tape/test/double_end.js b/tests/node_modules/tape/test/double_end.js new file mode 100644 index 0000000..23d6dc7 --- /dev/null +++ b/tests/node_modules/tape/test/double_end.js @@ -0,0 +1,64 @@ +'use strict'; + +var test = require('tap').test; +var path = require('path'); +var concat = require('concat-stream'); +var spawn = require('child_process').spawn; + +var stripFullStack = require('./common').stripFullStack; + +test(function (tt) { + tt.plan(2); + var ps = spawn(process.execPath, [path.join(__dirname, 'double_end', 'double.js')]); + ps.on('exit', function (code) { + tt.equal(code, 1); + }); + ps.stdout.pipe(concat(function (body) { + // The implementation of node's timer library has changed over time. We + // need to reverse engineer the error we expect to see. + + // This code is unfortunately by necessity highly coupled to node + // versions, and may require tweaking with future versions of the timers + // library. + function doEnd() { throw new Error(); }; + var to = setTimeout(doEnd, 5000); + clearTimeout(to); + to._onTimeout = doEnd; + + var stackExpected; + var atExpected; + try { + to._onTimeout(); + } + catch (e) { + stackExpected = stripFullStack(e.stack)[1]; + stackExpected = stackExpected.replace('double_end.js', 'double_end/double.js'); + stackExpected = stackExpected.trim(); + atExpected = stackExpected.replace(/^at\s+/, 'at: '); + } + + var stripped = stripFullStack(body.toString('utf8')); + tt.same(stripped, [ + 'TAP version 13', + '# double end', + 'ok 1 should be strictly equal', + 'not ok 2 .end() already called', + ' ---', + ' operator: fail', + ' ' + atExpected, + ' stack: |-', + ' Error: .end() already called', + ' [... stack stripped ...]', + ' ' + stackExpected, + ' [... stack stripped ...]', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ]); + })); +}); diff --git a/tests/node_modules/tape/test/double_end/double.js b/tests/node_modules/tape/test/double_end/double.js new file mode 100644 index 0000000..2c0ae40 --- /dev/null +++ b/tests/node_modules/tape/test/double_end/double.js @@ -0,0 +1,13 @@ +'use strict'; + +var test = require('../../'); + +test('double end', function (t) { + function doEnd() { + t.end(); + } + + t.equal(1 + 1, 2); + t.end(); + setTimeout(doEnd, 5); +}); diff --git a/tests/node_modules/tape/test/edge-cases.js b/tests/node_modules/tape/test/edge-cases.js new file mode 100644 index 0000000..bf4f2e3 --- /dev/null +++ b/tests/node_modules/tape/test/edge-cases.js @@ -0,0 +1,289 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('edge cases', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# zeroes', + 'not ok 1 0 equal to -0', + ' ---', + ' operator: equal', + ' expected: |-', + ' -0', + ' actual: |-', + ' 0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: 0 equal to -0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 2 -0 equal to 0', + ' ---', + ' operator: equal', + ' expected: |-', + ' 0', + ' actual: |-', + ' -0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: -0 equal to 0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 3 0 notEqual to -0', + 'ok 4 -0 notEqual to 0', + 'ok 5 0 looseEqual to -0', + 'ok 6 -0 looseEqual to 0', + 'not ok 7 0 notLooseEqual to -0', + ' ---', + ' operator: notLooseEqual', + ' expected: |-', + ' -0', + ' actual: |-', + ' 0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: 0 notLooseEqual to -0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 8 -0 notLooseEqual to 0', + ' ---', + ' operator: notLooseEqual', + ' expected: |-', + ' 0', + ' actual: |-', + ' -0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: -0 notLooseEqual to 0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 9 0 strictEqual to -0', + ' ---', + ' operator: equal', + ' expected: |-', + ' -0', + ' actual: |-', + ' 0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: 0 strictEqual to -0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 10 -0 strictEqual to 0', + ' ---', + ' operator: equal', + ' expected: |-', + ' 0', + ' actual: |-', + ' -0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: -0 strictEqual to 0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 11 0 notStrictEqual to -0', + 'ok 12 -0 notStrictEqual to 0', + 'ok 13 0 deepLooseEqual to -0', + 'ok 14 -0 deepLooseEqual to 0', + 'not ok 15 0 notDeepLooseEqual to -0', + ' ---', + ' operator: notDeepLooseEqual', + ' expected: |-', + ' -0', + ' actual: |-', + ' 0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: 0 notDeepLooseEqual to -0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 16 -0 notDeepLooseEqual to 0', + ' ---', + ' operator: notDeepLooseEqual', + ' expected: |-', + ' 0', + ' actual: |-', + ' -0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: -0 notDeepLooseEqual to 0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 17 0 deepEqual to -0', + ' ---', + ' operator: deepEqual', + ' expected: |-', + ' -0', + ' actual: |-', + ' 0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: 0 deepEqual to -0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 18 -0 deepEqual to 0', + ' ---', + ' operator: deepEqual', + ' expected: |-', + ' 0', + ' actual: |-', + ' -0', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: -0 deepEqual to 0', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 19 0 notDeepEqual to -0', + 'ok 20 -0 notDeepEqual to 0', + '# NaNs', + 'ok 21 NaN equal to NaN', + 'not ok 22 NaN notEqual to NaN', + ' ---', + ' operator: notEqual', + ' expected: NaN', + ' actual: NaN', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: NaN notEqual to NaN', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 23 NaN looseEqual to NaN', + ' ---', + ' operator: looseEqual', + ' expected: NaN', + ' actual: NaN', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: NaN looseEqual to NaN', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 24 NaN notLooseEqual to NaN', + 'ok 25 NaN strictEqual to NaN', + 'not ok 26 NaN notStrictEqual to NaN', + ' ---', + ' operator: notEqual', + ' expected: NaN', + ' actual: NaN', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: NaN notStrictEqual to NaN', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 27 NaN deepLooseEqual to NaN', + ' ---', + ' operator: deepLooseEqual', + ' expected: NaN', + ' actual: NaN', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: NaN deepLooseEqual to NaN', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 28 NaN notDeepLooseEqual to NaN', + 'ok 29 NaN deepEqual to NaN', + 'not ok 30 NaN notDeepEqual to NaN', + ' ---', + ' operator: notDeepEqual', + ' expected: NaN', + ' actual: NaN', + ' at: Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' stack: |-', + ' Error: NaN notDeepEqual to NaN', + ' [... stack stripped ...]', + ' at Test. ($TEST/edge-cases.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..30', + '# tests 30', + '# pass 15', + '# fail 15', + '' + ]); + })); + + test('zeroes', function (t) { + t.equal(0, -0, '0 equal to -0'); + t.equal(-0, 0, '-0 equal to 0'); + t.notEqual(0, -0, '0 notEqual to -0'); + t.notEqual(-0, 0, '-0 notEqual to 0'); + + t.looseEqual(0, -0, '0 looseEqual to -0'); + t.looseEqual(-0, 0, '-0 looseEqual to 0'); + t.notLooseEqual(0, -0, '0 notLooseEqual to -0'); + t.notLooseEqual(-0, 0, '-0 notLooseEqual to 0'); + + t.strictEqual(0, -0, '0 strictEqual to -0'); + t.strictEqual(-0, 0, '-0 strictEqual to 0'); + t.notStrictEqual(0, -0, '0 notStrictEqual to -0'); + t.notStrictEqual(-0, 0, '-0 notStrictEqual to 0'); + + t.deepLooseEqual(0, -0, '0 deepLooseEqual to -0'); + t.deepLooseEqual(-0, 0, '-0 deepLooseEqual to 0'); + t.notDeepLooseEqual(0, -0, '0 notDeepLooseEqual to -0'); + t.notDeepLooseEqual(-0, 0, '-0 notDeepLooseEqual to 0'); + + t.deepEqual(0, -0, '0 deepEqual to -0'); + t.deepEqual(-0, 0, '-0 deepEqual to 0'); + t.notDeepEqual(0, -0, '0 notDeepEqual to -0'); + t.notDeepEqual(-0, 0, '-0 notDeepEqual to 0'); + + t.end(); + }); + + test('NaNs', function (t) { + t.equal(NaN, NaN, 'NaN equal to NaN'); + t.notEqual(NaN, NaN, 'NaN notEqual to NaN'); + + t.looseEqual(NaN, NaN, 'NaN looseEqual to NaN'); + t.notLooseEqual(NaN, NaN, 'NaN notLooseEqual to NaN'); + + t.strictEqual(NaN, NaN, 'NaN strictEqual to NaN'); + t.notStrictEqual(NaN, NaN, 'NaN notStrictEqual to NaN'); + + t.deepLooseEqual(NaN, NaN, 'NaN deepLooseEqual to NaN'); + t.notDeepLooseEqual(NaN, NaN, 'NaN notDeepLooseEqual to NaN'); + + t.deepEqual(NaN, NaN, 'NaN deepEqual to NaN'); + t.notDeepEqual(NaN, NaN, 'NaN notDeepEqual to NaN'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/end-as-callback.js b/tests/node_modules/tape/test/end-as-callback.js new file mode 100644 index 0000000..d706202 --- /dev/null +++ b/tests/node_modules/tape/test/end-as-callback.js @@ -0,0 +1,90 @@ +'use strict'; + +var tap = require('tap'); +var forEach = require('for-each'); +var tape = require('../'); +var concat = require('concat-stream'); + +tap.test('tape assert.end as callback', function (tt) { + var test = tape.createHarness({ exit: false }); + + test.createStream().pipe(concat(function (rows) { + tt.equal(rows.toString('utf8'), [ + 'TAP version 13', + '# do a task and write', + 'ok 1 null', + 'ok 2 should be strictly equal', + '# do a task and write fail', + 'ok 3 null', + 'ok 4 should be strictly equal', + 'not ok 5 Error: fail', + getStackTrace(rows), // tap error stack + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1' + ].join('\n') + '\n'); + tt.end(); + })); + + test('do a task and write', function (assert) { + fakeAsyncTask('foo', function (err, value) { + assert.ifError(err); + assert.equal(value, 'taskfoo'); + + fakeAsyncWrite('bar', assert.end); + }); + }); + + test('do a task and write fail', function (assert) { + fakeAsyncTask('bar', function (err, value) { + assert.ifError(err); + assert.equal(value, 'taskbar'); + + fakeAsyncWriteFail('baz', assert.end); + }); + }); +}); + +function fakeAsyncTask(name, cb) { + cb(null, 'task' + name); +} + +function fakeAsyncWrite(name, cb) { + cb(null); +} + +function fakeAsyncWriteFail(name, cb) { + cb(new Error('fail')); +} + +/** + * extract the stack trace for the failed test. + * this will change dependent on the environment + * so no point hard-coding it in the test assertion + * see: https://git.io/v6hGG for example + * @param String rows - the tap output lines + * @returns String stacktrace - just the error stack part + */ +function getStackTrace(rows) { + var stacktrace = ' ---\n'; + var extract = false; + forEach(rows.toString('utf8').split('\n'), function (row) { + if (!extract) { + if (row.indexOf('---') > -1) { // start of stack trace + extract = true; + } + } else { + if (row.indexOf('...') > -1) { // end of stack trace + extract = false; + stacktrace += ' ...'; + } else { + stacktrace += row + '\n'; + } + + } + }); + // console.log(stacktrace); + return stacktrace; +} diff --git a/tests/node_modules/tape/test/error.js b/tests/node_modules/tape/test/error.js new file mode 100644 index 0000000..6b9025b --- /dev/null +++ b/tests/node_modules/tape/test/error.js @@ -0,0 +1,39 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('failures', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# error', + 'not ok 1 Error: this is a message', + ' ---', + ' operator: error', + ' at: Test. ($TEST/error.js:$LINE:$COL)', + ' stack: |-', + ' Error: this is a message', + ' at Test. ($TEST/error.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + })); + + test('error', function (t) { + t.plan(1); + t.error(new Error('this is a message')); + }); +}); diff --git a/tests/node_modules/tape/test/exit.js b/tests/node_modules/tape/test/exit.js new file mode 100644 index 0000000..d782b8f --- /dev/null +++ b/tests/node_modules/tape/test/exit.js @@ -0,0 +1,251 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('exit ok', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# array', + '# hi', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'ok 5 should be deeply equivalent', + '', + '1..5', + '# tests 5', + '# pass 5', + '', + '# ok', + '', // yes, these double-blank-lines at the end are required. + '' // if you can figure out how to remove them, please do! + ].join('\n')); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, 'exit', 'ok.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('exit fail', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'not ok 5 should be deeply equivalent', + ' ---', + ' operator: deepEqual', + ' expected: [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]', + ' actual: [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]', + ' at: ($TEST/exit/fail.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be deeply equivalent', + ' [... stack stripped ...]', + ' at $TEST/exit/fail.js:$LINE:$COL', + ' at eval (eval at ($TEST/exit/fail.js:$LINE:$COL))', + ' at eval (eval at ($TEST/exit/fail.js:$LINE:$COL))', + ' at Test. ($TEST/exit/fail.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, 'exit', 'fail.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('too few exit', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'ok 5 should be deeply equivalent', + 'not ok 6 plan != count', + ' ---', + ' operator: fail', + ' expected: 6', + ' actual: 5', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' ...', + '', + '1..6', + '# tests 6', + '# pass 5', + '# fail 1', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/too_few.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('more planned in a second test', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# first', + 'ok 1 should be truthy', + '# second', + 'ok 2 should be truthy', + 'not ok 3 plan != count', + ' ---', + ' operator: fail', + ' expected: 2', + ' actual: 1', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' ...', + '', + '1..3', + '# tests 3', + '# pass 2', + '# fail 1', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/second.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); + +tap.test('todo passing', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# TODO todo pass', + 'ok 1 should be truthy # TODO', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/todo.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('todo failing', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# TODO todo fail', + 'not ok 1 should be truthy # TODO', + ' ---', + ' operator: ok', + ' expected: true', + ' actual: false', + ' at: Test. ($TEST/exit/todo_fail.js:$LINE:$COL)', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/todo_fail.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('forgot to call t.end()', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# first', + 'ok 1 should be truthy', + '# oops forgot end', + 'ok 2 should be truthy', + 'not ok 3 test exited without ending: oops forgot end', + ' ---', + ' operator: fail', + ' at: process. ($TAPE/index.js:$LINE:$COL)', + ' stack: |-', + ' Error: test exited without ending: oops forgot end', + ' [... stack stripped ...]', + ' ...', + '', + '1..3', + '# tests 3', + '# pass 2', + '# fail 1', + '', + '' + ]); + }; + + var ps = spawn(process.execPath, [path.join(__dirname, '/exit/missing_end.js')]); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.notEqual(code, 0); + }); +}); diff --git a/tests/node_modules/tape/test/exit/fail.js b/tests/node_modules/tape/test/exit/fail.js new file mode 100644 index 0000000..a976d4c --- /dev/null +++ b/tests/node_modules/tape/test/exit/fail.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('../../'); +var falafel = require('falafel'); + +test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/test/exit/missing_end.js b/tests/node_modules/tape/test/exit/missing_end.js new file mode 100644 index 0000000..7616fec --- /dev/null +++ b/tests/node_modules/tape/test/exit/missing_end.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../../'); + +test('first', function (t) { + t.ok(true); + t.end(); +}); + +test('oops forgot end', function (t) { + t.ok(true); +}); diff --git a/tests/node_modules/tape/test/exit/ok.js b/tests/node_modules/tape/test/exit/ok.js new file mode 100644 index 0000000..084692f --- /dev/null +++ b/tests/node_modules/tape/test/exit/ok.js @@ -0,0 +1,38 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../../'); + +test('array', function (t) { + t.comment('hi'); + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/test/exit/second.js b/tests/node_modules/tape/test/exit/second.js new file mode 100644 index 0000000..79e632e --- /dev/null +++ b/tests/node_modules/tape/test/exit/second.js @@ -0,0 +1,13 @@ +'use strict'; + +var test = require('../../'); + +test('first', function (t) { + t.plan(1); + t.ok(true); +}); + +test('second', function (t) { + t.plan(2); + t.ok(true); +}); diff --git a/tests/node_modules/tape/test/exit/todo.js b/tests/node_modules/tape/test/exit/todo.js new file mode 100644 index 0000000..bf0de1a --- /dev/null +++ b/tests/node_modules/tape/test/exit/todo.js @@ -0,0 +1,8 @@ +'use strict'; + +var test = require('../../'); + +test('todo pass', { todo: true }, function (t) { + t.plan(1); + t.ok(true); +}); diff --git a/tests/node_modules/tape/test/exit/todo_fail.js b/tests/node_modules/tape/test/exit/todo_fail.js new file mode 100644 index 0000000..06ec32f --- /dev/null +++ b/tests/node_modules/tape/test/exit/todo_fail.js @@ -0,0 +1,8 @@ +'use strict'; + +var test = require('../../'); + +test('todo fail', { todo: true }, function (t) { + t.plan(1); + t.ok(false); +}); diff --git a/tests/node_modules/tape/test/exit/too_few.js b/tests/node_modules/tape/test/exit/too_few.js new file mode 100644 index 0000000..d92fe5c --- /dev/null +++ b/tests/node_modules/tape/test/exit/too_few.js @@ -0,0 +1,37 @@ +'use strict'; + +var falafel = require('falafel'); +var test = require('../../'); + +test('array', function (t) { + t.plan(6); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); +}); diff --git a/tests/node_modules/tape/test/exposed-harness.js b/tests/node_modules/tape/test/exposed-harness.js new file mode 100644 index 0000000..d153eda --- /dev/null +++ b/tests/node_modules/tape/test/exposed-harness.js @@ -0,0 +1,14 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); + +tap.test('main harness object is exposed', function (assert) { + + assert.equal(typeof tape.getHarness, 'function', 'tape.getHarness is a function'); + + assert.equal(tape.getHarness()._results.pass, 0); + + assert.end(); + +}); diff --git a/tests/node_modules/tape/test/fail.js b/tests/node_modules/tape/test/fail.js new file mode 100644 index 0000000..c5dab57 --- /dev/null +++ b/tests/node_modules/tape/test/fail.js @@ -0,0 +1,80 @@ +'use strict'; + +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'not ok 5 should be deeply equivalent', + ' ---', + ' operator: deepEqual', + ' expected: [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]', + ' actual: [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]', + ' at: ($TEST/fail.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be deeply equivalent', + ' [... stack stripped ...]', + ' at $TEST/fail.js:$LINE:$COL', + ' at eval (eval at ($TEST/fail.js:$LINE:$COL))', + ' at eval (eval at ($TEST/fail.js:$LINE:$COL))', + ' at Test. ($TEST/fail.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..5', + '# tests 5', + '# pass 4', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('array', function (t) { + t.plan(5); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4444 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape/test/has spaces.js b/tests/node_modules/tape/test/has spaces.js new file mode 100644 index 0000000..990c9d8 --- /dev/null +++ b/tests/node_modules/tape/test/has spaces.js @@ -0,0 +1,42 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# fail', + 'not ok 1 this should fail', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/has spaces.js:$LINE:$COL)', + ' stack: |-', + ' Error: this should fail', + ' [... stack stripped ...]', + ' at Test. ($TEST/has spaces.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('fail', function (t) { + t.fail('this should fail'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/ignore/.ignore b/tests/node_modules/tape/test/ignore/.ignore new file mode 100644 index 0000000..ec1cc29 --- /dev/null +++ b/tests/node_modules/tape/test/ignore/.ignore @@ -0,0 +1 @@ +fake_node_modules diff --git a/tests/node_modules/tape/test/ignore/fake_node_modules/stub1.js b/tests/node_modules/tape/test/ignore/fake_node_modules/stub1.js new file mode 100644 index 0000000..6ef0b71 --- /dev/null +++ b/tests/node_modules/tape/test/ignore/fake_node_modules/stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.plan(1); + t.fail('Should not print'); +}); diff --git a/tests/node_modules/tape/test/ignore/fake_node_modules/stub2.js b/tests/node_modules/tape/test/ignore/fake_node_modules/stub2.js new file mode 100644 index 0000000..27bebd8 --- /dev/null +++ b/tests/node_modules/tape/test/ignore/fake_node_modules/stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.fail('Should not print'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/ignore/test.js b/tests/node_modules/tape/test/ignore/test.js new file mode 100644 index 0000000..f2d6f57 --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../'); + +tape.test(function (t) { + t.plan(1); + t.ok('Okay'); +}); diff --git a/tests/node_modules/tape/test/ignore/test/stub1.js b/tests/node_modules/tape/test/ignore/test/stub1.js new file mode 100644 index 0000000..e91244e --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test/stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.plan(1); + t.pass('test/stub1'); +}); diff --git a/tests/node_modules/tape/test/ignore/test/stub2.js b/tests/node_modules/tape/test/ignore/test/stub2.js new file mode 100644 index 0000000..f4661b8 --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test/stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../'); + +tape.test(function (t) { + t.pass('test/stub2'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/ignore/test/sub/sub.stub1.js b/tests/node_modules/tape/test/ignore/test/sub/sub.stub1.js new file mode 100644 index 0000000..0f39cfe --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test/sub/sub.stub1.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../../'); + +tape.test(function (t) { + t.plan(1); + t.pass('test/sub/stub1'); +}); diff --git a/tests/node_modules/tape/test/ignore/test/sub/sub.stub2.js b/tests/node_modules/tape/test/ignore/test/sub/sub.stub2.js new file mode 100644 index 0000000..bec910d --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test/sub/sub.stub2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../../../'); + +tape.test(function (t) { + t.pass('test/sub/stub2'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/ignore/test2.js b/tests/node_modules/tape/test/ignore/test2.js new file mode 100644 index 0000000..a2ceecc --- /dev/null +++ b/tests/node_modules/tape/test/ignore/test2.js @@ -0,0 +1,8 @@ +'use strict'; + +var tape = require('../../'); + +tape.test(function (t) { + t.pass('Should print'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/ignore_from_gitignore.js b/tests/node_modules/tape/test/ignore_from_gitignore.js new file mode 100644 index 0000000..d95260b --- /dev/null +++ b/tests/node_modules/tape/test/ignore_from_gitignore.js @@ -0,0 +1,122 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +var tapeBin = path.join(process.cwd(), 'bin/tape'); + +tap.test('Should pass with ignoring', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(2); + + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# (anonymous)', + 'ok 1 should be truthy', + '# (anonymous)', + 'ok 2 test/stub1', + '# (anonymous)', + 'ok 3 test/stub2', + '# (anonymous)', + 'ok 4 test/sub/stub1', + '# (anonymous)', + 'ok 5 test/sub/stub2', + '# (anonymous)', + 'ok 6 Should print', + '', + '1..6', + '# tests 6', + '# pass 6', + '', + '# ok', + '', + '' + ]); + }; + + var ps = spawn(tapeBin, ['**/*.js', '-i', '.ignore'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + tt.equal(code, 0); // code 0 + }); +}); + +tap.test('Should pass', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(2); + + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# (anonymous)', + 'not ok 1 Should not print', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/ignore/fake_node_modules/stub1.js:$LINE:$COL)', + ' stack: |-', + ' Error: Should not print', + ' [... stack stripped ...]', + ' at Test. ($TEST/ignore/fake_node_modules/stub1.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# (anonymous)', + 'not ok 2 Should not print', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/ignore/fake_node_modules/stub2.js:$LINE:$COL)', + ' stack: |-', + ' Error: Should not print', + ' [... stack stripped ...]', + ' at Test. ($TEST/ignore/fake_node_modules/stub2.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# (anonymous)', + 'ok 3 should be truthy', + '# (anonymous)', + 'ok 4 test/stub1', + '# (anonymous)', + 'ok 5 test/stub2', + '# (anonymous)', + 'ok 6 test/sub/stub1', + '# (anonymous)', + 'ok 7 test/sub/stub2', + '# (anonymous)', + 'ok 8 Should print', + '', + '1..8', + '# tests 8', + '# pass 6', + '# fail 2', + '', + '' + ]); + }; + + var ps = spawn(tapeBin, ['**/*.js'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + tt.equal(code, 1); + }); +}); + +tap.test('Should fail when ignore file does not exist', { skip: process.platform === 'win32' }, function (tt) { + tt.plan(3); + + var testStdout = function (rows) { + tt.same(rows.toString('utf8'), ''); + }; + + var testStderr = function (rows) { + tt.ok(/^ENOENT[:,] no such file or directory,? (?:open )?'\$TEST\/ignore\/.gitignore'\n$/m.test(stripFullStack(rows.toString('utf8')).join('\n'))); + }; + + var ps = spawn(tapeBin, ['**/*.js', '-i'], {cwd: path.join(__dirname, 'ignore')}); + ps.stdout.pipe(concat(testStdout)); + ps.stderr.pipe(concat(testStderr)); + ps.on('exit', function (code) { + tt.equal(code, 2); + }); +}); diff --git a/tests/node_modules/tape/test/many.js b/tests/node_modules/tape/test/many.js new file mode 100644 index 0000000..6e5368a --- /dev/null +++ b/tests/node_modules/tape/test/many.js @@ -0,0 +1,10 @@ +'use strict'; + +var test = require('../'); + +test('many tests', function (t) { + t.plan(100); + for (var i = 0; i < 100; i++) { + setTimeout(function () { t.pass(); }, Math.random() * 50); + } +}); diff --git a/tests/node_modules/tape/test/match.js b/tests/node_modules/tape/test/match.js new file mode 100644 index 0000000..b598b9d --- /dev/null +++ b/tests/node_modules/tape/test/match.js @@ -0,0 +1,173 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('match', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# match', + 'ok 1 regex arg must be a regex', + 'ok 2 string arg must be a string', + 'not ok 3 The input did not match the regular expression /abc/. Input: \'string\'', + ' ---', + ' operator: match', + ' expected: /abc/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input did not match the regular expression /abc/. Input: \'string\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 4 "string" does not match /abc/', + ' ---', + ' operator: match', + ' expected: /abc/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "string" does not match /abc/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 5 The input matched the regular expression /pass$/. Input: \'I will pass\'', + 'ok 6 "I will pass" matches /pass$/', + '', + '1..6', + '# tests 6', + '# pass 4', + '# fail 2', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('match', function (t) { + t.plan(6); + + t.throws( + function () { t.match(/abc/, 'string'); }, + TypeError, + 'regex arg must be a regex' + ); + + t.throws( + function () { t.match({ abc: 123 }, /abc/); }, + TypeError, + 'string arg must be a string' + ); + + t.match('string', /abc/); + t.match('string', /abc/, '"string" does not match /abc/'); + + t.match('I will pass', /pass$/); + t.match('I will pass', /pass$/, '"I will pass" matches /pass$/'); + + t.end(); + }); +}); + +tap.test('doesNotMatch', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# doesNotMatch', + 'ok 1 regex arg must be a regex', + 'ok 2 string arg must be a string', + 'not ok 3 The input was expected to not match the regular expression /string/. Input: \'string\'', + ' ---', + ' operator: doesNotMatch', + ' expected: /string/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input was expected to not match the regular expression /string/. Input: \'string\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 4 "string" should not match /string/', + ' ---', + ' operator: doesNotMatch', + ' expected: /string/', + ' actual: \'string\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "string" should not match /string/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 5 The input was expected to not match the regular expression /pass$/. Input: \'I will pass\'', + ' ---', + ' operator: doesNotMatch', + ' expected: /pass$/', + ' actual: \'I will pass\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: The input was expected to not match the regular expression /pass$/. Input: \'I will pass\'', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 6 "I will pass" should not match /pass$/', + ' ---', + ' operator: doesNotMatch', + ' expected: /pass$/', + ' actual: \'I will pass\'', + ' at: Test. ($TEST/match.js:$LINE:$COL)', + ' stack: |-', + ' Error: "I will pass" should not match /pass$/', + ' [... stack stripped ...]', + ' at Test. ($TEST/match.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..6', + '# tests 6', + '# pass 2', + '# fail 4', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('doesNotMatch', function (t) { + t.plan(6); + + t.throws( + function () { t.doesNotMatch(/abc/, 'string'); }, + TypeError, + 'regex arg must be a regex' + ); + + t.throws( + function () { t.doesNotMatch({ abc: 123 }, /abc/); }, + TypeError, + 'string arg must be a string' + ); + + t.doesNotMatch('string', /string/); + t.doesNotMatch('string', /string/, '"string" should not match /string/'); + + t.doesNotMatch('I will pass', /pass$/); + t.doesNotMatch('I will pass', /pass$/, '"I will pass" should not match /pass$/'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/max_listeners.js b/tests/node_modules/tape/test/max_listeners.js new file mode 100644 index 0000000..286a2b1 --- /dev/null +++ b/tests/node_modules/tape/test/max_listeners.js @@ -0,0 +1,12 @@ +'use strict'; + +var spawn = require('child_process').spawn; +var path = require('path'); + +var ps = spawn(process.execPath, [path.join(__dirname, 'max_listeners', 'source.js')]); + +ps.stdout.pipe(process.stdout, { end: false }); + +ps.stderr.on('data', function (buf) { + console.log('not ok ' + buf); +}); diff --git a/tests/node_modules/tape/test/max_listeners/source.js b/tests/node_modules/tape/test/max_listeners/source.js new file mode 100644 index 0000000..e801853 --- /dev/null +++ b/tests/node_modules/tape/test/max_listeners/source.js @@ -0,0 +1,7 @@ +'use strict'; + +var test = require('../../'); + +for (var i = 0; i < 11; i++) { + test(function (t) { t.ok(true, 'true is truthy'); t.end(); }); +} diff --git a/tests/node_modules/tape/test/messages/defaults.js b/tests/node_modules/tape/test/messages/defaults.js new file mode 100644 index 0000000..e967214 --- /dev/null +++ b/tests/node_modules/tape/test/messages/defaults.js @@ -0,0 +1,25 @@ +'use strict'; + +var test = require('../../'); + +test('default messages', function (t) { + t.plan(12); + + t.ok(true); + t.notOk(false); + + t.equal(true, true); + t.notEqual(true, false); + + t.looseEqual(true, true); + t.notLooseEqual(true, false); + + t.strictEqual(true, true); + t.notStrictEqual(true, false); + + t.deepEqual(true, true); + t.notDeepEqual(true, true); + + t.deepLooseEqual(true, true); + t.notDeepLooseEqual(true, false); +}); diff --git a/tests/node_modules/tape/test/nested-async-plan-noend.js b/tests/node_modules/tape/test/nested-async-plan-noend.js new file mode 100644 index 0000000..a086d8e --- /dev/null +++ b/tests/node_modules/tape/test/nested-async-plan-noend.js @@ -0,0 +1,38 @@ +'use strict'; + +var test = require('../'); + +test('Harness async test support', function (t) { + t.plan(3); + + t.ok(true, 'sync child A'); + + t.test('sync child B', function (tt) { + tt.plan(2); + + setTimeout(function () { + tt.test('async grandchild A', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }, 50); + + setTimeout(function () { + tt.test('async grandchild B', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }, 100); + }); + + setTimeout(function () { + t.test('async child', function (tt) { + tt.plan(2); + tt.ok(true, 'sync grandchild in async child A'); + tt.test('sync grandchild in async child B', function (ttt) { + ttt.plan(1); + ttt.ok(true); + }); + }); + }, 200); +}); diff --git a/tests/node_modules/tape/test/nested-sync-noplan-noend.js b/tests/node_modules/tape/test/nested-sync-noplan-noend.js new file mode 100644 index 0000000..80a7da0 --- /dev/null +++ b/tests/node_modules/tape/test/nested-sync-noplan-noend.js @@ -0,0 +1,45 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('nested sync test without plan or end', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# nested without plan or end', + '# first', + 'ok 1 should be truthy', + '# second', + 'ok 2 should be truthy', + '', + '1..2', + '# tests 2', + '# pass 2', + '', + '# ok' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('nested without plan or end', function (t) { + t.test('first', function (q) { + setTimeout(function first() { + q.ok(true); + q.end(); + }, 10); + }); + t.test('second', function (q) { + setTimeout(function second() { + q.ok(true); + q.end(); + }, 10); + }); + }); + +}); diff --git a/tests/node_modules/tape/test/nested.js b/tests/node_modules/tape/test/nested.js new file mode 100644 index 0000000..d86e94c --- /dev/null +++ b/tests/node_modules/tape/test/nested.js @@ -0,0 +1,85 @@ +'use strict'; + +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(rows.toString('utf8'), [ + 'TAP version 13', + '# nested array test', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'ok 5 should be deeply equivalent', + '# inside test', + 'ok 6 should be truthy', + 'ok 7 should be truthy', + '# another', + 'ok 8 should be truthy', + '', + '1..8', + '# tests 8', + '# pass 8', + '', + '# ok' + ].join('\n') + '\n'); + }; + + test.createStream().pipe(concat(tc)); + + test('nested array test', function (t) { + t.plan(6); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + t.test('inside test', function (q) { + q.plan(2); + q.ok(true); + + setTimeout(function () { + q.ok(true); + }, 100); + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); + + test('another', function (t) { + t.plan(1); + setTimeout(function () { + t.ok(true); + }, 50); + }); +}); diff --git a/tests/node_modules/tape/test/nested2.js b/tests/node_modules/tape/test/nested2.js new file mode 100644 index 0000000..130b958 --- /dev/null +++ b/tests/node_modules/tape/test/nested2.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('../'); + +test(function (t) { + var i = 0; + t.test('setup', function (t) { + process.nextTick(function () { + t.equal(i, 0, 'called once'); + i++; + t.end(); + }); + }); + + + t.test('teardown', function (t) { + t.end(); + }); + + t.end(); +}); diff --git a/tests/node_modules/tape/test/no_callback.js b/tests/node_modules/tape/test/no_callback.js new file mode 100644 index 0000000..47a478d --- /dev/null +++ b/tests/node_modules/tape/test/no_callback.js @@ -0,0 +1,49 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('no callback', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + var body = stripFullStack(rows.toString('utf8')); + + tt.same(body, [ + 'TAP version 13', + '# group', + '# No callback.', + 'not ok 1 # TODO No callback.', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: # TODO No callback.', + ' [... stack stripped ...]', + ' ...', + '# SKIP No callback, skipped.', + '# TODO No callback, todo.', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('group', function (t) { + t.plan(3); + + t.test('No callback.'); + + t.test('No callback, skipped.', { skip: true }); + + t.test('No callback, todo.', { todo: true }); + }); +}); diff --git a/tests/node_modules/tape/test/not-deep-equal-failure.js b/tests/node_modules/tape/test/not-deep-equal-failure.js new file mode 100644 index 0000000..dadfa53 --- /dev/null +++ b/tests/node_modules/tape/test/not-deep-equal-failure.js @@ -0,0 +1,193 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('deep equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# not deep equal', + 'not ok 1 should not be deeply equivalent', + ' ---', + ' operator: notDeepEqual', + ' expected: |-', + ' { b: 2 }', + ' actual: |-', + ' { b: 2 }', + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be deeply equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ b: 2 }', + actual: '{ b: 2 }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be deeply equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ b: 2 }', + actual: '{ b: 2 }' + } + }); + }); + + test('not deep equal', function (t) { + t.plan(1); + t.notDeepEqual({b: 2}, {b: 2}); + }); +}); + +tap.test('not deep equal failure, depth 6, with option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# not deep equal', + 'not ok 1 should not be deeply equivalent', + ' ---', + ' operator: notDeepEqual', + ' expected: |-', + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + ' actual: |-', + ' { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be deeply equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be deeply equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }' + } + }); + }); + + test('not deep equal', {objectPrintDepth: 6}, function (t) { + t.plan(1); + t.notDeepEqual({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }); + }); +}); + +tap.test('not deep equal failure, depth 6, without option', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# not deep equal', + 'not ok 1 should not be deeply equivalent', + ' ---', + ' operator: notDeepEqual', + ' expected: |-', + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }', + ' actual: |-', + ' { a: { a1: { a2: { a3: { a4: [Object] } } } } }', + ' at: Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be deeply equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/not-deep-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be deeply equivalent', + diag: { + operator: 'notDeepEqual', + expected: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }', + actual: '{ a: { a1: { a2: { a3: { a4: [Object] } } } } }' + } + }); + }); + + test('not deep equal', function (t) { + t.plan(1); + t.notDeepEqual({ a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }, { a: { a1: { a2: { a3: { a4: { a5: 1 } } } } } }); + }); +}); diff --git a/tests/node_modules/tape/test/not-equal-failure.js b/tests/node_modules/tape/test/not-equal-failure.js new file mode 100644 index 0000000..4cf11f0 --- /dev/null +++ b/tests/node_modules/tape/test/not-equal-failure.js @@ -0,0 +1,69 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var common = require('./common'); + +var getDiag = common.getDiag; +var stripFullStack = common.stripFullStack; + +tap.test('not equal failure', function (assert) { + var test = tape.createHarness({ exit: false }); + var stream = test.createStream(); + var parser = tapParser(); + assert.plan(3); + + stream.pipe(parser); + stream.pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# not equal', + 'not ok 1 should not be strictly equal', + ' ---', + ' operator: notEqual', + ' expected: 2', + ' actual: 2', + ' at: Test. ($TEST/not-equal-failure.js:$LINE:$COL)', + ' stack: |-', + ' Error: should not be strictly equal', + ' [... stack stripped ...]', + ' at Test. ($TEST/not-equal-failure.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + + assert.deepEqual(getDiag(body), { + operator: 'notEqual', + expected: '2', + actual: '2' + }); + })); + + parser.once('assert', function (data) { + delete data.diag.stack; + delete data.diag.at; + assert.deepEqual(data, { + ok: false, + id: 1, + name: 'should not be strictly equal', + diag: { + operator: 'notEqual', + expected: '2', + actual: '2' + } + }); + }); + + test('not equal', function (t) { + t.plan(1); + t.notEqual(2, 2); + }); +}); diff --git a/tests/node_modules/tape/test/numerics.js b/tests/node_modules/tape/test/numerics.js new file mode 100644 index 0000000..746a509 --- /dev/null +++ b/tests/node_modules/tape/test/numerics.js @@ -0,0 +1,184 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('numerics', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# numeric strings', + 'not ok 1 number equal to string', + ' ---', + ' operator: equal', + ' expected: \'3\'', + ' actual: 3', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: number equal to string', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 2 string equal to number', + ' ---', + ' operator: equal', + ' expected: 3', + ' actual: \'3\'', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: string equal to number', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 3 number notEqual to string', + 'ok 4 string notEqual to number', + 'ok 5 number looseEqual to string', + 'ok 6 string looseEqual to number', + 'not ok 7 number notLooseEqual to string', + ' ---', + ' operator: notLooseEqual', + ' expected: \'3\'', + ' actual: 3', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: number notLooseEqual to string', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 8 string notLooseEqual to number', + ' ---', + ' operator: notLooseEqual', + ' expected: 3', + ' actual: \'3\'', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: string notLooseEqual to number', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 9 number strictEqual to string', + ' ---', + ' operator: equal', + ' expected: \'3\'', + ' actual: 3', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: number strictEqual to string', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 10 string strictEqual to number', + ' ---', + ' operator: equal', + ' expected: 3', + ' actual: \'3\'', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: string strictEqual to number', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 11 number notStrictEqual to string', + 'ok 12 string notStrictEqual to number', + 'ok 13 number deepLooseEqual to string', + 'ok 14 string deepLooseEqual to number', + 'not ok 15 number notDeepLooseEqual to string', + ' ---', + ' operator: notDeepLooseEqual', + ' expected: \'3\'', + ' actual: 3', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: number notDeepLooseEqual to string', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 16 string notDeepLooseEqual to number', + ' ---', + ' operator: notDeepLooseEqual', + ' expected: 3', + ' actual: \'3\'', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: string notDeepLooseEqual to number', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 17 number deepEqual to string', + ' ---', + ' operator: deepEqual', + ' expected: \'3\'', + ' actual: 3', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: number deepEqual to string', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'not ok 18 string deepEqual to number', + ' ---', + ' operator: deepEqual', + ' expected: 3', + ' actual: \'3\'', + ' at: Test. ($TEST/numerics.js:$LINE:$COL)', + ' stack: |-', + ' Error: string deepEqual to number', + ' [... stack stripped ...]', + ' at Test. ($TEST/numerics.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 19 number notDeepEqual to string', + 'ok 20 string notDeepEqual to number', + '', + '1..20', + '# tests 20', + '# pass 10', + '# fail 10', + '' + ]); + })); + + test('numeric strings', function (t) { + t.equal(3, '3', 'number equal to string'); + t.equal('3', 3, 'string equal to number'); + t.notEqual(3, '3', 'number notEqual to string'); + t.notEqual('3', 3, 'string notEqual to number'); + + t.looseEqual(3, '3', 'number looseEqual to string'); + t.looseEqual('3', 3, 'string looseEqual to number'); + t.notLooseEqual(3, '3', 'number notLooseEqual to string'); + t.notLooseEqual('3', 3, 'string notLooseEqual to number'); + + t.strictEqual(3, '3', 'number strictEqual to string'); + t.strictEqual('3', 3, 'string strictEqual to number'); + t.notStrictEqual(3, '3', 'number notStrictEqual to string'); + t.notStrictEqual('3', 3, 'string notStrictEqual to number'); + + t.deepLooseEqual(3, '3', 'number deepLooseEqual to string'); + t.deepLooseEqual('3', 3, 'string deepLooseEqual to number'); + t.notDeepLooseEqual(3, '3', 'number notDeepLooseEqual to string'); + t.notDeepLooseEqual('3', 3, 'string notDeepLooseEqual to number'); + + t.deepEqual(3, '3', 'number deepEqual to string'); + t.deepEqual('3', 3, 'string deepEqual to number'); + t.notDeepEqual(3, '3', 'number notDeepEqual to string'); + t.notDeepEqual('3', 3, 'string notDeepEqual to number'); + + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/objectMode.js b/tests/node_modules/tape/test/objectMode.js new file mode 100644 index 0000000..3a7cf37 --- /dev/null +++ b/tests/node_modules/tape/test/objectMode.js @@ -0,0 +1,71 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var forEach = require('for-each'); +var through = require('through'); + +tap.test('object results', function (assert) { + var printer = through({ objectMode: true }); + var objects = []; + + printer.write = function (obj) { + objects.push(obj); + }; + + printer.end = function (obj) { + if (obj) objects.push(obj); + + var todos = 0; + var skips = 0; + var testIds = []; + var endIds = []; + var asserts = 0; + + assert.equal(objects.length, 13); + + forEach(objects, function (obj) { + if (obj.type === 'assert') { + asserts++; + } else if (obj.type === 'test') { + testIds.push(obj.id); + + if (obj.skip) { + skips++; + } else if (obj.todo) { + todos++; + } + } else if (obj.type === 'end') { + endIds.push(obj.text); + // test object should exist + assert.notEqual(testIds.indexOf(obj.test), -1); + } + }); + + assert.equal(asserts, 5); + assert.equal(skips, 1); + assert.equal(todos, 2); + assert.equal(testIds.length, endIds.length); + assert.end(); + }; + + tape.createStream({ objectMode: true }).pipe(printer); + + tape('parent', function (t1) { + t1.equal(true, true); + t1.test('child1', {skip: true}, function (t2) { + t2.equal(true, true); + t2.equal(true, false); + t2.end(); + }); + t1.test('child2', {todo: true}, function (t3) { + t3.equal(true, false); + t3.equal(true, true); + t3.end(); + }); + t1.test('child3', {todo: true}); + t1.equal(true, true); + t1.equal(true, true); + t1.end(); + }); +}); diff --git a/tests/node_modules/tape/test/objectModeWithComment.js b/tests/node_modules/tape/test/objectModeWithComment.js new file mode 100644 index 0000000..9a34f27 --- /dev/null +++ b/tests/node_modules/tape/test/objectModeWithComment.js @@ -0,0 +1,41 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var through = require('through'); + +tap.test('test.comment() in objectMode', function (assert) { + var printer = through({ objectMode: true }); + var objects = []; + printer.on('error', function (e) { + assert.fail(e); + }); + + printer.write = function (obj) { + objects.push(obj); + }; + printer.end = function (obj) { + if (obj) { objects.push(obj); } + + assert.equal(objects.length, 3); + assert.deepEqual(objects, [ + { + type: 'test', + name: 'test.comment', + id: 0, + skip: false, + todo: false + }, + 'message', + { type: 'end', test: 0 } + ]); + assert.end(); + }; + + tape.createStream({ objectMode: true }).pipe(printer); + + tape('test.comment', function (test) { + test.comment('message'); + test.end(); + }); +}); diff --git a/tests/node_modules/tape/test/onFailure.js b/tests/node_modules/tape/test/onFailure.js new file mode 100644 index 0000000..7ae77df --- /dev/null +++ b/tests/node_modules/tape/test/onFailure.js @@ -0,0 +1,23 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../').createHarness(); + +//Because this test passing depends on a failure, +//we must direct the failing output of the inner test +var noop = function () {}; +var mockSink = {on: noop, removeListener: noop, emit: noop, end: noop}; +tape.createStream().pipe(mockSink); + +tap.test('on failure', { timeout: 1000 }, function (tt) { + tt.plan(1); + + tape('dummy test', function (t) { + t.fail(); + t.end(); + }); + + tape.onFailure(function () { + tt.pass('tape ended'); + }); +}); diff --git a/tests/node_modules/tape/test/onFinish.js b/tests/node_modules/tape/test/onFinish.js new file mode 100644 index 0000000..ba7597c --- /dev/null +++ b/tests/node_modules/tape/test/onFinish.js @@ -0,0 +1,14 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); + +tap.test('on finish', {timeout: 1000}, function (tt) { + tt.plan(1); + tape.onFinish(function () { + tt.pass('tape ended'); + }); + tape('dummy test', function (t) { + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/only-twice.js b/tests/node_modules/tape/test/only-twice.js new file mode 100644 index 0000000..7c7ab18 --- /dev/null +++ b/tests/node_modules/tape/test/only-twice.js @@ -0,0 +1,22 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); + +tap.test('only twice error', function (assert) { + var test = tape.createHarness({ exit: false }); + + test.only('first only', function (t) { + t.end(); + }); + + assert.throws(function () { + test.only('second only', function (t) { + t.end(); + }); + }, { + name: 'Error', + message: 'there can only be one only test' + }); + assert.end(); +}); diff --git a/tests/node_modules/tape/test/only.js b/tests/node_modules/tape/test/only.js new file mode 100644 index 0000000..4c4fc63 --- /dev/null +++ b/tests/node_modules/tape/test/only.js @@ -0,0 +1,47 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +tap.test('tape only test', function (tt) { + var test = tape.createHarness({ exit: false }); + var ran = []; + + var tc = function (rows) { + tt.deepEqual(rows.toString('utf8'), [ + 'TAP version 13', + '# run success', + 'ok 1 assert name', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok' + ].join('\n') + '\n'); + tt.deepEqual(ran, [ 3 ]); + + tt.end(); + }; + + test.createStream().pipe(concat(tc)); + + test('never run fail', function (t) { + ran.push(1); + t.equal(true, false); + t.end(); + }); + + test('never run success', function (t) { + ran.push(2); + t.equal(true, true); + t.end(); + }); + + test.only('run success', function (t) { + ran.push(3); + t.ok(true, 'assert name'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/only2.js b/tests/node_modules/tape/test/only2.js new file mode 100644 index 0000000..bf62997 --- /dev/null +++ b/tests/node_modules/tape/test/only2.js @@ -0,0 +1,11 @@ +'use strict'; + +var test = require('../'); + +test('only2 test 1', function (t) { + t.end(); +}); + +test.only('only2 test 2', function (t) { + t.end(); +}); diff --git a/tests/node_modules/tape/test/only3.js b/tests/node_modules/tape/test/only3.js new file mode 100644 index 0000000..6c73ef8 --- /dev/null +++ b/tests/node_modules/tape/test/only3.js @@ -0,0 +1,17 @@ +'use strict'; + +var test = require('../'); + +test('only3 test 1', function (t) { + t.fail('not 1'); + t.end(); +}); + +test.only('only3 test 2', function (t) { + t.end(); +}); + +test('only3 test 3', function (t) { + t.fail('not 3'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/only4.js b/tests/node_modules/tape/test/only4.js new file mode 100644 index 0000000..b436212 --- /dev/null +++ b/tests/node_modules/tape/test/only4.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../'); + +test('only4 duplicate test name', function (t) { + t.fail('not 1'); + t.end(); +}); + +test.only('only4 duplicate test name', function (t) { + t.end(); +}); diff --git a/tests/node_modules/tape/test/only5.js b/tests/node_modules/tape/test/only5.js new file mode 100644 index 0000000..abbfbe2 --- /dev/null +++ b/tests/node_modules/tape/test/only5.js @@ -0,0 +1,12 @@ +'use strict'; + +var test = require('../'); + +test.only('only5 duplicate test name', function (t) { + t.end(); +}); + +test('only5 duplicate test name', function (t) { + t.fail('not 2'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/order.js b/tests/node_modules/tape/test/order.js new file mode 100644 index 0000000..5c0ea71 --- /dev/null +++ b/tests/node_modules/tape/test/order.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('../'); +var current = 0; + +test(function (t) { + t.equal(current++, 0); + t.end(); +}); +test(function (t) { + t.plan(1); + setTimeout(function () { + t.equal(current++, 1); + }, 100); +}); +test(function (t) { + t.equal(current++, 2); + t.end(); +}); diff --git a/tests/node_modules/tape/test/plan_optional.js b/tests/node_modules/tape/test/plan_optional.js new file mode 100644 index 0000000..6731f26 --- /dev/null +++ b/tests/node_modules/tape/test/plan_optional.js @@ -0,0 +1,17 @@ +'use strict'; + +var test = require('../'); + +test('plan should be optional', function (t) { + t.pass('no plan here'); + t.end(); +}); + +test('no plan async', function (t) { + setTimeout(function () { + t.pass('ok'); + t.end(); + }, 100); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape/test/promise_fail.js b/tests/node_modules/tape/test/promise_fail.js new file mode 100644 index 0000000..fc38fb7 --- /dev/null +++ b/tests/node_modules/tape/test/promise_fail.js @@ -0,0 +1,105 @@ +'use strict'; + +var tap = require('tap'); +var path = require('path'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('callback returning rejected promise should cause that test (and only that test) to fail', function (tt) { + tt.plan(1); + + var ps = spawn(process.execPath, [path.join(__dirname, 'promises', 'fail.js')]); + + ps.stdout.pipe(concat(function (rows) { + var rowsString = rows.toString('utf8'); + + if (/^skip\n$/.test(rowsString)) { + return tt.pass('the test file indicated it should be skipped'); + } + + var strippedString = stripFullStack(rowsString).filter(function (line) { + return !/^(\s+)at(\s+)(?:Test\.)?(?:$|\s)/.test(line); + }).join('\n'); + + // hack for consistency across all versions of node + // some versions produce a longer stack trace for some reason + // since this doesn't affect the validity of the test, the extra line is removed if present + // the regex just removes the lines "at " and "[... stack stripped ...]" if they occur together + strippedString = strippedString + .replace(/.+at (?:Test\.)?\n.+\[\.\.\. stack stripped \.\.\.\]\n/g, '') + .replace(/(?:(.+)\[\.\.\. stack stripped \.\.\.\]\n)+/g, '$1[... stack stripped ...]\n'); + + tt.same(strippedString, [ + 'TAP version 13', + '# promise', + 'not ok 1 Error: rejection message', + ' ---', + ' operator: error', + ' stack: |-', + ' Error: rejection message', + ' at $TEST/promises/fail.js:$LINE:$COL', + ' [... stack stripped ...]', + ' ...', + '# after', + 'ok 2 should be truthy', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ].join('\n')); + })); +}); + +tap.test('subtest callback returning rejected promise should cause that subtest (and only that subtest) to fail', function (tt) { + tt.plan(1); + + var ps = spawn(process.execPath, [path.join(__dirname, 'promises', 'subTests.js')]); + + ps.stdout.pipe(concat(function (rows) { + var rowsString = rows.toString('utf8'); + + if (/^skip\n$/.test(rowsString)) { + return tt.pass('the test file indicated it should be skipped'); + } + + var strippedString = stripFullStack(rowsString).filter(function (line) { + return !/^(\s+)at(\s+)(?:Test\.)?(?:$|\s)/.test(line); + }).join('\n'); + + // hack for consistency across all versions of node + // some versions produce a longer stack trace for some reason + // since this doesn't affect the validity of the test, the extra line is removed if present + // the regex just removes the lines "at " and "[... stack stripped ...]" if they occur together + strippedString = strippedString + .replace(/.+at (?:Test\.)?\n.+\[\.\.\. stack stripped \.\.\.\]\n/, '') + .replace(/(?:(.+)\[\.\.\. stack stripped \.\.\.\]\n)+/g, '$1[... stack stripped ...]\n'); + + tt.same(strippedString, [ + 'TAP version 13', + '# promise', + '# sub test that should fail', + 'not ok 1 Error: rejection message', + ' ---', + ' operator: error', + ' stack: |-', + ' Error: rejection message', + ' at $TEST/promises/subTests.js:$LINE:$COL', + ' [... stack stripped ...]', + ' ...', + '# sub test that should pass', + 'ok 2 should be truthy', + '', + '1..2', + '# tests 2', + '# pass 1', + '# fail 1', + '', + '' + ].join('\n')); + })); +}); diff --git a/tests/node_modules/tape/test/promises/fail.js b/tests/node_modules/tape/test/promises/fail.js new file mode 100644 index 0000000..6ffb3f8 --- /dev/null +++ b/tests/node_modules/tape/test/promises/fail.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('../../'); + +if (typeof Promise === 'function' && typeof Promise.resolve === 'function') { + test('promise', function (t) { + return new Promise(function (resolve, reject) { + reject(new Error('rejection message')); + }); + }); + + test('after', function (t) { + t.plan(1); + t.ok(true); + }); +} else { + // if promises aren't supported pass the node-tap test + console.log('skip'); +} diff --git a/tests/node_modules/tape/test/promises/subTests.js b/tests/node_modules/tape/test/promises/subTests.js new file mode 100644 index 0000000..a4a6b12 --- /dev/null +++ b/tests/node_modules/tape/test/promises/subTests.js @@ -0,0 +1,20 @@ +'use strict'; + +var test = require('../../'); + +if (typeof Promise === 'function' && typeof Promise.resolve === 'function') { + test('promise', function (t) { + t.test('sub test that should fail', function (t) { + return new Promise(function (resolve, reject) { + reject(new Error('rejection message')); + }); + }); + t.test('sub test that should pass', function (t) { + t.plan(1); + t.ok(true); + }); + }); +} else { + // if promises aren't supported pass the node-tap test + console.log('skip'); +} diff --git a/tests/node_modules/tape/test/require.js b/tests/node_modules/tape/test/require.js new file mode 100644 index 0000000..d0c7c81 --- /dev/null +++ b/tests/node_modules/tape/test/require.js @@ -0,0 +1,71 @@ +'use strict'; + +var tap = require('tap'); +var spawn = require('child_process').spawn; +var concat = require('concat-stream'); + +tap.test('requiring a single module', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# module-a', + 'ok 1 loaded module a', + '# test-a', + 'ok 2 module-a loaded in same context', + 'ok 3 test ran after module-a was loaded', + '', + '1..3', + '# tests 3', + '# pass 3', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = tape('-r ./require/a require/test-a.js'); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +tap.test('requiring multiple modules', function (t) { + t.plan(2); + + var tc = function (rows) { + t.same(rows.toString('utf8'), [ + 'TAP version 13', + '# module-a', + 'ok 1 loaded module a', + '# module-b', + 'ok 2 loaded module b', + '# test-a', + 'ok 3 module-a loaded in same context', + 'ok 4 test ran after module-a was loaded', + '# test-b', + 'ok 5 module-b loaded in same context', + 'ok 6 test ran after module-b was loaded', + '', + '1..6', + '# tests 6', + '# pass 6', + '', + '# ok' + ].join('\n') + '\n\n'); + }; + + var ps = tape('-r ./require/a -r ./require/b require/test-a.js require/test-b.js'); + ps.stdout.pipe(concat(tc)); + ps.on('exit', function (code) { + t.equal(code, 0); + }); +}); + +function tape(args) { + var proc = require('child_process'); + var bin = __dirname + '/../bin/tape'; + + return proc.spawn('node', [bin].concat(args.split(' ')), { cwd: __dirname }); +} diff --git a/tests/node_modules/tape/test/require/a.js b/tests/node_modules/tape/test/require/a.js new file mode 100644 index 0000000..f4d8745 --- /dev/null +++ b/tests/node_modules/tape/test/require/a.js @@ -0,0 +1,10 @@ +'use strict'; + +var tape = require('../..'); + +tape.test('module-a', function (t) { + t.plan(1); + t.pass('loaded module a'); +}); + +global.module_a = true; diff --git a/tests/node_modules/tape/test/require/b.js b/tests/node_modules/tape/test/require/b.js new file mode 100644 index 0000000..f7fe3b1 --- /dev/null +++ b/tests/node_modules/tape/test/require/b.js @@ -0,0 +1,10 @@ +'use strict'; + +var tape = require('../..'); + +tape.test('module-b', function (t) { + t.plan(1); + t.pass('loaded module b'); +}); + +global.module_b = true; diff --git a/tests/node_modules/tape/test/require/test-a.js b/tests/node_modules/tape/test/require/test-a.js new file mode 100644 index 0000000..bcf15ca --- /dev/null +++ b/tests/node_modules/tape/test/require/test-a.js @@ -0,0 +1,9 @@ +'use strict'; + +var tape = require('../..'); + +tape.test('test-a', function (t) { + t.ok(global.module_a, 'module-a loaded in same context'); + t.pass('test ran after module-a was loaded'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/require/test-b.js b/tests/node_modules/tape/test/require/test-b.js new file mode 100644 index 0000000..6cd57bf --- /dev/null +++ b/tests/node_modules/tape/test/require/test-b.js @@ -0,0 +1,9 @@ +'use strict'; + +var tape = require('../..'); + +tape.test('test-b', function (t) { + t.ok(global.module_b, 'module-b loaded in same context'); + t.pass('test ran after module-b was loaded'); + t.end(); +}); diff --git a/tests/node_modules/tape/test/skip.js b/tests/node_modules/tape/test/skip.js new file mode 100644 index 0000000..6682f04 --- /dev/null +++ b/tests/node_modules/tape/test/skip.js @@ -0,0 +1,54 @@ +'use strict'; + +var test = require('../'); +var ran = 0; + +var concat = require('concat-stream'); +var tap = require('tap'); + +tap.test('test SKIP comment', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.equal(output.toString('utf8'), [ + 'TAP version 13', + '# SKIP skipped', + '', + '1..0', + '# tests 0', + '# pass 0', + '', + '# ok', + '' + ].join('\n')); + }; + + var tapeTest = test.createHarness(); + tapeTest.createStream().pipe(concat(verify)); + tapeTest('skipped', { skip: true }, function (t) { + t.end(); + }); +}); + +test('skip this', { skip: true }, function (t) { + t.fail('this should not even run'); + ran++; + t.end(); +}); + +test.skip('skip this too', function (t) { + t.fail('this should not even run'); + ran++; + t.end(); +}); + +test('skip subtest', function (t) { + ran++; + t.test('skip this', { skip: true }, function (t) { + t.fail('this should not even run'); + t.end(); + }); + t.end(); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape/test/skip_explanation.js b/tests/node_modules/tape/test/skip_explanation.js new file mode 100644 index 0000000..54c7688 --- /dev/null +++ b/tests/node_modules/tape/test/skip_explanation.js @@ -0,0 +1,84 @@ +'use strict'; + +var tap = require('tap'); +var test = require('../'); +var concat = require('concat-stream'); +var stripFullStack = require('./common').stripFullStack; + +tap.test('test skip explanations', function (assert) { + assert.plan(1); + + var verify = function (output) { + assert.deepEqual(stripFullStack(output.toString('utf8')), [ + 'TAP version 13', + '# SKIP (this skips)', + '# some tests might skip', + 'ok 1 this runs', + 'ok 2 failing assert is skipped # SKIP', + 'ok 3 this runs', + '# incomplete test', + 'ok 4 run sh', + 'ok 5 run openssl # SKIP', + '# incomplete test with explanation', + 'ok 6 run sh (conditional skip) # SKIP', + 'ok 7 run openssl # SKIP can\'t run on windows platforms', + 'ok 8 this runs', + '# too much explanation', + 'ok 9 run openssl # SKIP Installer cannot work on windows and fails to add to PATH Err: (2401) denied', + '', + '1..9', + '# tests 9', + '# pass 9', + '', + '# ok', + '' + ]); + }; + + var tapeTest = test.createHarness(); + tapeTest.createStream().pipe(concat(verify)); + + tapeTest('(this skips)', { skip: true }, function (t) { + t.fail('doesn\'t run'); + t.fail('this doesn\'t run too', { skip: false }); + t.end(); + }); + + tapeTest('some tests might skip', function (t) { + t.pass('this runs'); + t.fail('failing assert is skipped', { skip: true }); + t.pass('this runs'); + t.end(); + }); + + tapeTest('incomplete test', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.pass('run sh', { skip: platform !== 'win32' }); + t.pass('run openssl', { skip: platform === 'win32' }); + t.end(); + }); + + tapeTest('incomplete test with explanation', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.fail('run sh (conditional skip)', { skip: platform === 'win32' }); + t.fail('run openssl', { skip: platform === 'win32' && 'can\'t run on windows platforms' }); + t.pass('this runs'); + t.end(); + }); + + tapeTest('too much explanation', function (t) { + // var platform = process.platform; something like this needed + var platform = 'win32'; + + t.fail('run openssl', + { skip: platform === 'win32' && 'Installer cannot work on windows\nand fails to add to PATH\n\n Err: (2401) denied' } + ); + t.end(); + }); +}); + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/tests/node_modules/tape/test/stackTrace.js b/tests/node_modules/tape/test/stackTrace.js new file mode 100644 index 0000000..7906884 --- /dev/null +++ b/tests/node_modules/tape/test/stackTrace.js @@ -0,0 +1,307 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var tapParser = require('tap-parser'); +var yaml = require('js-yaml'); + +tap.test('preserves stack trace with newlines', function (tt) { + tt.plan(3); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + var stackTrace = 'foo\n bar'; + + parser.once('assert', function (data) { + delete data.diag.at; + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'Error: Preserve stack', + diag: { + stack: stackTrace, + operator: 'error' + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# multiline stack trace\n' + + 'not ok 1 Error: Preserve stack\n' + + ' ---\n' + + ' operator: error\n' + + ' stack: |-\n' + + ' foo\n' + + ' bar\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stackTrace, + operator: 'error' + }); + })); + + test('multiline stack trace', function (t) { + t.plan(1); + var err = new Error('Preserve stack'); + err.stack = stackTrace; + t.error(err); + }); +}); + +tap.test('parses function info from original stack', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('Test.testFunctionNameParsing', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + t.equal(true, false, 'true should be false'); + t.end(); + }); +}); + +tap.test('parses function info from original stack for anonymous function', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('Test.', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function (t) { + t.equal(true, false, 'true should be false'); + t.end(); + }); +}); + +if (typeof Promise === 'function' && typeof Promise.resolve === 'function') { + + tap.test('parses function info from original stack for Promise scenario', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('onfulfilled', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + new Promise(function (resolve) { + resolve(); + }).then(function onfulfilled() { + t.equal(true, false, 'true should be false'); + t.end(); + }); + }); + }); + + tap.test('parses function info from original stack for Promise scenario with anonymous function', function (tt) { + tt.plan(4); + + var test = tape.createHarness(); + test.createStream(); + + test._results._watch = function (t) { + t.on('result', function (res) { + tt.equal('', res.functionName); + tt.match(res.file, /stackTrace.js/i); + tt.ok(Number(res.line) > 0); + tt.ok(Number(res.column) > 0); + }); + }; + + test('t.equal stack trace', function testFunctionNameParsing(t) { + new Promise(function (resolve) { + resolve(); + }).then(function () { + t.equal(true, false, 'true should be false'); + t.end(); + }); + }); + }); + +} + +tap.test('preserves stack trace for failed assertions', function (tt) { + tt.plan(6); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + + var stack = ''; + parser.once('assert', function (data) { + tt.equal(typeof data.diag.at, 'string'); + tt.equal(typeof data.diag.stack, 'string'); + var at = data.diag.at || ''; + stack = data.diag.stack || ''; + tt.ok(/^Error: true should be false(\n at .+)+/.exec(stack), 'stack should be a stack'); + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'true should be false', + diag: { + at: at, + stack: stack, + operator: 'equal', + expected: false, + actual: true + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# t.equal stack trace\n' + + 'not ok 1 true should be false\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: false\n' + + ' actual: true\n' + + ' stack: |-\n' + + ' ' + + stack.replace(/\n/g, '\n ') + '\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stack, + operator: 'equal', + expected: false, + actual: true + }); + })); + + test('t.equal stack trace', function (t) { + t.plan(1); + t.equal(true, false, 'true should be false'); + }); +}); + +tap.test('preserves stack trace for failed assertions where actual===falsy', function (tt) { + tt.plan(6); + + var test = tape.createHarness(); + var stream = test.createStream(); + var parser = stream.pipe(tapParser()); + + var stack = ''; + parser.once('assert', function (data) { + tt.equal(typeof data.diag.at, 'string'); + tt.equal(typeof data.diag.stack, 'string'); + var at = data.diag.at || ''; + stack = data.diag.stack || ''; + tt.ok(/^Error: false should be true(\n at .+)+/.exec(stack), 'stack should be a stack'); + tt.deepEqual(data, { + ok: false, + id: 1, + name: 'false should be true', + diag: { + at: at, + stack: stack, + operator: 'equal', + expected: true, + actual: false + } + }); + }); + + stream.pipe(concat(function (body) { + var body = body.toString('utf8'); + body = stripAt(body); + tt.equal( + body, + 'TAP version 13\n' + + '# t.equal stack trace\n' + + 'not ok 1 false should be true\n' + + ' ---\n' + + ' operator: equal\n' + + ' expected: true\n' + + ' actual: false\n' + + ' stack: |-\n' + + ' ' + + stack.replace(/\n/g, '\n ') + '\n' + + ' ...\n' + + '\n' + + '1..1\n' + + '# tests 1\n' + + '# pass 0\n' + + '# fail 1\n' + ); + + tt.deepEqual(getDiag(body), { + stack: stack, + operator: 'equal', + expected: true, + actual: false + }); + })); + + test('t.equal stack trace', function (t) { + t.plan(1); + t.equal(false, true, 'false should be true'); + }); +}); + +function getDiag(body) { + var yamlStart = body.indexOf(' ---'); + var yamlEnd = body.indexOf(' ...\n'); + var diag = body.slice(yamlStart, yamlEnd).split('\n').map(function (line) { + return line.slice(2); + }).join('\n'); + + // Get rid of 'at' variable (which has a line number / path of its own that's + // difficult to check). + var withStack = yaml.safeLoad(diag); + delete withStack.at; + return withStack; +} + +function stripAt(body) { + return body.replace(/^\s*at:\s+Test.*$\n/m, ''); +} diff --git a/tests/node_modules/tape/test/subcount.js b/tests/node_modules/tape/test/subcount.js new file mode 100644 index 0000000..09cb135 --- /dev/null +++ b/tests/node_modules/tape/test/subcount.js @@ -0,0 +1,16 @@ +'use strict'; + +var test = require('../'); + +test('parent test', function (t) { + t.plan(2); + t.test('first child', function (t) { + t.plan(1); + t.pass('pass first child'); + }); + + t.test(function (t) { + t.plan(1); + t.pass('pass second child'); + }); +}); diff --git a/tests/node_modules/tape/test/subtest_and_async.js b/tests/node_modules/tape/test/subtest_and_async.js new file mode 100644 index 0000000..a5843e5 --- /dev/null +++ b/tests/node_modules/tape/test/subtest_and_async.js @@ -0,0 +1,27 @@ +'use strict'; + +var test = require('../'); + +var asyncFunction = function (callback) { + setTimeout(callback, Math.random * 50); +}; + +test('master test', function (t) { + t.test('subtest 1', function (st) { + st.pass('subtest 1 before async call'); + asyncFunction(function () { + st.pass('subtest 1 in async callback'); + st.end(); + }); + }); + + t.test('subtest 2', function (st) { + st.pass('subtest 2 before async call'); + asyncFunction(function () { + st.pass('subtest 2 in async callback'); + st.end(); + }); + }); + + t.end(); +}); diff --git a/tests/node_modules/tape/test/subtest_plan.js b/tests/node_modules/tape/test/subtest_plan.js new file mode 100644 index 0000000..9bab473 --- /dev/null +++ b/tests/node_modules/tape/test/subtest_plan.js @@ -0,0 +1,23 @@ +'use strict'; + +var test = require('../'); + +test('parent', function (t) { + t.plan(3); + + var firstChildRan = false; + + t.pass('assertion in parent'); + + t.test('first child', function (t) { + t.plan(1); + t.pass('pass first child'); + firstChildRan = true; + }); + + t.test('second child', function (t) { + t.plan(2); + t.ok(firstChildRan, 'first child ran first'); + t.pass('pass second child'); + }); +}); diff --git a/tests/node_modules/tape/test/teardown.js b/tests/node_modules/tape/test/teardown.js new file mode 100644 index 0000000..e5013cf --- /dev/null +++ b/tests/node_modules/tape/test/teardown.js @@ -0,0 +1,316 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var forEach = require('for-each'); +var v = require('es-value-fixtures'); +var inspect = require('object-inspect'); +var flatMap = require('array.prototype.flatmap'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('teardowns', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [].concat( + 'TAP version 13', + '# success', + 'ok 1 should be truthy', + '# success teardown', + '# success teardown 2', + '# success (async)', + 'ok 2 should be truthy', + '# success (async) teardown', + '# success (async) teardown 2', + '# nested teardowns', + '# nested success', + 'ok 3 should be truthy', + '# nested teardown (nested success level)', + '# nested teardown (nested success level) 2', + '# nested failure', + 'not ok 4 nested failure!', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/teardown.js:$LINE:$COL)', + ' stack: |-', + ' Error: nested failure!', + ' [... stack stripped ...]', + ' at Test. ($TEST/teardown.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# nested teardown (nested fail level)', + '# nested teardown (nested fail level) 2', + '# nested teardown (top level)', + '# nested teardown (top level) 2', + '# fail', + 'not ok 5 failure!', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/teardown.js:$LINE:$COL)', + ' stack: |-', + ' Error: failure!', + ' [... stack stripped ...]', + ' at Test. ($TEST/teardown.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# failure teardown', + '# failure teardown 2', + '# teardown errors do not stop the next teardown fn from running', + 'ok 6 should be truthy', + 'not ok 7 SyntaxError: teardown error!', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: SyntaxError: teardown error!', + ' [... stack stripped ...]', + ' ...', + 'not ok 8 plan != count', + ' ---', + ' operator: fail', + ' expected: 1', + ' actual: 2', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' ...', + '# teardown runs after teardown error', + '# teardown given non-function fails the test', + 'ok 9 should be truthy', + flatMap(v.nonFunctions, function (nonFunction, i) { + var offset = 10; + return [].concat( + 'not ok ' + (offset + (i > 0 ? i + 1 : i)) + ' teardown: ' + inspect(nonFunction) + ' is not a function', + ' ---', + ' operator: fail', + ' at: ($TEST/teardown.js:$LINE:$COL)', + ' stack: |-', + ' Error: teardown: ' + inspect(nonFunction) + ' is not a function', + ' [... stack stripped ...]', + ' at $TEST/teardown.js:$LINE:$COL', + ' [... stack stripped ...]', + ' at Test. ($TEST/teardown.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + i > 0 ? [] : [ + 'not ok '+ (offset + 1) +' plan != count', + ' ---', + ' operator: fail', + ' expected: 1', + ' actual: 2', + ' at: ($TEST/teardown.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' at $TEST/teardown.js:$LINE:$COL', + ' [... stack stripped ...]', + ' at Test. ($TEST/teardown.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...' + ] + ); + }), + typeof Promise === 'function' ? [ + '# teardown is only ever called once, even when async', + 'ok ' + (11 + v.nonFunctions.length) + ' passes', + '# teardown: once?', + '# success (promise)', + 'ok ' + (12 + v.nonFunctions.length) + ' should be truthy', + '# success (promise) teardown: 1', + '# success (promise) teardown: 2', + '# success (promise) teardown: 3' + ] : [ + '# SKIP teardown is only ever called once, even when async', + '# SKIP success (promise)' + ], [ + '', + '1..' + ((typeof Promise === 'function' ? 2 : 0) + 10 + v.nonFunctions.length), + '# tests ' + ((typeof Promise === 'function' ? 2 : 0) + 10 + v.nonFunctions.length), + '# pass ' + ((typeof Promise === 'function' ? 2 : 0) + 5), + '# fail ' + (5 + v.nonFunctions.length), + '' + ])); + })); + + test('success', function (t) { + t.plan(1); + t.teardown(function () { + t.comment('success teardown'); + }); + t.teardown(function () { + t.comment('success teardown 2'); + }); + t.ok('success!'); + }); + + test('success (async)', function (t) { + t.plan(1); + t.teardown(function () { + t.comment('success (async) teardown'); + }); + t.teardown(function () { + t.comment('success (async) teardown 2'); + }); + setTimeout(function () { + t.ok('success!'); + }, 10); + }); + + test('nested teardowns', function (t) { + t.plan(2); + + t.teardown(function () { + t.comment('nested teardown (top level)'); + }); + t.teardown(function () { + t.comment('nested teardown (top level) 2'); + }); + + t.test('nested success', function (st) { + st.teardown(function () { + st.comment('nested teardown (nested success level)'); + }); + st.teardown(function () { + st.comment('nested teardown (nested success level) 2'); + }); + + st.ok('nested success!'); + st.end(); + }); + + t.test('nested failure', function (st) { + st.plan(1); + + st.teardown(function () { + st.comment('nested teardown (nested fail level)'); + }); + st.teardown(function () { + st.comment('nested teardown (nested fail level) 2'); + }); + + st.fail('nested failure!'); + }); + }); + + test('fail', function (t) { + t.plan(1); + + t.teardown(function () { + t.comment('failure teardown'); + }); + t.teardown(function () { + t.comment('failure teardown 2'); + }); + + t.fail('failure!'); + }); + + test('teardown errors do not stop the next teardown fn from running', function (t) { + t.plan(1); + + t.ok('teardown error test'); + + t.teardown(function () { + throw new SyntaxError('teardown error!'); + }); + t.teardown(function () { + t.comment('teardown runs after teardown error'); + }); + }); + + test('teardown given non-function fails the test', function (t) { + t.plan(1); + + t.ok('non-function test'); + + forEach(v.nonFunctions, function (nonFunction) { + t.teardown(nonFunction); + }); + }); + + test('teardown is only ever called once, even when async', { skip: typeof Promise !== 'function' }, function (t) { + t.plan(1); + + t.teardown(function () { + t.comment('teardown: once?'); + }); + + t.pass('passes'); + + return Promise.resolve(); + }); + + test('success (promise)', { skip: typeof Promise !== 'function' }, function (t) { + t.plan(1); + + t.teardown(function () { + return new Promise(function (resolve) { + t.comment('success (promise) teardown: 1'); + setTimeout(resolve, 10); + }).then(function () { + t.comment('success (promise) teardown: 2'); + }); + }); + t.teardown(function () { + t.comment('success (promise) teardown: 3'); + }); + + setTimeout(function () { + t.ok('success!'); + }, 10); + }); +}); + +tap.test('teardown with promise', { skip: typeof Promise !== 'function', timeout: 1e3 }, function (tt) { + tt.plan(2); + tape('dummy test', function (t) { + var resolved = false; + t.teardown(function () { + tt.pass('tape teardown'); + var p = Promise.resolve(); + p.then(function () { + resolved = true; + }); + return p; + }); + t.on('end', function () { + tt.is(resolved, true); + }); + t.end(); + }); +}); + +tap.test('teardown only runs once', { skip: typeof Promise !== 'function', timeout: 1e3 }, function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [].concat( + 'TAP version 13', + '# teardown is only called once, even with a plan', + 'ok 1 passes', + '# Tearing down!', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok', + '' + )); + })); + + test('teardown is only called once, even with a plan', function (t) { + t.plan(1); + + t.teardown(function () { + t.comment('Tearing down!'); + }); + + t.pass('passes'); + + return Promise.resolve(); + }); +}); diff --git a/tests/node_modules/tape/test/throws.js b/tests/node_modules/tape/test/throws.js new file mode 100644 index 0000000..70d90ce --- /dev/null +++ b/tests/node_modules/tape/test/throws.js @@ -0,0 +1,315 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); +var inspect = require('object-inspect'); +var assign = require('object.assign'); + +var stripFullStack = require('./common').stripFullStack; + +function fn() { + throw new TypeError('RegExp'); +} + +function getNonFunctionMessage(fn) { + try { + fn(); + } catch (e) { + return e.message; + } +} + +var getter = function () { return 'message'; }; +var messageGetterError = Object.defineProperty( + { custom: 'error' }, + 'message', + { configurable: true, enumerable: true, get: getter } +); +var thrower = function () { throw messageGetterError; }; + +tap.test('failures', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# non functions', + 'ok 1 should throw', + 'ok 2 should throw', + 'ok 3 should throw', + 'ok 4 should throw', + 'ok 5 should throw', + 'ok 6 should throw', + 'ok 7 should throw', + 'ok 8 should throw', + '# function', + 'not ok 9 should throw', + ' ---', + ' operator: throws', + ' expected: undefined', + ' actual: undefined', + ' at: Test. ($TEST/throws.js:$LINE:$COL)', + ' stack: |-', + ' Error: should throw', + ' [... stack stripped ...]', + ' at Test. ($TEST/throws.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# custom error messages', + 'ok 10 "message" is enumerable', + "ok 11 { custom: 'error', message: 'message' }", + 'ok 12 getter is still the same', + '# throws null', + 'ok 13 throws null', + '# wrong type of error', + 'not ok 14 throws actual', + ' ---', + ' operator: throws', + ' expected: |-', + ' [Function: TypeError]', + ' actual: |-', + " { [RangeError: actual!] message: 'actual!' }", + ' at: Test. ($TEST/throws.js:$LINE:$COL)', + ' stack: |-', + ' RangeError: actual!', + ' at Test. ($TEST/throws.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '# object', + 'ok 15 object properties are validated', + '# object with regexes', + 'ok 16 object with regex values is validated', + '# similar error object', + 'ok 17 throwing a similar error', + '# validate with regex', + 'ok 18 regex against toString of error', + '# custom error validation', + 'ok 19 error is SyntaxError', + 'ok 20 error matches /value/', + 'ok 21 unexpected error', + '# throwing primitives', + 'ok 22 primitive: null', + 'ok 23 primitive: undefined', + 'ok 24 primitive: 0', + 'ok 25 primitive: NaN', + 'ok 26 primitive: 42', + 'ok 27 primitive: Infinity', + 'ok 28 primitive: \'\'', + 'ok 29 primitive: \'foo\'', + 'ok 30 primitive: true', + 'ok 31 primitive: false', + '# ambiguous arguments', + 'ok 32 Second', + 'ok 33 Second', + 'ok 34 Second', + 'ok 35 should throw', + 'not ok 36 should throw', + ' ---', + ' operator: throws', + ' expected: |-', + ' \'/Second$/\'', + ' actual: |-', + ' { [Error: First] message: \'First\' }', + ' at: Test. ($TEST/throws.js:$LINE:$COL)', + ' stack: |-', + ' Error: First', + ' at throwingFirst ($TEST/throws.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' at Test. ($TEST/throws.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..36', + '# tests 36', + '# pass 33', + '# fail 3', + '' + ]); + })); + + test('non functions', function (t) { + t.plan(8); + t.throws(); + t.throws(null); + t.throws(true); + t.throws(false); + t.throws('abc'); + t.throws(/a/g); + t.throws([]); + t.throws({}); + }); + + test('function', function (t) { + t.plan(1); + t.throws(function () {}); + }); + + test('custom error messages', function (t) { + t.plan(3); + t.equal(Object.prototype.propertyIsEnumerable.call(messageGetterError, 'message'), true, '"message" is enumerable'); + t.throws(thrower, "{ custom: 'error', message: 'message' }"); + t.equal(Object.getOwnPropertyDescriptor(messageGetterError, 'message').get, getter, 'getter is still the same'); + }); + + test('throws null', function (t) { + t.plan(1); + t.throws(function () { throw null; }, 'throws null'); + t.end(); + }); + + test('wrong type of error', function (t) { + t.plan(1); + var actual = new RangeError('actual!'); + t.throws(function () { throw actual; }, TypeError, 'throws actual'); + t.end(); + }); + + // taken from https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message + var err = new TypeError('Wrong value'); + err.code = 404; + err.foo = 'bar'; + err.info = { + nested: true, + baz: 'text' + }; + err.reg = /abc/i; + + test('object', function (t) { + t.plan(1); + + t.throws( + function () { throw err; }, + { + name: 'TypeError', + message: 'Wrong value', + info: { + nested: true, + baz: 'text' + } + // Only properties on the validation object will be tested for. + // Using nested objects requires all properties to be present. Otherwise + // the validation is going to fail. + }, + 'object properties are validated' + ); + + t.end(); + }); + + test('object with regexes', function (t) { + t.plan(1); + t.throws( + function () { throw err; }, + { + // The `name` and `message` properties are strings and using regular + // expressions on those will match against the string. If they fail, an + // error is thrown. + name: /^TypeError$/, + message: /Wrong/, + foo: 'bar', + info: { + nested: true, + // It is not possible to use regular expressions for nested properties! + baz: 'text' + }, + // The `reg` property contains a regular expression and only if the + // validation object contains an identical regular expression, it is going + // to pass. + reg: /abc/i + }, + 'object with regex values is validated' + ); + t.end(); + }); + + test('similar error object', function (t) { + t.plan(1); + t.throws( + function () { + var otherErr = new TypeError('Not found'); + // Copy all enumerable properties from `err` to `otherErr`. + assign(otherErr, err); + throw otherErr; + }, + // The error's `message` and `name` properties will also be checked when using + // an error as validation object. + err, + 'throwing a similar error' + ); + t.end(); + }); + + test('validate with regex', function (t) { + t.plan(1); + t.throws( + function () { throw new Error('Wrong value'); }, + /^Error: Wrong value$/, + 'regex against toString of error' + ); + t.end(); + }); + + test('custom error validation', function (t) { + t.plan(3); + t.throws( + function () { throw new SyntaxError('Wrong value'); }, + function (error) { + t.ok(error instanceof SyntaxError, 'error is SyntaxError'); + t.ok((/value/).test(error), 'error matches /value/'); + // Avoid returning anything from validation functions besides `true`. + // Otherwise, it's not clear what part of the validation failed. Instead, + // throw an error about the specific validation that failed (as done in this + // example) and add as much helpful debugging information to that error as + // possible. + return true; + }, + 'unexpected error' + ); + t.end(); + }); + + test('throwing primitives', function (t) { + [null, undefined, 0, NaN, 42, Infinity, '', 'foo', true, false].forEach(function (primitive) { + t.throws(function () { throw primitive; }, 'primitive: ' + inspect(primitive)); + }); + + t.end(); + }); + + test('ambiguous arguments', function (t) { + function throwingFirst() { + throw new Error('First'); + } + + function throwingSecond() { + throw new Error('Second'); + } + + function notThrowing() {} + + // The second argument is a string and the input function threw an Error. + // The first case will not throw as it does not match for the error message + // thrown by the input function! + t.throws(throwingFirst, 'Second'); + // In the next example the message has no benefit over the message from the + // error and since it is not clear if the user intended to actually match + // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + t.throws(throwingSecond, 'Second'); + // TypeError [ERR_AMBIGUOUS_ARGUMENT] + + // The string is only used (as message) in case the function does not throw: + t.doesNotThrow(notThrowing, 'Second'); + // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + + // If it was intended to match for the error message do this instead: + // It does not fail because the error messages match. + t.throws(throwingSecond, /Second$/); + + // If the error message does not match, an AssertionError is thrown. + t.throws(throwingFirst, /Second$/); + // AssertionError [ERR_ASSERTION] + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/timeout.js b/tests/node_modules/tape/test/timeout.js new file mode 100644 index 0000000..bf11242 --- /dev/null +++ b/tests/node_modules/tape/test/timeout.js @@ -0,0 +1,17 @@ +'use strict'; + +var test = require('../'); +var ran = 0; + +test('timeout', function (t) { + t.pass('this should run'); + ran++; + setTimeout(function () { + t.end(); + }, 100); +}); + +test('should still run', { timeout: 50 }, function (t) { + t.equal(ran, 1); + t.end(); +}); diff --git a/tests/node_modules/tape/test/timeoutAfter.js b/tests/node_modules/tape/test/timeoutAfter.js new file mode 100644 index 0000000..45f7709 --- /dev/null +++ b/tests/node_modules/tape/test/timeoutAfter.js @@ -0,0 +1,101 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('timeoutAfter test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# timeoutAfter', + 'not ok 1 timeoutAfter timed out after 1ms', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: timeoutAfter timed out after 1ms', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('timeoutAfter', function (t) { + t.plan(1); + t.timeoutAfter(1); + }); +}); + +tap.test('timeoutAfter with Promises', { skip: typeof Promise === 'undefined' }, function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# timeoutAfter with promises', + '# fulfilled promise', + 'not ok 1 fulfilled promise timed out after 1ms', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: fulfilled promise timed out after 1ms', + ' [... stack stripped ...]', + ' ...', + '# rejected promise', + 'not ok 2 rejected promise timed out after 1ms', + ' ---', + ' operator: fail', + ' stack: |-', + ' Error: rejected promise timed out after 1ms', + ' [... stack stripped ...]', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 0', + '# fail 2', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('timeoutAfter with promises', function (t) { + t.plan(2); + + t.test('fulfilled promise', function (st) { + st.plan(1); + st.timeoutAfter(1); + + return new Promise(function (resolve) { + setTimeout(function () { + resolve(); + }, 10); + }); + }); + + t.test('rejected promise', function (st) { + st.plan(1); + st.timeoutAfter(1); + + return new Promise(function (reject) { + setTimeout(function () { + reject(); + }, 10); + }); + }); + }); +}); diff --git a/tests/node_modules/tape/test/todo.js b/tests/node_modules/tape/test/todo.js new file mode 100644 index 0000000..f234b1c --- /dev/null +++ b/tests/node_modules/tape/test/todo.js @@ -0,0 +1,44 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# success', + 'ok 1 this test runs', + '# TODO failure', + 'not ok 2 should never happen # TODO', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/todo.js:$LINE:$COL)', + ' ...', + '', + '1..2', + '# tests 2', + '# pass 2', + '', + '# ok', + '' + ]); + })); + + test('success', function (t) { + t.equal(true, true, 'this test runs'); + t.end(); + }); + + test('failure', { todo: true }, function (t) { + t.fail('should never happen'); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/todo_explanation.js b/tests/node_modules/tape/test/todo_explanation.js new file mode 100644 index 0000000..d0a5711 --- /dev/null +++ b/tests/node_modules/tape/test/todo_explanation.js @@ -0,0 +1,72 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', { todo: process.versions.node.match(/0\.8\.\d+/) ? 'Fails on node 0.8': false }, function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.deepEqual( + stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# success', + 'ok 1 this test runs', + '# TODO incomplete test1', + 'not ok 2 check output # TODO', + ' ---', + ' operator: equal', + ' expected: false', + ' actual: true', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + 'not ok 3 check vars output # TODO name conflict', + ' ---', + ' operator: equal', + ' expected: 0', + ' actual: 1', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + '# incomplete test2', + 'not ok 4 run openssl # TODO installer needs fix', + ' ---', + ' operator: fail', + ' at: Test. ($TEST/todo_explanation.js:$LINE:$COL)', + ' ...', + '# TODO passing test', + '', + '1..4', + '# tests 4', + '# pass 4', + '', + '# ok', + '' + ] + ); + })); + + test('success', function (t) { + t.equal(true, true, 'this test runs'); + t.end(); + }); + + test('incomplete test1', { todo: true }, function (t) { + t.equal(true, false, 'check output'); + t.equal(1, 0, 'check vars output', { todo: 'name conflict' }); + t.end(); + }); + + test('incomplete test2', function (t) { + t.fail('run openssl', { todo: 'installer needs fix' }); + t.end(); + }); + + test('passing test', { todo: 'yet incomplete' }, function (t) { + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/todo_single.js b/tests/node_modules/tape/test/todo_single.js new file mode 100644 index 0000000..090fbe3 --- /dev/null +++ b/tests/node_modules/tape/test/todo_single.js @@ -0,0 +1,39 @@ +'use strict'; + +var tap = require('tap'); +var tape = require('../'); +var concat = require('concat-stream'); + +var common = require('./common'); +var stripFullStack = common.stripFullStack; + +tap.test('tape todo test', function (assert) { + var test = tape.createHarness({ exit: false }); + assert.plan(1); + + test.createStream().pipe(concat(function (body) { + assert.deepEqual(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# TODO failure', + 'not ok 1 should be strictly equal # TODO', + ' ---', + ' operator: equal', + ' expected: false', + ' actual: true', + ' at: Test. ($TEST/todo_single.js:$LINE:$COL)', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 1', + '', + '# ok', + '' + ]); + })); + + test('failure', { todo: true }, function (t) { + t.equal(true, false); + t.end(); + }); +}); diff --git a/tests/node_modules/tape/test/too_many.js b/tests/node_modules/tape/test/too_many.js new file mode 100644 index 0000000..530ceb2 --- /dev/null +++ b/tests/node_modules/tape/test/too_many.js @@ -0,0 +1,81 @@ +'use strict'; + +var falafel = require('falafel'); +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness({ exit: false }); + var tc = function (rows) { + tt.same(stripFullStack(rows.toString('utf8')), [ + 'TAP version 13', + '# array', + 'ok 1 should be deeply equivalent', + 'ok 2 should be deeply equivalent', + 'ok 3 should be deeply equivalent', + 'ok 4 should be deeply equivalent', + 'not ok 5 plan != count', + ' ---', + ' operator: fail', + ' expected: 3', + ' actual: 4', + ' at: ($TEST/too_many.js:$LINE:$COL)', + ' stack: |-', + ' Error: plan != count', + ' [... stack stripped ...]', + ' at $TEST/too_many.js:$LINE:$COL', + ' at eval (eval at ($TEST/too_many.js:$LINE:$COL))', + ' at eval (eval at ($TEST/too_many.js:$LINE:$COL))', + ' at Test. ($TEST/too_many.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + 'ok 6 should be deeply equivalent', + '', + '1..6', + '# tests 6', + '# pass 5', + '# fail 1', + '' + ]); + }; + + test.createStream().pipe(concat(tc)); + + test('array', function (t) { + t.plan(3); + + var src = '(' + function () { + var xs = [ 1, 2, [ 3, 4 ] ]; + var ys = [ 5, 6 ]; + g([ xs, ys ]); + } + ')()'; + + var output = falafel(src, function (node) { + if (node.type === 'ArrayExpression') { + node.update('fn(' + node.source() + ')'); + } + }); + + var arrays = [ + [ 3, 4 ], + [ 1, 2, [ 3, 4 ] ], + [ 5, 6 ], + [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ] + ]; + + Function(['fn','g'], output)( + function (xs) { + t.same(arrays.shift(), xs); + return xs; + }, + function (xs) { + t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); + } + ); + }); +}); diff --git a/tests/node_modules/tape/test/undef.js b/tests/node_modules/tape/test/undef.js new file mode 100644 index 0000000..204ac83 --- /dev/null +++ b/tests/node_modules/tape/test/undef.js @@ -0,0 +1,44 @@ +'use strict'; + +var tape = require('../'); +var tap = require('tap'); +var concat = require('concat-stream'); + +var stripFullStack = require('./common').stripFullStack; + +tap.test('array test', function (tt) { + tt.plan(1); + + var test = tape.createHarness(); + test.createStream().pipe(concat(function (body) { + tt.same(stripFullStack(body.toString('utf8')), [ + 'TAP version 13', + '# undef', + 'not ok 1 should be deeply equivalent', + ' ---', + ' operator: deepEqual', + ' expected: |-', + ' { beep: undefined }', + ' actual: |-', + ' {}', + ' at: Test. ($TEST/undef.js:$LINE:$COL)', + ' stack: |-', + ' Error: should be deeply equivalent', + ' [... stack stripped ...]', + ' at Test. ($TEST/undef.js:$LINE:$COL)', + ' [... stack stripped ...]', + ' ...', + '', + '1..1', + '# tests 1', + '# pass 0', + '# fail 1', + '' + ]); + })); + + test('undef', function (t) { + t.plan(1); + t.deepEqual({}, { beep: undefined }); + }); +}); diff --git a/tests/node_modules/through/.travis.yml b/tests/node_modules/through/.travis.yml new file mode 100644 index 0000000..c693a93 --- /dev/null +++ b/tests/node_modules/through/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - "0.10" diff --git a/tests/node_modules/through/LICENSE.APACHE2 b/tests/node_modules/through/LICENSE.APACHE2 new file mode 100644 index 0000000..6366c04 --- /dev/null +++ b/tests/node_modules/through/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/tests/node_modules/through/LICENSE.MIT b/tests/node_modules/through/LICENSE.MIT new file mode 100644 index 0000000..6eafbd7 --- /dev/null +++ b/tests/node_modules/through/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/through/index.js b/tests/node_modules/through/index.js new file mode 100644 index 0000000..ca5fc59 --- /dev/null +++ b/tests/node_modules/through/index.js @@ -0,0 +1,108 @@ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } + + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false + +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) + + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } + + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream +} + diff --git a/tests/node_modules/through/package.json b/tests/node_modules/through/package.json new file mode 100644 index 0000000..d7b335a --- /dev/null +++ b/tests/node_modules/through/package.json @@ -0,0 +1,69 @@ +{ + "_from": "through@^2.3.8", + "_id": "through@2.3.8", + "_inBundle": false, + "_integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "_location": "/through", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "through@^2.3.8", + "name": "through", + "escapedName": "through", + "rawSpec": "^2.3.8", + "saveSpec": null, + "fetchSpec": "^2.3.8" + }, + "_requiredBy": [ + "/resumer", + "/tape" + ], + "_resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "_shasum": "0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5", + "_spec": "through@^2.3.8", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tape", + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "bugs": { + "url": "https://github.com/dominictarr/through/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "simplified stream construction", + "devDependencies": { + "from": "~0.1.3", + "stream-spec": "~0.3.5", + "tape": "~2.3.2" + }, + "homepage": "https://github.com/dominictarr/through", + "keywords": [ + "stream", + "streams", + "user-streams", + "pipe" + ], + "license": "MIT", + "main": "index.js", + "name": "through", + "repository": { + "type": "git", + "url": "git+https://github.com/dominictarr/through.git" + }, + "scripts": { + "test": "set -e; for t in test/*.js; do node $t; done" + }, + "testling": { + "browsers": [ + "ie/8..latest", + "ff/15..latest", + "chrome/20..latest", + "safari/5.1..latest" + ], + "files": "test/*.js" + }, + "version": "2.3.8" +} diff --git a/tests/node_modules/through/readme.markdown b/tests/node_modules/through/readme.markdown new file mode 100644 index 0000000..cb34c81 --- /dev/null +++ b/tests/node_modules/through/readme.markdown @@ -0,0 +1,64 @@ +#through + +[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through) +[![testling badge](https://ci.testling.com/dominictarr/through.png)](https://ci.testling.com/dominictarr/through) + +Easy way to create a `Stream` that is both `readable` and `writable`. + +* Pass in optional `write` and `end` methods. +* `through` takes care of pause/resume logic if you use `this.queue(data)` instead of `this.emit('data', data)`. +* Use `this.pause()` and `this.resume()` to manage flow. +* Check `this.paused` to see current flow state. (`write` always returns `!this.paused`). + +This function is the basis for most of the synchronous streams in +[event-stream](http://github.com/dominictarr/event-stream). + +``` js +var through = require('through') + +through(function write(data) { + this.queue(data) //data *must* not be null + }, + function end () { //optional + this.queue(null) + }) +``` + +Or, can also be used _without_ buffering on pause, use `this.emit('data', data)`, +and this.emit('end') + +``` js +var through = require('through') + +through(function write(data) { + this.emit('data', data) + //this.pause() + }, + function end () { //optional + this.emit('end') + }) +``` + +## Extended Options + +You will probably not need these 99% of the time. + +### autoDestroy=false + +By default, `through` emits close when the writable +and readable side of the stream has ended. +If that is not desired, set `autoDestroy=false`. + +``` js +var through = require('through') + +//like this +var ts = through(write, end, {autoDestroy: false}) +//or like this +var ts = through(write, end) +ts.autoDestroy = false +``` + +## License + +MIT / Apache2 diff --git a/tests/node_modules/through/test/async.js b/tests/node_modules/through/test/async.js new file mode 100644 index 0000000..46bdbae --- /dev/null +++ b/tests/node_modules/through/test/async.js @@ -0,0 +1,28 @@ +var from = require('from') +var through = require('../') + +var tape = require('tape') + +tape('simple async example', function (t) { + + var n = 0, expected = [1,2,3,4,5], actual = [] + from(expected) + .pipe(through(function(data) { + this.pause() + n ++ + setTimeout(function(){ + console.log('pushing data', data) + this.push(data) + this.resume() + }.bind(this), 300) + })).pipe(through(function(data) { + console.log('pushing data second time', data); + this.push(data) + })).on('data', function (d) { + actual.push(d) + }).on('end', function() { + t.deepEqual(actual, expected) + t.end() + }) + +}) diff --git a/tests/node_modules/through/test/auto-destroy.js b/tests/node_modules/through/test/auto-destroy.js new file mode 100644 index 0000000..9a8fd00 --- /dev/null +++ b/tests/node_modules/through/test/auto-destroy.js @@ -0,0 +1,30 @@ +var test = require('tape') +var through = require('../') + +// must emit end before close. + +test('end before close', function (assert) { + var ts = through() + ts.autoDestroy = false + var ended = false, closed = false + + ts.on('end', function () { + assert.ok(!closed) + ended = true + }) + ts.on('close', function () { + assert.ok(ended) + closed = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + ts.end() + assert.ok(ended) + assert.notOk(closed) + ts.destroy() + assert.ok(closed) + assert.end() +}) + diff --git a/tests/node_modules/through/test/buffering.js b/tests/node_modules/through/test/buffering.js new file mode 100644 index 0000000..b0084bf --- /dev/null +++ b/tests/node_modules/through/test/buffering.js @@ -0,0 +1,71 @@ +var test = require('tape') +var through = require('../') + +// must emit end before close. + +test('buffering', function(assert) { + var ts = through(function (data) { + this.queue(data) + }, function () { + this.queue(null) + }) + + var ended = false, actual = [] + + ts.on('data', actual.push.bind(actual)) + ts.on('end', function () { + ended = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + assert.deepEqual(actual, [1, 2, 3]) + ts.pause() + ts.write(4) + ts.write(5) + ts.write(6) + assert.deepEqual(actual, [1, 2, 3]) + ts.resume() + assert.deepEqual(actual, [1, 2, 3, 4, 5, 6]) + ts.pause() + ts.end() + assert.ok(!ended) + ts.resume() + assert.ok(ended) + assert.end() +}) + +test('buffering has data in queue, when ends', function (assert) { + + /* + * If stream ends while paused with data in the queue, + * stream should still emit end after all data is written + * on resume. + */ + + var ts = through(function (data) { + this.queue(data) + }, function () { + this.queue(null) + }) + + var ended = false, actual = [] + + ts.on('data', actual.push.bind(actual)) + ts.on('end', function () { + ended = true + }) + + ts.pause() + ts.write(1) + ts.write(2) + ts.write(3) + ts.end() + assert.deepEqual(actual, [], 'no data written yet, still paused') + assert.ok(!ended, 'end not emitted yet, still paused') + ts.resume() + assert.deepEqual(actual, [1, 2, 3], 'resumed, all data should be delivered') + assert.ok(ended, 'end should be emitted once all data was delivered') + assert.end(); +}) diff --git a/tests/node_modules/through/test/end.js b/tests/node_modules/through/test/end.js new file mode 100644 index 0000000..fa113f5 --- /dev/null +++ b/tests/node_modules/through/test/end.js @@ -0,0 +1,45 @@ +var test = require('tape') +var through = require('../') + +// must emit end before close. + +test('end before close', function (assert) { + var ts = through() + var ended = false, closed = false + + ts.on('end', function () { + assert.ok(!closed) + ended = true + }) + ts.on('close', function () { + assert.ok(ended) + closed = true + }) + + ts.write(1) + ts.write(2) + ts.write(3) + ts.end() + assert.ok(ended) + assert.ok(closed) + assert.end() +}) + +test('end only once', function (t) { + + var ts = through() + var ended = false, closed = false + + ts.on('end', function () { + t.equal(ended, false) + ended = true + }) + + ts.queue(null) + ts.queue(null) + ts.queue(null) + + ts.resume() + + t.end() +}) diff --git a/tests/node_modules/through/test/index.js b/tests/node_modules/through/test/index.js new file mode 100644 index 0000000..96da82f --- /dev/null +++ b/tests/node_modules/through/test/index.js @@ -0,0 +1,133 @@ + +var test = require('tape') +var spec = require('stream-spec') +var through = require('../') + +/* + I'm using these two functions, and not streams and pipe + so there is less to break. if this test fails it must be + the implementation of _through_ +*/ + +function write(array, stream) { + array = array.slice() + function next() { + while(array.length) + if(stream.write(array.shift()) === false) + return stream.once('drain', next) + + stream.end() + } + + next() +} + +function read(stream, callback) { + var actual = [] + stream.on('data', function (data) { + actual.push(data) + }) + stream.once('end', function () { + callback(null, actual) + }) + stream.once('error', function (err) { + callback(err) + }) +} + +test('simple defaults', function(assert) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through() + var s = spec(t).through().pausable() + + read(t, function (err, actual) { + assert.ifError(err) + assert.deepEqual(actual, expected) + assert.end() + }) + + t.on('close', s.validate) + + write(expected, t) +}); + +test('simple functions', function(assert) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l * Math.random()) + + var t = through(function (data) { + this.emit('data', data*2) + }) + var s = spec(t).through().pausable() + + + read(t, function (err, actual) { + assert.ifError(err) + assert.deepEqual(actual, expected.map(function (data) { + return data*2 + })) + assert.end() + }) + + t.on('close', s.validate) + + write(expected, t) +}) + +test('pauses', function(assert) { + + var l = 1000 + , expected = [] + + while(l--) expected.push(l) //Math.random()) + + var t = through() + + var s = spec(t) + .through() + .pausable() + + t.on('data', function () { + if(Math.random() > 0.1) return + t.pause() + process.nextTick(function () { + t.resume() + }) + }) + + read(t, function (err, actual) { + assert.ifError(err) + assert.deepEqual(actual, expected) + }) + + t.on('close', function () { + s.validate() + assert.end() + }) + + write(expected, t) +}) + +test('does not soft-end on `undefined`', function(assert) { + var stream = through() + , count = 0 + + stream.on('data', function (data) { + count++ + }) + + stream.write(undefined) + stream.write(undefined) + + assert.equal(count, 2) + + assert.end() +}) diff --git a/tests/node_modules/through2/LICENSE.md b/tests/node_modules/through2/LICENSE.md new file mode 100644 index 0000000..a2429b6 --- /dev/null +++ b/tests/node_modules/through2/LICENSE.md @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +**Copyright (c) Rod Vagg (the "Original Author") and additional contributors** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/through2/README.md b/tests/node_modules/through2/README.md new file mode 100644 index 0000000..b5e44c7 --- /dev/null +++ b/tests/node_modules/through2/README.md @@ -0,0 +1,134 @@ +# through2 + +[![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/) + +**A tiny wrapper around Node streams.Transform (Streams2/3) to avoid explicit subclassing noise** + +Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`. + +Note: As 2.x.x this module starts using **Streams3** instead of Stream2. To continue using a Streams2 version use `npm install through2@0` to fetch the latest version of 0.x.x. More information about Streams2 vs Streams3 and recommendations see the article **[Why I don't use Node's core 'stream' module](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html)**. + +```js +fs.createReadStream('ex.txt') + .pipe(through2(function (chunk, enc, callback) { + for (var i = 0; i < chunk.length; i++) + if (chunk[i] == 97) + chunk[i] = 122 // swap 'a' for 'z' + + this.push(chunk) + + callback() + })) + .pipe(fs.createWriteStream('out.txt')) + .on('finish', () => doSomethingSpecial()) +``` + +Or object streams: + +```js +var all = [] + +fs.createReadStream('data.csv') + .pipe(csv2()) + .pipe(through2.obj(function (chunk, enc, callback) { + var data = { + name : chunk[0] + , address : chunk[3] + , phone : chunk[10] + } + this.push(data) + + callback() + })) + .on('data', (data) => { + all.push(data) + }) + .on('end', () => { + doSomethingSpecial(all) + }) +``` + +Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`. + +## API + +through2([ options, ] [ transformFunction ] [, flushFunction ]) + +Consult the **[stream.Transform](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`). + +### options + +The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`). + +The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call: + +```js +fs.createReadStream('/tmp/important.dat') + .pipe(through2({ objectMode: true, allowHalfOpen: false }, + (chunk, enc, cb) => { + cb(null, 'wut?') // note we can use the second argument on the callback + // to provide data as an alternative to this.push('wut?') + } + ) + .pipe(fs.createWriteStream('/tmp/wut.txt')) +``` + +### transformFunction + +The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk. + +To queue a new chunk, call `this.push(chunk)`—this can be called as many times as required before the `callback()` if you have multiple pieces to send on. + +Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error. + +If you **do not provide a `transformFunction`** then you will get a simple pass-through stream. + +### flushFunction + +The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress. + +```js +fs.createReadStream('/tmp/important.dat') + .pipe(through2( + (chunk, enc, cb) => cb(null, chunk), // transform is a noop + function (cb) { // flush function + this.push('tacking on an extra buffer to the end'); + cb(); + } + )) + .pipe(fs.createWriteStream('/tmp/wut.txt')); +``` + +through2.ctor([ options, ] transformFunction[, flushFunction ]) + +Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances. + +```js +var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) { + if (record.temp != null && record.unit == "F") { + record.temp = ( ( record.temp - 32 ) * 5 ) / 9 + record.unit = "C" + } + this.push(record) + callback() +}) + +// Create instances of FToC like so: +var converter = new FToC() +// Or: +var converter = FToC() +// Or specify/override options when you instantiate, if you prefer: +var converter = FToC({objectMode: true}) +``` + +## See Also + + - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams. + - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams. + - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams. + - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies. + - the [mississippi stream utility collection](https://github.com/maxogden/mississippi) includes `through2` as well as many more useful stream modules similar to this one + +## License + +**through2** is Copyright (c) Rod Vagg [@rvagg](https://twitter.com/rvagg) and additional contributors and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/tests/node_modules/through2/node_modules/isarray/.npmignore b/tests/node_modules/through2/node_modules/isarray/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/tests/node_modules/through2/node_modules/isarray/.travis.yml b/tests/node_modules/through2/node_modules/isarray/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/tests/node_modules/through2/node_modules/isarray/Makefile b/tests/node_modules/through2/node_modules/isarray/Makefile new file mode 100644 index 0000000..787d56e --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/tests/node_modules/through2/node_modules/isarray/README.md b/tests/node_modules/through2/node_modules/isarray/README.md new file mode 100644 index 0000000..16d2c59 --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/through2/node_modules/isarray/component.json b/tests/node_modules/through2/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/tests/node_modules/through2/node_modules/isarray/index.js b/tests/node_modules/through2/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/tests/node_modules/through2/node_modules/isarray/package.json b/tests/node_modules/through2/node_modules/isarray/package.json new file mode 100644 index 0000000..92053ef --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/package.json @@ -0,0 +1,73 @@ +{ + "_from": "isarray@~1.0.0", + "_id": "isarray@1.0.0", + "_inBundle": false, + "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "_location": "/through2/isarray", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "isarray@~1.0.0", + "name": "isarray", + "escapedName": "isarray", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/through2/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11", + "_spec": "isarray@~1.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/through2/node_modules/readable-stream", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Array#isArray for older browsers", + "devDependencies": { + "tape": "~2.13.4" + }, + "homepage": "https://github.com/juliangruber/isarray", + "keywords": [ + "browser", + "isarray", + "array" + ], + "license": "MIT", + "main": "index.js", + "name": "isarray", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "scripts": { + "test": "tape test.js" + }, + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.0" +} diff --git a/tests/node_modules/through2/node_modules/isarray/test.js b/tests/node_modules/through2/node_modules/isarray/test.js new file mode 100644 index 0000000..e0c3444 --- /dev/null +++ b/tests/node_modules/through2/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/tests/node_modules/through2/node_modules/process-nextick-args/index.js b/tests/node_modules/through2/node_modules/process-nextick-args/index.js new file mode 100644 index 0000000..3eecf11 --- /dev/null +++ b/tests/node_modules/through2/node_modules/process-nextick-args/index.js @@ -0,0 +1,45 @@ +'use strict'; + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + diff --git a/tests/node_modules/through2/node_modules/process-nextick-args/license.md b/tests/node_modules/through2/node_modules/process-nextick-args/license.md new file mode 100644 index 0000000..c67e353 --- /dev/null +++ b/tests/node_modules/through2/node_modules/process-nextick-args/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2015 Calvin Metcalf + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.** diff --git a/tests/node_modules/through2/node_modules/process-nextick-args/package.json b/tests/node_modules/through2/node_modules/process-nextick-args/package.json new file mode 100644 index 0000000..a53f8b0 --- /dev/null +++ b/tests/node_modules/through2/node_modules/process-nextick-args/package.json @@ -0,0 +1,50 @@ +{ + "_from": "process-nextick-args@~2.0.0", + "_id": "process-nextick-args@2.0.1", + "_inBundle": false, + "_integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "_location": "/through2/process-nextick-args", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "process-nextick-args@~2.0.0", + "name": "process-nextick-args", + "escapedName": "process-nextick-args", + "rawSpec": "~2.0.0", + "saveSpec": null, + "fetchSpec": "~2.0.0" + }, + "_requiredBy": [ + "/through2/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "_shasum": "7820d9b16120cc55ca9ae7792680ae7dba6d7fe2", + "_spec": "process-nextick-args@~2.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/through2/node_modules/readable-stream", + "author": "", + "bugs": { + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "process.nextTick but always with args", + "devDependencies": { + "tap": "~0.2.6" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/calvinmetcalf/process-nextick-args", + "license": "MIT", + "main": "index.js", + "name": "process-nextick-args", + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git" + }, + "scripts": { + "test": "node test.js" + }, + "version": "2.0.1" +} diff --git a/tests/node_modules/through2/node_modules/process-nextick-args/readme.md b/tests/node_modules/through2/node_modules/process-nextick-args/readme.md new file mode 100644 index 0000000..ecb432c --- /dev/null +++ b/tests/node_modules/through2/node_modules/process-nextick-args/readme.md @@ -0,0 +1,18 @@ +process-nextick-args +===== + +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args) + +```bash +npm install --save process-nextick-args +``` + +Always be able to pass arguments to process.nextTick, no matter the platform + +```js +var pna = require('process-nextick-args'); + +pna.nextTick(function (a, b, c) { + console.log(a, b, c); +}, 'step', 3, 'profit'); +``` diff --git a/tests/node_modules/through2/node_modules/readable-stream/.travis.yml b/tests/node_modules/through2/node_modules/readable-stream/.travis.yml new file mode 100644 index 0000000..f62cdac --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/.travis.yml @@ -0,0 +1,34 @@ +sudo: false +language: node_js +before_install: + - (test $NPM_LEGACY && npm install -g npm@2 && npm install -g npm@3) || true +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: NPM_LEGACY=true + - node_js: '0.10' + env: NPM_LEGACY=true + - node_js: '0.11' + env: NPM_LEGACY=true + - node_js: '0.12' + env: NPM_LEGACY=true + - node_js: 1 + env: NPM_LEGACY=true + - node_js: 2 + env: NPM_LEGACY=true + - node_js: 3 + env: NPM_LEGACY=true + - node_js: 4 + - node_js: 5 + - node_js: 6 + - node_js: 7 + - node_js: 8 + - node_js: 9 +script: "npm run test" +env: + global: + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/tests/node_modules/through2/node_modules/readable-stream/CONTRIBUTING.md b/tests/node_modules/through2/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/tests/node_modules/through2/node_modules/readable-stream/GOVERNANCE.md b/tests/node_modules/through2/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/tests/node_modules/through2/node_modules/readable-stream/LICENSE b/tests/node_modules/through2/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/tests/node_modules/through2/node_modules/readable-stream/README.md b/tests/node_modules/through2/node_modules/readable-stream/README.md new file mode 100644 index 0000000..23fe3f3 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/README.md @@ -0,0 +1,58 @@ +# readable-stream + +***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) + +```bash +npm install --save readable-stream +``` + +***Node-core streams for userland*** + +This package is a mirror of the Streams2 and Streams3 implementations in +Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com> + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com> +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> diff --git a/tests/node_modules/through2/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/tests/node_modules/through2/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md new file mode 100644 index 0000000..83275f1 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md @@ -0,0 +1,60 @@ +# streams WG Meeting 2015-01-30 + +## Links + +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/ + +## Agenda + +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting. + +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105) +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101) +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102) +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99) + +## Minutes + +### adopt a charter + +* group: +1's all around + +### What versioning scheme should be adopted? +* group: +1’s 3.0.0 +* domenic+group: pulling in patches from other sources where appropriate +* mikeal: version independently, suggesting versions for io.js +* mikeal+domenic: work with TC to notify in advance of changes +simpler stream creation + +### streamline creation of streams +* sam: streamline creation of streams +* domenic: nice simple solution posted + but, we lose the opportunity to change the model + may not be backwards incompatible (double check keys) + + **action item:** domenic will check + +### remove implicit flowing of streams on(‘data’) +* add isFlowing / isPaused +* mikeal: worrying that we’re documenting polyfill methods – confuses users +* domenic: more reflective API is probably good, with warning labels for users +* new section for mad scientists (reflective stream access) +* calvin: name the “third state” +* mikeal: maybe borrow the name from whatwg? +* domenic: we’re missing the “third state” +* consensus: kind of difficult to name the third state +* mikeal: figure out differences in states / compat +* mathias: always flow on data – eliminates third state + * explore what it breaks + +**action items:** +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream) +* ask rod/build for infrastructure +* **chris**: explore the “flow on data” approach +* add isPaused/isFlowing +* add new docs section +* move isPaused to that section + + diff --git a/tests/node_modules/through2/node_modules/readable-stream/duplex-browser.js b/tests/node_modules/through2/node_modules/readable-stream/duplex-browser.js new file mode 100644 index 0000000..f8b2db8 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/duplex-browser.js @@ -0,0 +1 @@ +module.exports = require('./lib/_stream_duplex.js'); diff --git a/tests/node_modules/through2/node_modules/readable-stream/duplex.js b/tests/node_modules/through2/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..46924cb --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require('./readable').Duplex diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_duplex.js b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..57003c3 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_passthrough.js b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..612edb4 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..0f80764 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1019 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..fcfc105 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,214 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..b0b0220 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,687 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(require('core-util-is')); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/BufferList.js b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/BufferList.js new file mode 100644 index 0000000..aefc68b --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/BufferList.js @@ -0,0 +1,79 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/destroy.js b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..5a0a0d8 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,74 @@ +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream.js b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/tests/node_modules/through2/node_modules/readable-stream/package.json b/tests/node_modules/through2/node_modules/readable-stream/package.json new file mode 100644 index 0000000..5410aa6 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/package.json @@ -0,0 +1,81 @@ +{ + "_from": "readable-stream@~2.3.6", + "_id": "readable-stream@2.3.7", + "_inBundle": false, + "_integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "_location": "/through2/readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "readable-stream@~2.3.6", + "name": "readable-stream", + "escapedName": "readable-stream", + "rawSpec": "~2.3.6", + "saveSpec": null, + "fetchSpec": "~2.3.6" + }, + "_requiredBy": [ + "/through2" + ], + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "_shasum": "1eca1cf711aef814c04f62252a36a62f6cb23b57", + "_spec": "readable-stream@~2.3.6", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/through2", + "browser": { + "util": false, + "./readable.js": "./readable-browser.js", + "./writable.js": "./writable-browser.js", + "./duplex.js": "./duplex-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + }, + "deprecated": false, + "description": "Streams3, a user-land copy of the stream library from Node.js", + "devDependencies": { + "assert": "^1.4.0", + "babel-polyfill": "^6.9.1", + "buffer": "^4.9.0", + "lolex": "^2.3.2", + "nyc": "^6.4.0", + "tap": "^0.7.0", + "tape": "^4.8.0" + }, + "homepage": "https://github.com/nodejs/readable-stream#readme", + "keywords": [ + "readable", + "stream", + "pipe" + ], + "license": "MIT", + "main": "readable.js", + "name": "readable-stream", + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream.git" + }, + "scripts": { + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js" + }, + "version": "2.3.7" +} diff --git a/tests/node_modules/through2/node_modules/readable-stream/passthrough.js b/tests/node_modules/through2/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..ffd791d --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require('./readable').PassThrough diff --git a/tests/node_modules/through2/node_modules/readable-stream/readable-browser.js b/tests/node_modules/through2/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..e503725 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,7 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/tests/node_modules/through2/node_modules/readable-stream/readable.js b/tests/node_modules/through2/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..ec89ec5 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/readable.js @@ -0,0 +1,19 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); +} diff --git a/tests/node_modules/through2/node_modules/readable-stream/transform.js b/tests/node_modules/through2/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..b1baba2 --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require('./readable').Transform diff --git a/tests/node_modules/through2/node_modules/readable-stream/writable-browser.js b/tests/node_modules/through2/node_modules/readable-stream/writable-browser.js new file mode 100644 index 0000000..ebdde6a --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/writable-browser.js @@ -0,0 +1 @@ +module.exports = require('./lib/_stream_writable.js'); diff --git a/tests/node_modules/through2/node_modules/readable-stream/writable.js b/tests/node_modules/through2/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..3211a6f --- /dev/null +++ b/tests/node_modules/through2/node_modules/readable-stream/writable.js @@ -0,0 +1,8 @@ +var Stream = require("stream") +var Writable = require("./lib/_stream_writable.js") + +if (process.env.READABLE_STREAM === 'disable') { + module.exports = Stream && Stream.Writable || Writable +} else { + module.exports = Writable +} diff --git a/tests/node_modules/through2/node_modules/string_decoder/.travis.yml b/tests/node_modules/through2/node_modules/string_decoder/.travis.yml new file mode 100644 index 0000000..3347a72 --- /dev/null +++ b/tests/node_modules/through2/node_modules/string_decoder/.travis.yml @@ -0,0 +1,50 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.10' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.11' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.12' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 1 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 2 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 3 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 6 + env: TASK=test + - node_js: 7 + env: TASK=test + - node_js: 8 + env: TASK=test + - node_js: 9 + env: TASK=test diff --git a/tests/node_modules/through2/node_modules/string_decoder/LICENSE b/tests/node_modules/through2/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/tests/node_modules/through2/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/tests/node_modules/through2/node_modules/string_decoder/README.md b/tests/node_modules/through2/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/tests/node_modules/through2/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/tests/node_modules/through2/node_modules/string_decoder/lib/string_decoder.js b/tests/node_modules/through2/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/tests/node_modules/through2/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/tests/node_modules/through2/node_modules/string_decoder/package.json b/tests/node_modules/through2/node_modules/string_decoder/package.json new file mode 100644 index 0000000..7d286d8 --- /dev/null +++ b/tests/node_modules/through2/node_modules/string_decoder/package.json @@ -0,0 +1,59 @@ +{ + "_from": "string_decoder@~1.1.1", + "_id": "string_decoder@1.1.1", + "_inBundle": false, + "_integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "_location": "/through2/string_decoder", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string_decoder@~1.1.1", + "name": "string_decoder", + "escapedName": "string_decoder", + "rawSpec": "~1.1.1", + "saveSpec": null, + "fetchSpec": "~1.1.1" + }, + "_requiredBy": [ + "/through2/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "_shasum": "9cf1611ba62685d7030ae9e4ba34149c3af03fc8", + "_spec": "string_decoder@~1.1.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/through2/node_modules/readable-stream", + "bugs": { + "url": "https://github.com/nodejs/string_decoder/issues" + }, + "bundleDependencies": false, + "dependencies": { + "safe-buffer": "~5.1.0" + }, + "deprecated": false, + "description": "The string_decoder module from Node core", + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "main": "lib/string_decoder.js", + "name": "string_decoder", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "scripts": { + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", + "test": "tap test/parallel/*.js && node test/verify-dependencies" + }, + "version": "1.1.1" +} diff --git a/tests/node_modules/through2/package.json b/tests/node_modules/through2/package.json new file mode 100644 index 0000000..781efcd --- /dev/null +++ b/tests/node_modules/through2/package.json @@ -0,0 +1,71 @@ +{ + "_from": "through2@^2.0.0", + "_id": "through2@2.0.5", + "_inBundle": false, + "_integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "_location": "/through2", + "_phantomChildren": { + "core-util-is": "1.0.2", + "inherits": "2.0.4", + "safe-buffer": "5.1.2", + "util-deprecate": "1.0.2" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "through2@^2.0.0", + "name": "through2", + "escapedName": "through2", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/tap-spec" + ], + "_resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "_shasum": "01c1e39eb31d07cb7d03a96a70823260b23132cd", + "_spec": "through2@^2.0.0", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tap-spec", + "author": { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + "bugs": { + "url": "https://github.com/rvagg/through2/issues" + }, + "bundleDependencies": false, + "dependencies": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + }, + "deprecated": false, + "description": "A tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise", + "devDependencies": { + "bl": "~2.0.1", + "faucet": "0.0.1", + "nyc": "~13.1.0", + "safe-buffer": "~5.1.2", + "stream-spigot": "~3.0.6", + "tape": "~4.9.1" + }, + "homepage": "https://github.com/rvagg/through2#readme", + "keywords": [ + "stream", + "streams2", + "through", + "transform" + ], + "license": "MIT", + "main": "through2.js", + "name": "through2", + "repository": { + "type": "git", + "url": "git+https://github.com/rvagg/through2.git" + }, + "scripts": { + "test": "node test/test.js | faucet" + }, + "version": "2.0.5" +} diff --git a/tests/node_modules/through2/through2.js b/tests/node_modules/through2/through2.js new file mode 100644 index 0000000..6baa6a1 --- /dev/null +++ b/tests/node_modules/through2/through2.js @@ -0,0 +1,96 @@ +var Transform = require('readable-stream').Transform + , inherits = require('util').inherits + , xtend = require('xtend') + +function DestroyableTransform(opts) { + Transform.call(this, opts) + this._destroyed = false +} + +inherits(DestroyableTransform, Transform) + +DestroyableTransform.prototype.destroy = function(err) { + if (this._destroyed) return + this._destroyed = true + + var self = this + process.nextTick(function() { + if (err) + self.emit('error', err) + self.emit('close') + }) +} + +// a noop _transform function +function noop (chunk, enc, callback) { + callback(null, chunk) +} + + +// create a new export function, used by both the main export and +// the .ctor export, contains common logic for dealing with arguments +function through2 (construct) { + return function (options, transform, flush) { + if (typeof options == 'function') { + flush = transform + transform = options + options = {} + } + + if (typeof transform != 'function') + transform = noop + + if (typeof flush != 'function') + flush = null + + return construct(options, transform, flush) + } +} + + +// main export, just make me a transform stream! +module.exports = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(options) + + t2._transform = transform + + if (flush) + t2._flush = flush + + return t2 +}) + + +// make me a reusable prototype that I can `new`, or implicitly `new` +// with a constructor call +module.exports.ctor = through2(function (options, transform, flush) { + function Through2 (override) { + if (!(this instanceof Through2)) + return new Through2(override) + + this.options = xtend(options, override) + + DestroyableTransform.call(this, this.options) + } + + inherits(Through2, DestroyableTransform) + + Through2.prototype._transform = transform + + if (flush) + Through2.prototype._flush = flush + + return Through2 +}) + + +module.exports.obj = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) + + t2._transform = transform + + if (flush) + t2._flush = flush + + return t2 +}) diff --git a/tests/node_modules/to-regex-range/LICENSE b/tests/node_modules/to-regex-range/LICENSE new file mode 100644 index 0000000..7cccaf9 --- /dev/null +++ b/tests/node_modules/to-regex-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/to-regex-range/README.md b/tests/node_modules/to-regex-range/README.md new file mode 100644 index 0000000..38887da --- /dev/null +++ b/tests/node_modules/to-regex-range/README.md @@ -0,0 +1,305 @@ +# to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) + +> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save to-regex-range +``` + +
+What does this do? + +
+ +This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. + +**Example** + +```js +const toRegexRange = require('to-regex-range'); +const regex = new RegExp(toRegexRange('15', '95')); +``` + +A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). + +
+ +
+ +
+Why use this library? + +
+ +### Convenience + +Creating regular expressions for matching numbers gets deceptively complicated pretty fast. + +For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: + +* regex for matching `1` => `/1/` (easy enough) +* regex for matching `1` through `5` => `/[1-5]/` (not bad...) +* regex for matching `1` or `5` => `/(1|5)/` (still easy...) +* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) +* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) +* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) +* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) + +The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. + +**Learn more** + +If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. + +### Heavily tested + +As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. + +Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. + +### Optimized + +Generated regular expressions are optimized: + +* duplicate sequences and character classes are reduced using quantifiers +* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative +* uses fragment caching to avoid processing the same exact string more than once + +
+ +
+ +## Usage + +Add this library to your javascript application with the following line of code + +```js +const toRegexRange = require('to-regex-range'); +``` + +The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). + +```js +const source = toRegexRange('15', '95'); +//=> 1[5-9]|[2-8][0-9]|9[0-5] + +const regex = new RegExp(`^${source}$`); +console.log(regex.test('14')); //=> false +console.log(regex.test('50')); //=> true +console.log(regex.test('94')); //=> true +console.log(regex.test('96')); //=> false +``` + +## Options + +### options.capture + +**Type**: `boolean` + +**Deafault**: `undefined` + +Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. + +```js +console.log(toRegexRange('-10', '10')); +//=> -[1-9]|-?10|[0-9] + +console.log(toRegexRange('-10', '10', { capture: true })); +//=> (-[1-9]|-?10|[0-9]) +``` + +### options.shorthand + +**Type**: `boolean` + +**Deafault**: `undefined` + +Use the regex shorthand for `[0-9]`: + +```js +console.log(toRegexRange('0', '999999')); +//=> [0-9]|[1-9][0-9]{1,5} + +console.log(toRegexRange('0', '999999', { shorthand: true })); +//=> \d|[1-9]\d{1,5} +``` + +### options.relaxZeros + +**Type**: `boolean` + +**Default**: `true` + +This option relaxes matching for leading zeros when when ranges are zero-padded. + +```js +const source = toRegexRange('-0010', '0010'); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> true +console.log(regex.test('-010')); //=> true +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> true +console.log(regex.test('010')); //=> true +console.log(regex.test('0010')); //=> true +``` + +When `relaxZeros` is false, matching is strict: + +```js +const source = toRegexRange('-0010', '0010', { relaxZeros: false }); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> false +console.log(regex.test('-010')); //=> false +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> false +console.log(regex.test('010')); //=> false +console.log(regex.test('0010')); //=> true +``` + +## Examples + +| **Range** | **Result** | **Compile time** | +| --- | --- | --- | +| `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | +| `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | +| `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | +| `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | +| `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | +| `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | +| `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | +| `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | +| `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | +| `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | +| `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | +| `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | +| `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | +| `toRegexRange(5, 5)` | `5` | _8μs_ | +| `toRegexRange(5, 6)` | `5\|6` | _11μs_ | +| `toRegexRange(1, 2)` | `1\|2` | _6μs_ | +| `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | +| `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | +| `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | +| `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | +| `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | +| `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | +| `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | +| `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | + +## Heads up! + +**Order of arguments** + +When the `min` is larger than the `max`, values will be flipped to create a valid range: + +```js +toRegexRange('51', '29'); +``` + +Is effectively flipped to: + +```js +toRegexRange('29', '51'); +//=> 29|[3-4][0-9]|5[0-1] +``` + +**Steps / increments** + +This library does not support steps (increments). A pr to add support would be welcome. + +## History + +### v2.0.0 - 2017-04-21 + +**New features** + +Adds support for zero-padding! + +### v1.0.0 + +**Optimizations** + +Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. + +## Attribution + +Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") +* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") +* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 63 | [jonschlinkert](https://github.com/jonschlinkert) | +| 3 | [doowb](https://github.com/doowb) | +| 2 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ \ No newline at end of file diff --git a/tests/node_modules/to-regex-range/index.js b/tests/node_modules/to-regex-range/index.js new file mode 100644 index 0000000..77fbace --- /dev/null +++ b/tests/node_modules/to-regex-range/index.js @@ -0,0 +1,288 @@ +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const isNumber = require('is-number'); + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + let intersected = filterPatterns(neg, pos, '-?', true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit, options); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; diff --git a/tests/node_modules/to-regex-range/package.json b/tests/node_modules/to-regex-range/package.json new file mode 100644 index 0000000..9c56471 --- /dev/null +++ b/tests/node_modules/to-regex-range/package.json @@ -0,0 +1,125 @@ +{ + "_from": "to-regex-range@^5.0.1", + "_id": "to-regex-range@5.0.1", + "_inBundle": false, + "_integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "_location": "/to-regex-range", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "to-regex-range@^5.0.1", + "name": "to-regex-range", + "escapedName": "to-regex-range", + "rawSpec": "^5.0.1", + "saveSpec": null, + "fetchSpec": "^5.0.1" + }, + "_requiredBy": [ + "/fill-range" + ], + "_resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "_shasum": "1648c44aae7c8d988a326018ed72f5b4dd0392e4", + "_spec": "to-regex-range@^5.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/fill-range", + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/micromatch/to-regex-range/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jon Schlinkert", + "url": "http://twitter.com/jonschlinkert" + }, + { + "name": "Rouven Weßling", + "url": "www.rouvenwessling.de" + } + ], + "dependencies": { + "is-number": "^7.0.0" + }, + "deprecated": false, + "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", + "devDependencies": { + "fill-range": "^6.0.0", + "gulp-format-md": "^2.0.0", + "mocha": "^6.0.2", + "text-table": "^0.2.0", + "time-diff": "^0.3.1" + }, + "engines": { + "node": ">=8.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/micromatch/to-regex-range", + "keywords": [ + "bash", + "date", + "expand", + "expansion", + "expression", + "glob", + "match", + "match date", + "match number", + "match numbers", + "match year", + "matches", + "matching", + "number", + "numbers", + "numerical", + "range", + "ranges", + "regex", + "regexp", + "regular", + "regular expression", + "sequence" + ], + "license": "MIT", + "main": "index.js", + "name": "to-regex-range", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/to-regex-range.git" + }, + "scripts": { + "test": "mocha" + }, + "verb": { + "layout": "default", + "toc": false, + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "helpers": { + "examples": { + "displayName": "examples" + } + }, + "related": { + "list": [ + "expand-range", + "fill-range", + "micromatch", + "repeat-element", + "repeat-string" + ] + } + }, + "version": "5.0.1" +} diff --git a/tests/node_modules/trim/.npmignore b/tests/node_modules/trim/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/tests/node_modules/trim/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/tests/node_modules/trim/History.md b/tests/node_modules/trim/History.md new file mode 100644 index 0000000..c8aa68f --- /dev/null +++ b/tests/node_modules/trim/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/tests/node_modules/trim/Makefile b/tests/node_modules/trim/Makefile new file mode 100644 index 0000000..4e9c8d3 --- /dev/null +++ b/tests/node_modules/trim/Makefile @@ -0,0 +1,7 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: test \ No newline at end of file diff --git a/tests/node_modules/trim/Readme.md b/tests/node_modules/trim/Readme.md new file mode 100644 index 0000000..3460f52 --- /dev/null +++ b/tests/node_modules/trim/Readme.md @@ -0,0 +1,69 @@ + +# trim + + Trims string whitespace. + +## Installation + +``` +$ npm install trim +$ component install component/trim +``` + +## API + + - [trim(str)](#trimstr) + - [.left(str)](#leftstr) + - [.right(str)](#rightstr) + + + +### trim(str) +should trim leading / trailing whitespace. + +```js +trim(' foo bar ').should.equal('foo bar'); +trim('\n\n\nfoo bar\n\r\n\n').should.equal('foo bar'); +``` + + +### .left(str) +should trim leading whitespace. + +```js +trim.left(' foo bar ').should.equal('foo bar '); +``` + + +### .right(str) +should trim trailing whitespace. + +```js +trim.right(' foo bar ').should.equal(' foo bar'); +``` + + +## License + +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/tests/node_modules/trim/component.json b/tests/node_modules/trim/component.json new file mode 100644 index 0000000..560b258 --- /dev/null +++ b/tests/node_modules/trim/component.json @@ -0,0 +1,7 @@ +{ + "name": "trim", + "version": "0.0.1", + "description": "Trim string whitespace", + "keywords": ["string", "trim"], + "scripts": ["index.js"] +} \ No newline at end of file diff --git a/tests/node_modules/trim/index.js b/tests/node_modules/trim/index.js new file mode 100644 index 0000000..640c24c --- /dev/null +++ b/tests/node_modules/trim/index.js @@ -0,0 +1,14 @@ + +exports = module.exports = trim; + +function trim(str){ + return str.replace(/^\s*|\s*$/g, ''); +} + +exports.left = function(str){ + return str.replace(/^\s*/, ''); +}; + +exports.right = function(str){ + return str.replace(/\s*$/, ''); +}; diff --git a/tests/node_modules/trim/package.json b/tests/node_modules/trim/package.json new file mode 100644 index 0000000..922528f --- /dev/null +++ b/tests/node_modules/trim/package.json @@ -0,0 +1,49 @@ +{ + "_from": "trim@0.0.1", + "_id": "trim@0.0.1", + "_inBundle": false, + "_integrity": "sha1-WFhUf2spB1fulczMZm+1AITEYN0=", + "_location": "/trim", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "trim@0.0.1", + "name": "trim", + "escapedName": "trim", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/tap-out" + ], + "_resolved": "https://registry.npmjs.org/trim/-/trim-0.0.1.tgz", + "_shasum": "5858547f6b290757ee95cccc666fb50084c460dd", + "_spec": "trim@0.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/tap-out", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "trim/index.js": "index.js" + } + }, + "dependencies": {}, + "deprecated": false, + "description": "Trim string whitespace", + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "keywords": [ + "string", + "trim" + ], + "main": "index", + "name": "trim", + "version": "0.0.1" +} diff --git a/tests/node_modules/unbox-primitive/.editorconfig b/tests/node_modules/unbox-primitive/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/tests/node_modules/unbox-primitive/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/tests/node_modules/unbox-primitive/.eslintignore b/tests/node_modules/unbox-primitive/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/unbox-primitive/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/unbox-primitive/.eslintrc b/tests/node_modules/unbox-primitive/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/tests/node_modules/unbox-primitive/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/tests/node_modules/unbox-primitive/.github/FUNDING.yml b/tests/node_modules/unbox-primitive/.github/FUNDING.yml new file mode 100644 index 0000000..30cbba9 --- /dev/null +++ b/tests/node_modules/unbox-primitive/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/unbox-primitive +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/unbox-primitive/.nycrc b/tests/node_modules/unbox-primitive/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/tests/node_modules/unbox-primitive/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/unbox-primitive/CHANGELOG.md b/tests/node_modules/unbox-primitive/CHANGELOG.md new file mode 100644 index 0000000..4da114c --- /dev/null +++ b/tests/node_modules/unbox-primitive/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/unbox-primitive/compare/v1.0.0...v1.0.1) - 2021-03-25 + +### Commits + +- [Tests] use shared travis-ci configs [`f977e5f`](https://github.com/ljharb/unbox-primitive/commit/f977e5f8fa532dbc519bd78a48cf4b81c14720fe) +- [Tests] migrate tests to Github Actions [`b89def6`](https://github.com/ljharb/unbox-primitive/commit/b89def60908a236aa1b5c756426f7cc61cf458dd) +- [meta] do not publish github action workflow files [`325d1f1`](https://github.com/ljharb/unbox-primitive/commit/325d1f1836cecbe57ee148545de5aefcbe7a7dce) +- readme [`810cd70`](https://github.com/ljharb/unbox-primitive/commit/810cd70f7b3c670cd55eae64466c89595175ee2a) +- [Tests] run `nyc` on all tests; use `tape` runner [`2f5fb08`](https://github.com/ljharb/unbox-primitive/commit/2f5fb08930c8f8e5e069ac61891dc9bd76cb762b) +- [meta] add `auto-changelog` [`03ed375`](https://github.com/ljharb/unbox-primitive/commit/03ed3759284493f19323eb0500f726d0851fc085) +- [actions] add automatic rebasing / merge commit blocking [`6dec48d`](https://github.com/ljharb/unbox-primitive/commit/6dec48daa357fa79a5cac1add9ca33f7b56276cc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `object-is`, `tape` [`528ed88`](https://github.com/ljharb/unbox-primitive/commit/528ed8826664b67f7eaf1fe7e2031c063b2d315f) +- [actions] check out the entire repo [`5095b29`](https://github.com/ljharb/unbox-primitive/commit/5095b2981f44a78b3f9bfaa1a526f17a6823e383) +- [actions] add "Allow Edits" workflow [`5aa26d7`](https://github.com/ljharb/unbox-primitive/commit/5aa26d7f0c32e0e78ba4bf3e5f9abb5478fd97fa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `object-is`, `safe-publish-latest`, `tape` [`afc18c6`](https://github.com/ljharb/unbox-primitive/commit/afc18c6cb59cbb6b514e0d8004c6fd264e2a27eb) +- [readme] remove travis badge [`a025899`](https://github.com/ljharb/unbox-primitive/commit/a0258997a21604e1266840e6d167f0a870966e9b) +- [Dev Deps] update `auto-changelog` [`9219a32`](https://github.com/ljharb/unbox-primitive/commit/9219a32844b2ce3ed0a7ea12a5910a3e92424e4e) +- [readme] Fix missing paren in example [`73f5a33`](https://github.com/ljharb/unbox-primitive/commit/73f5a3340ca1ab6c227ed4632117d816d5e35317) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`e450acc`](https://github.com/ljharb/unbox-primitive/commit/e450accb54ab452f240768a5f0a98e5887b0ba8c) +- [Deps] update `has-bigints`, `has-symbols`, `which-boxed-primitive` [`a4279b5`](https://github.com/ljharb/unbox-primitive/commit/a4279b504732002074e5dcb9c5509038d605f563) +- [Dev Deps] update `auto-changelog`, `in-publish`, `tape` [`b351548`](https://github.com/ljharb/unbox-primitive/commit/b351548d31789c0d0af4c3bce55c2bdefe51b40f) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f600382`](https://github.com/ljharb/unbox-primitive/commit/f600382db83025270969354ac52a72aadb0a7ffa) +- [readme] fix travis links [`4d02fa9`](https://github.com/ljharb/unbox-primitive/commit/4d02fa9a4990812b048f8aefe6e46be80b68beef) +- [Dev Deps] update `auto-changelog`; add `aud` [`07e74a3`](https://github.com/ljharb/unbox-primitive/commit/07e74a3ca90688122593095849757e3c05c46db0) +- [meta] add `funding` field [`7ca4bd7`](https://github.com/ljharb/unbox-primitive/commit/7ca4bd71196e90a2fc9c7cb0ef4e30f949d5a853) +- [Tests] only audit prod deps [`47d8d5f`](https://github.com/ljharb/unbox-primitive/commit/47d8d5fbd58bf472e7e83f79ccef7e8379d06b35) +- [Deps] update `has-symbols` [`c70c15e`](https://github.com/ljharb/unbox-primitive/commit/c70c15e924191d11a271cff25bde657b0c3c3016) + +## v1.0.0 - 2019-08-10 + +### Commits + +- [Tests] add `.travis.yml` [`8c9a5ef`](https://github.com/ljharb/unbox-primitive/commit/8c9a5efdb54be4866e2884bf32cbe830788b2c2a) +- Initial commit [`feaff15`](https://github.com/ljharb/unbox-primitive/commit/feaff159eb999adc8763ff3e51d2d3d56d6164f8) +- [Tests] add tests [`3dd18d6`](https://github.com/ljharb/unbox-primitive/commit/3dd18d65748efb4af9b8ca66f8d8c5521d8f2dec) +- implementation [`472fb41`](https://github.com/ljharb/unbox-primitive/commit/472fb41d049ddee80ebf3219a5837e639a6e9341) +- npm init [`e9e426f`](https://github.com/ljharb/unbox-primitive/commit/e9e426fc90b9a3f07ffc48db75f78c414f77bc2b) +- [Tests] add linting [`139e74b`](https://github.com/ljharb/unbox-primitive/commit/139e74b94cdfd187b43b24de76c6d84af21ee467) +- [meta] create FUNDING.yml [`a9509e1`](https://github.com/ljharb/unbox-primitive/commit/a9509e122163e2b9d98af421e5c0575df36e2310) +- Only apps should have lockfiles [`b3d0834`](https://github.com/ljharb/unbox-primitive/commit/b3d0834d69dcbf4cbc1e61ccfaef05acf96cf630) diff --git a/tests/node_modules/unbox-primitive/LICENSE b/tests/node_modules/unbox-primitive/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/tests/node_modules/unbox-primitive/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/unbox-primitive/README.md b/tests/node_modules/unbox-primitive/README.md new file mode 100644 index 0000000..f267e33 --- /dev/null +++ b/tests/node_modules/unbox-primitive/README.md @@ -0,0 +1,41 @@ +# unbox-primitive [![Version Badge][2]][1] + +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Unbox a boxed JS primitive value. This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and works despite ES6 Symbol.toStringTag. + +## Example + +```js +var unboxPrimitive = require('unbox-primitive'); +var assert = require('assert'); + +assert.equal(unboxPrimitive(new Boolean(false)), false); +assert.equal(unboxPrimitive(new String('f')), 'f'); +assert.equal(unboxPrimitive(new Number(42)), 42); +const s = Symbol(); +assert.equal(unboxPrimitive(Object(s)), s); +assert.equal(unboxPrimitive(new BigInt(42)), 42n); + +// any primitive, or non-boxed-primitive object, will throw +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/unbox-primitive +[2]: https://versionbadg.es/ljharb/unbox-primitive.svg +[5]: https://david-dm.org/ljharb/unbox-primitive.svg +[6]: https://david-dm.org/ljharb/unbox-primitive +[7]: https://david-dm.org/ljharb/unbox-primitive/dev-status.svg +[8]: https://david-dm.org/ljharb/unbox-primitive#info=devDependencies +[11]: https://nodei.co/npm/unbox-primitive.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/unbox-primitive.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/unbox-primitive.svg +[downloads-url]: https://npm-stat.com/charts.html?package=unbox-primitive diff --git a/tests/node_modules/unbox-primitive/index.js b/tests/node_modules/unbox-primitive/index.js new file mode 100644 index 0000000..f5e9f3b --- /dev/null +++ b/tests/node_modules/unbox-primitive/index.js @@ -0,0 +1,39 @@ +'use strict'; + +var whichBoxedPrimitive = require('which-boxed-primitive'); +var bind = require('function-bind'); +var hasSymbols = require('has-symbols')(); +var hasBigInts = require('has-bigints')(); + +var stringToString = bind.call(Function.call, String.prototype.toString); +var numberValueOf = bind.call(Function.call, Number.prototype.valueOf); +var booleanValueOf = bind.call(Function.call, Boolean.prototype.valueOf); +var symbolValueOf = hasSymbols && bind.call(Function.call, Symbol.prototype.valueOf); +var bigIntValueOf = hasBigInts && bind.call(Function.call, BigInt.prototype.valueOf); + +module.exports = function unboxPrimitive(value) { + var which = whichBoxedPrimitive(value); + if (typeof which !== 'string') { + throw new TypeError(which === null ? 'value is an unboxed primitive' : 'value is a non-boxed-primitive object'); + } + + if (which === 'String') { + return stringToString(value); + } + if (which === 'Number') { + return numberValueOf(value); + } + if (which === 'Boolean') { + return booleanValueOf(value); + } + if (which === 'Symbol') { + if (!hasSymbols) { + throw new EvalError('somehow this environment does not have Symbols, but you have a boxed Symbol value. Please report this!'); + } + return symbolValueOf(value); + } + if (which === 'BigInt') { + return bigIntValueOf(value); + } + throw new RangeError('unknown boxed primitive found: ' + which); +}; diff --git a/tests/node_modules/unbox-primitive/package.json b/tests/node_modules/unbox-primitive/package.json new file mode 100644 index 0000000..a0141aa --- /dev/null +++ b/tests/node_modules/unbox-primitive/package.json @@ -0,0 +1,92 @@ +{ + "_from": "unbox-primitive@^1.0.1", + "_id": "unbox-primitive@1.0.1", + "_inBundle": false, + "_integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "_location": "/unbox-primitive", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "unbox-primitive@^1.0.1", + "name": "unbox-primitive", + "escapedName": "unbox-primitive", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", + "_shasum": "085e215625ec3162574dc8859abee78a59b14471", + "_spec": "unbox-primitive@^1.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/es-abstract", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/ljharb/unbox-primitive/issues" + }, + "bundleDependencies": false, + "dependencies": { + "function-bind": "^1.1.1", + "has-bigints": "^1.0.1", + "has-symbols": "^1.0.2", + "which-boxed-primitive": "^1.0.2" + }, + "deprecated": false, + "description": "Unbox a boxed JS primitive value.", + "devDependencies": { + "@ljharb/eslint-config": "^17.5.1", + "aud": "^1.1.4", + "auto-changelog": "^2.2.1", + "eslint": "^7.22.0", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "nyc": "^10.3.2", + "object-inspect": "^1.9.0", + "object-is": "^1.1.5", + "safe-publish-latest": "^1.1.4", + "tape": "^5.2.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/ljharb/unbox-primitive#readme", + "keywords": [ + "unbox", + "boxed", + "primitive", + "object", + "javascript", + "ecmascript" + ], + "license": "MIT", + "main": "index.js", + "name": "unbox-primitive", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/unbox-primitive.git" + }, + "scripts": { + "lint": "eslint .", + "posttest": "npx aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "not-in-publish || safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "version": "1.0.1" +} diff --git a/tests/node_modules/unbox-primitive/test/index.js b/tests/node_modules/unbox-primitive/test/index.js new file mode 100644 index 0000000..73688ac --- /dev/null +++ b/tests/node_modules/unbox-primitive/test/index.js @@ -0,0 +1,59 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var is = require('object-is'); +var forEach = require('for-each'); +var hasSymbols = require('has-symbols')(); +var hasBigInts = require('has-bigints')(); + +var unboxPrimitive = require('..'); + +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +test('primitives', function (t) { + var primitives = [ + true, + false, + '', + 'foo', + 42, + NaN, + Infinity, + 0 + ]; + if (hasSymbols) { + primitives.push(Symbol(), Symbol.iterator, Symbol('f')); + } + if (hasBigInts) { + primitives.push(BigInt(42), BigInt(0)); + } + forEach(primitives, function (primitive) { + var obj = Object(primitive); + t.ok( + is(unboxPrimitive(obj), primitive), + debug(obj, 'unboxes to ' + inspect(primitive)) + ); + }); + + t.end(); +}); + +test('objects', function (t) { + var objects = [ + {}, + [], + function () {}, + /a/g, + new Date() + ]; + forEach(objects, function (object) { + t['throws']( + function () { unboxPrimitive(object); }, + TypeError, + debug(object, 'is not a primitive') + ); + }); + + t.end(); +}); diff --git a/tests/node_modules/util-deprecate/History.md b/tests/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/tests/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/tests/node_modules/util-deprecate/LICENSE b/tests/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/tests/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/util-deprecate/README.md b/tests/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/tests/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/node_modules/util-deprecate/browser.js b/tests/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/tests/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/tests/node_modules/util-deprecate/node.js b/tests/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/tests/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/tests/node_modules/util-deprecate/package.json b/tests/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..038519b --- /dev/null +++ b/tests/node_modules/util-deprecate/package.json @@ -0,0 +1,57 @@ +{ + "_from": "util-deprecate@~1.0.1", + "_id": "util-deprecate@1.0.2", + "_inBundle": false, + "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "_location": "/util-deprecate", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "util-deprecate@~1.0.1", + "name": "util-deprecate", + "escapedName": "util-deprecate", + "rawSpec": "~1.0.1", + "saveSpec": null, + "fetchSpec": "~1.0.1" + }, + "_requiredBy": [ + "/readable-stream", + "/through2/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "_spec": "util-deprecate@~1.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/readable-stream", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The Node.js `util.deprecate()` function with browser support", + "homepage": "https://github.com/TooTallNate/util-deprecate", + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "license": "MIT", + "main": "node.js", + "name": "util-deprecate", + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "version": "1.0.2" +} diff --git a/tests/node_modules/which-boxed-primitive/.editorconfig b/tests/node_modules/which-boxed-primitive/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/tests/node_modules/which-boxed-primitive/.eslintignore b/tests/node_modules/which-boxed-primitive/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/which-boxed-primitive/.eslintrc b/tests/node_modules/which-boxed-primitive/.eslintrc new file mode 100644 index 0000000..bfa96d1 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements": [2, 12], + }, +} diff --git a/tests/node_modules/which-boxed-primitive/.github/FUNDING.yml b/tests/node_modules/which-boxed-primitive/.github/FUNDING.yml new file mode 100644 index 0000000..0cdbbd8 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/which-boxed-primitive +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/which-boxed-primitive/.nycrc b/tests/node_modules/which-boxed-primitive/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/which-boxed-primitive/CHANGELOG.md b/tests/node_modules/which-boxed-primitive/CHANGELOG.md new file mode 100644 index 0000000..23e5422 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/CHANGELOG.md @@ -0,0 +1,54 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/which-boxed-primitive/compare/v1.0.1...v1.0.2) - 2020-12-14 + +### Commits + +- [Tests] use shared travis-ci configs [`8674582`](https://github.com/inspect-js/which-boxed-primitive/commit/86745829b6a92cff2cfb0d3c0414ec9afdc2a087) +- [Tests] migrate tests to Github Actions [`dff6643`](https://github.com/inspect-js/which-boxed-primitive/commit/dff6643405ba4d6dc6694a25904c8f72f273ece8) +- [meta] do not publish github action workflow files [`b26112a`](https://github.com/inspect-js/which-boxed-primitive/commit/b26112a4e4ac6beec8f54c734135dbf9e9ba16f9) +- [meta] make `auto-changelog` config consistent [`8d10175`](https://github.com/inspect-js/which-boxed-primitive/commit/8d10175171154cd6c8f8a016aa7fb71b5044acf6) +- [readme] fix repo URLs, remove defunct badges [`ab8db24`](https://github.com/inspect-js/which-boxed-primitive/commit/ab8db247573723dbcda68469118d08c7c2692c67) +- [Tests] run `nyc` on all tests; use `tape` runner [`7d084df`](https://github.com/inspect-js/which-boxed-primitive/commit/7d084dfc5251230e9399a81782c0b9d7ae5d1901) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`576f6f3`](https://github.com/inspect-js/which-boxed-primitive/commit/576f6f308aed35ef1d3392bb9472def59482ed13) +- [actions] add automatic rebasing / merge commit blocking [`97efa53`](https://github.com/inspect-js/which-boxed-primitive/commit/97efa53a307678323e63f576c07db9ff84846fd3) +- [actions] add "Allow Edits" workflow [`fb1b4f7`](https://github.com/inspect-js/which-boxed-primitive/commit/fb1b4f7cd753fcced74ac054b20c8b2bfafe7953) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `has-symbols`, `object-inspect`, `safe-publish-latest` [`1e03c61`](https://github.com/inspect-js/which-boxed-primitive/commit/1e03c6153693d385833acc15178f675e6ce5ddd0) +- [Deps] update `is-boolean-object`, `is-number-object`, `is-string`, `is-symbol` [`13673df`](https://github.com/inspect-js/which-boxed-primitive/commit/13673dff6e43f0a915377c3e5740ec24e86d6bb7) +- [Dev Deps] update `auto-changelog`, `in-publish`, `tape` [`65a0e15`](https://github.com/inspect-js/which-boxed-primitive/commit/65a0e155fc46a9237692233a51ec9573621135d2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`f8a0afe`](https://github.com/inspect-js/which-boxed-primitive/commit/f8a0afea82938d64f3d2d240268afbd346d0c4da) +- [Deps] update `is-bigint`, `is-boolean-object` [`e7a1ce2`](https://github.com/inspect-js/which-boxed-primitive/commit/e7a1ce25371c00ee726f1c0cc5b6acf10d51ec50) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`e46f193`](https://github.com/inspect-js/which-boxed-primitive/commit/e46f193298b158db5c8aba889803513e4ee38957) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`df3da14`](https://github.com/inspect-js/which-boxed-primitive/commit/df3da1424552a5d22e203a0abf1710106bfd4ae2) +- [Dev Deps] update `auto-changelog`; add `aud` [`e2e8a12`](https://github.com/inspect-js/which-boxed-primitive/commit/e2e8a12c6fbf8c48e760ea1d1ccd5e8d2d6fbf24) +- [meta] add `funding` field [`7df404b`](https://github.com/inspect-js/which-boxed-primitive/commit/7df404b20cd50b2b87e6645b130fefa8ee98810e) +- [Dev Deps] update `auto-changelog` [`0d6b76d`](https://github.com/inspect-js/which-boxed-primitive/commit/0d6b76dbbe760581fa86a0c3f254988fe5d27770) +- [Tests] only audit prod deps [`246151c`](https://github.com/inspect-js/which-boxed-primitive/commit/246151cc1407b3b1ef42014db993f62670bd82ff) +- [meta] fix changelog [`c2d1685`](https://github.com/inspect-js/which-boxed-primitive/commit/c2d16856deffbf86e0b5029e69b65d8aa758ec3d) +- [readme] Fix spelling error [`25fb2b5`](https://github.com/inspect-js/which-boxed-primitive/commit/25fb2b56e1f708c6364923e4bae384f818ecf57f) + +## [v1.0.1](https://github.com/inspect-js/which-boxed-primitive/compare/v1.0.0...v1.0.1) - 2019-08-10 + +### Commits + +- [meta] avoid running `safe-publish-latest` when not publishing [`df44b27`](https://github.com/inspect-js/which-boxed-primitive/commit/df44b27875a8f5c3c596663ecb4a063f9fc7bde3) + +## v1.0.0 - 2019-08-10 + +### Commits + +- [Tests] add `.travis.yml` [`764b0cf`](https://github.com/inspect-js/which-boxed-primitive/commit/764b0cf75f8d2b3a0ad2056de5f4ad85d5d1b765) +- Initial commit [`da7d068`](https://github.com/inspect-js/which-boxed-primitive/commit/da7d068913d591294bf155db5d438f7804d71b9a) +- readme [`1395bb2`](https://github.com/inspect-js/which-boxed-primitive/commit/1395bb27b72137ac01e48ee398a0f54e93fd87f5) +- [Tests] add tests [`0ff580f`](https://github.com/inspect-js/which-boxed-primitive/commit/0ff580f99579cd4424af7b814bd76fcb69a2b04e) +- implementation [`8811c32`](https://github.com/inspect-js/which-boxed-primitive/commit/8811c3262a57963634cdc83ceb5bb2c5e9ae4e7e) +- npm init [`cffdea9`](https://github.com/inspect-js/which-boxed-primitive/commit/cffdea9755eabfa2f9ec62a6fcbce0c28f04495b) +- [Tests] add `npm run lint` [`a8be993`](https://github.com/inspect-js/which-boxed-primitive/commit/a8be9933fec1b21267acd847df77f6438e07e3b9) +- [meta] add FUNDING.yml [`941258c`](https://github.com/inspect-js/which-boxed-primitive/commit/941258c70c9a397466e05b614126cb8c7be77b99) +- Only apps should have lockfiles [`6857316`](https://github.com/inspect-js/which-boxed-primitive/commit/68573165d8ce842cdf15d94af82f8cccb961b8cf) +- [Tests] use `npx aud` in `posttest` [`ee48a91`](https://github.com/inspect-js/which-boxed-primitive/commit/ee48a9144bea23bde5cc47788a54d5aa7969d489) diff --git a/tests/node_modules/which-boxed-primitive/LICENSE b/tests/node_modules/which-boxed-primitive/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/which-boxed-primitive/README.md b/tests/node_modules/which-boxed-primitive/README.md new file mode 100644 index 0000000..e08f26a --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/README.md @@ -0,0 +1,73 @@ +# which-boxed-primitive [![Version Badge][2]][1] + +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Which kind of boxed JS primitive is this? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and works despite ES6 Symbol.toStringTag. + +## Example + +```js +var whichBoxedPrimitive = require('which-boxed-primitive'); +var assert = require('assert'); + +// unboxed primitives return `null` +// boxed primitives return the builtin constructor name + +assert.equal(whichBoxedPrimitive(undefined), null); +assert.equal(whichBoxedPrimitive(null), null); + +assert.equal(whichBoxedPrimitive(false), null); +assert.equal(whichBoxedPrimitive(true), null); +assert.equal(whichBoxedPrimitive(new Boolean(false)), 'Boolean'); +assert.equal(whichBoxedPrimitive(new Boolean(true)), 'Boolean'); + +assert.equal(whichBoxedPrimitive(42), null); +assert.equal(whichBoxedPrimitive(NaN), null); +assert.equal(whichBoxedPrimitive(Infinity), null); +assert.equal(whichBoxedPrimitive(new Number(42)), 'Number'); +assert.equal(whichBoxedPrimitive(new Number(NaN)), 'Number'); +assert.equal(whichBoxedPrimitive(new Number(Infinity)), 'Number'); + +assert.equal(whichBoxedPrimitive(''), null); +assert.equal(whichBoxedPrimitive('foo'), null); +assert.equal(whichBoxedPrimitive(new String('')), 'String'); +assert.equal(whichBoxedPrimitive(new String('foo')), 'String'); + +assert.equal(whichBoxedPrimitive(Symbol()), null); +assert.equal(whichBoxedPrimitive(Object(Symbol()), 'Symbol'); + +assert.equal(whichBoxedPrimitive(42n), null); +assert.equal(whichBoxedPrimitive(Object(42n), 'BigInt'); + +// non-boxed-primitive objects return `undefined` +assert.equal(whichBoxedPrimitive([]), undefined); +assert.equal(whichBoxedPrimitive({}), undefined); +assert.equal(whichBoxedPrimitive(/a/g), undefined); +assert.equal(whichBoxedPrimitive(new RegExp('a', 'g')), undefined); +assert.equal(whichBoxedPrimitive(new Date()), undefined); +assert.equal(whichBoxedPrimitive(function () {}), undefined); +assert.equal(whichBoxedPrimitive(function* () {}), undefined); +assert.equal(whichBoxedPrimitive(x => x * x), undefined); +assert.equal(whichBoxedPrimitive([]), undefined); + +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/which-boxed-primitive +[2]: https://versionbadg.es/inspect-js/which-boxed-primitive.svg +[5]: https://david-dm.org/inspect-js/which-boxed-primitive.svg +[6]: https://david-dm.org/inspect-js/which-boxed-primitive +[7]: https://david-dm.org/inspect-js/which-boxed-primitive/dev-status.svg +[8]: https://david-dm.org/inspect-js/which-boxed-primitive#info=devDependencies +[11]: https://nodei.co/npm/which-boxed-primitive.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/which-boxed-primitive.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/which-boxed-primitive.svg +[downloads-url]: https://npm-stat.com/charts.html?package=which-boxed-primitive diff --git a/tests/node_modules/which-boxed-primitive/index.js b/tests/node_modules/which-boxed-primitive/index.js new file mode 100644 index 0000000..f8ea564 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/index.js @@ -0,0 +1,30 @@ +'use strict'; + +var isString = require('is-string'); +var isNumber = require('is-number-object'); +var isBoolean = require('is-boolean-object'); +var isSymbol = require('is-symbol'); +var isBigInt = require('is-bigint'); + +// eslint-disable-next-line consistent-return +module.exports = function whichBoxedPrimitive(value) { + // eslint-disable-next-line eqeqeq + if (value == null || (typeof value !== 'object' && typeof value !== 'function')) { + return null; + } + if (isString(value)) { + return 'String'; + } + if (isNumber(value)) { + return 'Number'; + } + if (isBoolean(value)) { + return 'Boolean'; + } + if (isSymbol(value)) { + return 'Symbol'; + } + if (isBigInt(value)) { + return 'BigInt'; + } +}; diff --git a/tests/node_modules/which-boxed-primitive/package.json b/tests/node_modules/which-boxed-primitive/package.json new file mode 100644 index 0000000..7d25e82 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/package.json @@ -0,0 +1,94 @@ +{ + "_from": "which-boxed-primitive@^1.0.1", + "_id": "which-boxed-primitive@1.0.2", + "_inBundle": false, + "_integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "_location": "/which-boxed-primitive", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "which-boxed-primitive@^1.0.1", + "name": "which-boxed-primitive", + "escapedName": "which-boxed-primitive", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/deep-equal", + "/unbox-primitive" + ], + "_resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "_shasum": "13757bc89b209b049fe5d86430e21cf40a89a8e6", + "_spec": "which-boxed-primitive@^1.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/deep-equal", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/inspect-js/which-boxed-primitive/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "deprecated": false, + "description": "Which kind of boxed JS primitive is this?", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.15.0", + "has-symbols": "^1.0.1", + "in-publish": "^2.0.1", + "nyc": "^10.3.2", + "object-inspect": "^1.9.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/inspect-js/which-boxed-primitive#readme", + "keywords": [ + "boxed", + "primitive", + "object", + "ecmascript", + "javascript", + "which" + ], + "license": "MIT", + "main": "index.js", + "name": "which-boxed-primitive", + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/which-boxed-primitive.git" + }, + "scripts": { + "lint": "eslint --ext=js,mjs .", + "posttest": "aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "not-in-publish || safe-publish-latest", + "pretest": "npm run lint", + "preversion": "auto-changelog", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "version": "1.0.2" +} diff --git a/tests/node_modules/which-boxed-primitive/test/index.js b/tests/node_modules/which-boxed-primitive/test/index.js new file mode 100644 index 0000000..f9ea998 --- /dev/null +++ b/tests/node_modules/which-boxed-primitive/test/index.js @@ -0,0 +1,66 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var whichBoxedPrimitive = require('..'); + +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +var hasSymbols = require('has-symbols')(); +var hasBigInts = typeof BigInt === 'function'; + +var primitives = [ + true, + false, + 42, + NaN, + Infinity, + '', + 'foo' +].concat( + hasSymbols ? [Symbol(), Symbol.iterator] : [], + hasBigInts ? BigInt(42) : [] +); + +var objects = [ + /a/g, + new Date(), + function () {}, + [], + {} +]; + +test('isBoxedPrimitive', function (t) { + t.test('unboxed primitives', function (st) { + forEach([null, undefined].concat(primitives), function (primitive) { + st.equal(null, whichBoxedPrimitive(primitive), debug(primitive, 'is a primitive, but not a boxed primitive')); + }); + st.end(); + }); + + t.test('boxed primitives', function (st) { + forEach(primitives, function (primitive) { + var boxed = Object(primitive); + var expected = boxed.constructor.name; + st.equal(typeof expected, 'string', 'expected is string'); + st.equal(whichBoxedPrimitive(boxed), expected, debug(boxed, 'is a boxed primitive: ' + expected)); + }); + st.end(); + }); + + t.test('non-primitive objects', function (st) { + forEach(objects, function (object) { + st.equal(undefined, whichBoxedPrimitive(object), debug(object, 'is not a primitive, boxed or otherwise')); + }); + st.end(); + }); + + t.end(); +}); diff --git a/tests/node_modules/which-collection/.eslintrc b/tests/node_modules/which-collection/.eslintrc new file mode 100644 index 0000000..4d08f25 --- /dev/null +++ b/tests/node_modules/which-collection/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "overrides": [ + { + "files": "test/**", + "globals": { + "WeakMap": false, + "WeakSet": false, + }, + }, + ], +} diff --git a/tests/node_modules/which-collection/.github/FUNDING.yml b/tests/node_modules/which-collection/.github/FUNDING.yml new file mode 100644 index 0000000..7570eaa --- /dev/null +++ b/tests/node_modules/which-collection/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/which-collection +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/which-collection/.github/workflows/rebase.yml b/tests/node_modules/which-collection/.github/workflows/rebase.yml new file mode 100644 index 0000000..436cb79 --- /dev/null +++ b/tests/node_modules/which-collection/.github/workflows/rebase.yml @@ -0,0 +1,15 @@ +name: Automatic Rebase + +on: [pull_request] + +jobs: + _: + name: "Automatic Rebase" + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - uses: ljharb/rebase@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/tests/node_modules/which-collection/.travis.yml b/tests/node_modules/which-collection/.travis.yml new file mode 100644 index 0000000..5ed0fa5 --- /dev/null +++ b/tests/node_modules/which-collection/.travis.yml @@ -0,0 +1,8 @@ +version: ~> 1.0 +language: node_js +os: + - linux +import: + - ljharb/travis-ci:node/all.yml + - ljharb/travis-ci:node/pretest.yml + - ljharb/travis-ci:node/posttest.yml diff --git a/tests/node_modules/which-collection/CHANGELOG.md b/tests/node_modules/which-collection/CHANGELOG.md new file mode 100644 index 0000000..62d2da6 --- /dev/null +++ b/tests/node_modules/which-collection/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). + +## [v1.0.1](https://github.com/inspect-js/which-collection/compare/v1.0.0...v1.0.1) - 2020-01-26 + +### Commits + +- [actions] add automatic rebasing / merge commit blocking [`c3820b2`](https://github.com/inspect-js/which-collection/commit/c3820b2e8c88548f2c7da4080b1d1b6b41be97a4) +- [patch] add "exports" [`10983b5`](https://github.com/inspect-js/which-collection/commit/10983b5fdcc453c64216c3d6aa3fb93340091818) +- [Deps] update `is-map`, `is-set`, `is-weakmap`, `is-weakset` [`1565925`](https://github.com/inspect-js/which-collection/commit/1565925705c4abfe88065b211d1d960791f7cd3c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`92ef871`](https://github.com/inspect-js/which-collection/commit/92ef871338395352f1bafc3156088361a3fd917a) +- [Dev Deps] update `@ljharb/eslint-config` [`61e9cde`](https://github.com/inspect-js/which-collection/commit/61e9cde1830ccc2b551dd6a1a873ae2cf27a74c7) + +## v1.0.0 - 2019-11-13 + +### Commits + +- Initial commit [`a21fddf`](https://github.com/inspect-js/which-collection/commit/a21fddffef3b2f21923e4d056295dd63661d8155) +- Tests [`ec86bc1`](https://github.com/inspect-js/which-collection/commit/ec86bc12f0516bd662c6e2966b36de2e1128a431) +- readme [`ffe969c`](https://github.com/inspect-js/which-collection/commit/ffe969cf4388d18e12c664cc51498bbdef08e565) +- implementation [`9acb669`](https://github.com/inspect-js/which-collection/commit/9acb6695e6a5e60f4c0b6de59eaf8b1f681d78e5) +- npm init [`124a63e`](https://github.com/inspect-js/which-collection/commit/124a63ee68a0015b47cbcc08b0d5598e553e7c9a) +- [meta] add `auto-changelog`, `safe-publish-latest` [`df0d6d4`](https://github.com/inspect-js/which-collection/commit/df0d6d4f1efbc4d9b327471b9c659bd487b25b49) +- [meta] add `funding` field; create FUNDING.yml [`032c81c`](https://github.com/inspect-js/which-collection/commit/032c81c826d68acd6242fa87fd6348db70135506) +- [Tests] add `npm run lint` [`6ae406d`](https://github.com/inspect-js/which-collection/commit/6ae406d9e459779abbdd90f48559552f740b05c9) +- fixup [`a2cad36`](https://github.com/inspect-js/which-collection/commit/a2cad363f12e30afe7619597187c5d4dc840a2a7) +- Only apps should have lockfiles [`30b3aae`](https://github.com/inspect-js/which-collection/commit/30b3aae37155f0786e4582501369f738b3282cd7) diff --git a/tests/node_modules/which-collection/LICENSE b/tests/node_modules/which-collection/LICENSE new file mode 100644 index 0000000..c05eb20 --- /dev/null +++ b/tests/node_modules/which-collection/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/node_modules/which-collection/README.md b/tests/node_modules/which-collection/README.md new file mode 100644 index 0000000..ae5e99a --- /dev/null +++ b/tests/node_modules/which-collection/README.md @@ -0,0 +1,64 @@ +# which-collection [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Which kind of Collection (Map, Set, WeakMap, WeakSet) is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag. + +## Example + +```js +var whichCollection = require('which-collection'); +var assert = require('assert'); + +assert.equal(false, whichCollection(undefined)); +assert.equal(false, whichCollection(null)); +assert.equal(false, whichCollection(false)); +assert.equal(false, whichCollection(true)); +assert.equal(false, whichCollection([])); +assert.equal(false, whichCollection({})); +assert.equal(false, whichCollection(/a/g)); +assert.equal(false, whichCollection(new RegExp('a', 'g'))); +assert.equal(false, whichCollection(new Date())); +assert.equal(false, whichCollection(42)); +assert.equal(false, whichCollection(NaN)); +assert.equal(false, whichCollection(Infinity)); +assert.equal(false, whichCollection(new Number(42))); +assert.equal(false, whichCollection(42n)); +assert.equal(false, whichCollection(Object(42n))); +assert.equal(false, whichCollection('foo')); +assert.equal(false, whichCollection(Object('foo'))); +assert.equal(false, whichCollection(function () {})); +assert.equal(false, whichCollection(function* () {})); +assert.equal(false, whichCollection(x => x * x)); +assert.equal(false, whichCollection([])); + +assert.equal('Map', whichCollection(new Map())); +assert.equal('Set', whichCollection(new Set())); +assert.equal('WeakMap', whichCollection(new WeakMap())); +assert.equal('WeakSet', whichCollection(new WeakSet())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/which-collection +[2]: http://versionbadg.es/inspect-js/which-collection.svg +[3]: https://travis-ci.org/inspect-js/which-collection.svg +[4]: https://travis-ci.org/inspect-js/which-collection +[5]: https://david-dm.org/inspect-js/which-collection.svg +[6]: https://david-dm.org/inspect-js/which-collection +[7]: https://david-dm.org/inspect-js/which-collection/dev-status.svg +[8]: https://david-dm.org/inspect-js/which-collection#info=devDependencies +[9]: https://ci.testling.com/inspect-js/which-collection.png +[10]: https://ci.testling.com/inspect-js/which-collection +[11]: https://nodei.co/npm/which-collection.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/which-collection.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/which-collection.svg +[downloads-url]: http://npm-stat.com/charts.html?package=which-collection diff --git a/tests/node_modules/which-collection/index.js b/tests/node_modules/which-collection/index.js new file mode 100644 index 0000000..71c7f95 --- /dev/null +++ b/tests/node_modules/which-collection/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var isMap = require('is-map'); +var isSet = require('is-set'); +var isWeakMap = require('is-weakmap'); +var isWeakSet = require('is-weakset'); + +module.exports = function whichCollection(value) { + if (value && typeof value === 'object') { + if (isMap(value)) { + return 'Map'; + } + if (isSet(value)) { + return 'Set'; + } + if (isWeakMap(value)) { + return 'WeakMap'; + } + if (isWeakSet(value)) { + return 'WeakSet'; + } + } + return false; +}; diff --git a/tests/node_modules/which-collection/package.json b/tests/node_modules/which-collection/package.json new file mode 100644 index 0000000..f12c700 --- /dev/null +++ b/tests/node_modules/which-collection/package.json @@ -0,0 +1,97 @@ +{ + "_from": "which-collection@^1.0.1", + "_id": "which-collection@1.0.1", + "_inBundle": false, + "_integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "_location": "/which-collection", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "which-collection@^1.0.1", + "name": "which-collection", + "escapedName": "which-collection", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/deep-equal" + ], + "_resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "_shasum": "70eab71ebbbd2aefaf32f917082fc62cdcb70906", + "_spec": "which-collection@^1.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/deep-equal", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false + }, + "bugs": { + "url": "https://github.com/inspect-js/which-collection/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + }, + "deprecated": false, + "description": "Which kind of Collection (Map, Set, WeakMap, WeakSet) is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.", + "devDependencies": { + "@ljharb/eslint-config": "^16.0.0", + "auto-changelog": "^1.16.2", + "eslint": "^6.8.0", + "for-each": "^0.3.3", + "object-inspect": "^1.7.0", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.0-next.4" + }, + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/inspect-js/which-collection#readme", + "keywords": [ + "map", + "set", + "weakmap", + "weakset", + "collection.es6", + "es2015" + ], + "license": "MIT", + "main": "index.js", + "name": "which-collection", + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/which-collection.git" + }, + "scripts": { + "lint": "eslint .", + "posttest": "npx aud", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "node test", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "type": "commonjs", + "version": "1.0.1" +} diff --git a/tests/node_modules/which-collection/test/index.js b/tests/node_modules/which-collection/test/index.js new file mode 100644 index 0000000..3a5becc --- /dev/null +++ b/tests/node_modules/which-collection/test/index.js @@ -0,0 +1,59 @@ +'use strict'; + +var test = require('tape'); +var debug = require('object-inspect'); +var forEach = require('for-each'); + +var whichCollection = require('..'); + +test('non-collections', function (t) { + forEach([ + null, + undefined, + true, + false, + 42, + 0, + -0, + NaN, + Infinity, + '', + 'foo', + /a/g, + [], + {}, + function () {} + ], function (nonCollection) { + t.equal(whichCollection(nonCollection), false, debug(nonCollection) + ' is not a collection'); + }); + + t.end(); +}); + +test('Maps', { skip: typeof Map !== 'function' }, function (t) { + var m = new Map(); + t.equal(whichCollection(m), 'Map', debug(m) + ' is a Map'); + + t.end(); +}); + +test('Sets', { skip: typeof Set !== 'function' }, function (t) { + var s = new Set(); + t.equal(whichCollection(s), 'Set', debug(s) + ' is a Set'); + + t.end(); +}); + +test('WeakMaps', { skip: typeof WeakMap !== 'function' }, function (t) { + var wm = new WeakMap(); + t.equal(whichCollection(wm), 'WeakMap', debug(wm) + ' is a WeakMap'); + + t.end(); +}); + +test('WeakSets', { skip: typeof WeakSet !== 'function' }, function (t) { + var ws = new WeakSet(); + t.equal(whichCollection(ws), 'WeakSet', debug(ws) + ' is a WeakSet'); + + t.end(); +}); diff --git a/tests/node_modules/which-typed-array/.editorconfig b/tests/node_modules/which-typed-array/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/tests/node_modules/which-typed-array/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/tests/node_modules/which-typed-array/.eslintignore b/tests/node_modules/which-typed-array/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/tests/node_modules/which-typed-array/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/tests/node_modules/which-typed-array/.eslintrc b/tests/node_modules/which-typed-array/.eslintrc new file mode 100644 index 0000000..8b2ada0 --- /dev/null +++ b/tests/node_modules/which-typed-array/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + }, +} diff --git a/tests/node_modules/which-typed-array/.github/FUNDING.yml b/tests/node_modules/which-typed-array/.github/FUNDING.yml new file mode 100644 index 0000000..d6aa180 --- /dev/null +++ b/tests/node_modules/which-typed-array/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/which-typed-array +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/node_modules/which-typed-array/.nycrc b/tests/node_modules/which-typed-array/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/tests/node_modules/which-typed-array/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tests/node_modules/which-typed-array/CHANGELOG.md b/tests/node_modules/which-typed-array/CHANGELOG.md new file mode 100644 index 0000000..2c4f969 --- /dev/null +++ b/tests/node_modules/which-typed-array/CHANGELOG.md @@ -0,0 +1,123 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). + +## [v1.1.4](https://github.com/inspect-js/which-typed-array/compare/v1.1.3...v1.1.4) - 2020-12-05 + +### Commits + +- [meta] npmignore github action workflows [`aa427e7`](https://github.com/inspect-js/which-typed-array/commit/aa427e79a230a985953695a8129ceb6bb7d42527) + +## [v1.1.3](https://github.com/inspect-js/which-typed-array/compare/v1.1.2...v1.1.3) - 2020-12-05 + +### Commits + +- [Tests] migrate tests to Github Actions [`803d4dd`](https://github.com/inspect-js/which-typed-array/commit/803d4ddb601ff03e587be792bd452de0e2783d03) +- [Tests] run `nyc` on all tests [`205a13f`](https://github.com/inspect-js/which-typed-array/commit/205a13f7aa172e014ddc2079c84af6ba575581c8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `is-callable`, `tape` [`97ceb07`](https://github.com/inspect-js/which-typed-array/commit/97ceb070d5aea1c3a696c6f695800ae468bafc0b) +- [actions] add "Allow Edits" workflow [`b140492`](https://github.com/inspect-js/which-typed-array/commit/b14049211eff32bd4149767def4f939483810051) +- [Deps] update `es-abstract`; use `call-bind` where applicable [`2abdb87`](https://github.com/inspect-js/which-typed-array/commit/2abdb871961b4e1b58925115a7d56a9cc5966a02) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`256d34b`](https://github.com/inspect-js/which-typed-array/commit/256d34b8bdb67b8af0e9f83c9a318e54f3340e3b) +- [Dev Deps] update `auto-changelog`; add `aud` [`ddea96f`](https://github.com/inspect-js/which-typed-array/commit/ddea96fe320dbdd0c7d7569812399a7f64d43e04) +- [meta] gitignore nyc output [`8a812bd`](https://github.com/inspect-js/which-typed-array/commit/8a812bd1ce7c5609988fb4fe2e9af2089eccd07d) + +## [v1.1.2](https://github.com/inspect-js/which-typed-array/compare/v1.1.1...v1.1.2) - 2020-04-07 + +### Commits + +- [Dev Deps] update `make-arrow-function`, `make-generator-function` [`28c61ef`](https://github.com/inspect-js/which-typed-array/commit/28c61eff4903ff6509f65c2f500858b9cb4636f1) +- [Dev Deps] update `@ljharb/eslint-config` [`a233879`](https://github.com/inspect-js/which-typed-array/commit/a2338798d3a4a3169cda54e322b2f2eb0e976ad0) +- [Dev Deps] update `auto-changelog` [`df0134c`](https://github.com/inspect-js/which-typed-array/commit/df0134c0e20ec6d94993988ad670e1b3cf350bea) +- [Fix] move `foreach` to dependencies [`6ef29c0`](https://github.com/inspect-js/which-typed-array/commit/6ef29c0dbb91a7ec21df7ce8736f99f41efea39e) +- [Tests] only audit prod deps [`eb21044`](https://github.com/inspect-js/which-typed-array/commit/eb210446bd7a433657204d2314ef56fe264c21ad) +- [Deps] update `es-abstract` [`5ef0236`](https://github.com/inspect-js/which-typed-array/commit/5ef02368d9876a1074123aa7725d6759b4f3e358) +- [Dev Deps] update `tape` [`7456037`](https://github.com/inspect-js/which-typed-array/commit/745603728c6c3da8bdddee321e8a9196f4827aa3) +- [Deps] update `available-typed-arrays` [`8a856c9`](https://github.com/inspect-js/which-typed-array/commit/8a856c9aa707c1e6f7a52e834485356b31395ea6) + +## [v1.1.1](https://github.com/inspect-js/which-typed-array/compare/v1.1.0...v1.1.1) - 2020-01-24 + +### Commits + +- [Tests] use shared travis-ci configs [`0a627d9`](https://github.com/inspect-js/which-typed-array/commit/0a627d9694d0eabdaee63b19e605584166995a79) +- [meta] add `auto-changelog` [`2a14c58`](https://github.com/inspect-js/which-typed-array/commit/2a14c58b79f72e32ef2078efb40d31a4bf8c197a) +- [meta] remove unused Makefile and associated utilities [`75f7f22`](https://github.com/inspect-js/which-typed-array/commit/75f7f222199f42618c290de363c542b11f5a5632) +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`4162327`](https://github.com/inspect-js/which-typed-array/commit/416232725e7d127cbd886af0f8988dae612a342f) +- [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` [`9b04a2a`](https://github.com/inspect-js/which-typed-array/commit/9b04a2a14c758600cffcf59485b7b3c85839c266) +- [readme] fix repo URLs, remove testling [`03ed52f`](https://github.com/inspect-js/which-typed-array/commit/03ed52f3ae4fcd35614bcda7e947b14e62009c71) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`bfbcf3e`](https://github.com/inspect-js/which-typed-array/commit/bfbcf3ec9c449bd0089ed805c01a32ba4e7e5938) +- [actions] add automatic rebasing / merge commit blocking [`cc88ac5`](https://github.com/inspect-js/which-typed-array/commit/cc88ac56bcfb71cb26c656ebde4c560a22fadd85) +- [meta] create FUNDING.yml [`acbc723`](https://github.com/inspect-js/which-typed-array/commit/acbc7230929b1256c83df28be4a456eed3e147e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `tape` [`f1ab63e`](https://github.com/inspect-js/which-typed-array/commit/f1ab63e9366027eae2e29398c035181dac164132) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` [`ac9f50b`](https://github.com/inspect-js/which-typed-array/commit/ac9f50b59558933292dff993df2e68eaa44b07e2) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`aaaa15d`](https://github.com/inspect-js/which-typed-array/commit/aaaa15dfb5bd8228c0cfb8f2aba267efb405b0a1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`602fc9a`](https://github.com/inspect-js/which-typed-array/commit/602fc9a0a7d708236f90c76f592e6a980ecde940) +- [Deps] update `available-typed-arrays`, `is-typed-array` [`b2d69b6`](https://github.com/inspect-js/which-typed-array/commit/b2d69b639bf14344d09f8512dbc060cd4f533161) +- [meta] add `funding` field [`156f613`](https://github.com/inspect-js/which-typed-array/commit/156f613d0ce547c4b15e1ae279198b66e3cef55e) + +## [v1.1.0](https://github.com/inspect-js/which-typed-array/compare/v1.0.1...v1.1.0) - 2019-02-16 + +### Commits + +- [Tests] remove `jscs` [`381c9b4`](https://github.com/inspect-js/which-typed-array/commit/381c9b4bd858da1adedf23d8555af3a3ed901a83) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v5.8`; improve matrix; newer npm breaks on older node [`7015c19`](https://github.com/inspect-js/which-typed-array/commit/7015c196ba86540b04d18d9b1d2c368909492023) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`ad67885`](https://github.com/inspect-js/which-typed-array/commit/ad678853e245986720d7650be1c974a9ff3ac814) +- [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` [`dd94bfb`](https://github.com/inspect-js/which-typed-array/commit/dd94bfb6309a92d1537352f2d1100f9e913ebc01) +- [Refactor] use an array instead of an object for storing Typed Array names [`de98bc1`](https://github.com/inspect-js/which-typed-array/commit/de98bc1d44af92909a34212e276deb5d79ac428a) +- [meta] ignore `test.html` [`06cfb1b`](https://github.com/inspect-js/which-typed-array/commit/06cfb1bc0ca7881d1bd1621fa946a16366cd6afc) +- [Tests] up to `node` `v7.0`, `v6.9`, `v4.6`; improve test matrix [`df76eaa`](https://github.com/inspect-js/which-typed-array/commit/df76eaa39b94b28147e81a89bb587e8aa3e3dba3) +- [New] add `BigInt64Array` and `BigUint64Array` [`d6bca3a`](https://github.com/inspect-js/which-typed-array/commit/d6bca3a68ccfe33f6659a24b770068e89dab1592) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`f23b45b`](https://github.com/inspect-js/which-typed-array/commit/f23b45b2796bd1f63ddddf28b4b80b9709478cb3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `semver`, `tape` [`ddb4484`](https://github.com/inspect-js/which-typed-array/commit/ddb4484adc3b45c4396632611556055f3b2f5990) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `is-callable`, `replace`, `semver`, `tape` [`4524e59`](https://github.com/inspect-js/which-typed-array/commit/4524e593e9387c185d5632696c62c1600c0b380f) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`1ec7056`](https://github.com/inspect-js/which-typed-array/commit/1ec70568565c479a6168b03e0a5aec6ec9ac5a21) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`799487d`](https://github.com/inspect-js/which-typed-array/commit/799487d666b32d1ae0d27cfededf2f5480c5faea) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`8092598`](https://github.com/inspect-js/which-typed-array/commit/8092598998a1f9f8005b4e3d299eb09c96fa2e21) +- [Tests] up to `node` `v11.10` [`a5aabb1`](https://github.com/inspect-js/which-typed-array/commit/a5aabb1910e8408f857a791253487824c7c758d3) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint`, `nsp`, `semver`, `tape` [`277be33`](https://github.com/inspect-js/which-typed-array/commit/277be331d9f05ff95644d6bcd896547ca620cd8e) +- [Tests] use `npm audit` instead of `nsp` [`ee97dc7`](https://github.com/inspect-js/which-typed-array/commit/ee97dc7c5d384d68f60ce6cb5a85d9509e75f72b) +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` [`262ffb0`](https://github.com/inspect-js/which-typed-array/commit/262ffb025facb0795b33fbd5131183bdbc0a40f6) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`d6bbcfc`](https://github.com/inspect-js/which-typed-array/commit/d6bbcfc3eea427f0156fbdcf9ae11dbf3745a755) +- [Tests] up to `node` `v6.2` [`2ff89eb`](https://github.com/inspect-js/which-typed-array/commit/2ff89eb91754146c0bc1ae689f37458d84f6e690) +- Only apps should have lockfiles [`e2bc271`](https://github.com/inspect-js/which-typed-array/commit/e2bc271e1e9a6481a2836f892177825a808c331c) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`b79e93b`](https://github.com/inspect-js/which-typed-array/commit/b79e93bf15c871ce0ff24fa3ad61001707eea463) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`016dbff`](https://github.com/inspect-js/which-typed-array/commit/016dbff8c49c32cda7ec80d86006c8a7c43bc40c) +- [Dev Deps] update `eslint`, `tape` [`6ce4bbc`](https://github.com/inspect-js/which-typed-array/commit/6ce4bbc5f6caf632cbcf9ababbfe36e1bf4093d7) +- [Tests] on `node` `v10.1` [`f0683a0`](https://github.com/inspect-js/which-typed-array/commit/f0683a0c17e039e926ecaad4c4c341cd8e5878f1) +- [Tests] up to `node` `v7.2` [`2f29cef`](https://github.com/inspect-js/which-typed-array/commit/2f29cef42d30f87259cd6687c25a79ae4651d0c9) +- [Dev Deps] update `replace` [`73b5ba6`](https://github.com/inspect-js/which-typed-array/commit/73b5ba6e87638d13553985977cab9d1bad33e242) +- [Deps] update `function-bind` [`c8a18c2`](https://github.com/inspect-js/which-typed-array/commit/c8a18c2982e6b126ecc1d4655ec2e53b05535b20) +- [Tests] on `node` `v5.12` [`812102b`](https://github.com/inspect-js/which-typed-array/commit/812102bf223422da8f7a89e5a1308214dd158571) +- [Tests] on `node` `v5.10` [`271584f`](https://github.com/inspect-js/which-typed-array/commit/271584f3a8b10ef68a7d419ac0062b444e63d07c) + +## [v1.0.1](https://github.com/inspect-js/which-typed-array/compare/v1.0.0...v1.0.1) - 2016-03-19 + +### Commits + +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` [`4a628c5`](https://github.com/inspect-js/which-typed-array/commit/4a628c520d8e080a9fa7e8218947d3b2ceedca72) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is-callable` [`8e09372`](https://github.com/inspect-js/which-typed-array/commit/8e09372ded877a191cbf777060483227d5071e84) +- [Tests] up to `node` `v5.6`, `v4.3` [`3a35bf9`](https://github.com/inspect-js/which-typed-array/commit/3a35bf9fb9c7f8e6ac1b579ed2754087351ad1a5) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`9410d5e`](https://github.com/inspect-js/which-typed-array/commit/9410d5e35db4b834827b31ea1723bbeebbcde5ba) +- [Fix] `Symbol.toStringTag` is on the super-[[Prototype]] of Float32Array, not the [[Prototype]]. [`7c40a3a`](https://github.com/inspect-js/which-typed-array/commit/7c40a3a05046bbbd188340fb19471ad913e4af05) +- [Tests] up to `node` `v5.9`, `v4.4` [`07878e7`](https://github.com/inspect-js/which-typed-array/commit/07878e7cd23d586ddb9e85a03f675e0a574db246) +- Use the object form of "author" in package.json [`65caa56`](https://github.com/inspect-js/which-typed-array/commit/65caa560d1c0c15c1080b25a9df55c7373c73f08) +- [Tests] use pretest/posttest for linting/security [`c170f7e`](https://github.com/inspect-js/which-typed-array/commit/c170f7ebcf07475d6420f2d2d2d08b1646280cd4) +- [Deps] update `is-typed-array` [`9ab324e`](https://github.com/inspect-js/which-typed-array/commit/9ab324e746a7552b2d9363777fc5c9f5c2e31ce7) +- [Deps] update `function-bind` [`a723142`](https://github.com/inspect-js/which-typed-array/commit/a723142c70a5b6a4f8f5feecc9705619590f4eeb) +- [Deps] update `is-typed-array` [`ed82ce4`](https://github.com/inspect-js/which-typed-array/commit/ed82ce4e8ecc657fc6e839d23ef6347497bc93be) +- [Tests] on `node` `v4.2` [`f581c20`](https://github.com/inspect-js/which-typed-array/commit/f581c2031990668894a8e5a08eaf01a2548e822c) + +## v1.0.0 - 2015-10-05 + +### Commits + +- Dotfiles / Makefile [`667f89a`](https://github.com/inspect-js/which-typed-array/commit/667f89a9046502594e2559dbf5568e062af3b770) +- Tests. [`a14d05e`](https://github.com/inspect-js/which-typed-array/commit/a14d05ef443d2ac678cb0567befc0abf8cf21709) +- package.json [`560b1aa`](https://github.com/inspect-js/which-typed-array/commit/560b1aa4f8bbc5d41d9cee96c93faf08c25be0e5) +- Read me [`a22096e`](https://github.com/inspect-js/which-typed-array/commit/a22096e05773f93b34e672d3f743ec6f1963bc24) +- Implementation [`0b1ae28`](https://github.com/inspect-js/which-typed-array/commit/0b1ae2848372f6256cf075d687e3722878e67aca) +- Initial commit [`4b32f0a`](https://github.com/inspect-js/which-typed-array/commit/4b32f0a9d32165d6ab91797d6971ea83cf4ce9da) diff --git a/tests/node_modules/which-typed-array/LICENSE b/tests/node_modules/which-typed-array/LICENSE new file mode 100644 index 0000000..b43df44 --- /dev/null +++ b/tests/node_modules/which-typed-array/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/tests/node_modules/which-typed-array/README.md b/tests/node_modules/which-typed-array/README.md new file mode 100644 index 0000000..cda64c0 --- /dev/null +++ b/tests/node_modules/which-typed-array/README.md @@ -0,0 +1,67 @@ +# which-typed-array [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag. + +## Example + +```js +var whichTypedArray = require('which-typed-array'); +var assert = require('assert'); + +assert.equal(false, whichTypedArray(undefined)); +assert.equal(false, whichTypedArray(null)); +assert.equal(false, whichTypedArray(false)); +assert.equal(false, whichTypedArray(true)); +assert.equal(false, whichTypedArray([])); +assert.equal(false, whichTypedArray({})); +assert.equal(false, whichTypedArray(/a/g)); +assert.equal(false, whichTypedArray(new RegExp('a', 'g'))); +assert.equal(false, whichTypedArray(new Date())); +assert.equal(false, whichTypedArray(42)); +assert.equal(false, whichTypedArray(NaN)); +assert.equal(false, whichTypedArray(Infinity)); +assert.equal(false, whichTypedArray(new Number(42))); +assert.equal(false, whichTypedArray('foo')); +assert.equal(false, whichTypedArray(Object('foo'))); +assert.equal(false, whichTypedArray(function () {})); +assert.equal(false, whichTypedArray(function* () {})); +assert.equal(false, whichTypedArray(x => x * x)); +assert.equal(false, whichTypedArray([])); + +assert.equal('Int8Array', whichTypedArray(new Int8Array())); +assert.equal('Uint8Array', whichTypedArray(new Uint8Array())); +assert.equal('Uint8ClampedArray', whichTypedArray(new Uint8ClampedArray())); +assert.equal('Int16Array', whichTypedArray(new Int16Array())); +assert.equal('Uint16Array', whichTypedArray(new Uint16Array())); +assert.equal('Int32Array', whichTypedArray(new Int32Array())); +assert.equal('Uint32Array', whichTypedArray(new Uint32Array())); +assert.equal('Float32Array', whichTypedArray(new Float32Array())); +assert.equal('Float64Array', whichTypedArray(new Float64Array())); +assert.equal('BigInt64Array', whichTypedArray(new BigInt64Array())); +assert.equal('BigUint64Array', whichTypedArray(new BigUint64Array())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/which-typed-array +[2]: http://versionbadg.es/inspect-js/which-typed-array.svg +[3]: https://travis-ci.org/inspect-js/which-typed-array.svg +[4]: https://travis-ci.org/inspect-js/which-typed-array +[5]: https://david-dm.org/inspect-js/which-typed-array.svg +[6]: https://david-dm.org/inspect-js/which-typed-array +[7]: https://david-dm.org/inspect-js/which-typed-array/dev-status.svg +[8]: https://david-dm.org/inspect-js/which-typed-array#info=devDependencies +[11]: https://nodei.co/npm/which-typed-array.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/which-typed-array.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/which-typed-array.svg +[downloads-url]: http://npm-stat.com/charts.html?package=which-typed-array diff --git a/tests/node_modules/which-typed-array/index.js b/tests/node_modules/which-typed-array/index.js new file mode 100644 index 0000000..a49a04d --- /dev/null +++ b/tests/node_modules/which-typed-array/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var forEach = require('foreach'); +var availableTypedArrays = require('available-typed-arrays'); +var callBound = require('call-bind/callBound'); + +var $toString = callBound('Object.prototype.toString'); +var hasSymbols = require('has-symbols')(); +var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; + +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var toStrTags = {}; +var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var arr = new global[typedArray](); + if (!(Symbol.toStringTag in arr)) { + throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); + } + var proto = getPrototypeOf(arr); + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD(superProto, Symbol.toStringTag); + } + toStrTags[typedArray] = descriptor.get; + } + }); +} + +var tryTypedArrays = function tryAllTypedArrays(value) { + var foundName = false; + forEach(toStrTags, function (getter, typedArray) { + if (!foundName) { + try { + var name = getter.call(value); + if (name === typedArray) { + foundName = name; + } + } catch (e) {} + } + }); + return foundName; +}; + +var isTypedArray = require('is-typed-array'); + +module.exports = function whichTypedArray(value) { + if (!isTypedArray(value)) { return false; } + if (!hasToStringTag) { return $slice($toString(value), 8, -1); } + return tryTypedArrays(value); +}; diff --git a/tests/node_modules/which-typed-array/package.json b/tests/node_modules/which-typed-array/package.json new file mode 100644 index 0000000..6f918e2 --- /dev/null +++ b/tests/node_modules/which-typed-array/package.json @@ -0,0 +1,135 @@ +{ + "_from": "which-typed-array@^1.1.2", + "_id": "which-typed-array@1.1.4", + "_inBundle": false, + "_integrity": "sha512-49E0SpUe90cjpoc7BOJwyPHRqSAd12c10Qm2amdEZrJPCY2NDxaW01zHITrem+rnETY3dwrbH3UUrUwagfCYDA==", + "_location": "/which-typed-array", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "which-typed-array@^1.1.2", + "name": "which-typed-array", + "escapedName": "which-typed-array", + "rawSpec": "^1.1.2", + "saveSpec": null, + "fetchSpec": "^1.1.2" + }, + "_requiredBy": [ + "/deep-equal" + ], + "_resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.4.tgz", + "_shasum": "8fcb7d3ee5adf2d771066fba7cf37e32fe8711ff", + "_spec": "which-typed-array@^1.1.2", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/deep-equal", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false + }, + "bugs": { + "url": "https://github.com/inspect-js/which-typed-array/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": { + "available-typed-arrays": "^1.0.2", + "call-bind": "^1.0.0", + "es-abstract": "^1.18.0-next.1", + "foreach": "^2.0.5", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.1", + "is-typed-array": "^1.1.3" + }, + "deprecated": false, + "description": "Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.15.0", + "is-callable": "^1.2.2", + "make-arrow-function": "^1.2.0", + "make-generator-function": "^2.0.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/inspect-js/which-typed-array#readme", + "keywords": [ + "array", + "TypedArray", + "typed array", + "which", + "typed", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "ES6", + "toStringTag", + "Symbol.toStringTag", + "@@toStringTag" + ], + "license": "MIT", + "main": "index.js", + "name": "which-typed-array", + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/which-typed-array.git" + }, + "scripts": { + "lint": "eslint .", + "posttest": "npx aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run tests-only && npm run test:harmony", + "test:harmony": "nyc node --harmony --es-staging test", + "tests-only": "nyc tape test", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.1.4" +} diff --git a/tests/node_modules/which-typed-array/test/index.js b/tests/node_modules/which-typed-array/test/index.js new file mode 100644 index 0000000..eafe676 --- /dev/null +++ b/tests/node_modules/which-typed-array/test/index.js @@ -0,0 +1,99 @@ +'use strict'; + +var test = require('tape'); +var whichTypedArray = require('../'); +var isCallable = require('is-callable'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; +var generators = require('make-generator-function')(); +var arrows = require('make-arrow-function').list(); +var forEach = require('foreach'); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; + +test('not arrays', function (t) { + t.test('non-number/string primitives', function (st) { + st.equal(false, whichTypedArray(), 'undefined is not typed array'); + st.equal(false, whichTypedArray(null), 'null is not typed array'); + st.equal(false, whichTypedArray(false), 'false is not typed array'); + st.equal(false, whichTypedArray(true), 'true is not typed array'); + st.end(); + }); + + t.equal(false, whichTypedArray({}), 'object is not typed array'); + t.equal(false, whichTypedArray(/a/g), 'regex literal is not typed array'); + t.equal(false, whichTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); + t.equal(false, whichTypedArray(new Date()), 'new Date() is not typed array'); + + t.test('numbers', function (st) { + st.equal(false, whichTypedArray(42), 'number is not typed array'); + st.equal(false, whichTypedArray(Object(42)), 'number object is not typed array'); + st.equal(false, whichTypedArray(NaN), 'NaN is not typed array'); + st.equal(false, whichTypedArray(Infinity), 'Infinity is not typed array'); + st.end(); + }); + + t.test('strings', function (st) { + st.equal(false, whichTypedArray('foo'), 'string primitive is not typed array'); + st.equal(false, whichTypedArray(Object('foo')), 'string object is not typed array'); + st.end(); + }); + + t.end(); +}); + +test('Functions', function (t) { + t.equal(false, whichTypedArray(function () {}), 'function is not typed array'); + t.end(); +}); + +test('Generators', { skip: generators.length === 0 }, function (t) { + forEach(generators, function (genFn) { + t.equal(false, whichTypedArray(genFn), 'generator function ' + genFn + ' is not typed array'); + }); + t.end(); +}); + +test('Arrow functions', { skip: arrows.length === 0 }, function (t) { + forEach(arrows, function (arrowFn) { + t.equal(false, whichTypedArray(arrowFn), 'arrow function ' + arrowFn + ' is not typed array'); + }); + t.end(); +}); + +test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { + forEach(typedArrayNames, function (typedArray) { + if (typeof global[typedArray] === 'function') { + var fakeTypedArray = []; + fakeTypedArray[Symbol.toStringTag] = typedArray; + t.equal(false, whichTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); + +test('Typed Arrays', function (t) { + forEach(typedArrayNames, function (typedArray) { + var TypedArray = global[typedArray]; + if (isCallable(TypedArray)) { + var arr = new TypedArray(10); + t.equal(typedArray, whichTypedArray(arr), 'new ' + typedArray + '(10) is typed array of type ' + typedArray); + } else { + t.comment('# SKIP ' + typedArray + ' is not supported'); + } + }); + t.end(); +}); diff --git a/tests/node_modules/wrappy/LICENSE b/tests/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/tests/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/tests/node_modules/wrappy/README.md b/tests/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/tests/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/tests/node_modules/wrappy/package.json b/tests/node_modules/wrappy/package.json new file mode 100644 index 0000000..fd0606d --- /dev/null +++ b/tests/node_modules/wrappy/package.json @@ -0,0 +1,59 @@ +{ + "_from": "wrappy@1", + "_id": "wrappy@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "_location": "/wrappy", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "wrappy@1", + "name": "wrappy", + "escapedName": "wrappy", + "rawSpec": "1", + "saveSpec": null, + "fetchSpec": "1" + }, + "_requiredBy": [ + "/inflight", + "/once" + ], + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "_shasum": "b5243d8f3ec1aa35f1364605bc0d1036e30ab69f", + "_spec": "wrappy@1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/inflight", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Callback wrapping utility", + "devDependencies": { + "tap": "^2.3.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "wrappy.js" + ], + "homepage": "https://github.com/npm/wrappy", + "license": "ISC", + "main": "wrappy.js", + "name": "wrappy", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "version": "1.0.2" +} diff --git a/tests/node_modules/wrappy/wrappy.js b/tests/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/tests/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/tests/node_modules/xtend/.jshintrc b/tests/node_modules/xtend/.jshintrc new file mode 100644 index 0000000..77887b5 --- /dev/null +++ b/tests/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/tests/node_modules/xtend/LICENSE b/tests/node_modules/xtend/LICENSE new file mode 100644 index 0000000..0099f4f --- /dev/null +++ b/tests/node_modules/xtend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2012-2014 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tests/node_modules/xtend/README.md b/tests/node_modules/xtend/README.md new file mode 100644 index 0000000..4a2703c --- /dev/null +++ b/tests/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: "c" +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licensed + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/tests/node_modules/xtend/immutable.js b/tests/node_modules/xtend/immutable.js new file mode 100644 index 0000000..94889c9 --- /dev/null +++ b/tests/node_modules/xtend/immutable.js @@ -0,0 +1,19 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/tests/node_modules/xtend/mutable.js b/tests/node_modules/xtend/mutable.js new file mode 100644 index 0000000..72debed --- /dev/null +++ b/tests/node_modules/xtend/mutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/tests/node_modules/xtend/package.json b/tests/node_modules/xtend/package.json new file mode 100644 index 0000000..5a2bb56 --- /dev/null +++ b/tests/node_modules/xtend/package.json @@ -0,0 +1,86 @@ +{ + "_from": "xtend@~4.0.1", + "_id": "xtend@4.0.2", + "_inBundle": false, + "_integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "_location": "/xtend", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "xtend@~4.0.1", + "name": "xtend", + "escapedName": "xtend", + "rawSpec": "~4.0.1", + "saveSpec": null, + "fetchSpec": "~4.0.1" + }, + "_requiredBy": [ + "/through2" + ], + "_resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "_shasum": "bb72779f5fa465186b1f438f674fa347fdb5db54", + "_spec": "xtend@~4.0.1", + "_where": "/home/lilleman/go/src/gitlab.larvit.se/power-plan/auth/tests/node_modules/through2", + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "extend like a boss", + "devDependencies": { + "tape": "~1.1.0" + }, + "engines": { + "node": ">=0.4" + }, + "homepage": "https://github.com/Raynos/xtend", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "license": "MIT", + "main": "immutable", + "name": "xtend", + "repository": { + "type": "git", + "url": "git://github.com/Raynos/xtend.git" + }, + "scripts": { + "test": "node test" + }, + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "version": "4.0.2" +} diff --git a/tests/node_modules/xtend/test.js b/tests/node_modules/xtend/test.js new file mode 100644 index 0000000..b895b42 --- /dev/null +++ b/tests/node_modules/xtend/test.js @@ -0,0 +1,103 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("null prototype", function(assert) { + var a = { a: "foo" } + var b = Object.create(null) + b.b = "bar"; + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("null prototype mutable", function (assert) { + var a = { foo: "bar" } + var b = Object.create(null) + b.bar = "baz"; + + mutableExtend(a, b) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("prototype pollution", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + extend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) + +test("prototype pollution mutable", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + mutableExtend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) diff --git a/tests/package-lock.json b/tests/package-lock.json new file mode 100644 index 0000000..71bed70 --- /dev/null +++ b/tests/package-lock.json @@ -0,0 +1,1262 @@ +{ + "name": "tests", + "version": "0.1.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@sindresorhus/is": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.0.1.tgz", + "integrity": "sha512-Qm9hBEBu18wt1PO2flE7LPb30BHMQt1eQgbV76YntdNk73XZGpn3izvGTYxbGgzXKgbCjiia0uxTd3aTNQrY/g==" + }, + "@szmarczak/http-timer": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.5.tgz", + "integrity": "sha512-PyRA9sm1Yayuj5OIoJ1hGt2YISX45w9WcFbh6ddT0Z/0yaFxOtGLInr4jUfU1EAFVs0Yfyfev4RNwBlUaHdlDQ==", + "requires": { + "defer-to-connect": "^2.0.0" + } + }, + "@types/cacheable-request": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.1.tgz", + "integrity": "sha512-ykFq2zmBGOCbpIXtoVbz4SKY5QriWPh3AjyU4G74RYbtt5yOc5OfaY75ftjg7mikMOla1CTGpX3lLbuJh8DTrQ==", + "requires": { + "@types/http-cache-semantics": "*", + "@types/keyv": "*", + "@types/node": "*", + "@types/responselike": "*" + } + }, + "@types/http-cache-semantics": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz", + "integrity": "sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==" + }, + "@types/keyv": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.1.tgz", + "integrity": "sha512-MPtoySlAZQ37VoLaPcTHCu1RWJ4llDkULYZIzOYxlhxBqYPB0RsRlmMU0R6tahtFe27mIdkHV+551ZWV4PLmVw==", + "requires": { + "@types/node": "*" + } + }, + "@types/node": { + "version": "15.12.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-15.12.4.tgz", + "integrity": "sha512-zrNj1+yqYF4WskCMOHwN+w9iuD12+dGm0rQ35HLl9/Ouuq52cEtd0CH9qMgrdNmi5ejC1/V7vKEXYubB+65DkA==" + }, + "@types/responselike": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", + "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", + "requires": { + "@types/node": "*" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, + "anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "available-typed-arrays": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.4.tgz", + "integrity": "sha512-SA5mXJWrId1TaQjfxUYghbqQ/hYioKmLJvPJyDuYRtXXenFNMjj4hSSt1Cf1xsuXSXrtxrVC5Ot4eU6cOtBDdA==" + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "buffer-shims": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", + "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=" + }, + "cacheable-lookup": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==" + }, + "cacheable-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", + "integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", + "requires": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" + } + }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "chokidar": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz", + "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==", + "requires": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "fsevents": "~2.3.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + } + }, + "clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "requires": { + "mimic-response": "^1.0.0" + } + }, + "commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "requires": { + "mimic-response": "^3.1.0" + }, + "dependencies": { + "mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==" + } + } + }, + "deep-equal": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.0.5.tgz", + "integrity": "sha512-nPiRgmbAtm1a3JsnLCf6/SLfXcjyN5v8L1TXzdCmHrXJ4hx+gW/w1YCcn7z8gJtSiDArZCgYtbao3QqLm/N1Sw==", + "requires": { + "call-bind": "^1.0.0", + "es-get-iterator": "^1.1.1", + "get-intrinsic": "^1.0.1", + "is-arguments": "^1.0.4", + "is-date-object": "^1.0.2", + "is-regex": "^1.1.1", + "isarray": "^2.0.5", + "object-is": "^1.1.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "regexp.prototype.flags": "^1.3.0", + "side-channel": "^1.0.3", + "which-boxed-primitive": "^1.0.1", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.2" + } + }, + "defer-to-connect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", + "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==" + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "requires": { + "object-keys": "^1.0.12" + } + }, + "defined": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", + "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=" + }, + "dotenv": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz", + "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==" + }, + "dotignore": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/dotignore/-/dotignore-0.1.2.tgz", + "integrity": "sha512-UGGGWfSauusaVJC+8fgV+NVvBXkCTmVv7sk6nojDZZvuOUNGUy0Zk4UpHQD6EDjS0jpBwcACvH4eofvyzBcRDw==", + "requires": { + "minimatch": "^3.0.4" + } + }, + "duplexer": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", + "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==" + }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, + "es-abstract": { + "version": "1.18.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", + "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", + "requires": { + "call-bind": "^1.0.2", + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "get-intrinsic": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", + "is-negative-zero": "^2.0.1", + "is-regex": "^1.1.3", + "is-string": "^1.0.6", + "object-inspect": "^1.10.3", + "object-keys": "^1.1.1", + "object.assign": "^4.1.2", + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.1" + } + }, + "es-get-iterator": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.2.tgz", + "integrity": "sha512-+DTO8GYwbMCwbywjimwZMHp8AuYXOS2JZFWoi2AlPOS3ebnII9w/NLpNZtA7A0YLaVDw+O7KFCeoIV7OPvM7hQ==", + "requires": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.0", + "has-symbols": "^1.0.1", + "is-arguments": "^1.1.0", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.5", + "isarray": "^2.0.5" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "figures": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", + "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", + "requires": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "requires": { + "is-callable": "^1.1.3" + } + }, + "foreach": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", + "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "optional": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + } + }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "requires": { + "pump": "^3.0.0" + } + }, + "glob": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "got": { + "version": "11.8.2", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.2.tgz", + "integrity": "sha512-D0QywKgIe30ODs+fm8wMZiAcZjypcCodPNuMz5H9Mny7RJ+IjJ10BdmGW7OM7fHXP+O7r6ZwapQ/YQmMSvB0UQ==", + "requires": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.1", + "decompress-response": "^6.0.0", + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-bigints": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", + "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==" + }, + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==" + }, + "http-cache-semantics": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", + "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==" + }, + "http2-wrapper": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", + "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", + "requires": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.0.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "is-arguments": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.0.tgz", + "integrity": "sha512-1Ij4lOMPl/xB5kBDn7I+b2ttPMKa8szhEIrXDuXQD/oe3HJLTLhqhgGspwgyGd6MOywBUqVvYicF72lkgDnIHg==", + "requires": { + "call-bind": "^1.0.0" + } + }, + "is-bigint": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", + "integrity": "sha512-0JV5+SOCQkIdzjBK9buARcV804Ddu7A0Qet6sHi3FimE9ne6m4BGQZfRn+NZiXbBk4F4XmHfDZIipLj9pX8dSA==" + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-boolean-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", + "integrity": "sha512-bXdQWkECBUIAcCkeH1unwJLIpZYaa5VvuygSyS/c2lf719mTKZDU5UdDRlpd01UjADgmW8RfqaP+mRaVPdr/Ng==", + "requires": { + "call-bind": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==" + }, + "is-core-module": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz", + "integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==", + "requires": { + "has": "^1.0.3" + } + }, + "is-date-object": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.4.tgz", + "integrity": "sha512-/b4ZVsG7Z5XVtIxs/h9W8nvfLgSAyKYdtGWQLbqy6jA1icmgjf8WCoTKgeS4wy5tYaPePouzFMANbnj94c2Z+A==" + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" + }, + "is-finite": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.1.0.tgz", + "integrity": "sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w==" + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.2.tgz", + "integrity": "sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==" + }, + "is-negative-zero": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", + "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==" + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "is-number-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.5.tgz", + "integrity": "sha512-RU0lI/n95pMoUKu9v1BZP5MBcZuNSVJkMkAG2dJqC4z2GlkGUNeH68SuHuBKBD/XFe+LHZ+f9BKkLET60Niedw==" + }, + "is-regex": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", + "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.2" + } + }, + "is-set": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.2.tgz", + "integrity": "sha512-+2cnTEZeY5z/iXGbLhPrOAaK/Mau5k5eXq9j14CpRTftq0pAJu2MwVRSZhyZWBzx3o6X795Lz6Bpb6R0GKf37g==" + }, + "is-string": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", + "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==" + }, + "is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "requires": { + "has-symbols": "^1.0.2" + } + }, + "is-typed-array": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.5.tgz", + "integrity": "sha512-S+GRDgJlR3PyEbsX/Fobd9cqpZBuvUS+8asRqYDMLCb2qMzt1oz5m5oxQCxOgUDxiWsOVNi4yaF+/uvdlHlYug==", + "requires": { + "available-typed-arrays": "^1.0.2", + "call-bind": "^1.0.2", + "es-abstract": "^1.18.0-next.2", + "foreach": "^2.0.5", + "has-symbols": "^1.0.1" + } + }, + "is-weakmap": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.1.tgz", + "integrity": "sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA==" + }, + "is-weakset": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.1.tgz", + "integrity": "sha512-pi4vhbhVHGLxohUw7PhGsueT4vRGFoXhP7+RGN0jKIv9+8PWYCQTqtADngrxOm2g46hoH0+g8uZZBzMrvVGDmw==" + }, + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==" + }, + "json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==" + }, + "jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + } + }, + "jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "requires": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "keyv": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.0.3.tgz", + "integrity": "sha512-zdGa2TOpSZPq5mU6iowDARnMBZgtCqJ11dJROFi6tg6kTn4nuUdU09lFyLFSaHrWqpIJ+EBq4E8/Dc0Vx5vLdA==", + "requires": { + "json-buffer": "3.0.1" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" + }, + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" + }, + "normalize-url": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" + }, + "object-inspect": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", + "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==" + }, + "object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "p-cancelable": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", + "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==" + }, + "parse-ms": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-1.0.1.tgz", + "integrity": "sha1-VjRtR0nXjyNDDKDHE4UK75GqNh0=" + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" + }, + "picomatch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==" + }, + "plur": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/plur/-/plur-1.0.0.tgz", + "integrity": "sha1-24XGgU9eXlo7Se/CjWBP7GKXUVY=" + }, + "pretty-ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-2.1.0.tgz", + "integrity": "sha1-QlfCVt8/sLRR1q/6qwIYhBJpgdw=", + "requires": { + "is-finite": "^1.0.1", + "parse-ms": "^1.0.0", + "plur": "^1.0.0" + } + }, + "process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=" + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==" + }, + "re-emitter": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/re-emitter/-/re-emitter-1.1.3.tgz", + "integrity": "sha1-+p4xn/3u6zWycpbvDz03TawvUqc=" + }, + "readable-stream": { + "version": "2.2.9", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.2.9.tgz", + "integrity": "sha1-z3jsb0ptHrQ9JkiMrJfwQudLf8g=", + "requires": { + "buffer-shims": "~1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~1.0.0", + "util-deprecate": "~1.0.1" + }, + "dependencies": { + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + } + } + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "requires": { + "picomatch": "^2.2.1" + } + }, + "regexp.prototype.flags": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.3.1.tgz", + "integrity": "sha512-JiBdRBq91WlY7uRJ0ds7R+dU02i6LKi8r3BuQhNXn+kmeLN+EfHhfjqMRis1zJxnlu88hq/4dx0P2OP3APRTOA==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" + }, + "resolve": { + "version": "2.0.0-next.3", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.3.tgz", + "integrity": "sha512-W8LucSynKUIDu9ylraa7ueVZ7hc0uAgJBxVsQSKOXOyle8a93qXhcz+XAXZ8bIq2d6i4Ehddn6Evt+0/UwKk6Q==", + "requires": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + }, + "resolve-alpn": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.1.2.tgz", + "integrity": "sha512-8OyfzhAtA32LVUsJSke3auIyINcwdh5l3cvYKdKO0nvsYSKuiLfTM5i78PJswFPT8y6cPW+L1v6/hE95chcpDA==" + }, + "responselike": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.0.tgz", + "integrity": "sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw==", + "requires": { + "lowercase-keys": "^2.0.0" + } + }, + "resumer": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/resumer/-/resumer-0.0.0.tgz", + "integrity": "sha1-8ej0YeQGS6Oegq883CqMiT0HZ1k=", + "requires": { + "through": "~2.3.4" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "requires": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + } + }, + "split": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/split/-/split-1.0.0.tgz", + "integrity": "sha1-xDlc5oOrzSVLwo/h2rtuXCfc/64=", + "requires": { + "through": "2" + } + }, + "string.prototype.trim": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.4.tgz", + "integrity": "sha512-hWCk/iqf7lp0/AgTF7/ddO1IWtSNPASjlzCicV5irAVdE1grjsneK26YG6xACMBEdCvO8fUST0UzDMh/2Qy+9Q==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0-next.2" + } + }, + "string.prototype.trimend": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string.prototype.trimstart": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "string_decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", + "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + }, + "tap-out": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tap-out/-/tap-out-2.1.0.tgz", + "integrity": "sha512-LJE+TBoVbOWhwdz4+FQk40nmbIuxJLqaGvj3WauQw3NYYU5TdjoV3C0x/yq37YAvVyi+oeBXmWnxWSjJ7IEyUw==", + "requires": { + "re-emitter": "1.1.3", + "readable-stream": "2.2.9", + "split": "1.0.0", + "trim": "0.0.1" + } + }, + "tap-spec": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/tap-spec/-/tap-spec-5.0.0.tgz", + "integrity": "sha512-zMDVJiE5I6Y4XGjlueGXJIX2YIkbDN44broZlnypT38Hj/czfOXrszHNNJBF/DXR8n+x6gbfSx68x04kIEHdrw==", + "requires": { + "chalk": "^1.0.0", + "duplexer": "^0.1.1", + "figures": "^1.4.0", + "lodash": "^4.17.10", + "pretty-ms": "^2.1.0", + "repeat-string": "^1.5.2", + "tap-out": "^2.1.0", + "through2": "^2.0.0" + } + }, + "tape": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/tape/-/tape-5.2.2.tgz", + "integrity": "sha512-grXrzPC1ly2kyTMKdqxh5GiLpb0BpNctCuecTB0psHX4Gu0nc+uxWR4xKjTh/4CfQlH4zhvTM2/EXmHXp6v/uA==", + "requires": { + "call-bind": "^1.0.2", + "deep-equal": "^2.0.5", + "defined": "^1.0.0", + "dotignore": "^0.1.2", + "for-each": "^0.3.3", + "glob": "^7.1.6", + "has": "^1.0.3", + "inherits": "^2.0.4", + "is-regex": "^1.1.2", + "minimist": "^1.2.5", + "object-inspect": "^1.9.0", + "object-is": "^1.1.5", + "object.assign": "^4.1.2", + "resolve": "^2.0.0-next.3", + "resumer": "^0.0.0", + "string.prototype.trim": "^1.2.4", + "through": "^2.3.8" + } + }, + "tape-es": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/tape-es/-/tape-es-1.2.15.tgz", + "integrity": "sha512-b8saVSzLFvxPro394o718mAN37iMvHrOt9XLx+caZIewBeA2Q4LobUtW2Gjv5JMsrm9VrZ4L9+4xRVUyUokmpQ==", + "requires": { + "chokidar": "^3.5.1", + "commander": "^4.1.1", + "glob": "^7.1.6", + "tape": "^4.13.3" + }, + "dependencies": { + "deep-equal": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.1.tgz", + "integrity": "sha512-yd9c5AdiqVcR+JjcwUQb9DkhJc8ngNr0MahEBGvDiJw8puWab2yZlh+nkasOnZP+EGTAP6rRp2JzJhJZzvNF8g==", + "requires": { + "is-arguments": "^1.0.4", + "is-date-object": "^1.0.1", + "is-regex": "^1.0.4", + "object-is": "^1.0.1", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.2.0" + } + }, + "is-regex": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz", + "integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==", + "requires": { + "has": "^1.0.3" + } + }, + "object-inspect": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz", + "integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==" + }, + "resolve": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", + "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", + "requires": { + "path-parse": "^1.0.6" + } + }, + "tape": { + "version": "4.13.3", + "resolved": "https://registry.npmjs.org/tape/-/tape-4.13.3.tgz", + "integrity": "sha512-0/Y20PwRIUkQcTCSi4AASs+OANZZwqPKaipGCEwp10dQMipVvSZwUUCi01Y/OklIGyHKFhIcjock+DKnBfLAFw==", + "requires": { + "deep-equal": "~1.1.1", + "defined": "~1.0.0", + "dotignore": "~0.1.2", + "for-each": "~0.3.3", + "function-bind": "~1.1.1", + "glob": "~7.1.6", + "has": "~1.0.3", + "inherits": "~2.0.4", + "is-regex": "~1.0.5", + "minimist": "~1.2.5", + "object-inspect": "~1.7.0", + "resolve": "~1.17.0", + "resumer": "~0.0.0", + "string.prototype.trim": "~1.2.1", + "through": "~2.3.8" + } + } + } + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + }, + "dependencies": { + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + }, + "trim": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/trim/-/trim-0.0.1.tgz", + "integrity": "sha1-WFhUf2spB1fulczMZm+1AITEYN0=" + }, + "unbox-primitive": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", + "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "requires": { + "function-bind": "^1.1.1", + "has-bigints": "^1.0.1", + "has-symbols": "^1.0.2", + "which-boxed-primitive": "^1.0.2" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "requires": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + } + }, + "which-collection": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.1.tgz", + "integrity": "sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A==", + "requires": { + "is-map": "^2.0.1", + "is-set": "^2.0.1", + "is-weakmap": "^2.0.1", + "is-weakset": "^2.0.1" + } + }, + "which-typed-array": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.4.tgz", + "integrity": "sha512-49E0SpUe90cjpoc7BOJwyPHRqSAd12c10Qm2amdEZrJPCY2NDxaW01zHITrem+rnETY3dwrbH3UUrUwagfCYDA==", + "requires": { + "available-typed-arrays": "^1.0.2", + "call-bind": "^1.0.0", + "es-abstract": "^1.18.0-next.1", + "foreach": "^2.0.5", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.1", + "is-typed-array": "^1.1.3" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" + } + } +} diff --git a/tests/package.json b/tests/package.json new file mode 100644 index 0000000..2b150f2 --- /dev/null +++ b/tests/package.json @@ -0,0 +1,20 @@ +{ + "name": "tests", + "version": "0.1.0", + "description": "Integration tests for the auth app", + "type": "module", + "main": "index.js", + "scripts": { + "test": "tape-es \"test-cases/*.js\" | tap-spec" + }, + "author": "Lilleman", + "license": "ISC", + "dependencies": { + "dotenv": "10.0.0", + "got": "11.8.2", + "jsonwebtoken": "8.5.1", + "tap-spec": "5.0.0", + "tape": "5.2.2", + "tape-es": "1.2.15" + } +} diff --git a/tests/test-cases/00start.js b/tests/test-cases/00start.js new file mode 100644 index 0000000..315a7cb --- /dev/null +++ b/tests/test-cases/00start.js @@ -0,0 +1,14 @@ +import {} from 'dotenv/config'; +import got from 'got'; +import test from 'tape'; +import setConfig from '../test-helpers/config.js'; + +test('test-cases/00start.js: Wait for auth API to be ready', async t => { + setConfig({ printConfig: true }); + + const backendHealthCheck = await got(process.env.AUTH_URL, { retry: 2000 }); + + t.equal(backendHealthCheck.statusCode, 200, 'Auth API should answer with status code 200'); + + t.end(); +}); diff --git a/tests/test-cases/01basic.js b/tests/test-cases/01basic.js new file mode 100644 index 0000000..7c9f861 --- /dev/null +++ b/tests/test-cases/01basic.js @@ -0,0 +1,48 @@ +import got from 'got'; +import jwt from 'jsonwebtoken' +import setConfig from '../test-helpers/config.js'; +import test from 'tape'; + +test('test-cases/01basic.js: Basic stuff', async t => { + t.comment('Authing with configurated API KEY'); + + // Wrong API key + try { + await got.post(`${process.env.AUTH_URL}/auth/api-key`, { + json: 'a09ifa908wjf92fowreigaoijfaosidfđ@€£đawef', + responseType: 'json', + }); + + t.fail('Calling /auth/api-key with wrong api-key should result in a 403'); + } catch (err) { + t.equal(err.message, 'Response code 403 (Forbidden)', 'Calling /auth/api-key with wrong api-key should result in a 403') + } + + const authRes = await got.post(`${process.env.AUTH_URL}/auth/api-key`, { + json: 'hihi', + responseType: 'json', + }); + t.notEqual(authRes.body.jwt, undefined, 'The body should include a jwt key'); + t.notEqual(authRes.body.renewalToken, undefined, 'The body should include a renewalToken'); + + const adminJWT = jwt.verify(authRes.body.jwt, process.env.JWT_SHARED_SECRET); + t.equal(adminJWT.accountName, 'admin', 'The verified account name should be "admin"'); + + t.comment('GETting the admin account, with the token we just obtained'); + + try { + await got(`${process.env.AUTH_URL}/account/${adminJWT.accountId}`); + t.fail('Calling /account/{id} without proper auth token should give 403'); + } catch (err) { + t.equal(err.message, 'Response code 403 (Forbidden)', 'Calling /account/{id} without proper auth token should give 403'); + } + + const accountRes = await got(`${process.env.AUTH_URL}/account/${adminJWT.accountId}`, { + headers: { 'Authorization': `bearer ${authRes.body.jwt}`}, + responseType: 'json', + }); + + t.equal(adminJWT.accountId, accountRes.body.id, 'The account ids should match'); + + t.end(); +}); diff --git a/tests/test-helpers/config.js b/tests/test-helpers/config.js new file mode 100644 index 0000000..4fc2dbd --- /dev/null +++ b/tests/test-helpers/config.js @@ -0,0 +1,26 @@ +import { fileURLToPath } from 'url'; +import {} from 'dotenv/config'; +import path from 'path'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default function setConfig({ printConfig = false } = { printConfig: false }) { + if (!process.env.ADMIN_API_KEY) { + console.error('ENV ADMIN_API_KEY is required'); + throw new Error('ENV ADMIN_API_KEY is required'); + } + + if (!process.env.AUTH_URL) process.env.AUTH_URL = 'http://localhost:4000'; + + if (!process.env.JWT_SHARED_SECRET) { + console.error('ENV JWT_SHARED_SECRET is required'); + throw new Error('ENV JWT_SHARED_SECRET is required'); + } + + if (printConfig) { + console.log('Starting with ENV:'); + console.log('ADMIN_API_KEY', '***') + console.log('AUTH_URL', process.env.AUTH_URL); + console.log('JWT_SHARED_SECRET', '***') + } +}