new license file version [CI SKIP]
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"SubscriptionLog.js","sources":["../../src/internal/testing/SubscriptionLog.ts"],"names":[],"mappings":";;AAAA;IACE,yBAAmB,eAAuB,EACvB,iBAAoD;QAApD,kCAAA,EAAA,oBAA4B,MAAM,CAAC,iBAAiB;QADpD,oBAAe,GAAf,eAAe,CAAQ;QACvB,sBAAiB,GAAjB,iBAAiB,CAAmC;IACvE,CAAC;IACH,sBAAC;AAAD,CAAC,AAJD,IAIC;AAJY,0CAAe"}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "macos-release",
|
||||
"version": "2.5.0",
|
||||
"description": "Get the name and version of a macOS release from the Darwin version",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/macos-release",
|
||||
"funding": "https://github.com/sponsors/sindresorhus",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava && tsd"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"macos",
|
||||
"os",
|
||||
"darwin",
|
||||
"operating",
|
||||
"system",
|
||||
"platform",
|
||||
"name",
|
||||
"title",
|
||||
"release",
|
||||
"version"
|
||||
],
|
||||
"devDependencies": {
|
||||
"ava": "^1.4.1",
|
||||
"tsd": "^0.7.1",
|
||||
"xo": "^0.24.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mergeMapTo.js","sources":["../src/operator/mergeMapTo.ts"],"names":[],"mappings":";;;;;AAAA,qDAAgD"}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"mergeScan.js","sources":["../../../src/internal/operators/mergeScan.ts"],"names":[],"mappings":"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"}
|
||||
@@ -0,0 +1 @@
|
||||
export * from 'rxjs-compat/operator/min';
|
||||
@@ -0,0 +1,10 @@
|
||||
// These are all the basic types that's compatible with all supported TypeScript versions.
|
||||
export * from '../base';
|
||||
|
||||
// These are special types that require at least TypeScript 4.1.
|
||||
export {CamelCase} from './camel-case';
|
||||
export {KebabCase} from './kebab-case';
|
||||
export {PascalCase} from './pascal-case';
|
||||
export {SnakeCase} from './snake-case';
|
||||
export {DelimiterCase} from './delimiter-case';
|
||||
export {Get} from './get';
|
||||
@@ -0,0 +1,3 @@
|
||||
import { Observable } from '../Observable';
|
||||
import { SchedulerLike } from '../types';
|
||||
export declare function fromPromise<T>(input: PromiseLike<T>, scheduler?: SchedulerLike): Observable<T>;
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var AnimationFrameAction_1 = require("./AnimationFrameAction");
|
||||
var AnimationFrameScheduler_1 = require("./AnimationFrameScheduler");
|
||||
exports.animationFrameScheduler = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
|
||||
exports.animationFrame = exports.animationFrameScheduler;
|
||||
//# sourceMappingURL=animationFrame.js.map
|
||||
@@ -0,0 +1 @@
|
||||
module.exports={C:{"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0.01182,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0.00394,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0.00788,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0.00394,"96":0,"97":0,"98":0.00394,"99":0.00394,"100":0,"101":0,"102":0.0197,"103":0,"104":0,"105":0,"106":0,"107":0.22458,"108":0.10244,"109":0.05122,"110":0,"111":0,"3.5":0,"3.6":0},D:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0.01182,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0.05516,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0.00394,"68":0.00394,"69":0,"70":0,"71":0.00394,"72":0.01576,"73":0.00788,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0.00788,"80":0,"81":0.00788,"83":0.00394,"84":0.00394,"85":0.00394,"86":0.00394,"87":0.01576,"88":0.00788,"89":0.00788,"90":0.00394,"91":0.00394,"92":0.00394,"93":0.00394,"94":0.11426,"95":0,"96":0.00394,"97":0.00788,"98":0.00788,"99":0.00394,"100":0.03546,"101":0.05122,"102":0.01182,"103":0.01576,"104":0.02758,"105":0.01182,"106":0.01576,"107":4.62556,"108":6.107,"109":2.05668,"110":0,"111":0.00394,"112":0},F:{"9":0,"11":0,"12":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0.00394,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0.00788,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"60":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0.00394,"74":0,"75":0.00394,"76":0,"77":0,"78":0,"79":0.00788,"80":0,"81":0,"82":0,"83":0,"84":0.00394,"85":0.0394,"86":0,"87":0,"88":0,"89":0,"90":0.01182,"91":0,"92":0,"93":0.07486,"94":0.36642,"9.5-9.6":0,"10.0-10.1":0,"10.5":0,"10.6":0,"11.1":0,"11.5":0,"11.6":0,"12.1":0},B:{"12":0,"13":0,"14":0,"15":0.00788,"16":0,"17":0,"18":0,"79":0,"80":0,"81":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0.00394,"104":0,"105":0,"106":0,"107":0.00394,"108":0.1182,"109":0.10638},E:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0.00394,"15":0,_:"0","3.1":0,"3.2":0,"5.1":0.0394,"6.1":0,"7.1":0,"9.1":0,"10.1":0,"11.1":0,"12.1":0.00394,"13.1":0.00788,"14.1":0.01182,"15.1":0.00394,"15.2-15.3":0,"15.4":0.00394,"15.5":0.03546,"15.6":0.05122,"16.0":0.00788,"16.1":0.06304,"16.2":0.07092,"16.3":0.00394},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0,"5.0-5.1":0.0015,"6.0-6.1":0,"7.0-7.1":0.00299,"8.1-8.4":0,"9.0-9.2":0.00299,"9.3":0.01196,"10.0-10.2":0,"10.3":0.01346,"11.0-11.2":0.00897,"11.3-11.4":0,"12.0-12.1":0.00299,"12.2-12.5":0.28856,"13.0-13.1":0.00449,"13.2":0.00598,"13.3":0.01495,"13.4-13.7":0.06878,"14.0-14.4":0.305,"14.5-14.8":0.5517,"15.0-15.1":0.20633,"15.2-15.3":0.36032,"15.4":0.46647,"15.5":0.86866,"15.6":1.17815,"16.0":3.46267,"16.1":3.00666,"16.2":2.52225,"16.3":0.25267},P:{"4":0.21272,"5.0-5.4":0.01013,"6.2-6.4":0.03039,"7.2-7.4":0.22285,"8.2":0.01013,"9.2":0.02026,"10.1":0.01013,"11.1-11.2":0.06078,"12.0":0.02026,"13.0":0.06078,"14.0":0.07091,"15.0":0.04052,"16.0":0.90151,"17.0":0.13168,"18.0":0.18233,"19.0":1.49915},I:{"0":0,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0.00168,"4.2-4.3":0.00168,"4.4":0,"4.4.3-4.4.4":0.01846},K:{_:"0 10 11 12 11.1 11.5 12.1"},A:{"6":0,"7":0,"8":0,"9":0,"10":0,"11":0.00788,"5.5":0},J:{"7":0,"10":0},N:{"10":0,"11":0},R:{_:"0"},M:{"0":0.0303},Q:{"13.1":0},O:{"0":0.41208},H:{"0":0.32128},L:{"0":64.40302},S:{"2.5":0}};
|
||||
@@ -0,0 +1,34 @@
|
||||
# array-union [](https://travis-ci.org/sindresorhus/array-union)
|
||||
|
||||
> Create an array of unique values, in order, from the input arrays
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install array-union
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const arrayUnion = require('array-union');
|
||||
|
||||
arrayUnion([1, 1, 2, 3], [2, 3]);
|
||||
//=> [1, 2, 3]
|
||||
|
||||
arrayUnion(['foo', 'foo', 'bar']);
|
||||
//=> ['foo', 'bar']
|
||||
|
||||
arrayUnion(['🐱', '🦄', '🐻'], ['🦄', '🌈']);
|
||||
//=> ['🐱', '🦄', '🐻', '🌈']
|
||||
|
||||
arrayUnion(['🐱', '🦄'], ['🐻', '🦄'], ['🐶', '🌈', '🌈']);
|
||||
//=> ['🐱', '🦄', '🐻', '🐶', '🌈']
|
||||
```
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Sindre Sorhus](https://sindresorhus.com)
|
||||
@@ -0,0 +1 @@
|
||||
import 'rxjs-compat/add/operator/takeUntil';
|
||||
@@ -0,0 +1,869 @@
|
||||
'use strict'
|
||||
|
||||
const tape = require('tape')
|
||||
const crypto = require('crypto')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const BufferList = require('../')
|
||||
const { Buffer } = require('buffer')
|
||||
|
||||
const encodings =
|
||||
('hex utf8 utf-8 ascii binary base64' +
|
||||
(process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ')
|
||||
|
||||
require('./indexOf')
|
||||
require('./isBufferList')
|
||||
require('./convert')
|
||||
|
||||
tape('single bytes from single buffer', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
|
||||
t.equal(bl.length, 4)
|
||||
t.equal(bl.get(-1), undefined)
|
||||
t.equal(bl.get(0), 97)
|
||||
t.equal(bl.get(1), 98)
|
||||
t.equal(bl.get(2), 99)
|
||||
t.equal(bl.get(3), 100)
|
||||
t.equal(bl.get(4), undefined)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('single bytes from multiple buffers', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
bl.append(Buffer.from('efg'))
|
||||
bl.append(Buffer.from('hi'))
|
||||
bl.append(Buffer.from('j'))
|
||||
|
||||
t.equal(bl.length, 10)
|
||||
|
||||
t.equal(bl.get(0), 97)
|
||||
t.equal(bl.get(1), 98)
|
||||
t.equal(bl.get(2), 99)
|
||||
t.equal(bl.get(3), 100)
|
||||
t.equal(bl.get(4), 101)
|
||||
t.equal(bl.get(5), 102)
|
||||
t.equal(bl.get(6), 103)
|
||||
t.equal(bl.get(7), 104)
|
||||
t.equal(bl.get(8), 105)
|
||||
t.equal(bl.get(9), 106)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('multi bytes from single buffer', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
|
||||
t.equal(bl.length, 4)
|
||||
|
||||
t.equal(bl.slice(0, 4).toString('ascii'), 'abcd')
|
||||
t.equal(bl.slice(0, 3).toString('ascii'), 'abc')
|
||||
t.equal(bl.slice(1, 4).toString('ascii'), 'bcd')
|
||||
t.equal(bl.slice(-4, -1).toString('ascii'), 'abc')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('multi bytes from single buffer (negative indexes)', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('buffer'))
|
||||
|
||||
t.equal(bl.length, 6)
|
||||
|
||||
t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe')
|
||||
t.equal(bl.slice(-6, -2).toString('ascii'), 'buff')
|
||||
t.equal(bl.slice(-5, -2).toString('ascii'), 'uff')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('multiple bytes from multiple buffers', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
bl.append(Buffer.from('efg'))
|
||||
bl.append(Buffer.from('hi'))
|
||||
bl.append(Buffer.from('j'))
|
||||
|
||||
t.equal(bl.length, 10)
|
||||
|
||||
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
|
||||
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
|
||||
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
|
||||
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
|
||||
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
|
||||
t.equal(bl.slice(-7, -4).toString('ascii'), 'def')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('multiple bytes from multiple buffer lists', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(new BufferList([Buffer.from('abcd'), Buffer.from('efg')]))
|
||||
bl.append(new BufferList([Buffer.from('hi'), Buffer.from('j')]))
|
||||
|
||||
t.equal(bl.length, 10)
|
||||
|
||||
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
|
||||
|
||||
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
|
||||
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
|
||||
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
|
||||
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
// same data as previous test, just using nested constructors
|
||||
tape('multiple bytes from crazy nested buffer lists', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(new BufferList([
|
||||
new BufferList([
|
||||
new BufferList(Buffer.from('abc')),
|
||||
Buffer.from('d'),
|
||||
new BufferList(Buffer.from('efg'))
|
||||
]),
|
||||
new BufferList([Buffer.from('hi')]),
|
||||
new BufferList(Buffer.from('j'))
|
||||
]))
|
||||
|
||||
t.equal(bl.length, 10)
|
||||
|
||||
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
|
||||
|
||||
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
|
||||
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
|
||||
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
|
||||
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('append accepts arrays of Buffers', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abc'))
|
||||
bl.append([Buffer.from('def')])
|
||||
bl.append([Buffer.from('ghi'), Buffer.from('jkl')])
|
||||
bl.append([Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz')])
|
||||
t.equal(bl.length, 26)
|
||||
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('append accepts arrays of Uint8Arrays', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(new Uint8Array([97, 98, 99]))
|
||||
bl.append([Uint8Array.from([100, 101, 102])])
|
||||
bl.append([new Uint8Array([103, 104, 105]), new Uint8Array([106, 107, 108])])
|
||||
bl.append([new Uint8Array([109, 110, 111, 112]), new Uint8Array([113, 114, 115, 116, 117]), new Uint8Array([118, 119, 120, 121, 122])])
|
||||
t.equal(bl.length, 26)
|
||||
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('append accepts arrays of BufferLists', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abc'))
|
||||
bl.append([new BufferList('def')])
|
||||
bl.append(new BufferList([Buffer.from('ghi'), new BufferList('jkl')]))
|
||||
bl.append([Buffer.from('mnop'), new BufferList([Buffer.from('qrstu'), Buffer.from('vwxyz')])])
|
||||
t.equal(bl.length, 26)
|
||||
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('append chainable', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
t.ok(bl.append(Buffer.from('abcd')) === bl)
|
||||
t.ok(bl.append([Buffer.from('abcd')]) === bl)
|
||||
t.ok(bl.append(new BufferList(Buffer.from('abcd'))) === bl)
|
||||
t.ok(bl.append([new BufferList(Buffer.from('abcd'))]) === bl)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('append chainable (test results)', function (t) {
|
||||
const bl = new BufferList('abc')
|
||||
.append([new BufferList('def')])
|
||||
.append(new BufferList([Buffer.from('ghi'), new BufferList('jkl')]))
|
||||
.append([Buffer.from('mnop'), new BufferList([Buffer.from('qrstu'), Buffer.from('vwxyz')])])
|
||||
|
||||
t.equal(bl.length, 26)
|
||||
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('consuming from multiple buffers', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
bl.append(Buffer.from('efg'))
|
||||
bl.append(Buffer.from('hi'))
|
||||
bl.append(Buffer.from('j'))
|
||||
|
||||
t.equal(bl.length, 10)
|
||||
|
||||
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
|
||||
|
||||
bl.consume(3)
|
||||
t.equal(bl.length, 7)
|
||||
t.equal(bl.slice(0, 7).toString('ascii'), 'defghij')
|
||||
|
||||
bl.consume(2)
|
||||
t.equal(bl.length, 5)
|
||||
t.equal(bl.slice(0, 5).toString('ascii'), 'fghij')
|
||||
|
||||
bl.consume(1)
|
||||
t.equal(bl.length, 4)
|
||||
t.equal(bl.slice(0, 4).toString('ascii'), 'ghij')
|
||||
|
||||
bl.consume(1)
|
||||
t.equal(bl.length, 3)
|
||||
t.equal(bl.slice(0, 3).toString('ascii'), 'hij')
|
||||
|
||||
bl.consume(2)
|
||||
t.equal(bl.length, 1)
|
||||
t.equal(bl.slice(0, 1).toString('ascii'), 'j')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('complete consumption', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('a'))
|
||||
bl.append(Buffer.from('b'))
|
||||
|
||||
bl.consume(2)
|
||||
|
||||
t.equal(bl.length, 0)
|
||||
t.equal(bl._bufs.length, 0)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readUInt8 / readInt8', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(3)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf1[0] = 0x1
|
||||
buf2[1] = 0x3
|
||||
buf2[2] = 0x4
|
||||
buf3[0] = 0x23
|
||||
buf3[1] = 0x42
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
t.equal(bl.readUInt8(), 0x1)
|
||||
t.equal(bl.readUInt8(2), 0x3)
|
||||
t.equal(bl.readInt8(2), 0x3)
|
||||
t.equal(bl.readUInt8(3), 0x4)
|
||||
t.equal(bl.readInt8(3), 0x4)
|
||||
t.equal(bl.readUInt8(4), 0x23)
|
||||
t.equal(bl.readInt8(4), 0x23)
|
||||
t.equal(bl.readUInt8(5), 0x42)
|
||||
t.equal(bl.readInt8(5), 0x42)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(3)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf1[0] = 0x1
|
||||
buf2[1] = 0x3
|
||||
buf2[2] = 0x4
|
||||
buf3[0] = 0x23
|
||||
buf3[1] = 0x42
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
t.equal(bl.readUInt16BE(), 0x0100)
|
||||
t.equal(bl.readUInt16LE(), 0x0001)
|
||||
t.equal(bl.readUInt16BE(2), 0x0304)
|
||||
t.equal(bl.readUInt16LE(2), 0x0403)
|
||||
t.equal(bl.readInt16BE(2), 0x0304)
|
||||
t.equal(bl.readInt16LE(2), 0x0403)
|
||||
t.equal(bl.readUInt16BE(3), 0x0423)
|
||||
t.equal(bl.readUInt16LE(3), 0x2304)
|
||||
t.equal(bl.readInt16BE(3), 0x0423)
|
||||
t.equal(bl.readInt16LE(3), 0x2304)
|
||||
t.equal(bl.readUInt16BE(4), 0x2342)
|
||||
t.equal(bl.readUInt16LE(4), 0x4223)
|
||||
t.equal(bl.readInt16BE(4), 0x2342)
|
||||
t.equal(bl.readInt16LE(4), 0x4223)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(3)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf1[0] = 0x1
|
||||
buf2[1] = 0x3
|
||||
buf2[2] = 0x4
|
||||
buf3[0] = 0x23
|
||||
buf3[1] = 0x42
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
t.equal(bl.readUInt32BE(), 0x01000304)
|
||||
t.equal(bl.readUInt32LE(), 0x04030001)
|
||||
t.equal(bl.readUInt32BE(2), 0x03042342)
|
||||
t.equal(bl.readUInt32LE(2), 0x42230403)
|
||||
t.equal(bl.readInt32BE(2), 0x03042342)
|
||||
t.equal(bl.readInt32LE(2), 0x42230403)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readUIntLE / readUIntBE / readIntLE / readIntBE', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(3)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf2[0] = 0x2
|
||||
buf2[1] = 0x3
|
||||
buf2[2] = 0x4
|
||||
buf3[0] = 0x23
|
||||
buf3[1] = 0x42
|
||||
buf3[2] = 0x61
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
t.equal(bl.readUIntBE(1, 1), 0x02)
|
||||
t.equal(bl.readUIntBE(1, 2), 0x0203)
|
||||
t.equal(bl.readUIntBE(1, 3), 0x020304)
|
||||
t.equal(bl.readUIntBE(1, 4), 0x02030423)
|
||||
t.equal(bl.readUIntBE(1, 5), 0x0203042342)
|
||||
t.equal(bl.readUIntBE(1, 6), 0x020304234261)
|
||||
t.equal(bl.readUIntLE(1, 1), 0x02)
|
||||
t.equal(bl.readUIntLE(1, 2), 0x0302)
|
||||
t.equal(bl.readUIntLE(1, 3), 0x040302)
|
||||
t.equal(bl.readUIntLE(1, 4), 0x23040302)
|
||||
t.equal(bl.readUIntLE(1, 5), 0x4223040302)
|
||||
t.equal(bl.readUIntLE(1, 6), 0x614223040302)
|
||||
t.equal(bl.readIntBE(1, 1), 0x02)
|
||||
t.equal(bl.readIntBE(1, 2), 0x0203)
|
||||
t.equal(bl.readIntBE(1, 3), 0x020304)
|
||||
t.equal(bl.readIntBE(1, 4), 0x02030423)
|
||||
t.equal(bl.readIntBE(1, 5), 0x0203042342)
|
||||
t.equal(bl.readIntBE(1, 6), 0x020304234261)
|
||||
t.equal(bl.readIntLE(1, 1), 0x02)
|
||||
t.equal(bl.readIntLE(1, 2), 0x0302)
|
||||
t.equal(bl.readIntLE(1, 3), 0x040302)
|
||||
t.equal(bl.readIntLE(1, 4), 0x23040302)
|
||||
t.equal(bl.readIntLE(1, 5), 0x4223040302)
|
||||
t.equal(bl.readIntLE(1, 6), 0x614223040302)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readFloatLE / readFloatBE', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(3)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf1[0] = 0x01
|
||||
buf2[1] = 0x00
|
||||
buf2[2] = 0x00
|
||||
buf3[0] = 0x80
|
||||
buf3[1] = 0x3f
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
const canonical = Buffer.concat([buf1, buf2, buf3])
|
||||
t.equal(bl.readFloatLE(), canonical.readFloatLE())
|
||||
t.equal(bl.readFloatBE(), canonical.readFloatBE())
|
||||
t.equal(bl.readFloatLE(2), canonical.readFloatLE(2))
|
||||
t.equal(bl.readFloatBE(2), canonical.readFloatBE(2))
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test readDoubleLE / readDoubleBE', function (t) {
|
||||
const buf1 = Buffer.alloc(1)
|
||||
const buf2 = Buffer.alloc(3)
|
||||
const buf3 = Buffer.alloc(10)
|
||||
const bl = new BufferList()
|
||||
|
||||
buf1[0] = 0x01
|
||||
buf2[1] = 0x55
|
||||
buf2[2] = 0x55
|
||||
buf3[0] = 0x55
|
||||
buf3[1] = 0x55
|
||||
buf3[2] = 0x55
|
||||
buf3[3] = 0x55
|
||||
buf3[4] = 0xd5
|
||||
buf3[5] = 0x3f
|
||||
|
||||
bl.append(buf1)
|
||||
bl.append(buf2)
|
||||
bl.append(buf3)
|
||||
|
||||
const canonical = Buffer.concat([buf1, buf2, buf3])
|
||||
t.equal(bl.readDoubleBE(), canonical.readDoubleBE())
|
||||
t.equal(bl.readDoubleLE(), canonical.readDoubleLE())
|
||||
t.equal(bl.readDoubleBE(2), canonical.readDoubleBE(2))
|
||||
t.equal(bl.readDoubleLE(2), canonical.readDoubleLE(2))
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test toString', function (t) {
|
||||
const bl = new BufferList()
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
bl.append(Buffer.from('efg'))
|
||||
bl.append(Buffer.from('hi'))
|
||||
bl.append(Buffer.from('j'))
|
||||
|
||||
t.equal(bl.toString('ascii', 0, 10), 'abcdefghij')
|
||||
t.equal(bl.toString('ascii', 3, 10), 'defghij')
|
||||
t.equal(bl.toString('ascii', 3, 6), 'def')
|
||||
t.equal(bl.toString('ascii', 3, 8), 'defgh')
|
||||
t.equal(bl.toString('ascii', 5, 10), 'fghij')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test toString encoding', function (t) {
|
||||
const bl = new BufferList()
|
||||
const b = Buffer.from('abcdefghij\xff\x00')
|
||||
|
||||
bl.append(Buffer.from('abcd'))
|
||||
bl.append(Buffer.from('efg'))
|
||||
bl.append(Buffer.from('hi'))
|
||||
bl.append(Buffer.from('j'))
|
||||
bl.append(Buffer.from('\xff\x00'))
|
||||
|
||||
encodings.forEach(function (enc) {
|
||||
t.equal(bl.toString(enc), b.toString(enc), enc)
|
||||
})
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('uninitialized memory', function (t) {
|
||||
const secret = crypto.randomBytes(256)
|
||||
for (let i = 0; i < 1e6; i++) {
|
||||
const clone = Buffer.from(secret)
|
||||
const bl = new BufferList()
|
||||
bl.append(Buffer.from('a'))
|
||||
bl.consume(-1024)
|
||||
const buf = bl.slice(1)
|
||||
if (buf.indexOf(clone) !== -1) {
|
||||
t.fail(`Match (at ${i})`)
|
||||
break
|
||||
}
|
||||
}
|
||||
t.end()
|
||||
})
|
||||
|
||||
!process.browser && tape('test stream', function (t) {
|
||||
const random = crypto.randomBytes(65534)
|
||||
|
||||
const bl = new BufferList((err, buf) => {
|
||||
t.ok(Buffer.isBuffer(buf))
|
||||
t.ok(err === null)
|
||||
t.ok(random.equals(bl.slice()))
|
||||
t.ok(random.equals(buf.slice()))
|
||||
|
||||
bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat'))
|
||||
.on('close', function () {
|
||||
const rndhash = crypto.createHash('md5').update(random).digest('hex')
|
||||
const md5sum = crypto.createHash('md5')
|
||||
const s = fs.createReadStream('/tmp/bl_test_rnd_out.dat')
|
||||
|
||||
s.on('data', md5sum.update.bind(md5sum))
|
||||
s.on('end', function () {
|
||||
t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!')
|
||||
t.end()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
fs.writeFileSync('/tmp/bl_test_rnd.dat', random)
|
||||
fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl)
|
||||
})
|
||||
|
||||
tape('instantiation with Buffer', function (t) {
|
||||
const buf = crypto.randomBytes(1024)
|
||||
const buf2 = crypto.randomBytes(1024)
|
||||
let b = BufferList(buf)
|
||||
|
||||
t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer')
|
||||
b = BufferList([buf, buf2])
|
||||
t.equal(b.slice().toString('hex'), Buffer.concat([buf, buf2]).toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test String appendage', function (t) {
|
||||
const bl = new BufferList()
|
||||
const b = Buffer.from('abcdefghij\xff\x00')
|
||||
|
||||
bl.append('abcd')
|
||||
bl.append('efg')
|
||||
bl.append('hi')
|
||||
bl.append('j')
|
||||
bl.append('\xff\x00')
|
||||
|
||||
encodings.forEach(function (enc) {
|
||||
t.equal(bl.toString(enc), b.toString(enc))
|
||||
})
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('test Number appendage', function (t) {
|
||||
const bl = new BufferList()
|
||||
const b = Buffer.from('1234567890')
|
||||
|
||||
bl.append(1234)
|
||||
bl.append(567)
|
||||
bl.append(89)
|
||||
bl.append(0)
|
||||
|
||||
encodings.forEach(function (enc) {
|
||||
t.equal(bl.toString(enc), b.toString(enc))
|
||||
})
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('write nothing, should get empty buffer', function (t) {
|
||||
t.plan(3)
|
||||
BufferList(function (err, data) {
|
||||
t.notOk(err, 'no error')
|
||||
t.ok(Buffer.isBuffer(data), 'got a buffer')
|
||||
t.equal(0, data.length, 'got a zero-length buffer')
|
||||
t.end()
|
||||
}).end()
|
||||
})
|
||||
|
||||
tape('unicode string', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const inp1 = '\u2600'
|
||||
const inp2 = '\u2603'
|
||||
const exp = inp1 + ' and ' + inp2
|
||||
const bl = BufferList()
|
||||
|
||||
bl.write(inp1)
|
||||
bl.write(' and ')
|
||||
bl.write(inp2)
|
||||
t.equal(exp, bl.toString())
|
||||
t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex'))
|
||||
})
|
||||
|
||||
tape('should emit finish', function (t) {
|
||||
const source = BufferList()
|
||||
const dest = BufferList()
|
||||
|
||||
source.write('hello')
|
||||
source.pipe(dest)
|
||||
|
||||
dest.on('finish', function () {
|
||||
t.equal(dest.toString('utf8'), 'hello')
|
||||
t.end()
|
||||
})
|
||||
})
|
||||
|
||||
tape('basic copy', function (t) {
|
||||
const buf = crypto.randomBytes(1024)
|
||||
const buf2 = Buffer.alloc(1024)
|
||||
const b = BufferList(buf)
|
||||
|
||||
b.copy(buf2)
|
||||
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('copy after many appends', function (t) {
|
||||
const buf = crypto.randomBytes(512)
|
||||
const buf2 = Buffer.alloc(1024)
|
||||
const b = BufferList(buf)
|
||||
|
||||
b.append(buf)
|
||||
b.copy(buf2)
|
||||
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('copy at a precise position', function (t) {
|
||||
const buf = crypto.randomBytes(1004)
|
||||
const buf2 = Buffer.alloc(1024)
|
||||
const b = BufferList(buf)
|
||||
|
||||
b.copy(buf2, 20)
|
||||
t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('copy starting from a precise location', function (t) {
|
||||
const buf = crypto.randomBytes(10)
|
||||
const buf2 = Buffer.alloc(5)
|
||||
const b = BufferList(buf)
|
||||
|
||||
b.copy(buf2, 0, 5)
|
||||
t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('copy in an interval', function (t) {
|
||||
const rnd = crypto.randomBytes(10)
|
||||
const b = BufferList(rnd) // put the random bytes there
|
||||
const actual = Buffer.alloc(3)
|
||||
const expected = Buffer.alloc(3)
|
||||
|
||||
rnd.copy(expected, 0, 5, 8)
|
||||
b.copy(actual, 0, 5, 8)
|
||||
|
||||
t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('copy an interval between two buffers', function (t) {
|
||||
const buf = crypto.randomBytes(10)
|
||||
const buf2 = Buffer.alloc(10)
|
||||
const b = BufferList(buf)
|
||||
|
||||
b.append(buf)
|
||||
b.copy(buf2, 0, 5, 15)
|
||||
|
||||
t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('shallow slice across buffer boundaries', function (t) {
|
||||
const bl = new BufferList(['First', 'Second', 'Third'])
|
||||
|
||||
t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('shallow slice within single buffer', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList(['First', 'Second', 'Third'])
|
||||
|
||||
t.equal(bl.shallowSlice(5, 10).toString(), 'Secon')
|
||||
t.equal(bl.shallowSlice(7, 10).toString(), 'con')
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape('shallow slice single buffer', function (t) {
|
||||
t.plan(3)
|
||||
|
||||
const bl = new BufferList(['First', 'Second', 'Third'])
|
||||
|
||||
t.equal(bl.shallowSlice(0, 5).toString(), 'First')
|
||||
t.equal(bl.shallowSlice(5, 11).toString(), 'Second')
|
||||
t.equal(bl.shallowSlice(11, 16).toString(), 'Third')
|
||||
})
|
||||
|
||||
tape('shallow slice with negative or omitted indices', function (t) {
|
||||
t.plan(4)
|
||||
|
||||
const bl = new BufferList(['First', 'Second', 'Third'])
|
||||
|
||||
t.equal(bl.shallowSlice().toString(), 'FirstSecondThird')
|
||||
t.equal(bl.shallowSlice(5).toString(), 'SecondThird')
|
||||
t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh')
|
||||
t.equal(bl.shallowSlice(-8).toString(), 'ondThird')
|
||||
})
|
||||
|
||||
tape('shallow slice does not make a copy', function (t) {
|
||||
t.plan(1)
|
||||
|
||||
const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
|
||||
const bl = (new BufferList(buffers)).shallowSlice(5, -3)
|
||||
|
||||
buffers[1].fill('h')
|
||||
buffers[2].fill('h')
|
||||
|
||||
t.equal(bl.toString(), 'hhhhhhhh')
|
||||
})
|
||||
|
||||
tape('shallow slice with 0 length', function (t) {
|
||||
t.plan(1)
|
||||
|
||||
const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
|
||||
const bl = (new BufferList(buffers)).shallowSlice(0, 0)
|
||||
|
||||
t.equal(bl.length, 0)
|
||||
})
|
||||
|
||||
tape('shallow slice with 0 length from middle', function (t) {
|
||||
t.plan(1)
|
||||
|
||||
const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
|
||||
const bl = (new BufferList(buffers)).shallowSlice(10, 10)
|
||||
|
||||
t.equal(bl.length, 0)
|
||||
})
|
||||
|
||||
tape('duplicate', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList('abcdefghij\xff\x00')
|
||||
const dup = bl.duplicate()
|
||||
|
||||
t.equal(bl.prototype, dup.prototype)
|
||||
t.equal(bl.toString('hex'), dup.toString('hex'))
|
||||
})
|
||||
|
||||
tape('destroy no pipe', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList('alsdkfja;lsdkfja;lsdk')
|
||||
|
||||
bl.destroy()
|
||||
|
||||
t.equal(bl._bufs.length, 0)
|
||||
t.equal(bl.length, 0)
|
||||
})
|
||||
|
||||
tape('destroy with error', function (t) {
|
||||
t.plan(3)
|
||||
|
||||
const bl = new BufferList('alsdkfja;lsdkfja;lsdk')
|
||||
const err = new Error('kaboom')
|
||||
|
||||
bl.destroy(err)
|
||||
bl.on('error', function (_err) {
|
||||
t.equal(_err, err)
|
||||
})
|
||||
|
||||
t.equal(bl._bufs.length, 0)
|
||||
t.equal(bl.length, 0)
|
||||
})
|
||||
|
||||
!process.browser && tape('destroy with pipe before read end', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList()
|
||||
fs.createReadStream(path.join(__dirname, '/test.js'))
|
||||
.pipe(bl)
|
||||
|
||||
bl.destroy()
|
||||
|
||||
t.equal(bl._bufs.length, 0)
|
||||
t.equal(bl.length, 0)
|
||||
})
|
||||
|
||||
!process.browser && tape('destroy with pipe before read end with race', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList()
|
||||
|
||||
fs.createReadStream(path.join(__dirname, '/test.js'))
|
||||
.pipe(bl)
|
||||
|
||||
setTimeout(function () {
|
||||
bl.destroy()
|
||||
setTimeout(function () {
|
||||
t.equal(bl._bufs.length, 0)
|
||||
t.equal(bl.length, 0)
|
||||
}, 500)
|
||||
}, 500)
|
||||
})
|
||||
|
||||
!process.browser && tape('destroy with pipe after read end', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
const bl = new BufferList()
|
||||
|
||||
fs.createReadStream(path.join(__dirname, '/test.js'))
|
||||
.on('end', onEnd)
|
||||
.pipe(bl)
|
||||
|
||||
function onEnd () {
|
||||
bl.destroy()
|
||||
|
||||
t.equal(bl._bufs.length, 0)
|
||||
t.equal(bl.length, 0)
|
||||
}
|
||||
})
|
||||
|
||||
!process.browser && tape('destroy with pipe while writing to a destination', function (t) {
|
||||
t.plan(4)
|
||||
|
||||
const bl = new BufferList()
|
||||
const ds = new BufferList()
|
||||
|
||||
fs.createReadStream(path.join(__dirname, '/test.js'))
|
||||
.on('end', onEnd)
|
||||
.pipe(bl)
|
||||
|
||||
function onEnd () {
|
||||
bl.pipe(ds)
|
||||
|
||||
setTimeout(function () {
|
||||
bl.destroy()
|
||||
|
||||
t.equals(bl._bufs.length, 0)
|
||||
t.equals(bl.length, 0)
|
||||
|
||||
ds.destroy()
|
||||
|
||||
t.equals(bl._bufs.length, 0)
|
||||
t.equals(bl.length, 0)
|
||||
}, 100)
|
||||
}
|
||||
})
|
||||
|
||||
!process.browser && tape('handle error', function (t) {
|
||||
t.plan(2)
|
||||
|
||||
fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) {
|
||||
t.ok(err instanceof Error, 'has error')
|
||||
t.notOk(data, 'no data')
|
||||
}))
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Subscriber } from '../Subscriber';
|
||||
export function ignoreElements() {
|
||||
return function ignoreElementsOperatorFunction(source) {
|
||||
return source.lift(new IgnoreElementsOperator());
|
||||
};
|
||||
}
|
||||
class IgnoreElementsOperator {
|
||||
call(subscriber, source) {
|
||||
return source.subscribe(new IgnoreElementsSubscriber(subscriber));
|
||||
}
|
||||
}
|
||||
class IgnoreElementsSubscriber extends Subscriber {
|
||||
_next(unused) {
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=ignoreElements.js.map
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
function __export(m) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
||||
}
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__export(require("rxjs-compat/operators/bufferWhen"));
|
||||
//# sourceMappingURL=bufferWhen.js.map
|
||||
@@ -0,0 +1,6 @@
|
||||
/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */
|
||||
import { distinctUntilChanged } from './distinctUntilChanged';
|
||||
export function distinctUntilKeyChanged(key, compare) {
|
||||
return distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
|
||||
}
|
||||
//# sourceMappingURL=distinctUntilKeyChanged.js.map
|
||||
@@ -0,0 +1 @@
|
||||
module.exports={A:{A:{"2":"J E F G A B BC"},B:{"1":"P Q R S T U V W X Y Z a b c d f g h i j k l m n o p q r s D t","2":"C K L H M N O"},C:{"1":"JB KB LB MB NB OB PB QB RB","2":"CC tB I u J E F G SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB e lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d f g h i j k l m n o p q r s D t xB yB DC EC","132":"0 1 2 3 4 5 6 7 8 9 M N O v w x y z AB BB CB DB EB FB GB HB IB","164":"A B C K L H"},D:{"1":"EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB e lB mB nB oB pB P Q R S T U V W X Y Z a b c d f g h i j k l m n o p q r s D t xB yB FC","2":"0 1 2 3 4 5 6 7 8 9 I u J E F G A B C K L H M N O v w x y z AB BB CB","66":"DB"},E:{"2":"I u J E F G A B C K L H GC zB HC IC JC KC 0B qB rB 1B LC MC 2B 3B 4B 5B sB 6B 7B 8B NC"},F:{"1":"1 2 3 4 5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB e lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d","2":"0 G B C H M N O v w x y z OC PC QC RC qB 9B SC rB"},G:{"2":"F zB TC AC UC VC WC XC YC ZC aC bC cC dC eC fC gC hC iC jC kC lC mC 2B 3B 4B 5B sB 6B 7B 8B"},H:{"2":"nC"},I:{"1":"D","2":"tB I oC pC qC rC AC sC tC"},J:{"2":"E A"},K:{"1":"e","2":"A B C qB 9B rB"},L:{"1":"D"},M:{"2":"D"},N:{"2":"A B"},O:{"1":"uC"},P:{"1":"I vC wC xC yC zC 0B 0C 1C 2C 3C 4C sB 5C 6C 7C"},Q:{"1":"1B"},R:{"1":"8C"},S:{"1":"9C"}},B:4,C:"Battery Status API"};
|
||||
@@ -0,0 +1 @@
|
||||
export * from 'rxjs-compat/operators/timestamp';
|
||||
@@ -0,0 +1,382 @@
|
||||
import { Operator } from './Operator';
|
||||
import { Subscriber } from './Subscriber';
|
||||
import { Subscription } from './Subscription';
|
||||
import { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';
|
||||
import { canReportError } from './util/canReportError';
|
||||
import { toSubscriber } from './util/toSubscriber';
|
||||
import { iif } from './observable/iif';
|
||||
import { throwError } from './observable/throwError';
|
||||
import { observable as Symbol_observable } from './symbol/observable';
|
||||
import { pipeFromArray } from './util/pipe';
|
||||
import { config } from './config';
|
||||
|
||||
/**
|
||||
* A representation of any set of values over any amount of time. This is the most basic building block
|
||||
* of RxJS.
|
||||
*
|
||||
* @class Observable<T>
|
||||
*/
|
||||
export class Observable<T> implements Subscribable<T> {
|
||||
|
||||
/** Internal implementation detail, do not use directly. */
|
||||
public _isScalar: boolean = false;
|
||||
|
||||
/** @deprecated This is an internal implementation detail, do not use. */
|
||||
source: Observable<any>;
|
||||
|
||||
/** @deprecated This is an internal implementation detail, do not use. */
|
||||
operator: Operator<any, T>;
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* @param {Function} subscribe the function that is called when the Observable is
|
||||
* initially subscribed to. This function is given a Subscriber, to which new values
|
||||
* can be `next`ed, or an `error` method can be called to raise an error, or
|
||||
* `complete` can be called to notify of a successful completion.
|
||||
*/
|
||||
constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
|
||||
if (subscribe) {
|
||||
this._subscribe = subscribe;
|
||||
}
|
||||
}
|
||||
|
||||
// HACK: Since TypeScript inherits static properties too, we have to
|
||||
// fight against TypeScript here so Subject can have a different static create signature
|
||||
/**
|
||||
* Creates a new cold Observable by calling the Observable constructor
|
||||
* @static true
|
||||
* @owner Observable
|
||||
* @method create
|
||||
* @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
|
||||
* @return {Observable} a new cold observable
|
||||
* @nocollapse
|
||||
* @deprecated use new Observable() instead
|
||||
*/
|
||||
static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
|
||||
return new Observable<T>(subscribe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Observable, with this Observable as the source, and the passed
|
||||
* operator defined as the new observable's operator.
|
||||
* @method lift
|
||||
* @param {Operator} operator the operator defining the operation to take on the observable
|
||||
* @return {Observable} a new observable with the Operator applied
|
||||
*/
|
||||
lift<R>(operator: Operator<T, R>): Observable<R> {
|
||||
const observable = new Observable<R>();
|
||||
observable.source = this;
|
||||
observable.operator = operator;
|
||||
return observable;
|
||||
}
|
||||
|
||||
subscribe(observer?: PartialObserver<T>): Subscription;
|
||||
/** @deprecated Use an observer instead of a complete callback */
|
||||
subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;
|
||||
/** @deprecated Use an observer instead of an error callback */
|
||||
subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
|
||||
/** @deprecated Use an observer instead of a complete callback */
|
||||
subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;
|
||||
subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
|
||||
/**
|
||||
* Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
|
||||
*
|
||||
* <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
|
||||
*
|
||||
* `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
|
||||
* might be for example a function that you passed to Observable's constructor, but most of the time it is
|
||||
* a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
|
||||
* that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
|
||||
* the thought.
|
||||
*
|
||||
* Apart from starting the execution of an Observable, this method allows you to listen for values
|
||||
* that an Observable emits, as well as for when it completes or errors. You can achieve this in two
|
||||
* of the following ways.
|
||||
*
|
||||
* The first way is creating an object that implements {@link Observer} interface. It should have methods
|
||||
* defined by that interface, but note that it should be just a regular JavaScript object, which you can create
|
||||
* yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
|
||||
* not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
|
||||
* that your object does not have to implement all methods. If you find yourself creating a method that doesn't
|
||||
* do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will
|
||||
* be left uncaught.
|
||||
*
|
||||
* The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
|
||||
* This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
|
||||
* of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,
|
||||
* if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
|
||||
* since `subscribe` recognizes these functions by where they were placed in function call. When it comes
|
||||
* to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
|
||||
*
|
||||
* Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
|
||||
* This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
|
||||
* up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
|
||||
* provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
|
||||
*
|
||||
* Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
|
||||
* It is an Observable itself that decides when these functions will be called. For example {@link of}
|
||||
* by default emits all its values synchronously. Always check documentation for how given Observable
|
||||
* will behave when subscribed and if its default behavior can be modified with a `scheduler`.
|
||||
*
|
||||
* ## Example
|
||||
* ### Subscribe with an Observer
|
||||
* ```ts
|
||||
* import { of } from 'rxjs';
|
||||
*
|
||||
* const sumObserver = {
|
||||
* sum: 0,
|
||||
* next(value) {
|
||||
* console.log('Adding: ' + value);
|
||||
* this.sum = this.sum + value;
|
||||
* },
|
||||
* error() {
|
||||
* // We actually could just remove this method,
|
||||
* // since we do not really care about errors right now.
|
||||
* },
|
||||
* complete() {
|
||||
* console.log('Sum equals: ' + this.sum);
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
|
||||
* .subscribe(sumObserver);
|
||||
*
|
||||
* // Logs:
|
||||
* // "Adding: 1"
|
||||
* // "Adding: 2"
|
||||
* // "Adding: 3"
|
||||
* // "Sum equals: 6"
|
||||
* ```
|
||||
*
|
||||
* ### Subscribe with functions
|
||||
* ```ts
|
||||
* import { of } from 'rxjs'
|
||||
*
|
||||
* let sum = 0;
|
||||
*
|
||||
* of(1, 2, 3).subscribe(
|
||||
* value => {
|
||||
* console.log('Adding: ' + value);
|
||||
* sum = sum + value;
|
||||
* },
|
||||
* undefined,
|
||||
* () => console.log('Sum equals: ' + sum)
|
||||
* );
|
||||
*
|
||||
* // Logs:
|
||||
* // "Adding: 1"
|
||||
* // "Adding: 2"
|
||||
* // "Adding: 3"
|
||||
* // "Sum equals: 6"
|
||||
* ```
|
||||
*
|
||||
* ### Cancel a subscription
|
||||
* ```ts
|
||||
* import { interval } from 'rxjs';
|
||||
*
|
||||
* const subscription = interval(1000).subscribe(
|
||||
* num => console.log(num),
|
||||
* undefined,
|
||||
* () => {
|
||||
* // Will not be called, even when cancelling subscription.
|
||||
* console.log('completed!');
|
||||
* }
|
||||
* );
|
||||
*
|
||||
* setTimeout(() => {
|
||||
* subscription.unsubscribe();
|
||||
* console.log('unsubscribed!');
|
||||
* }, 2500);
|
||||
*
|
||||
* // Logs:
|
||||
* // 0 after 1s
|
||||
* // 1 after 2s
|
||||
* // "unsubscribed!" after 2.5s
|
||||
* ```
|
||||
*
|
||||
* @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
|
||||
* or the first of three possible handlers, which is the handler for each value emitted from the subscribed
|
||||
* Observable.
|
||||
* @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
|
||||
* the error will be thrown as unhandled.
|
||||
* @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
|
||||
* @return {ISubscription} a subscription reference to the registered handlers
|
||||
* @method subscribe
|
||||
*/
|
||||
subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
|
||||
error?: (error: any) => void,
|
||||
complete?: () => void): Subscription {
|
||||
|
||||
const { operator } = this;
|
||||
const sink = toSubscriber(observerOrNext, error, complete);
|
||||
|
||||
if (operator) {
|
||||
sink.add(operator.call(sink, this.source));
|
||||
} else {
|
||||
sink.add(
|
||||
this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
|
||||
this._subscribe(sink) :
|
||||
this._trySubscribe(sink)
|
||||
);
|
||||
}
|
||||
|
||||
if (config.useDeprecatedSynchronousErrorHandling) {
|
||||
if (sink.syncErrorThrowable) {
|
||||
sink.syncErrorThrowable = false;
|
||||
if (sink.syncErrorThrown) {
|
||||
throw sink.syncErrorValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sink;
|
||||
}
|
||||
|
||||
/** @deprecated This is an internal implementation detail, do not use. */
|
||||
_trySubscribe(sink: Subscriber<T>): TeardownLogic {
|
||||
try {
|
||||
return this._subscribe(sink);
|
||||
} catch (err) {
|
||||
if (config.useDeprecatedSynchronousErrorHandling) {
|
||||
sink.syncErrorThrown = true;
|
||||
sink.syncErrorValue = err;
|
||||
}
|
||||
if (canReportError(sink)) {
|
||||
sink.error(err);
|
||||
} else {
|
||||
console.warn(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @method forEach
|
||||
* @param {Function} next a handler for each value emitted by the observable
|
||||
* @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise
|
||||
* @return {Promise} a promise that either resolves on observable completion or
|
||||
* rejects with the handled error
|
||||
*/
|
||||
forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
|
||||
promiseCtor = getPromiseCtor(promiseCtor);
|
||||
|
||||
return new promiseCtor<void>((resolve, reject) => {
|
||||
// Must be declared in a separate statement to avoid a ReferenceError when
|
||||
// accessing subscription below in the closure due to Temporal Dead Zone.
|
||||
let subscription: Subscription;
|
||||
subscription = this.subscribe((value) => {
|
||||
try {
|
||||
next(value);
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
if (subscription) {
|
||||
subscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
}, reject, resolve);
|
||||
}) as Promise<void>;
|
||||
}
|
||||
|
||||
/** @internal This is an internal implementation detail, do not use. */
|
||||
_subscribe(subscriber: Subscriber<any>): TeardownLogic {
|
||||
const { source } = this;
|
||||
return source && source.subscribe(subscriber);
|
||||
}
|
||||
|
||||
// `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in
|
||||
// favor of iif and throwError functions.
|
||||
/**
|
||||
* @nocollapse
|
||||
* @deprecated In favor of iif creation function: import { iif } from 'rxjs';
|
||||
*/
|
||||
static if: typeof iif;
|
||||
/**
|
||||
* @nocollapse
|
||||
* @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';
|
||||
*/
|
||||
static throw: typeof throwError;
|
||||
|
||||
/**
|
||||
* An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
|
||||
* @method Symbol.observable
|
||||
* @return {Observable} this instance of the observable
|
||||
*/
|
||||
[Symbol_observable]() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/* tslint:disable:max-line-length */
|
||||
pipe(): Observable<T>;
|
||||
pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
|
||||
pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
|
||||
pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
|
||||
pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;
|
||||
pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;
|
||||
pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;
|
||||
pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;
|
||||
pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;
|
||||
pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;
|
||||
pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;
|
||||
/* tslint:enable:max-line-length */
|
||||
|
||||
/**
|
||||
* Used to stitch together functional operators into a chain.
|
||||
* @method pipe
|
||||
* @return {Observable} the Observable result of all of the operators having
|
||||
* been called in the order they were passed in.
|
||||
*
|
||||
* ### Example
|
||||
* ```ts
|
||||
* import { interval } from 'rxjs';
|
||||
* import { map, filter, scan } from 'rxjs/operators';
|
||||
*
|
||||
* interval(1000)
|
||||
* .pipe(
|
||||
* filter(x => x % 2 === 0),
|
||||
* map(x => x + x),
|
||||
* scan((acc, x) => acc + x)
|
||||
* )
|
||||
* .subscribe(x => console.log(x))
|
||||
* ```
|
||||
*/
|
||||
pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
|
||||
if (operations.length === 0) {
|
||||
return this as any;
|
||||
}
|
||||
|
||||
return pipeFromArray(operations)(this);
|
||||
}
|
||||
|
||||
/* tslint:disable:max-line-length */
|
||||
toPromise<T>(this: Observable<T>): Promise<T>;
|
||||
toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;
|
||||
toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;
|
||||
/* tslint:enable:max-line-length */
|
||||
|
||||
toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {
|
||||
promiseCtor = getPromiseCtor(promiseCtor);
|
||||
|
||||
return new promiseCtor((resolve, reject) => {
|
||||
let value: any;
|
||||
this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));
|
||||
}) as Promise<T>;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides between a passed promise constructor from consuming code,
|
||||
* A default configured promise constructor, and the native promise
|
||||
* constructor and returns it. If nothing can be found, it will throw
|
||||
* an error.
|
||||
* @param promiseCtor The optional promise constructor to passed by consuming code
|
||||
*/
|
||||
function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
|
||||
if (!promiseCtor) {
|
||||
promiseCtor = config.Promise || Promise;
|
||||
}
|
||||
|
||||
if (!promiseCtor) {
|
||||
throw new Error('no Promise impl found');
|
||||
}
|
||||
|
||||
return promiseCtor;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
const path = require('path');
|
||||
const semver = require('semver');
|
||||
const urlJoin = require('url-join');
|
||||
const Plugin = require('../Plugin');
|
||||
const { hasAccess, rejectAfter, parseVersion, e } = require('../../util');
|
||||
const prompts = require('./prompts');
|
||||
|
||||
const docs = 'https://git.io/release-it-npm';
|
||||
|
||||
const options = { write: false };
|
||||
|
||||
const MANIFEST_PATH = './package.json';
|
||||
const DEFAULT_TAG = 'latest';
|
||||
const DEFAULT_TAG_PRERELEASE = 'next';
|
||||
const NPM_BASE_URL = 'https://www.npmjs.com';
|
||||
|
||||
const fixArgs = args => (args ? (typeof args === 'string' ? args.split(' ') : args) : []);
|
||||
|
||||
class npm extends Plugin {
|
||||
static isEnabled(options) {
|
||||
return hasAccess(MANIFEST_PATH) && options !== false;
|
||||
}
|
||||
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.registerPrompts(prompts);
|
||||
}
|
||||
|
||||
async init() {
|
||||
const { name, version: latestVersion, private: isPrivate, publishConfig } = require(path.resolve(MANIFEST_PATH));
|
||||
this.setContext({ name, latestVersion, private: isPrivate, publishConfig });
|
||||
|
||||
const { publish, skipChecks } = this.options;
|
||||
|
||||
const timeout = Number(this.options.timeout) * 1000;
|
||||
|
||||
if (publish === false || isPrivate) return;
|
||||
|
||||
if (skipChecks) return;
|
||||
|
||||
const validations = Promise.all([this.isRegistryUp(), this.isAuthenticated(), this.getLatestRegistryVersion()]);
|
||||
|
||||
await Promise.race([validations, rejectAfter(timeout, e(`Timed out after ${timeout}ms.`, docs))]);
|
||||
|
||||
const [isRegistryUp, isAuthenticated, latestVersionInRegistry] = await validations;
|
||||
|
||||
if (!isRegistryUp) {
|
||||
throw e(`Unable to reach npm registry (timed out after ${timeout}ms).`, docs);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
throw e('Not authenticated with npm. Please `npm login` and try again.', docs);
|
||||
}
|
||||
|
||||
if (!(await this.isCollaborator())) {
|
||||
const { username } = this.getContext();
|
||||
throw e(`User ${username} is not a collaborator for ${name}.`, docs);
|
||||
}
|
||||
|
||||
if (!latestVersionInRegistry) {
|
||||
this.log.warn('No version found in npm registry. Assuming new package.');
|
||||
} else {
|
||||
if (!semver.eq(latestVersion, latestVersionInRegistry)) {
|
||||
this.log.warn(
|
||||
`Latest version in registry (${latestVersionInRegistry}) does not match package.json (${latestVersion}).`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getName() {
|
||||
return this.getContext('name');
|
||||
}
|
||||
|
||||
getLatestVersion() {
|
||||
return this.options.ignoreVersion ? null : this.getContext('latestVersion');
|
||||
}
|
||||
|
||||
async bump(version) {
|
||||
const task = () =>
|
||||
this.exec(`npm version ${version} --no-git-tag-version`).catch(err => {
|
||||
if (/version not changed/i.test(err)) {
|
||||
this.log.warn(`Did not update version in package.json, etc. (already at ${version}).`);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
const tag = this.options.tag || (await this.resolveTag(version));
|
||||
this.setContext({ version, tag });
|
||||
return this.spinner.show({ task, label: 'npm version' });
|
||||
}
|
||||
|
||||
release() {
|
||||
if (this.options.publish === false) return false;
|
||||
const publish = () => this.publish({ otpCallback });
|
||||
const otpCallback = this.config.isCI ? null : task => this.step({ prompt: 'otp', task });
|
||||
return this.step({ task: publish, label: 'npm publish', prompt: 'publish' });
|
||||
}
|
||||
|
||||
isRegistryUp() {
|
||||
const registry = this.getRegistry();
|
||||
const registryArg = registry ? ` --registry ${registry}` : '';
|
||||
return this.exec(`npm ping${registryArg}`, { options }).then(
|
||||
() => true,
|
||||
err => {
|
||||
if (/code E40[04]|404.*(ping not found|No content for path)/.test(err)) {
|
||||
this.log.warn('Ignoring response from unsupported `npm ping` command.');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
isAuthenticated() {
|
||||
const registry = this.getRegistry();
|
||||
const registryArg = registry ? ` --registry ${registry}` : '';
|
||||
return this.exec(`npm whoami${registryArg}`, { options }).then(
|
||||
output => {
|
||||
const username = output ? output.trim() : null;
|
||||
this.setContext({ username });
|
||||
return true;
|
||||
},
|
||||
err => {
|
||||
this.debug(err);
|
||||
if (/code E40[04]/.test(err)) {
|
||||
this.log.warn('Ignoring response from unsupported `npm whoami` command.');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
isCollaborator() {
|
||||
const registry = this.getRegistry();
|
||||
const registryArg = registry ? ` --registry ${registry}` : '';
|
||||
const name = this.getName();
|
||||
const { username } = this.getContext();
|
||||
if (username === undefined) return true;
|
||||
if (username === null) return false;
|
||||
return this.exec(`npm access ls-collaborators ${name}${registryArg}`, { options }).then(
|
||||
output => {
|
||||
try {
|
||||
const collaborators = JSON.parse(output);
|
||||
const permissions = collaborators[username];
|
||||
return permissions && permissions.includes('write');
|
||||
} catch (err) {
|
||||
this.debug(err);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
err => {
|
||||
this.debug(err);
|
||||
if (/code E400/.test(err)) {
|
||||
this.log.warn('Ignoring response from unsupported `npm access` command.');
|
||||
} else {
|
||||
this.log.warn(`Unable to verify if user ${username} is a collaborator for ${name}.`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async getLatestRegistryVersion() {
|
||||
const registry = this.getRegistry();
|
||||
const registryArg = registry ? ` --registry ${registry}` : '';
|
||||
const name = this.getName();
|
||||
const latestVersion = this.getLatestVersion();
|
||||
const tag = await this.resolveTag(latestVersion);
|
||||
return this.exec(`npm show ${name}@${tag} version${registryArg}`, { options }).catch(() => null);
|
||||
}
|
||||
|
||||
getRegistryPreReleaseTags() {
|
||||
return this.exec(`npm view ${this.getName()} dist-tags --json`, { options }).then(
|
||||
output => {
|
||||
try {
|
||||
const tags = JSON.parse(output);
|
||||
return Object.keys(tags).filter(tag => tag !== DEFAULT_TAG);
|
||||
} catch (err) {
|
||||
this.debug(err);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
() => []
|
||||
);
|
||||
}
|
||||
|
||||
getPackageUrl() {
|
||||
const baseUrl = this.getRegistry() || NPM_BASE_URL;
|
||||
return urlJoin(baseUrl, 'package', this.getName());
|
||||
}
|
||||
|
||||
getRegistry() {
|
||||
const { publishConfig } = this.getContext();
|
||||
const registries = publishConfig
|
||||
? publishConfig.registry
|
||||
? [publishConfig.registry]
|
||||
: Object.keys(publishConfig)
|
||||
.filter(key => key.endsWith('registry'))
|
||||
.map(key => publishConfig[key])
|
||||
: [];
|
||||
return registries[0];
|
||||
}
|
||||
|
||||
async guessPreReleaseTag() {
|
||||
const [tag] = await this.getRegistryPreReleaseTags();
|
||||
if (tag) {
|
||||
return tag;
|
||||
} else {
|
||||
this.log.warn(`Unable to get pre-release tag(s) from npm registry. Using "${DEFAULT_TAG_PRERELEASE}".`);
|
||||
return DEFAULT_TAG_PRERELEASE;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveTag(version) {
|
||||
const { tag } = this.options;
|
||||
const { isPreRelease, preReleaseId } = parseVersion(version);
|
||||
if (!isPreRelease) {
|
||||
return DEFAULT_TAG;
|
||||
} else {
|
||||
return tag || preReleaseId || (await this.guessPreReleaseTag());
|
||||
}
|
||||
}
|
||||
|
||||
async publish({ otp = this.options.otp, otpCallback } = {}) {
|
||||
const { publishPath = '.', publishArgs } = this.options;
|
||||
const { private: isPrivate, tag = DEFAULT_TAG } = this.getContext();
|
||||
const otpArg = otp ? `--otp ${otp}` : '';
|
||||
const dryRunArg = this.config.isDryRun ? '--dry-run' : '';
|
||||
if (isPrivate) {
|
||||
this.log.warn('Skip publish: package is private.');
|
||||
return false;
|
||||
}
|
||||
const args = [publishPath, `--tag ${tag}`, otpArg, dryRunArg, ...fixArgs(publishArgs)].filter(Boolean);
|
||||
return this.exec(`npm publish ${args.join(' ')}`, { options })
|
||||
.then(() => {
|
||||
this.setContext({ isReleased: true });
|
||||
})
|
||||
.catch(err => {
|
||||
this.debug(err);
|
||||
if (/one-time pass/.test(err)) {
|
||||
if (otp != null) {
|
||||
this.log.warn('The provided OTP is incorrect or has expired.');
|
||||
}
|
||||
if (otpCallback) {
|
||||
return otpCallback(otp => this.publish({ otp, otpCallback }));
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
afterRelease() {
|
||||
const { isReleased } = this.getContext();
|
||||
if (isReleased) {
|
||||
this.log.log(`🔗 ${this.getPackageUrl()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = npm;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"combineLatest.js","sources":["../../../src/internal/observable/combineLatest.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAG,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAG,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,IAAI,GAAG,EAAE,CAAC;AAsNhB,MAAM,UAAU,aAAa,CAC3B,GAAG,WAA6E;IAEhF,IAAI,cAAc,GAAgD,SAAS,CAAC;IAC5E,IAAI,SAAS,GAA4B,SAAS,CAAC;IAEnD,IAAI,WAAW,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE;QACpD,SAAS,GAAG,WAAW,CAAC,GAAG,EAAmB,CAAC;KAChD;IAED,IAAI,OAAO,WAAW,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,UAAU,EAAE;QAC7D,cAAc,GAAG,WAAW,CAAC,GAAG,EAAkC,CAAC;KACpE;IAID,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE;QACvD,WAAW,GAAG,WAAW,CAAC,CAAC,CAAQ,CAAC;KACrC;IAED,OAAO,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,qBAAqB,CAAC,cAAc,CAAC,CAAC,CAAC;AAC3F,CAAC;AAED,MAAM,OAAO,qBAAqB;IAChC,YAAoB,cAA6C;QAA7C,mBAAc,GAAd,cAAc,CAA+B;IACjE,CAAC;IAED,IAAI,CAAC,UAAyB,EAAE,MAAW;QACzC,OAAO,MAAM,CAAC,SAAS,CAAC,IAAI,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC;IACxF,CAAC;CACF;AAOD,MAAM,OAAO,uBAA8B,SAAQ,eAAqB;IAMtE,YAAY,WAA0B,EAAU,cAA6C;QAC3F,KAAK,CAAC,WAAW,CAAC,CAAC;QAD2B,mBAAc,GAAd,cAAc,CAA+B;QALrF,WAAM,GAAW,CAAC,CAAC;QACnB,WAAM,GAAU,EAAE,CAAC;QACnB,gBAAW,GAAU,EAAE,CAAC;IAKhC,CAAC;IAES,KAAK,CAAC,UAAe;QAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACpC,CAAC;IAES,SAAS;QACjB,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;QACrC,MAAM,GAAG,GAAG,WAAW,CAAC,MAAM,CAAC;QAC/B,IAAI,GAAG,KAAK,CAAC,EAAE;YACb,IAAI,CAAC,WAAW,CAAC,QAAS,EAAE,CAAC;SAC9B;aAAM;YACL,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC;YAClB,IAAI,CAAC,SAAS,GAAG,GAAG,CAAC;YACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;gBAC5B,MAAM,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;gBAClC,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;aAC7D;SACF;IACH,CAAC;IAED,cAAc,CAAC,MAAqB;QAClC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE;YAC5B,IAAI,CAAC,WAAW,CAAC,QAAS,EAAE,CAAC;SAC9B;IACH,CAAC;IAED,UAAU,CAAC,WAAc,EAAE,UAAa,EAC7B,UAAkB;QAC3B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;QAClC,MAAM,SAAS,GAAG,CAAC,IAAI,CAAC,SAAS;YAC/B,CAAC,CAAC,CAAC;YACH,CAAC,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;QACxD,MAAM,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;QAEhC,IAAI,SAAS,KAAK,CAAC,EAAE;YACnB,IAAI,IAAI,CAAC,cAAc,EAAE;gBACvB,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;aACjC;iBAAM;gBACL,IAAI,CAAC,WAAW,CAAC,IAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;aACxC;SACF;IACH,CAAC;IAEO,kBAAkB,CAAC,MAAa;QACtC,IAAI,MAAW,CAAC;QAChB,IAAI;YACF,MAAM,GAAG,IAAI,CAAC,cAAe,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;SACnD;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,CAAC,WAAW,CAAC,KAAM,CAAC,GAAG,CAAC,CAAC;YAC7B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,CAAC,IAAK,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;CACF"}
|
||||
@@ -0,0 +1,658 @@
|
||||
<div align="center">
|
||||
<br>
|
||||
<br>
|
||||
<img src="media/logo.svg" alt="type-fest" height="300">
|
||||
<br>
|
||||
<br>
|
||||
<b>A collection of essential TypeScript types</b>
|
||||
<br>
|
||||
<hr>
|
||||
</div>
|
||||
<br>
|
||||
<br>
|
||||
|
||||
[](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i)
|
||||
<!-- Commented out until they actually show anything
|
||||
[](https://www.npmjs.com/package/type-fest?activeTab=dependents) [](https://www.npmjs.com/package/type-fest)
|
||||
-->
|
||||
|
||||
Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
|
||||
|
||||
PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install type-fest
|
||||
```
|
||||
|
||||
*Requires TypeScript >=3.4*
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import {Except} from 'type-fest';
|
||||
|
||||
type Foo = {
|
||||
unicorn: string;
|
||||
rainbow: boolean;
|
||||
};
|
||||
|
||||
type FooWithoutRainbow = Except<Foo, 'rainbow'>;
|
||||
//=> {unicorn: string}
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
Click the type names for complete docs.
|
||||
|
||||
### Basic
|
||||
|
||||
- [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
|
||||
- [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
|
||||
- [`TypedArray`](source/basic.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
|
||||
- [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
|
||||
- [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
|
||||
- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.
|
||||
- [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
|
||||
|
||||
### Utilities
|
||||
|
||||
- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type).
|
||||
- [`Mutable`](source/mutable.d.ts) - Convert an object with `readonly` keys into a mutable object. The inverse of `Readonly<T>`.
|
||||
- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
|
||||
- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
|
||||
- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
|
||||
- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
|
||||
- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) if you only need one level deep.
|
||||
- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) if you only need one level deep.
|
||||
- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
|
||||
- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
|
||||
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
|
||||
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
|
||||
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
|
||||
- [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from.
|
||||
- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise`.
|
||||
- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`.
|
||||
- [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type.
|
||||
- [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type.
|
||||
- [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type.
|
||||
- [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type.
|
||||
- [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type.
|
||||
- [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length.
|
||||
- [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
|
||||
- [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection.
|
||||
- [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection.
|
||||
- [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type.
|
||||
- [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type.
|
||||
|
||||
### Template literal types
|
||||
|
||||
*Note:* These require [TypeScript 4.1 or newer](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#template-literal-types).
|
||||
|
||||
- [`CamelCase`](ts41/camel-case.d.ts) – Convert a string literal to camel-case (`fooBar`).
|
||||
- [`KebabCase`](ts41/kebab-case.d.ts) – Convert a string literal to kebab-case (`foo-bar`).
|
||||
- [`PascalCase`](ts41/pascal-case.d.ts) – Converts a string literal to pascal-case (`FooBar`)
|
||||
- [`SnakeCase`](ts41/snake-case.d.ts) – Convert a string literal to snake-case (`foo_bar`).
|
||||
- [`DelimiterCase`](ts41/delimiter-case.d.ts) – Convert a string literal to a custom string delimiter casing.
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file).
|
||||
- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7).
|
||||
|
||||
## Declined types
|
||||
|
||||
*If we decline a type addition, we will make sure to document the better solution here.*
|
||||
|
||||
- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The PR author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider.
|
||||
- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary<number>` vs `Record<string, number>`) from [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now.
|
||||
- [`SubType`](https://github.com/sindresorhus/type-fest/issues/22) - The type is powerful, but lacks good use-cases and is prone to misuse.
|
||||
- [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies.
|
||||
|
||||
## Tips
|
||||
|
||||
### Built-in types
|
||||
|
||||
There are many advanced types most users don't know about.
|
||||
|
||||
- [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA)
|
||||
|
||||
```ts
|
||||
interface NodeConfig {
|
||||
appName: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
class NodeAppBuilder {
|
||||
private configuration: NodeConfig = {
|
||||
appName: 'NodeApp',
|
||||
port: 3000
|
||||
};
|
||||
|
||||
private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
|
||||
this.configuration[key] = value;
|
||||
}
|
||||
|
||||
config(config: Partial<NodeConfig>) {
|
||||
type NodeConfigKey = keyof NodeConfig;
|
||||
|
||||
for (const key of Object.keys(config) as NodeConfigKey[]) {
|
||||
const updateValue = config[key];
|
||||
|
||||
if (updateValue === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.updateConfig(key, updateValue);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
// `Partial<NodeConfig>`` allows us to provide only a part of the
|
||||
// NodeConfig interface.
|
||||
new NodeAppBuilder().config({appName: 'ToDoApp'});
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Required<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)
|
||||
|
||||
```ts
|
||||
interface ContactForm {
|
||||
email?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
function submitContactForm(formData: Required<ContactForm>) {
|
||||
// Send the form data to the server.
|
||||
}
|
||||
|
||||
submitContactForm({
|
||||
email: 'ex@mple.com',
|
||||
message: 'Hi! Could you tell me more about…',
|
||||
});
|
||||
|
||||
// TypeScript error: missing property 'message'
|
||||
submitContactForm({
|
||||
email: 'ex@mple.com',
|
||||
});
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)
|
||||
|
||||
```ts
|
||||
enum LogLevel {
|
||||
Off,
|
||||
Debug,
|
||||
Error,
|
||||
Fatal
|
||||
};
|
||||
|
||||
interface LoggerConfig {
|
||||
name: string;
|
||||
level: LogLevel;
|
||||
}
|
||||
|
||||
class Logger {
|
||||
config: Readonly<LoggerConfig>;
|
||||
|
||||
constructor({name, level}: LoggerConfig) {
|
||||
this.config = {name, level};
|
||||
Object.freeze(this.config);
|
||||
}
|
||||
}
|
||||
|
||||
const config: LoggerConfig = {
|
||||
name: 'MyApp',
|
||||
level: LogLevel.Debug
|
||||
};
|
||||
|
||||
const logger = new Logger(config);
|
||||
|
||||
// TypeScript Error: cannot assign to read-only property.
|
||||
logger.config.level = LogLevel.Error;
|
||||
|
||||
// We are able to edit config variable as we please.
|
||||
config.level = LogLevel.Error;
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Pick<T, K>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1422-L1427) - From `T`, pick a set of properties whose keys are in the union `K`.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)
|
||||
|
||||
```ts
|
||||
interface Article {
|
||||
title: string;
|
||||
thumbnail: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
// Creates new type out of the `Article` interface composed
|
||||
// from the Articles' two properties: `title` and `thumbnail`.
|
||||
// `ArticlePreview = {title: string; thumbnail: string}`
|
||||
type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
|
||||
|
||||
// Render a list of articles using only title and description.
|
||||
function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
|
||||
const articles = document.createElement('div');
|
||||
|
||||
for (const preview of previews) {
|
||||
// Append preview to the articles.
|
||||
}
|
||||
|
||||
return articles;
|
||||
}
|
||||
|
||||
const articles = renderArticlePreviews([
|
||||
{
|
||||
title: 'TypeScript tutorial!',
|
||||
thumbnail: '/assets/ts.jpg'
|
||||
}
|
||||
]);
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Record<K, T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434) - Construct a type with a set of properties `K` of type `T`.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)
|
||||
|
||||
```ts
|
||||
// Positions of employees in our company.
|
||||
type MemberPosition = 'intern' | 'developer' | 'tech-lead';
|
||||
|
||||
// Interface describing properties of a single employee.
|
||||
interface Employee {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
yearsOfExperience: number;
|
||||
}
|
||||
|
||||
// Create an object that has all possible `MemberPosition` values set as keys.
|
||||
// Those keys will store a collection of Employees of the same position.
|
||||
const team: Record<MemberPosition, Employee[]> = {
|
||||
intern: [],
|
||||
developer: [],
|
||||
'tech-lead': [],
|
||||
};
|
||||
|
||||
// Our team has decided to help John with his dream of becoming Software Developer.
|
||||
team.intern.push({
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
yearsOfExperience: 0
|
||||
});
|
||||
|
||||
// `Record` forces you to initialize all of the property keys.
|
||||
// TypeScript Error: "tech-lead" property is missing
|
||||
const teamEmpty: Record<MemberPosition, null> = {
|
||||
intern: null,
|
||||
developer: null,
|
||||
};
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Exclude<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1436-L1439) - Exclude from `T` those types that are assignable to `U`.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)
|
||||
|
||||
```ts
|
||||
interface ServerConfig {
|
||||
port: null | string | number;
|
||||
}
|
||||
|
||||
type RequestHandler = (request: Request, response: Response) => void;
|
||||
|
||||
// Exclude `null` type from `null | string | number`.
|
||||
// In case the port is equal to `null`, we will use default value.
|
||||
function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
|
||||
if (typeof port === 'string') {
|
||||
return parseInt(port, 10);
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function startServer(handler: RequestHandler, config: ServerConfig): void {
|
||||
const server = require('http').createServer(handler);
|
||||
|
||||
const port = config.port === null ? 3000 : getPortValue(config.port);
|
||||
server.listen(port);
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Extract<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1441-L1444) - Extract from `T` those types that are assignable to `U`.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)
|
||||
|
||||
```ts
|
||||
declare function uniqueId(): number;
|
||||
|
||||
const ID = Symbol('ID');
|
||||
|
||||
interface Person {
|
||||
[ID]: number;
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
|
||||
// Allows changing the person data as long as the property key is of string type.
|
||||
function changePersonData<
|
||||
Obj extends Person,
|
||||
Key extends Extract<keyof Person, string>,
|
||||
Value extends Obj[Key]
|
||||
> (obj: Obj, key: Key, value: Value): void {
|
||||
obj[key] = value;
|
||||
}
|
||||
|
||||
// Tiny Andrew was born.
|
||||
const andrew = {
|
||||
[ID]: uniqueId(),
|
||||
name: 'Andrew',
|
||||
age: 0,
|
||||
};
|
||||
|
||||
// Cool, we're fine with that.
|
||||
changePersonData(andrew, 'name', 'Pony');
|
||||
|
||||
// Goverment didn't like the fact that you wanted to change your identity.
|
||||
changePersonData(andrew, ID, uniqueId());
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`NonNullable<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
Works with <code>strictNullChecks</code> set to <code>true</code>. (Read more <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html">here</a>)
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)
|
||||
|
||||
```ts
|
||||
type PortNumber = string | number | null;
|
||||
|
||||
/** Part of a class definition that is used to build a server */
|
||||
class ServerBuilder {
|
||||
portNumber!: NonNullable<PortNumber>;
|
||||
|
||||
port(this: ServerBuilder, port: PortNumber): ServerBuilder {
|
||||
if (port == null) {
|
||||
this.portNumber = 8000;
|
||||
} else {
|
||||
this.portNumber = port;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
const serverBuilder = new ServerBuilder();
|
||||
|
||||
serverBuilder
|
||||
.port('8000') // portNumber = '8000'
|
||||
.port(null) // portNumber = 8000
|
||||
.port(3000); // portNumber = 3000
|
||||
|
||||
// TypeScript error
|
||||
serverBuilder.portNumber = null;
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Parameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1451-L1454) - Obtain the parameters of a function type in a tuple.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)
|
||||
|
||||
```ts
|
||||
function shuffle(input: any[]): void {
|
||||
// Mutate array randomly changing its' elements indexes.
|
||||
}
|
||||
|
||||
function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
|
||||
// Type that represents the type of the received function parameters.
|
||||
type FunctionParameters = Parameters<Fn>;
|
||||
|
||||
return function (...args: FunctionParameters) {
|
||||
for (let i = 0; i < callCount; i++) {
|
||||
func(...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const shuffleTwice = callNTimes(shuffle, 2);
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`ConstructorParameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1456-L1459) - Obtain the parameters of a constructor function type in a tuple.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)
|
||||
|
||||
```ts
|
||||
class ArticleModel {
|
||||
title: string;
|
||||
content?: string;
|
||||
|
||||
constructor(title: string) {
|
||||
this.title = title;
|
||||
}
|
||||
}
|
||||
|
||||
class InstanceCache<T extends (new (...args: any[]) => any)> {
|
||||
private ClassConstructor: T;
|
||||
private cache: Map<string, InstanceType<T>> = new Map();
|
||||
|
||||
constructor (ctr: T) {
|
||||
this.ClassConstructor = ctr;
|
||||
}
|
||||
|
||||
getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
|
||||
const hash = this.calculateArgumentsHash(...args);
|
||||
|
||||
const existingInstance = this.cache.get(hash);
|
||||
if (existingInstance !== undefined) {
|
||||
return existingInstance;
|
||||
}
|
||||
|
||||
return new this.ClassConstructor(...args);
|
||||
}
|
||||
|
||||
private calculateArgumentsHash(...args: any[]): string {
|
||||
// Calculate hash.
|
||||
return 'hash';
|
||||
}
|
||||
}
|
||||
|
||||
const articleCache = new InstanceCache(ArticleModel);
|
||||
const amazonArticle = articleCache.getInstance('Amazon forests burining!');
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`ReturnType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) – Obtain the return type of a function type.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
|
||||
|
||||
```ts
|
||||
/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
|
||||
function mapIter<
|
||||
Elem,
|
||||
Func extends (elem: Elem) => any,
|
||||
Ret extends ReturnType<Func>
|
||||
>(iter: Iterable<Elem>, callback: Func): Ret[] {
|
||||
const mapped: Ret[] = [];
|
||||
|
||||
for (const elem of iter) {
|
||||
mapped.push(callback(elem));
|
||||
}
|
||||
|
||||
return mapped;
|
||||
}
|
||||
|
||||
const setObject: Set<string> = new Set();
|
||||
const mapObject: Map<number, string> = new Map();
|
||||
|
||||
mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
|
||||
|
||||
mapIter(mapObject, ([key, value]: [number, string]) => {
|
||||
return key % 2 === 0 ? value : 'Odd';
|
||||
}); // string[]
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`InstanceType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1466-L1469) – Obtain the instance type of a constructor function type.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
|
||||
|
||||
```ts
|
||||
class IdleService {
|
||||
doNothing (): void {}
|
||||
}
|
||||
|
||||
class News {
|
||||
title: string;
|
||||
content: string;
|
||||
|
||||
constructor(title: string, content: string) {
|
||||
this.title = title;
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
|
||||
const instanceCounter: Map<Function, number> = new Map();
|
||||
|
||||
interface Constructor {
|
||||
new(...args: any[]): any;
|
||||
}
|
||||
|
||||
// Keep track how many instances of `Constr` constructor have been created.
|
||||
function getInstance<
|
||||
Constr extends Constructor,
|
||||
Args extends ConstructorParameters<Constr>
|
||||
>(constructor: Constr, ...args: Args): InstanceType<Constr> {
|
||||
let count = instanceCounter.get(constructor) || 0;
|
||||
|
||||
const instance = new constructor(...args);
|
||||
|
||||
instanceCounter.set(constructor, count + 1);
|
||||
|
||||
console.log(`Created ${count + 1} instances of ${Constr.name} class`);
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
|
||||
const idleService = getInstance(IdleService);
|
||||
// Will log: `Created 1 instances of IdleService class`
|
||||
const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
|
||||
// Will log: `Created 1 instances of News class`
|
||||
```
|
||||
</details>
|
||||
|
||||
- [`Omit<T, K>`](https://github.com/microsoft/TypeScript/blob/71af02f7459dc812e85ac31365bfe23daf14b4e4/src/lib/es5.d.ts#L1446) – Constructs a type by picking all properties from T and then removing K.
|
||||
<details>
|
||||
<summary>
|
||||
Example
|
||||
</summary>
|
||||
|
||||
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)
|
||||
|
||||
```ts
|
||||
interface Animal {
|
||||
imageUrl: string;
|
||||
species: string;
|
||||
images: string[];
|
||||
paragraphs: string[];
|
||||
}
|
||||
|
||||
// Creates new type with all properties of the `Animal` interface
|
||||
// except 'images' and 'paragraphs' properties. We can use this
|
||||
// type to render small hover tooltip for a wiki entry list.
|
||||
type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
|
||||
|
||||
function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
|
||||
const container = document.createElement('div');
|
||||
// Internal implementation.
|
||||
return container;
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types).
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Jarek Radosz](https://github.com/CvX)
|
||||
- [Dimitri Benin](https://github.com/BendingBender)
|
||||
- [Pelle Wessman](https://github.com/voxpelli)
|
||||
|
||||
## License
|
||||
|
||||
(MIT OR CC0-1.0)
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<b>
|
||||
<a href="https://tidelift.com/subscription/pkg/npm-type-fest?utm_source=npm-type-fest&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
|
||||
</b>
|
||||
<br>
|
||||
<sub>
|
||||
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
|
||||
</sub>
|
||||
</div>
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"min.js","sources":["../src/operator/min.ts"],"names":[],"mappings":";;;;;AAAA,8CAAyC"}
|
||||
Reference in New Issue
Block a user