Mukho

Board hits, Profile-session, Add link, etc

Showing 288 changed files with 4762 additions and 5 deletions
var express = require('express')
var app = express()
// 설치한 express 모듈 불러오기
const express = require('express')
// 설치한 socket.io 모듈 불러오기
const socket = require('socket.io')
// Node.js 기본 내장 모듈 불러오기
const http = require('http')
const fs = require('fs')
// express 객체 생성
const app = express()
// express http 서버 생성
const server = http.createServer(app)
// 생성된 서버를 socket.io에 바인딩
const io = socket(server)
var bodyParser = require('body-parser')
var router = require('./router/index')
var passport = require('passport')
......@@ -17,6 +34,7 @@ app.use("/views", express.static(__dirname + "/views"))
app.use("/css", express.static(__dirname + "/css"));
app.use("/assets", express.static(__dirname + "/assets"));
app.use("/js", express.static(__dirname + "/js"));
app.use("/chat", express.static(__dirname+ "/chat"));
app.set('view engine', 'ejs')
app.use(session({
......@@ -30,6 +48,40 @@ app.use(passport.session())
app.use(flash())
app.use(router) // router 정의
app.listen(PORT, function(){
// Socket.io
io.sockets.on('connection', function(socket) {
/* 새로운 유저가 접속했을 경우 다른 소켓에게도 알려줌 */
socket.on('newUser', function(name) {
console.log(name + ' 님이 접속하였습니다.')
/* 소켓에 이름 저장해두기 */
socket.name = name
/* 모든 소켓에게 전송 */
io.sockets.emit('update', {type: 'connect', name: 'SERVER', message: name + '님이 접속하였습니다.'})
})
/* 전송한 메시지 받기 */
socket.on('message', function(data) {
/* 받은 데이터에 누가 보냈는지 이름을 추가 */
data.name = socket.name
console.log(data)
/* 보낸 사람을 제외한 나머지 유저에게 메시지 전송 */
socket.broadcast.emit('update', data);
})
/* 접속 종료 */
socket.on('disconnect', function() {
console.log(socket.name + '님이 나가셨습니다.')
/* 나가는 사람을 제외한 나머지 유저에게 메시지 전송 */
socket.broadcast.emit('update', {type: 'disconnect', name: 'SERVER', message: socket.name + '님이 나가셨습니다.'});
})
})
server.listen(PORT, function(){
console.log("서버를 구동합니다.(Port: "+PORT+")");
});
\ No newline at end of file
......
......@@ -6,7 +6,7 @@ module.exports=function(){
init: function(){
return mysql.createConnection({
host:'localhost',
port:'3306',
port:3306,
user:'root',
password:'',
database:'singer_composer'
......
......@@ -2,7 +2,7 @@ module.exports=(function(){
return{
board:{
host:'localhost',
port:'3306',
port:3306,
user:'root',
password:'',
database:'singer_composer'
......
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/component-emitter`
# Summary
This package contains type definitions for component-emitter (https://www.npmjs.com/package/component-emitter).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/component-emitter.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/component-emitter/index.d.ts)
````ts
// Type definitions for component-emitter v1.2.1
// Project: https://www.npmjs.com/package/component-emitter
// Definitions by: Peter Snider <https://github.com/psnider>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
interface Emitter<Event = string> {
on(event: Event, listener: Function): Emitter;
once(event: Event, listener: Function): Emitter;
off(event?: Event, listener?: Function): Emitter;
emit(event: Event, ...args: any[]): Emitter;
listeners(event: Event): Function[];
hasListeners(event: Event): boolean;
removeListener(event?: Event, listener?: Function): Emitter;
removeEventListener(event?: Event, listener?: Function): Emitter;
removeAllListeners(event?: Event): Emitter;
}
declare const Emitter: {
(obj?: object): Emitter;
new (obj?: object): Emitter;
};
export = Emitter;
````
### Additional Details
* Last updated: Thu, 14 Oct 2021 19:01:31 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Peter Snider](https://github.com/psnider).
// Type definitions for component-emitter v1.2.1
// Project: https://www.npmjs.com/package/component-emitter
// Definitions by: Peter Snider <https://github.com/psnider>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
interface Emitter<Event = string> {
on(event: Event, listener: Function): Emitter;
once(event: Event, listener: Function): Emitter;
off(event?: Event, listener?: Function): Emitter;
emit(event: Event, ...args: any[]): Emitter;
listeners(event: Event): Function[];
hasListeners(event: Event): boolean;
removeListener(event?: Event, listener?: Function): Emitter;
removeEventListener(event?: Event, listener?: Function): Emitter;
removeAllListeners(event?: Event): Emitter;
}
declare const Emitter: {
(obj?: object): Emitter;
new (obj?: object): Emitter;
};
export = Emitter;
{
"_from": "@types/component-emitter@^1.2.10",
"_id": "@types/component-emitter@1.2.11",
"_inBundle": false,
"_integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==",
"_location": "/@types/component-emitter",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/component-emitter@^1.2.10",
"name": "@types/component-emitter",
"escapedName": "@types%2fcomponent-emitter",
"scope": "@types",
"rawSpec": "^1.2.10",
"saveSpec": null,
"fetchSpec": "^1.2.10"
},
"_requiredBy": [
"/socket.io-parser"
],
"_resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz",
"_shasum": "50d47d42b347253817a39709fef03ce66a108506",
"_spec": "@types/component-emitter@^1.2.10",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\socket.io-parser",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Peter Snider",
"url": "https://github.com/psnider"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for component-emitter",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/component-emitter",
"license": "MIT",
"main": "",
"name": "@types/component-emitter",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/component-emitter"
},
"scripts": {},
"typeScriptVersion": "3.7",
"types": "index.d.ts",
"typesPublisherContentHash": "d86d217b63101effae1228ebbfe02ac682ee4eb8abd6fc0dcc9948a4b6fdf572",
"version": "1.2.11"
}
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/cookie`
# Summary
This package contains type definitions for cookie (https://github.com/jshttp/cookie).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie.
### Additional Details
* Last updated: Tue, 06 Jul 2021 20:32:30 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Pine Mizune](https://github.com/pine), and [Piotr Błażejewicz](https://github.com/peterblazejewicz).
// Type definitions for cookie 0.4
// Project: https://github.com/jshttp/cookie
// Definitions by: Pine Mizune <https://github.com/pine>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Basic HTTP cookie parser and serializer for HTTP servers.
*/
/**
* Additional serialization options
*/
export interface CookieSerializeOptions {
/**
* Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
* domain is set, and most clients will consider the cookie to apply to only
* the current domain.
*/
domain?: string | undefined;
/**
* Specifies a function that will be used to encode a cookie's value. Since
* value of a cookie has a limited character set (and must be a simple
* string), this function can be used to encode a value into a string suited
* for a cookie's value.
*
* The default function is the global `encodeURIComponent`, which will
* encode a JavaScript string into UTF-8 byte sequences and then URL-encode
* any that fall outside of the cookie range.
*/
encode?(value: string): string;
/**
* Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,
* no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
* it on a condition like exiting a web browser application.
*
* *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
* states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
expires?: Date | undefined;
/**
* Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
* When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
* default, the `HttpOnly` attribute is not set.
*
* *Note* be careful when setting this to true, as compliant clients will
* not allow client-side JavaScript to see the cookie in `document.cookie`.
*/
httpOnly?: boolean | undefined;
/**
* Specifies the number (in seconds) to be the value for the `Max-Age`
* `Set-Cookie` attribute. The given number will be converted to an integer
* by rounding down. By default, no maximum age is set.
*
* *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
* states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
maxAge?: number | undefined;
/**
* Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
* By default, the path is considered the "default path".
*/
path?: string | undefined;
/**
* Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.
*
* - `true` will set the `SameSite` attribute to `Strict` for strict same
* site enforcement.
* - `false` will not set the `SameSite` attribute.
* - `'lax'` will set the `SameSite` attribute to Lax for lax same site
* enforcement.
* - `'strict'` will set the `SameSite` attribute to Strict for strict same
* site enforcement.
* - `'none'` will set the SameSite attribute to None for an explicit
* cross-site cookie.
*
* More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
*
* *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
*/
sameSite?: true | false | 'lax' | 'strict' | 'none' | undefined;
/**
* Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
* `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
*
* *Note* be careful when setting this to `true`, as compliant clients will
* not send the cookie back to the server in the future if the browser does
* not have an HTTPS connection.
*/
secure?: boolean | undefined;
}
/**
* Additional parsing options
*/
export interface CookieParseOptions {
/**
* Specifies a function that will be used to decode a cookie's value. Since
* the value of a cookie has a limited character set (and must be a simple
* string), this function can be used to decode a previously-encoded cookie
* value into a JavaScript string or other object.
*
* The default function is the global `decodeURIComponent`, which will decode
* any URL-encoded sequences into their byte representations.
*
* *Note* if an error is thrown from this function, the original, non-decoded
* cookie value will be returned as the cookie's value.
*/
decode?(value: string): string;
}
/**
* Parse an HTTP Cookie header string and returning an object of all cookie
* name-value pairs.
*
* @param str the string representing a `Cookie` header value
* @param [options] object containing parsing options
*/
export function parse(str: string, options?: CookieParseOptions): { [key: string]: string };
/**
* Serialize a cookie name-value pair into a `Set-Cookie` header string.
*
* @param name the name for the cookie
* @param value value to set the cookie to
* @param [options] object containing serialization options
* @throws {TypeError} when `maxAge` options is invalid
*/
export function serialize(name: string, value: string, options?: CookieSerializeOptions): string;
{
"_from": "@types/cookie@^0.4.1",
"_id": "@types/cookie@0.4.1",
"_inBundle": false,
"_integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==",
"_location": "/@types/cookie",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/cookie@^0.4.1",
"name": "@types/cookie",
"escapedName": "@types%2fcookie",
"scope": "@types",
"rawSpec": "^0.4.1",
"saveSpec": null,
"fetchSpec": "^0.4.1"
},
"_requiredBy": [
"/engine.io"
],
"_resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz",
"_shasum": "bfd02c1f2224567676c1545199f87c3a861d878d",
"_spec": "@types/cookie@^0.4.1",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\engine.io",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Pine Mizune",
"url": "https://github.com/pine"
},
{
"name": "Piotr Błażejewicz",
"url": "https://github.com/peterblazejewicz"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for cookie",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie",
"license": "MIT",
"main": "",
"name": "@types/cookie",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/cookie"
},
"scripts": {},
"typeScriptVersion": "3.6",
"types": "index.d.ts",
"typesPublisherContentHash": "7d4a6dd505c896319459ae131b5fa8fc0a2ed25552db53dac87946119bb21559",
"version": "0.4.1"
}
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/cors`
# Summary
This package contains type definitions for cors (https://github.com/expressjs/cors/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors/index.d.ts)
````ts
// Type definitions for cors 2.8
// Project: https://github.com/expressjs/cors/
// Definitions by: Alan Plum <https://github.com/pluma>
// Gaurav Sharma <https://github.com/gtpan77>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { IncomingHttpHeaders } from 'http';
type StaticOrigin = boolean | string | RegExp | (boolean | string | RegExp)[];
type CustomOrigin = (requestOrigin: string | undefined, callback: (err: Error | null, origin?: StaticOrigin) => void) => void;
declare namespace e {
interface CorsRequest {
method?: string | undefined;
headers: IncomingHttpHeaders;
}
interface CorsOptions {
/**
* @default '*''
*/
origin?: StaticOrigin | CustomOrigin | undefined;
/**
* @default 'GET,HEAD,PUT,PATCH,POST,DELETE'
*/
methods?: string | string[] | undefined;
allowedHeaders?: string | string[] | undefined;
exposedHeaders?: string | string[] | undefined;
credentials?: boolean | undefined;
maxAge?: number | undefined;
/**
* @default false
*/
preflightContinue?: boolean | undefined;
/**
* @default 204
*/
optionsSuccessStatus?: number | undefined;
}
type CorsOptionsDelegate<T extends CorsRequest = CorsRequest> = (
req: T,
callback: (err: Error | null, options?: CorsOptions) => void,
) => void;
}
declare function e<T extends e.CorsRequest = e.CorsRequest>(
options?: e.CorsOptions | e.CorsOptionsDelegate<T>,
): (
req: T,
res: {
statusCode?: number | undefined;
setHeader(key: string, value: string): any;
end(): any;
},
next: (err?: any) => any,
) => void;
export = e;
````
### Additional Details
* Last updated: Fri, 09 Jul 2021 07:31:29 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Alan Plum](https://github.com/pluma), and [Gaurav Sharma](https://github.com/gtpan77).
// Type definitions for cors 2.8
// Project: https://github.com/expressjs/cors/
// Definitions by: Alan Plum <https://github.com/pluma>
// Gaurav Sharma <https://github.com/gtpan77>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { IncomingHttpHeaders } from 'http';
type StaticOrigin = boolean | string | RegExp | (boolean | string | RegExp)[];
type CustomOrigin = (requestOrigin: string | undefined, callback: (err: Error | null, origin?: StaticOrigin) => void) => void;
declare namespace e {
interface CorsRequest {
method?: string | undefined;
headers: IncomingHttpHeaders;
}
interface CorsOptions {
/**
* @default '*''
*/
origin?: StaticOrigin | CustomOrigin | undefined;
/**
* @default 'GET,HEAD,PUT,PATCH,POST,DELETE'
*/
methods?: string | string[] | undefined;
allowedHeaders?: string | string[] | undefined;
exposedHeaders?: string | string[] | undefined;
credentials?: boolean | undefined;
maxAge?: number | undefined;
/**
* @default false
*/
preflightContinue?: boolean | undefined;
/**
* @default 204
*/
optionsSuccessStatus?: number | undefined;
}
type CorsOptionsDelegate<T extends CorsRequest = CorsRequest> = (
req: T,
callback: (err: Error | null, options?: CorsOptions) => void,
) => void;
}
declare function e<T extends e.CorsRequest = e.CorsRequest>(
options?: e.CorsOptions | e.CorsOptionsDelegate<T>,
): (
req: T,
res: {
statusCode?: number | undefined;
setHeader(key: string, value: string): any;
end(): any;
},
next: (err?: any) => any,
) => void;
export = e;
{
"_from": "@types/cors@^2.8.12",
"_id": "@types/cors@2.8.12",
"_inBundle": false,
"_integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==",
"_location": "/@types/cors",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/cors@^2.8.12",
"name": "@types/cors",
"escapedName": "@types%2fcors",
"scope": "@types",
"rawSpec": "^2.8.12",
"saveSpec": null,
"fetchSpec": "^2.8.12"
},
"_requiredBy": [
"/engine.io"
],
"_resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz",
"_shasum": "6b2c510a7ad7039e98e7b8d3d6598f4359e5c080",
"_spec": "@types/cors@^2.8.12",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\engine.io",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Alan Plum",
"url": "https://github.com/pluma"
},
{
"name": "Gaurav Sharma",
"url": "https://github.com/gtpan77"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for cors",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors",
"license": "MIT",
"main": "",
"name": "@types/cors",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/cors"
},
"scripts": {},
"typeScriptVersion": "3.6",
"types": "index.d.ts",
"typesPublisherContentHash": "53ea51a6543d58d3c1b9035a9c361d8f06d7be01973be2895820b2fb7ad9563a",
"version": "2.8.12"
}
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Mon, 08 Nov 2021 21:31:28 GMT
* Dependencies: none
* Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), and [wafuwafu13](https://github.com/wafuwafu13).
This diff is collapsed. Click to expand it.
declare module 'assert/strict' {
import { strict } from 'node:assert';
export = strict;
}
declare module 'node:assert/strict' {
import { strict } from 'node:assert';
export = strict;
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module 'constants' {
import { constants as osConstants, SignalConstants } from 'node:os';
import { constants as cryptoConstants } from 'node:crypto';
import { constants as fsConstants } from 'node:fs';
const exp: typeof osConstants.errno &
typeof osConstants.priority &
SignalConstants &
typeof cryptoConstants &
typeof fsConstants;
export = exp;
}
declare module 'node:constants' {
import constants = require('constants');
export = constants;
}
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
/**
* The `diagnostics_channel` module provides an API to create named channels
* to report arbitrary message data for diagnostics purposes.
*
* It can be accessed using:
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
* ```
*
* It is intended that a module writer wanting to report diagnostics messages
* will create one or many top-level channels to report messages through.
* Channels may also be acquired at runtime but it is not encouraged
* due to the additional overhead of doing so. Channels may be exported for
* convenience, but as long as the name is known it can be acquired anywhere.
*
* If you intend for your module to produce diagnostics data for others to
* consume it is recommended that you include documentation of what named
* channels are used along with the shape of the message data. Channel names
* should generally include the module name to avoid collisions with data from
* other modules.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/diagnostics_channel.js)
*/
declare module 'diagnostics_channel' {
/**
* Check if there are active subscribers to the named channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
*
* if (diagnostics_channel.hasSubscribers('my-channel')) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return If there are active subscribers
*/
function hasSubscribers(name: string): boolean;
/**
* This is the primary entry-point for anyone wanting to interact with a named
* channel. It produces a channel object which is optimized to reduce overhead at
* publish time as much as possible.
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return The named channel object
*/
function channel(name: string): Channel;
type ChannelListener = (name: string, message: unknown) => void;
/**
* The class `Channel` represents an individual named channel within the data
* pipeline. It is use to track subscribers and to publish messages when there
* are subscribers present. It exists as a separate object to avoid channel
* lookups at publish time, enabling very fast publish speeds and allowing
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
* with `new Channel(name)` is not supported.
* @since v15.1.0, v14.17.0
*/
class Channel {
readonly name: string;
/**
* Check if there are active subscribers to this channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* if (channel.hasSubscribers) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
*/
readonly hasSubscribers: boolean;
private constructor(name: string);
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.subscribe((message, name) => {
* // Received data
* });
* ```
* @since v15.1.0, v14.17.0
* @param onMessage The handler to receive channel messages
*/
subscribe(onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
*
* ```js
* import diagnostics_channel from 'diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* function onMessage(message, name) {
* // Received data
* }
*
* channel.subscribe(onMessage);
*
* channel.unsubscribe(onMessage);
* ```
* @since v15.1.0, v14.17.0
* @param onMessage The previous subscribed handler to remove
*/
unsubscribe(onMessage: ChannelListener): void;
}
}
declare module 'node:diagnostics_channel' {
export * from 'diagnostics_channel';
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/**
* **This module is pending deprecation.** Once a replacement API has been
* finalized, this module will be fully deprecated. Most developers should**not** have cause to use this module. Users who absolutely must have
* the functionality that domains provide may rely on it for the time being
* but should expect to have to migrate to a different solution
* in the future.
*
* Domains provide a way to handle multiple different IO operations as a
* single group. If any of the event emitters or callbacks registered to a
* domain emit an `'error'` event, or throw an error, then the domain object
* will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/domain.js)
*/
declare module 'domain' {
import EventEmitter = require('node:events');
/**
* The `Domain` class encapsulates the functionality of routing errors and
* uncaught exceptions to the active `Domain` object.
*
* To handle the errors that it catches, listen to its `'error'` event.
*/
class Domain extends EventEmitter {
/**
* An array of timers and event emitters that have been explicitly added
* to the domain.
*/
members: Array<EventEmitter | NodeJS.Timer>;
/**
* The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly
* pushes the domain onto the domain
* stack managed by the domain module (see {@link exit} for details on the
* domain stack). The call to `enter()` delimits the beginning of a chain of
* asynchronous calls and I/O operations bound to a domain.
*
* Calling `enter()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
enter(): void;
/**
* The `exit()` method exits the current domain, popping it off the domain stack.
* Any time execution is going to switch to the context of a different chain of
* asynchronous calls, it's important to ensure that the current domain is exited.
* The call to `exit()` delimits either the end of or an interruption to the chain
* of asynchronous calls and I/O operations bound to a domain.
*
* If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain.
*
* Calling `exit()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
exit(): void;
/**
* Run the supplied function in the context of the domain, implicitly
* binding all event emitters, timers, and lowlevel requests that are
* created in that context. Optionally, arguments can be passed to
* the function.
*
* This is the most basic way to use a domain.
*
* ```js
* const domain = require('domain');
* const fs = require('fs');
* const d = domain.create();
* d.on('error', (er) => {
* console.error('Caught error!', er);
* });
* d.run(() => {
* process.nextTick(() => {
* setTimeout(() => { // Simulating some various async stuff
* fs.open('non-existent file', 'r', (er, fd) => {
* if (er) throw er;
* // proceed...
* });
* }, 100);
* });
* });
* ```
*
* In this example, the `d.on('error')` handler will be triggered, rather
* than crashing the program.
*/
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
/**
* Explicitly adds an emitter to the domain. If any event handlers called by
* the emitter throw an error, or if the emitter emits an `'error'` event, it
* will be routed to the domain's `'error'` event, just like with implicit
* binding.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter or timer to be removed from the domain
*/
remove(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The returned function will be a wrapper around the supplied callback
* function. When the returned function is called, any errors that are
* thrown will be routed to the domain's `'error'` event.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
* // If this throws, it will also be passed to the domain.
* return cb(er, data ? JSON.parse(data) : null);
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The bound function
*/
bind<T extends Function>(callback: T): T;
/**
* This method is almost identical to {@link bind}. However, in
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
*
* In this way, the common `if (err) return callback(err);` pattern can be replaced
* with a single error handler in a single place.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.intercept((data) => {
* // Note, the first argument is never passed to the
* // callback since it is assumed to be the 'Error' argument
* // and thus intercepted by the domain.
*
* // If this throws, it will also be passed to the domain
* // so the error-handling logic can be moved to the 'error'
* // event on the domain instead of being repeated throughout
* // the program.
* return cb(null, JSON.parse(data));
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The intercepted function
*/
intercept<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module 'node:domain' {
export * from 'domain';
}
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require { }
interface RequireResolve extends NodeJS.RequireResolve { }
interface NodeModule extends NodeJS.Module { }
declare var process: NodeJS.Process;
declare var console: Console;
declare var __filename: string;
declare var __dirname: string;
declare var require: NodeRequire;
declare var module: NodeModule;
// Same as module.exports
declare var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
declare var gc: undefined | (() => void);
//#region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
*/
readonly signal: AbortSignal;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
*/
abort(): void;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
}
declare var AbortController: {
prototype: AbortController;
new(): AbortController;
};
declare var AbortSignal: {
prototype: AbortSignal;
new(): AbortSignal;
// TODO: Add abort() static
};
//#endregion borrowed
//#region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
//#endregion ArrayLike.at() end
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
declare namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | null;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string | Buffer;
setEncoding(encoding: BufferEncoding): this;
pause(): this;
resume(): this;
isPaused(): boolean;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined; }): T;
unpipe(destination?: WritableStream): this;
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
wrap(oldStream: ReadableStream): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
}
interface WritableStream extends EventEmitter {
writable: boolean;
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
end(cb?: () => void): void;
end(data: string | Uint8Array, cb?: () => void): void;
end(str: string, encoding?: BufferEncoding, cb?: () => void): void;
}
interface ReadWriteStream extends ReadableStream, WritableStream { }
interface RefCounted {
ref(): this;
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined; }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
'.js': (m: Module, filename: string) => any;
'.json': (m: Module, filename: string) => any;
'.node': (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since 11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
}
declare var global: typeof globalThis;
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
// Type definitions for non-npm package Node.js 16.11
// Project: https://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
// DefinitelyTyped <https://github.com/DefinitelyTyped>
// Alberto Schiabel <https://github.com/jkomyno>
// Alvis HT Tang <https://github.com/alvis>
// Andrew Makarov <https://github.com/r3nya>
// Benjamin Toueg <https://github.com/btoueg>
// Chigozirim C. <https://github.com/smac89>
// David Junger <https://github.com/touffy>
// Deividas Bakanas <https://github.com/DeividasBakanas>
// Eugene Y. Q. Shen <https://github.com/eyqs>
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
// Huw <https://github.com/hoo29>
// Kelvin Jin <https://github.com/kjin>
// Klaus Meinhardt <https://github.com/ajafff>
// Lishude <https://github.com/islishude>
// Mariusz Wiktorczyk <https://github.com/mwiktorczyk>
// Mohsen Azimi <https://github.com/mohsen1>
// Nicolas Even <https://github.com/n-e>
// Nikita Galkin <https://github.com/galkin>
// Parambir Singh <https://github.com/parambirs>
// Sebastian Silbermann <https://github.com/eps1lon>
// Simon Schick <https://github.com/SimonSchick>
// Thomas den Hollander <https://github.com/ThomasdenH>
// Wilco Bakker <https://github.com/WilcoBakker>
// wwwy3y3 <https://github.com/wwwy3y3>
// Samuel Ainsworth <https://github.com/samuela>
// Kyle Uehlein <https://github.com/kuehlein>
// Thanik Bhongbhibhat <https://github.com/bhongy>
// Marcin Kopacz <https://github.com/chyzwar>
// Trivikram Kamat <https://github.com/trivikr>
// Junxiao Shi <https://github.com/yoursunny>
// Ilia Baryshnikov <https://github.com/qwelias>
// ExE Boss <https://github.com/ExE-Boss>
// Surasak Chaisurin <https://github.com/Ryan-Willpower>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Anna Henningsen <https://github.com/addaleax>
// Victor Perin <https://github.com/victorperin>
// Yongsheng Zhang <https://github.com/ZYSzys>
// NodeJS Contributors <https://github.com/NodeJS>
// Linus Unnebäck <https://github.com/LinusU>
// wafuwafu13 <https://github.com/wafuwafu13>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* License for programmatically and manually incorporated
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
*
* Copyright Node.js contributors. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
// NOTE: These definitions support NodeJS and TypeScript 3.7+.
// Reference required types from the default lib:
/// <reference lib="es2020" />
/// <reference lib="esnext.asynciterable" />
/// <reference lib="esnext.intl" />
/// <reference lib="esnext.bigint" />
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
/// <reference path="assert.d.ts" />
/// <reference path="assert/strict.d.ts" />
/// <reference path="globals.d.ts" />
/// <reference path="async_hooks.d.ts" />
/// <reference path="buffer.d.ts" />
/// <reference path="child_process.d.ts" />
/// <reference path="cluster.d.ts" />
/// <reference path="console.d.ts" />
/// <reference path="constants.d.ts" />
/// <reference path="crypto.d.ts" />
/// <reference path="dgram.d.ts" />
/// <reference path="diagnostics_channel.d.ts" />
/// <reference path="dns.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="domain.d.ts" />
/// <reference path="events.d.ts" />
/// <reference path="fs.d.ts" />
/// <reference path="fs/promises.d.ts" />
/// <reference path="http.d.ts" />
/// <reference path="http2.d.ts" />
/// <reference path="https.d.ts" />
/// <reference path="inspector.d.ts" />
/// <reference path="module.d.ts" />
/// <reference path="net.d.ts" />
/// <reference path="os.d.ts" />
/// <reference path="path.d.ts" />
/// <reference path="perf_hooks.d.ts" />
/// <reference path="process.d.ts" />
/// <reference path="punycode.d.ts" />
/// <reference path="querystring.d.ts" />
/// <reference path="readline.d.ts" />
/// <reference path="repl.d.ts" />
/// <reference path="stream.d.ts" />
/// <reference path="stream/promises.d.ts" />
/// <reference path="stream/consumers.d.ts" />
/// <reference path="stream/web.d.ts" />
/// <reference path="string_decoder.d.ts" />
/// <reference path="timers.d.ts" />
/// <reference path="timers/promises.d.ts" />
/// <reference path="tls.d.ts" />
/// <reference path="trace_events.d.ts" />
/// <reference path="tty.d.ts" />
/// <reference path="url.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="v8.d.ts" />
/// <reference path="vm.d.ts" />
/// <reference path="wasi.d.ts" />
/// <reference path="worker_threads.d.ts" />
/// <reference path="zlib.d.ts" />
/// <reference path="globals.global.d.ts" />
This diff could not be displayed because it is too large.
/**
* @since v0.3.7
*/
declare module 'module' {
import { URL } from 'node:url';
namespace Module {
/**
* The `module.syncBuiltinESMExports()` method updates all the live bindings for
* builtin `ES Modules` to match the properties of the `CommonJS` exports. It
* does not add or remove exported names from the `ES Modules`.
*
* ```js
* const fs = require('fs');
* const assert = require('assert');
* const { syncBuiltinESMExports } = require('module');
*
* fs.readFile = newAPI;
*
* delete fs.readFileSync;
*
* function newAPI() {
* // ...
* }
*
* fs.newAPI = newAPI;
*
* syncBuiltinESMExports();
*
* import('fs').then((esmFS) => {
* // It syncs the existing readFile property with the new value
* assert.strictEqual(esmFS.readFile, newAPI);
* // readFileSync has been deleted from the required fs
* assert.strictEqual('readFileSync' in fs, false);
* // syncBuiltinESMExports() does not remove readFileSync from esmFS
* assert.strictEqual('readFileSync' in esmFS, true);
* // syncBuiltinESMExports() does not add names
* assert.strictEqual(esmFS.newAPI, undefined);
* });
* ```
* @since v12.12.0
*/
function syncBuiltinESMExports(): void;
/**
* `path` is the resolved path for the file for which a corresponding source map
* should be fetched.
* @since v13.7.0, v12.17.0
*/
function findSourceMap(path: string, error?: Error): SourceMap;
interface SourceMapPayload {
file: string;
version: number;
sources: string[];
sourcesContent: string[];
names: string[];
mappings: string;
sourceRoot: string;
}
interface SourceMapping {
generatedLine: number;
generatedColumn: number;
originalSource: string;
originalLine: number;
originalColumn: number;
}
/**
* @since v13.7.0, v12.17.0
*/
class SourceMap {
/**
* Getter for the payload used to construct the `SourceMap` instance.
*/
readonly payload: SourceMapPayload;
constructor(payload: SourceMapPayload);
/**
* Given a line number and column number in the generated source file, returns
* an object representing the position in the original file. The object returned
* consists of the following keys:
*/
findEntry(line: number, column: number): SourceMapping;
}
}
interface Module extends NodeModule {}
class Module {
static runMain(): void;
static wrap(code: string): string;
static createRequire(path: string | URL): NodeRequire;
static builtinModules: string[];
static Module: typeof Module;
constructor(id: string, parent?: Module);
}
global {
interface ImportMeta {
url: string;
/**
* @experimental
* This feature is only available with the `--experimental-import-meta-resolve`
* command flag enabled.
*
* Provides a module-relative resolution function scoped to each module, returning
* the URL string.
*
* @param specified The module specifier to resolve relative to `parent`.
* @param parent The absolute parent module URL to resolve from. If none
* is specified, the value of `import.meta.url` is used as the default.
*/
resolve?(specified: string, parent?: string | URL): Promise<string>;
}
}
export = Module;
}
declare module 'node:module' {
import module = require('module');
export = module;
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
{
"_from": "@types/node@>=10.0.0",
"_id": "@types/node@16.11.7",
"_inBundle": false,
"_integrity": "sha512-QB5D2sqfSjCmTuWcBWyJ+/44bcjO7VbjSbOE0ucoVbAsSNQc4Lt6QkgkVXkTDwkL4z/beecZNDvVX15D4P8Jbw==",
"_location": "/@types/node",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/node@>=10.0.0",
"name": "@types/node",
"escapedName": "@types%2fnode",
"scope": "@types",
"rawSpec": ">=10.0.0",
"saveSpec": null,
"fetchSpec": ">=10.0.0"
},
"_requiredBy": [
"/engine.io"
],
"_resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.7.tgz",
"_shasum": "36820945061326978c42a01e56b61cd223dfdc42",
"_spec": "@types/node@>=10.0.0",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\engine.io",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Microsoft TypeScript",
"url": "https://github.com/Microsoft"
},
{
"name": "DefinitelyTyped",
"url": "https://github.com/DefinitelyTyped"
},
{
"name": "Alberto Schiabel",
"url": "https://github.com/jkomyno"
},
{
"name": "Alvis HT Tang",
"url": "https://github.com/alvis"
},
{
"name": "Andrew Makarov",
"url": "https://github.com/r3nya"
},
{
"name": "Benjamin Toueg",
"url": "https://github.com/btoueg"
},
{
"name": "Chigozirim C.",
"url": "https://github.com/smac89"
},
{
"name": "David Junger",
"url": "https://github.com/touffy"
},
{
"name": "Deividas Bakanas",
"url": "https://github.com/DeividasBakanas"
},
{
"name": "Eugene Y. Q. Shen",
"url": "https://github.com/eyqs"
},
{
"name": "Hannes Magnusson",
"url": "https://github.com/Hannes-Magnusson-CK"
},
{
"name": "Huw",
"url": "https://github.com/hoo29"
},
{
"name": "Kelvin Jin",
"url": "https://github.com/kjin"
},
{
"name": "Klaus Meinhardt",
"url": "https://github.com/ajafff"
},
{
"name": "Lishude",
"url": "https://github.com/islishude"
},
{
"name": "Mariusz Wiktorczyk",
"url": "https://github.com/mwiktorczyk"
},
{
"name": "Mohsen Azimi",
"url": "https://github.com/mohsen1"
},
{
"name": "Nicolas Even",
"url": "https://github.com/n-e"
},
{
"name": "Nikita Galkin",
"url": "https://github.com/galkin"
},
{
"name": "Parambir Singh",
"url": "https://github.com/parambirs"
},
{
"name": "Sebastian Silbermann",
"url": "https://github.com/eps1lon"
},
{
"name": "Simon Schick",
"url": "https://github.com/SimonSchick"
},
{
"name": "Thomas den Hollander",
"url": "https://github.com/ThomasdenH"
},
{
"name": "Wilco Bakker",
"url": "https://github.com/WilcoBakker"
},
{
"name": "wwwy3y3",
"url": "https://github.com/wwwy3y3"
},
{
"name": "Samuel Ainsworth",
"url": "https://github.com/samuela"
},
{
"name": "Kyle Uehlein",
"url": "https://github.com/kuehlein"
},
{
"name": "Thanik Bhongbhibhat",
"url": "https://github.com/bhongy"
},
{
"name": "Marcin Kopacz",
"url": "https://github.com/chyzwar"
},
{
"name": "Trivikram Kamat",
"url": "https://github.com/trivikr"
},
{
"name": "Junxiao Shi",
"url": "https://github.com/yoursunny"
},
{
"name": "Ilia Baryshnikov",
"url": "https://github.com/qwelias"
},
{
"name": "ExE Boss",
"url": "https://github.com/ExE-Boss"
},
{
"name": "Surasak Chaisurin",
"url": "https://github.com/Ryan-Willpower"
},
{
"name": "Piotr Błażejewicz",
"url": "https://github.com/peterblazejewicz"
},
{
"name": "Anna Henningsen",
"url": "https://github.com/addaleax"
},
{
"name": "Victor Perin",
"url": "https://github.com/victorperin"
},
{
"name": "Yongsheng Zhang",
"url": "https://github.com/ZYSzys"
},
{
"name": "NodeJS Contributors",
"url": "https://github.com/NodeJS"
},
{
"name": "Linus Unnebäck",
"url": "https://github.com/LinusU"
},
{
"name": "wafuwafu13",
"url": "https://github.com/wafuwafu13"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for Node.js",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
"license": "MIT",
"main": "",
"name": "@types/node",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/node"
},
"scripts": {},
"typeScriptVersion": "3.7",
"types": "index.d.ts",
"typesPublisherContentHash": "f35526242fcaf9fa8ad50a3aadb0bb8c2e9aba5a332ca0523451167ec6a19f2e",
"version": "16.11.7"
}
declare module 'path/posix' {
import path = require('path');
export = path;
}
declare module 'path/win32' {
import path = require('path');
export = path;
}
/**
* The `path` module provides utilities for working with file and directory paths.
* It can be accessed using:
*
* ```js
* const path = require('path');
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/path.js)
*/
declare module 'path' {
namespace path {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
interface FormatInputPathObject {
/**
* The root of the path such as '/' or 'c:\'
*/
root?: string | undefined;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir?: string | undefined;
/**
* The file name including extension (if any) such as 'index.html'
*/
base?: string | undefined;
/**
* The file extension (if any) such as '.html'
*/
ext?: string | undefined;
/**
* The file name without extension (if any) such as 'index'
*/
name?: string | undefined;
}
interface PlatformPath {
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
*
* @param p string path to normalize.
*/
normalize(p: string): string;
/**
* Join all arguments together and normalize the resulting path.
* Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
*
* @param paths paths to join.
*/
join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} parameter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order,
* until an absolute path is found. If after using all {from} paths still no absolute path is found,
* the current working directory is used as well. The resulting path is normalized,
* and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param pathSegments string paths to join. Non-string arguments are ignored.
*/
resolve(...pathSegments: string[]): string;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* @param path path to test.
*/
isAbsolute(p: string): boolean;
/**
* Solve the relative path from {from} to {to}.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*/
relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param p the path to evaluate.
*/
dirname(p: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param p the path to evaluate.
* @param ext optionally, an extension to remove from the result.
*/
basename(p: string, ext?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
*
* @param p the path to evaluate.
*/
extname(p: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
readonly sep: string;
/**
* The platform-specific file delimiter. ';' or ':'.
*/
readonly delimiter: string;
/**
* Returns an object from a path string - the opposite of format().
*
* @param pathString path to evaluate.
*/
parse(p: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathString path to evaluate.
*/
format(pP: FormatInputPathObject): string;
/**
* On Windows systems only, returns an equivalent namespace-prefixed path for the given path.
* If path is not a string, path will be returned without modifications.
* This method is meaningful only on Windows system.
* On POSIX systems, the method is non-operational and always returns path without modifications.
*/
toNamespacedPath(path: string): string;
/**
* Posix specific pathing.
* Same as parent object on posix.
*/
readonly posix: PlatformPath;
/**
* Windows specific pathing.
* Same as parent object on windows
*/
readonly win32: PlatformPath;
}
}
const path: path.PlatformPath;
export = path;
}
declare module 'node:path' {
import path = require('path');
export = path;
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/**
* **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users
* currently depending on the `punycode` module should switch to using the
* userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL
* encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`.
*
* The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It
* can be accessed using:
*
* ```js
* const punycode = require('punycode');
* ```
*
* [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is
* primarily intended for use in Internationalized Domain Names. Because host
* names in URLs are limited to ASCII characters only, Domain Names that contain
* non-ASCII characters must be converted into ASCII using the Punycode scheme.
* For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent
* to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`.
*
* The `punycode` module provides a simple implementation of the Punycode standard.
*
* The `punycode` module is a third-party dependency used by Node.js and
* made available to developers as a convenience. Fixes or other modifications to
* the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project.
* @deprecated Since v7.0.0 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/punycode.js)
*/
declare module 'punycode' {
/**
* The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only
* characters to the equivalent string of Unicode codepoints.
*
* ```js
* punycode.decode('maana-pta'); // 'mañana'
* punycode.decode('--dqo34k'); // '☃-⌘'
* ```
* @since v0.5.1
*/
function decode(string: string): string;
/**
* The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters.
*
* ```js
* punycode.encode('mañana'); // 'maana-pta'
* punycode.encode('☃-⌘'); // '--dqo34k'
* ```
* @since v0.5.1
*/
function encode(string: string): string;
/**
* The `punycode.toUnicode()` method converts a string representing a domain name
* containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be
* converted.
*
* ```js
* // decode domain names
* punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
* punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
* punycode.toUnicode('example.com'); // 'example.com'
* ```
* @since v0.6.1
*/
function toUnicode(domain: string): string;
/**
* The `punycode.toASCII()` method converts a Unicode string representing an
* Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the
* domain name will be converted. Calling `punycode.toASCII()` on a string that
* already only contains ASCII characters will have no effect.
*
* ```js
* // encode domain names
* punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
* punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
* punycode.toASCII('example.com'); // 'example.com'
* ```
* @since v0.6.1
*/
function toASCII(domain: string): string;
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
const ucs2: ucs2;
interface ucs2 {
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
decode(string: string): number[];
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
encode(codePoints: ReadonlyArray<number>): string;
}
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
const version: string;
}
declare module 'node:punycode' {
export * from 'punycode';
}
/**
* The `querystring` module provides utilities for parsing and formatting URL
* query strings. It can be accessed using:
*
* ```js
* const querystring = require('querystring');
* ```
*
* The `querystring` API is considered Legacy. While it is still maintained,
* new code should use the `URLSearchParams` API instead.
* @deprecated Legacy
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/querystring.js)
*/
declare module 'querystring' {
interface StringifyOptions {
encodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParseOptions {
maxKeys?: number | undefined;
decodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> {}
interface ParsedUrlQueryInput extends NodeJS.Dict<string | number | boolean | ReadonlyArray<string> | ReadonlyArray<number> | ReadonlyArray<boolean> | null> {}
/**
* The `querystring.stringify()` method produces a URL query string from a
* given `obj` by iterating through the object's "own properties".
*
* It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) |
* [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to
* empty strings.
*
* ```js
* querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
* // Returns 'foo=bar&#x26;baz=qux&#x26;baz=quux&#x26;corge='
*
* querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
* // Returns 'foo:bar;baz:qux'
* ```
*
* By default, characters requiring percent-encoding within the query string will
* be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkEncodeURIComponent function already exists,
*
* querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
* { encodeURIComponent: gbkEncodeURIComponent });
* ```
* @since v0.1.25
* @param obj The object to serialize into a URL query string
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] . The substring used to delimit keys and values in the query string.
*/
function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string;
/**
* The `querystring.parse()` method parses a URL query string (`str`) into a
* collection of key and value pairs.
*
* For example, the query string `'foo=bar&#x26;abc=xyz&#x26;abc=123'` is parsed into:
*
* ```js
* {
* foo: 'bar',
* abc: ['xyz', '123']
* }
* ```
*
* The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`,
* `obj.hasOwnProperty()`, and others
* are not defined and _will not work_.
*
* By default, percent-encoded characters within the query string will be assumed
* to use UTF-8 encoding. If an alternative character encoding is used, then an
* alternative `decodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkDecodeURIComponent function already exists...
*
* querystring.parse('w=%D6%D0%CE%C4&#x26;foo=bar', null, null,
* { decodeURIComponent: gbkDecodeURIComponent });
* ```
* @since v0.1.25
* @param str The URL query string to parse
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] . The substring used to delimit keys and values in the query string.
*/
function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery;
/**
* The querystring.encode() function is an alias for querystring.stringify().
*/
const encode: typeof stringify;
/**
* The querystring.decode() function is an alias for querystring.parse().
*/
const decode: typeof parse;
/**
* The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL
* query strings.
*
* The `querystring.escape()` method is used by `querystring.stringify()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement percent-encoding implementation if
* necessary by assigning `querystring.escape` to an alternative function.
* @since v0.1.25
*/
function escape(str: string): string;
/**
* The `querystring.unescape()` method performs decoding of URL percent-encoded
* characters on the given `str`.
*
* The `querystring.unescape()` method is used by `querystring.parse()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement decoding implementation if
* necessary by assigning `querystring.unescape` to an alternative function.
*
* By default, the `querystring.unescape()` method will attempt to use the
* JavaScript built-in `decodeURIComponent()` method to decode. If that fails,
* a safer equivalent that does not throw on malformed URLs will be used.
* @since v0.1.25
*/
function unescape(str: string): string;
}
declare module 'node:querystring' {
export * from 'querystring';
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
// Duplicates of interface in lib.dom.ts.
// Duplicated here rather than referencing lib.dom.ts because doing so causes lib.dom.ts to be loaded for "test-all"
// Which in turn causes tests to pass that shouldn't pass.
//
// This interface is not, and should not be, exported.
interface Blob {
readonly size: number;
readonly type: string;
arrayBuffer(): Promise<ArrayBuffer>;
slice(start?: number, end?: number, contentType?: string): Blob;
stream(): NodeJS.ReadableStream;
text(): Promise<string>;
}
declare module 'stream/consumers' {
import { Readable } from 'node:stream';
function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator<any>): Promise<Buffer>;
function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator<any>): Promise<string>;
function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator<any>): Promise<ArrayBuffer>;
function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator<any>): Promise<Blob>;
function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator<any>): Promise<unknown>;
}
declare module 'node:stream/consumers' {
export * from 'stream/consumers';
}
declare module 'stream/promises' {
import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream';
function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise<void>;
function pipeline<A extends PipelineSource<any>, B extends PipelineDestination<A, any>>(source: A, destination: B, options?: PipelineOptions): PipelinePromise<B>;
function pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B extends PipelineDestination<T1, any>>(
source: A,
transform1: T1,
destination: B,
options?: PipelineOptions
): PipelinePromise<B>;
function pipeline<A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B extends PipelineDestination<T2, any>>(
source: A,
transform1: T1,
transform2: T2,
destination: B,
options?: PipelineOptions
): PipelinePromise<B>;
function pipeline<
A extends PipelineSource<any>,
T1 extends PipelineTransform<A, any>,
T2 extends PipelineTransform<T1, any>,
T3 extends PipelineTransform<T2, any>,
B extends PipelineDestination<T3, any>
>(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise<B>;
function pipeline<
A extends PipelineSource<any>,
T1 extends PipelineTransform<A, any>,
T2 extends PipelineTransform<T1, any>,
T3 extends PipelineTransform<T2, any>,
T4 extends PipelineTransform<T3, any>,
B extends PipelineDestination<T4, any>
>(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise<B>;
function pipeline(streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, options?: PipelineOptions): Promise<void>;
function pipeline(
stream1: NodeJS.ReadableStream,
stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream,
...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | PipelineOptions>
): Promise<void>;
}
declare module 'node:stream/promises' {
export * from 'stream/promises';
}
declare module 'stream/web' {
// stub module, pending copy&paste from .d.ts or manual impl
}
declare module 'node:stream/web' {
export * from 'stream/web';
}
/**
* The `string_decoder` module provides an API for decoding `Buffer` objects into
* strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
* characters. It can be accessed using:
*
* ```js
* const { StringDecoder } = require('string_decoder');
* ```
*
* The following example shows the basic use of the `StringDecoder` class.
*
* ```js
* const { StringDecoder } = require('string_decoder');
* const decoder = new StringDecoder('utf8');
*
* const cent = Buffer.from([0xC2, 0xA2]);
* console.log(decoder.write(cent));
*
* const euro = Buffer.from([0xE2, 0x82, 0xAC]);
* console.log(decoder.write(euro));
* ```
*
* When a `Buffer` instance is written to the `StringDecoder` instance, an
* internal buffer is used to ensure that the decoded string does not contain
* any incomplete multibyte characters. These are held in the buffer until the
* next call to `stringDecoder.write()` or until `stringDecoder.end()` is called.
*
* In the following example, the three UTF-8 encoded bytes of the European Euro
* symbol (`€`) are written over three separate operations:
*
* ```js
* const { StringDecoder } = require('string_decoder');
* const decoder = new StringDecoder('utf8');
*
* decoder.write(Buffer.from([0xE2]));
* decoder.write(Buffer.from([0x82]));
* console.log(decoder.end(Buffer.from([0xAC])));
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/string_decoder.js)
*/
declare module 'string_decoder' {
class StringDecoder {
constructor(encoding?: BufferEncoding);
/**
* Returns a decoded string, ensuring that any incomplete multibyte characters at
* the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the
* returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`.
* @since v0.1.99
* @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.
*/
write(buffer: Buffer): string;
/**
* Returns any remaining input stored in the internal buffer as a string. Bytes
* representing incomplete UTF-8 and UTF-16 characters will be replaced with
* substitution characters appropriate for the character encoding.
*
* If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input.
* After `end()` is called, the `stringDecoder` object can be reused for new input.
* @since v0.9.3
* @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.
*/
end(buffer?: Buffer): string;
}
}
declare module 'node:string_decoder' {
export * from 'string_decoder';
}
/**
* The `timer` module exposes a global API for scheduling functions to
* be called at some future period of time. Because the timer functions are
* globals, there is no need to call `require('timers')` to use the API.
*
* The timer functions within Node.js implement a similar API as the timers API
* provided by Web Browsers but use a different internal implementation that is
* built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/timers.js)
*/
declare module 'timers' {
import { Abortable } from 'node:events';
import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises';
interface TimerOptions extends Abortable {
/**
* Set to `false` to indicate that the scheduled `Timeout`
* should not require the Node.js event loop to remain active.
* @default true
*/
ref?: boolean | undefined;
}
let setTimeout: typeof global.setTimeout;
let clearTimeout: typeof global.clearTimeout;
let setInterval: typeof global.setInterval;
let clearInterval: typeof global.clearInterval;
let setImmediate: typeof global.setImmediate;
let clearImmediate: typeof global.clearImmediate;
global {
namespace NodeJS {
// compatibility with older typings
interface Timer extends RefCounted {
hasRef(): boolean;
refresh(): this;
[Symbol.toPrimitive](): number;
}
interface Immediate extends RefCounted {
/**
* If true, the `Immediate` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
_onImmediate: Function; // to distinguish it from the Timeout class
}
interface Timeout extends Timer {
/**
* If true, the `Timeout` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* Sets the timer's start time to the current time, and reschedules the timer to
* call its callback at the previously specified duration adjusted to the current
* time. This is useful for refreshing a timer without allocating a new
* JavaScript object.
*
* Using this on a timer that has already called its callback will reactivate the
* timer.
* @since v10.2.0
* @return a reference to `timeout`
*/
refresh(): this;
[Symbol.toPrimitive](): number;
}
}
function setTimeout<TArgs extends any[]>(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout;
namespace setTimeout {
const __promisify__: typeof setTimeoutPromise;
}
function clearTimeout(timeoutId: NodeJS.Timeout): void;
function setInterval<TArgs extends any[]>(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer;
namespace setInterval {
const __promisify__: typeof setIntervalPromise;
}
function clearInterval(intervalId: NodeJS.Timeout): void;
function setImmediate<TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setImmediate(callback: (args: void) => void): NodeJS.Immediate;
namespace setImmediate {
const __promisify__: typeof setImmediatePromise;
}
function clearImmediate(immediateId: NodeJS.Immediate): void;
function queueMicrotask(callback: () => void): void;
}
}
declare module 'node:timers' {
export * from 'timers';
}
/**
* The `timers/promises` API provides an alternative set of timer functions
* that return `Promise` objects. The API is accessible via`require('timers/promises')`.
*
* ```js
* import {
* setTimeout,
* setImmediate,
* setInterval,
* } from 'timers/promises';
* ```
* @since v15.0.0
*/
declare module 'timers/promises' {
import { TimerOptions } from 'node:timers';
/**
* ```js
* import {
* setTimeout,
* } from 'timers/promises';
*
* const res = await setTimeout(100, 'result');
*
* console.log(res); // Prints 'result'
* ```
* @since v15.0.0
* @param [delay=1] The number of milliseconds to wait before fulfilling the promise.
* @param value A value with which the promise is fulfilled.
*/
function setTimeout<T = void>(delay?: number, value?: T, options?: TimerOptions): Promise<T>;
/**
* ```js
* import {
* setImmediate,
* } from 'timers/promises';
*
* const res = await setImmediate('result');
*
* console.log(res); // Prints 'result'
* ```
* @since v15.0.0
* @param value A value with which the promise is fulfilled.
*/
function setImmediate<T = void>(value?: T, options?: TimerOptions): Promise<T>;
/**
* Returns an async iterator that generates values in an interval of `delay` ms.
*
* ```js
* import {
* setInterval,
* } from 'timers/promises';
*
* const interval = 100;
* for await (const startTime of setInterval(interval, Date.now())) {
* const now = Date.now();
* console.log(now);
* if ((now - startTime) > 1000)
* break;
* }
* console.log(Date.now());
* ```
* @since v15.9.0
*/
function setInterval<T = void>(delay?: number, value?: T, options?: TimerOptions): AsyncIterable<T>;
}
declare module 'node:timers/promises' {
export * from 'timers/promises';
}
This diff is collapsed. Click to expand it.
/**
* The `trace_events` module provides a mechanism to centralize tracing information
* generated by V8, Node.js core, and userspace code.
*
* Tracing can be enabled with the `--trace-event-categories` command-line flag
* or by using the `trace_events` module. The `--trace-event-categories` flag
* accepts a list of comma-separated category names.
*
* The available categories are:
*
* * `node`: An empty placeholder.
* * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data.
* The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property.
* * `node.bootstrap`: Enables capture of Node.js bootstrap milestones.
* * `node.console`: Enables capture of `console.time()` and `console.count()`output.
* * `node.dns.native`: Enables capture of trace data for DNS queries.
* * `node.environment`: Enables capture of Node.js Environment milestones.
* * `node.fs.sync`: Enables capture of trace data for file system sync methods.
* * `node.perf`: Enables capture of `Performance API` measurements.
* * `node.perf.usertiming`: Enables capture of only Performance API User Timing
* measures and marks.
* * `node.perf.timerify`: Enables capture of only Performance API timerify
* measurements.
* * `node.promises.rejections`: Enables capture of trace data tracking the number
* of unhandled Promise rejections and handled-after-rejections.
* * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.
* * `v8`: The `V8` events are GC, compiling, and execution related.
*
* By default the `node`, `node.async_hooks`, and `v8` categories are enabled.
*
* ```bash
* node --trace-event-categories v8,node,node.async_hooks server.js
* ```
*
* Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be
* used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default.
*
* ```bash
* node --trace-events-enabled
*
* # is equivalent to
*
* node --trace-event-categories v8,node,node.async_hooks
* ```
*
* Alternatively, trace events may be enabled using the `trace_events` module:
*
* ```js
* const trace_events = require('trace_events');
* const tracing = trace_events.createTracing({ categories: ['node.perf'] });
* tracing.enable(); // Enable trace event capture for the 'node.perf' category
*
* // do work
*
* tracing.disable(); // Disable trace event capture for the 'node.perf' category
* ```
*
* Running Node.js with tracing enabled will produce log files that can be opened
* in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome.
*
* The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can
* be specified with `--trace-event-file-pattern` that accepts a template
* string that supports `${rotation}` and `${pid}`:
*
* ```bash
* node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
* ```
*
* The tracing system uses the same time source
* as the one used by `process.hrtime()`.
* However the trace-event timestamps are expressed in microseconds,
* unlike `process.hrtime()` which returns nanoseconds.
*
* The features from this module are not available in `Worker` threads.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/trace_events.js)
*/
declare module 'trace_events' {
/**
* The `Tracing` object is used to enable or disable tracing for sets of
* categories. Instances are created using the
* `trace_events.createTracing()` method.
*
* When created, the `Tracing` object is disabled. Calling the
* `tracing.enable()` method adds the categories to the set of enabled trace
* event categories. Calling `tracing.disable()` will remove the categories
* from the set of enabled trace event categories.
*/
interface Tracing {
/**
* A comma-separated list of the trace event categories covered by this
* `Tracing` object.
*/
readonly categories: string;
/**
* Disables this `Tracing` object.
*
* Only trace event categories _not_ covered by other enabled `Tracing`
* objects and _not_ specified by the `--trace-event-categories` flag
* will be disabled.
*/
disable(): void;
/**
* Enables this `Tracing` object for the set of categories covered by
* the `Tracing` object.
*/
enable(): void;
/**
* `true` only if the `Tracing` object has been enabled.
*/
readonly enabled: boolean;
}
interface CreateTracingOptions {
/**
* An array of trace category names. Values included in the array are
* coerced to a string when possible. An error will be thrown if the
* value cannot be coerced.
*/
categories: string[];
}
/**
* Creates and returns a `Tracing` object for the given set of `categories`.
*
* ```js
* const trace_events = require('trace_events');
* const categories = ['node.perf', 'node.async_hooks'];
* const tracing = trace_events.createTracing({ categories });
* tracing.enable();
* // do stuff
* tracing.disable();
* ```
* @since v10.0.0
* @return .
*/
function createTracing(options: CreateTracingOptions): Tracing;
/**
* Returns a comma-separated list of all currently-enabled trace event
* categories. The current set of enabled trace event categories is determined
* by the _union_ of all currently-enabled `Tracing` objects and any categories
* enabled using the `--trace-event-categories` flag.
*
* Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console.
*
* ```js
* const trace_events = require('trace_events');
* const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
* const t2 = trace_events.createTracing({ categories: ['node.perf'] });
* const t3 = trace_events.createTracing({ categories: ['v8'] });
*
* t1.enable();
* t2.enable();
*
* console.log(trace_events.getEnabledCategories());
* ```
* @since v10.0.0
*/
function getEnabledCategories(): string | undefined;
}
declare module 'node:trace_events' {
export * from 'trace_events';
}
/**
* The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes.
* In most cases, it will not be necessary or possible to use this module directly.
* However, it can be accessed using:
*
* ```js
* const tty = require('tty');
* ```
*
* When Node.js detects that it is being run with a text terminal ("TTY")
* attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by
* default, be instances of `tty.WriteStream`. The preferred method of determining
* whether Node.js is being run within a TTY context is to check that the value of
* the `process.stdout.isTTY` property is `true`:
*
* ```console
* $ node -p -e "Boolean(process.stdout.isTTY)"
* true
* $ node -p -e "Boolean(process.stdout.isTTY)" | cat
* false
* ```
*
* In most cases, there should be little to no reason for an application to
* manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes.
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/tty.js)
*/
declare module 'tty' {
import * as net from 'node:net';
/**
* The `tty.isatty()` method returns `true` if the given `fd` is associated with
* a TTY and `false` if it is not, including whenever `fd` is not a non-negative
* integer.
* @since v0.5.8
* @param fd A numeric file descriptor
*/
function isatty(fd: number): boolean;
/**
* Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js
* process and there should be no reason to create additional instances.
* @since v0.5.8
*/
class ReadStream extends net.Socket {
constructor(fd: number, options?: net.SocketConstructorOpts);
/**
* A `boolean` that is `true` if the TTY is currently configured to operate as a
* raw device. Defaults to `false`.
* @since v0.7.7
*/
isRaw: boolean;
/**
* Allows configuration of `tty.ReadStream` so that it operates as a raw device.
*
* When in raw mode, input is always available character-by-character, not
* including modifiers. Additionally, all special processing of characters by the
* terminal is disabled, including echoing input characters.Ctrl+C will no longer cause a `SIGINT` when in this mode.
* @since v0.7.7
* @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw`
* property will be set to the resulting mode.
* @return The read stream instance.
*/
setRawMode(mode: boolean): this;
/**
* A `boolean` that is always `true` for `tty.ReadStream` instances.
* @since v0.5.8
*/
isTTY: boolean;
}
/**
* -1 - to the left from cursor
* 0 - the entire line
* 1 - to the right from cursor
*/
type Direction = -1 | 0 | 1;
/**
* Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there
* should be no reason to create additional instances.
* @since v0.5.8
*/
class WriteStream extends net.Socket {
constructor(fd: number);
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'resize', listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'resize'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'resize', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'resize', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'resize', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'resize', listener: () => void): this;
/**
* `writeStream.clearLine()` clears the current line of this `WriteStream` in a
* direction identified by `dir`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
clearLine(dir: Direction, callback?: () => void): boolean;
/**
* `writeStream.clearScreenDown()` clears this `WriteStream` from the current
* cursor down.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
clearScreenDown(callback?: () => void): boolean;
/**
* `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified
* position.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
cursorTo(x: number, y?: number, callback?: () => void): boolean;
cursorTo(x: number, callback: () => void): boolean;
/**
* `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its
* current position.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
moveCursor(dx: number, dy: number, callback?: () => void): boolean;
/**
* Returns:
*
* * `1` for 2,
* * `4` for 16,
* * `8` for 256,
* * `24` for 16,777,216 colors supported.
*
* Use this to determine what colors the terminal supports. Due to the nature of
* colors in terminals it is possible to either have false positives or false
* negatives. It depends on process information and the environment variables that
* may lie about what terminal is used.
* It is possible to pass in an `env` object to simulate the usage of a specific
* terminal. This can be useful to check how specific environment settings behave.
*
* To enforce a specific color support, use one of the below environment settings.
*
* * 2 colors: `FORCE_COLOR = 0` (Disables colors)
* * 16 colors: `FORCE_COLOR = 1`
* * 256 colors: `FORCE_COLOR = 2`
* * 16,777,216 colors: `FORCE_COLOR = 3`
*
* Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables.
* @since v9.9.0
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
*/
getColorDepth(env?: object): number;
/**
* Returns `true` if the `writeStream` supports at least as many colors as provided
* in `count`. Minimum support is 2 (black and white).
*
* This has the same false positives and negatives as described in `writeStream.getColorDepth()`.
*
* ```js
* process.stdout.hasColors();
* // Returns true or false depending on if `stdout` supports at least 16 colors.
* process.stdout.hasColors(256);
* // Returns true or false depending on if `stdout` supports at least 256 colors.
* process.stdout.hasColors({ TMUX: '1' });
* // Returns true.
* process.stdout.hasColors(2 ** 24, { TMUX: '1' });
* // Returns false (the environment setting pretends to support 2 ** 8 colors).
* ```
* @since v11.13.0, v10.16.0
* @param [count=16] The number of colors that are requested (minimum 2).
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
*/
hasColors(count?: number): boolean;
hasColors(env?: object): boolean;
hasColors(count: number, env?: object): boolean;
/**
* `writeStream.getWindowSize()` returns the size of the TTY
* corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number
* of columns and rows in the corresponding TTY.
* @since v0.7.7
*/
getWindowSize(): [number, number];
/**
* A `number` specifying the number of columns the TTY currently has. This property
* is updated whenever the `'resize'` event is emitted.
* @since v0.7.7
*/
columns: number;
/**
* A `number` specifying the number of rows the TTY currently has. This property
* is updated whenever the `'resize'` event is emitted.
* @since v0.7.7
*/
rows: number;
/**
* A `boolean` that is always `true`.
* @since v0.5.8
*/
isTTY: boolean;
}
}
declare module 'node:tty' {
export * from 'tty';
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/**
* The WASI API provides an implementation of the [WebAssembly System Interface](https://wasi.dev/) specification. WASI gives sandboxed WebAssembly applications access to the
* underlying operating system via a collection of POSIX-like functions.
*
* ```js
* import { readFile } from 'fs/promises';
* import { WASI } from 'wasi';
* import { argv, env } from 'process';
*
* const wasi = new WASI({
* args: argv,
* env,
* preopens: {
* '/sandbox': '/some/real/path/that/wasm/can/access'
* }
* });
*
* // Some WASI binaries require:
* // const importObject = { wasi_unstable: wasi.wasiImport };
* const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
*
* const wasm = await WebAssembly.compile(
* await readFile(new URL('./demo.wasm', import.meta.url))
* );
* const instance = await WebAssembly.instantiate(wasm, importObject);
*
* wasi.start(instance);
* ```
*
* To run the above example, create a new WebAssembly text format file named`demo.wat`:
*
* ```text
* (module
* ;; Import the required fd_write WASI function which will write the given io vectors to stdout
* ;; The function signature for fd_write is:
* ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
* (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
*
* (memory 1)
* (export "memory" (memory 0))
*
* ;; Write 'hello world\n' to memory at an offset of 8 bytes
* ;; Note the trailing newline which is required for the text to appear
* (data (i32.const 8) "hello world\n")
*
* (func $main (export "_start")
* ;; Creating a new io vector within linear memory
* (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
* (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string
*
* (call $fd_write
* (i32.const 1) ;; file_descriptor - 1 for stdout
* (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
* (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
* (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
* )
* drop ;; Discard the number of bytes written from the top of the stack
* )
* )
* ```
*
* Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm`
*
* ```console
* $ wat2wasm demo.wat
* ```
*
* The `--experimental-wasi-unstable-preview1` CLI argument is needed for this
* example to run.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/wasi.js)
*/
declare module 'wasi' {
interface WASIOptions {
/**
* An array of strings that the WebAssembly application will
* see as command line arguments. The first argument is the virtual path to the
* WASI command itself.
*/
args?: string[] | undefined;
/**
* An object similar to `process.env` that the WebAssembly
* application will see as its environment.
*/
env?: object | undefined;
/**
* This object represents the WebAssembly application's
* sandbox directory structure. The string keys of `preopens` are treated as
* directories within the sandbox. The corresponding values in `preopens` are
* the real paths to those directories on the host machine.
*/
preopens?: NodeJS.Dict<string> | undefined;
/**
* By default, WASI applications terminate the Node.js
* process via the `__wasi_proc_exit()` function. Setting this option to `true`
* causes `wasi.start()` to return the exit code rather than terminate the
* process.
* @default false
*/
returnOnExit?: boolean | undefined;
/**
* The file descriptor used as standard input in the WebAssembly application.
* @default 0
*/
stdin?: number | undefined;
/**
* The file descriptor used as standard output in the WebAssembly application.
* @default 1
*/
stdout?: number | undefined;
/**
* The file descriptor used as standard error in the WebAssembly application.
* @default 2
*/
stderr?: number | undefined;
}
/**
* The `WASI` class provides the WASI system call API and additional convenience
* methods for working with WASI-based applications. Each `WASI` instance
* represents a distinct sandbox environment. For security purposes, each `WASI`instance must have its command-line arguments, environment variables, and
* sandbox directory structure configured explicitly.
* @since v13.3.0, v12.16.0
*/
class WASI {
constructor(options?: WASIOptions);
/**
* Attempt to begin execution of `instance` as a WASI command by invoking its`_start()` export. If `instance` does not contain a `_start()` export, or if`instance` contains an `_initialize()`
* export, then an exception is thrown.
*
* `start()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. If
* `instance` does not have a `memory` export an exception is thrown.
*
* If `start()` is called more than once, an exception is thrown.
* @since v13.3.0, v12.16.0
*/
start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
/**
* Attempt to initialize `instance` as a WASI reactor by invoking its`_initialize()` export, if it is present. If `instance` contains a `_start()`export, then an exception is thrown.
*
* `initialize()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`.
* If `instance` does not have a `memory` export an exception is thrown.
*
* If `initialize()` is called more than once, an exception is thrown.
* @since v14.6.0, v12.19.0
*/
initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
/**
* `wasiImport` is an object that implements the WASI system call API. This object
* should be passed as the `wasi_snapshot_preview1` import during the instantiation
* of a [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance).
* @since v13.3.0, v12.16.0
*/
readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types
}
}
declare module 'node:wasi' {
export * from 'wasi';
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [1.0.1](https://github.com/niklasvh/base64-arraybuffer/compare/v1.0.0...v1.0.1) (2021-08-10)
### fix
* make lib loadable on ie9 (#30) ([a618d14](https://github.com/niklasvh/base64-arraybuffer/commit/a618d14d323f4eb230321a3609bfbc9f23f430c0)), closes [#30](https://github.com/niklasvh/base64-arraybuffer/issues/30)
# [1.0.0](https://github.com/niklasvh/base64-arraybuffer/compare/v0.2.0...v1.0.0) (2021-08-10)
### docs
* update readme (#29) ([0a0253d](https://github.com/niklasvh/base64-arraybuffer/commit/0a0253dcc2e3f01a1f6d04fa81d578f714fce27f)), closes [#29](https://github.com/niklasvh/base64-arraybuffer/issues/29)
Copyright (c) 2012 Niklas von Hertzen
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# base64-arraybuffer
![CI](https://github.com/niklasvh/base64-arraybuffer/workflows/CI/badge.svg?branch=master)
[![NPM Downloads](https://img.shields.io/npm/dm/base64-arraybuffer.svg)](https://www.npmjs.org/package/base64-arraybuffer)
[![NPM Version](https://img.shields.io/npm/v/base64-arraybuffer.svg)](https://www.npmjs.org/package/base64-arraybuffer)
Encode/decode base64 data into ArrayBuffers
### Installing
You can install the module via npm:
npm install base64-arraybuffer
## API
The library encodes and decodes base64 to and from ArrayBuffers
- __encode(buffer)__ - Encodes `ArrayBuffer` into base64 string
- __decode(str)__ - Decodes base64 string to `ArrayBuffer`
### Testing
You can run the test suite with:
npm test
## License
Copyright (c) 2012 Niklas von Hertzen
Licensed under the MIT license.
/*
* base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var encode = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
}
else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
var decode = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
export { decode, encode };
//# sourceMappingURL=base64-arraybuffer.es5.js.map
{"version":3,"file":"base64-arraybuffer.es5.js","sources":["../../src/index.ts"],"sourcesContent":[null],"names":[],"mappings":"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"}
\ No newline at end of file
/*
* base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['base64-arraybuffer'] = {}));
}(this, (function (exports) { 'use strict';
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var encode = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
}
else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
var decode = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
exports.decode = decode;
exports.encode = encode;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=base64-arraybuffer.umd.js.map
{"version":3,"file":"base64-arraybuffer.umd.js","sources":["../../src/index.ts"],"sourcesContent":[null],"names":[],"mappings":"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"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = exports.encode = void 0;
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var encode = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
}
else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
exports.encode = encode;
var decode = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
exports.decode = decode;
//# sourceMappingURL=index.js.map
\ No newline at end of file
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"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"}
\ No newline at end of file
export declare const encode: (arraybuffer: ArrayBuffer) => string;
export declare const decode: (base64: string) => ArrayBuffer;
{
"_from": "base64-arraybuffer@~1.0.1",
"_id": "base64-arraybuffer@1.0.1",
"_inBundle": false,
"_integrity": "sha512-vFIUq7FdLtjZMhATwDul5RZWv2jpXQ09Pd6jcVEOvIsqCWTRFD/ONHNfyOS8dA/Ippi5dsIgpyKWKZaAKZltbA==",
"_location": "/base64-arraybuffer",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "base64-arraybuffer@~1.0.1",
"name": "base64-arraybuffer",
"escapedName": "base64-arraybuffer",
"rawSpec": "~1.0.1",
"saveSpec": null,
"fetchSpec": "~1.0.1"
},
"_requiredBy": [
"/engine.io-parser"
],
"_resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.1.tgz",
"_shasum": "87bd13525626db4a9838e00a508c2b73efcf348c",
"_spec": "base64-arraybuffer@~1.0.1",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\engine.io-parser",
"author": {
"name": "Niklas von Hertzen",
"email": "niklasvh@gmail.com",
"url": "https://hertzen.com"
},
"bugs": {
"url": "https://github.com/niklasvh/base64-arraybuffer/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Encode/decode base64 data into ArrayBuffers",
"devDependencies": {
"@rollup/plugin-commonjs": "^19.0.0",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-typescript": "^8.2.1",
"@types/mocha": "^8.2.2",
"@types/node": "^16.0.0",
"mocha": "9.0.2",
"prettier": "^2.3.2",
"rimraf": "3.0.2",
"rollup": "^2.52.7",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-sourcemaps": "^0.6.3",
"standard-version": "^9.3.0",
"ts-node": "^10.0.0",
"tslib": "^2.3.0",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0",
"typescript": "^4.3.5"
},
"engines": {
"node": ">= 0.6.0"
},
"homepage": "https://github.com/niklasvh/base64-arraybuffer",
"keywords": [],
"license": "MIT",
"main": "dist/base64-arraybuffer.umd.js",
"module": "dist/base64-arraybuffer.es5.js",
"name": "base64-arraybuffer",
"repository": {
"type": "git",
"url": "git+https://github.com/niklasvh/base64-arraybuffer.git"
},
"scripts": {
"build": "tsc --module commonjs && rollup -c rollup.config.ts",
"format": "prettier --write \"{src,test}/**/*.ts\"",
"lint": "tslint -c tslint.json --project tsconfig.json -t codeFrame src/**/*.ts test/**/*.ts",
"mocha": "mocha --require ts-node/register test/*.ts",
"prebuild": "rimraf dist/",
"release": "standard-version",
"test": "npm run lint && npm run mocha"
},
"typings": "dist/types/index.d.ts",
"version": "1.0.1"
}
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from '@rollup/plugin-typescript';
import json from 'rollup-plugin-json';
const pkg = require('./package.json');
const banner = `/*
* ${pkg.name} ${pkg.version} <${pkg.homepage}>
* Copyright (c) ${(new Date()).getFullYear()} ${pkg.author.name} <${pkg.author.url}>
* Released under ${pkg.license} License
*/`;
export default {
input: `src/index.ts`,
output: [
{ file: pkg.main, name: pkg.name, format: 'umd', banner, sourcemap: true },
{ file: pkg.module, format: 'esm', banner, sourcemap: true },
],
external: [],
watch: {
include: 'src/**',
},
plugins: [
// Allow node_modules resolution, so you can use 'external' to control
// which external modules to include in the bundle
// https://github.com/rollup/rollup-plugin-node-resolve#usage
resolve(),
// Allow json resolution
json(),
// Compile TypeScript files
typescript(),
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs(),
// Resolve source maps to the original source
sourceMaps(),
],
}
# [2.0.0](https://github.com/faeldt/base64id/compare/1.0.0...2.0.0) (2019-05-27)
### Code Refactoring
* **buffer:** replace deprecated Buffer constructor usage ([#11](https://github.com/faeldt/base64id/issues/11)) ([ccfba54](https://github.com/faeldt/base64id/commit/ccfba54))
### BREAKING CHANGES
* **buffer:** drop support for Node.js ≤ 4.4.x and 5.0.0 - 5.9.x
See: https://nodejs.org/en/docs/guides/buffer-constructor-deprecation/
(The MIT License)
Copyright (c) 2012-2016 Kristian Faeldt <faeldt_kristian@cyberagent.co.jp>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
base64id
========
Node.js module that generates a base64 id.
Uses crypto.randomBytes when available, falls back to unsafe methods for node.js <= 0.4.
To increase performance, random bytes are buffered to minimize the number of synchronous calls to crypto.randomBytes.
## Installation
$ npm install base64id
## Usage
var base64id = require('base64id');
var id = base64id.generateId();
/*!
* base64id v0.1.0
*/
/**
* Module dependencies
*/
var crypto = require('crypto');
/**
* Constructor
*/
var Base64Id = function() { };
/**
* Get random bytes
*
* Uses a buffer if available, falls back to crypto.randomBytes
*/
Base64Id.prototype.getRandomBytes = function(bytes) {
var BUFFER_SIZE = 4096
var self = this;
bytes = bytes || 12;
if (bytes > BUFFER_SIZE) {
return crypto.randomBytes(bytes);
}
var bytesInBuffer = parseInt(BUFFER_SIZE/bytes);
var threshold = parseInt(bytesInBuffer*0.85);
if (!threshold) {
return crypto.randomBytes(bytes);
}
if (this.bytesBufferIndex == null) {
this.bytesBufferIndex = -1;
}
if (this.bytesBufferIndex == bytesInBuffer) {
this.bytesBuffer = null;
this.bytesBufferIndex = -1;
}
// No buffered bytes available or index above threshold
if (this.bytesBufferIndex == -1 || this.bytesBufferIndex > threshold) {
if (!this.isGeneratingBytes) {
this.isGeneratingBytes = true;
crypto.randomBytes(BUFFER_SIZE, function(err, bytes) {
self.bytesBuffer = bytes;
self.bytesBufferIndex = 0;
self.isGeneratingBytes = false;
});
}
// Fall back to sync call when no buffered bytes are available
if (this.bytesBufferIndex == -1) {
return crypto.randomBytes(bytes);
}
}
var result = this.bytesBuffer.slice(bytes*this.bytesBufferIndex, bytes*(this.bytesBufferIndex+1));
this.bytesBufferIndex++;
return result;
}
/**
* Generates a base64 id
*
* (Original version from socket.io <http://socket.io>)
*/
Base64Id.prototype.generateId = function () {
var rand = Buffer.alloc(15); // multiple of 3 for base64
if (!rand.writeInt32BE) {
return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
+ Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
}
this.sequenceNumber = (this.sequenceNumber + 1) | 0;
rand.writeInt32BE(this.sequenceNumber, 11);
if (crypto.randomBytes) {
this.getRandomBytes(12).copy(rand);
} else {
// not secure for node 0.4
[0, 4, 8].forEach(function(i) {
rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
});
}
return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
};
/**
* Export
*/
exports = module.exports = new Base64Id();
{
"_from": "base64id@~2.0.0",
"_id": "base64id@2.0.0",
"_inBundle": false,
"_integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
"_location": "/base64id",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "base64id@~2.0.0",
"name": "base64id",
"escapedName": "base64id",
"rawSpec": "~2.0.0",
"saveSpec": null,
"fetchSpec": "~2.0.0"
},
"_requiredBy": [
"/engine.io",
"/socket.io"
],
"_resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
"_shasum": "2770ac6bc47d312af97a8bf9a634342e0cd25cb6",
"_spec": "base64id@~2.0.0",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\socket.io",
"author": {
"name": "Kristian Faeldt",
"email": "faeldt_kristian@cyberagent.co.jp"
},
"bugs": {
"url": "https://github.com/faeldt/base64id/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Generates a base64 id",
"engines": {
"node": "^4.5.0 || >= 5.9"
},
"homepage": "https://github.com/faeldt/base64id#readme",
"license": "MIT",
"main": "./lib/base64id.js",
"name": "base64id",
"repository": {
"type": "git",
"url": "git+https://github.com/faeldt/base64id.git"
},
"version": "2.0.0"
}
1.3.0 / 2018-04-15
==================
* removed bower support
* expose emitter on `exports`
* prevent de-optimization from using `arguments`
1.2.1 / 2016-04-18
==================
* enable client side use
1.2.0 / 2014-02-12
==================
* prefix events with `$` to support object prototype method names
1.1.3 / 2014-06-20
==================
* republish for npm
* add LICENSE file
1.1.2 / 2014-02-10
==================
* package: rename to "component-emitter"
* package: update "main" and "component" fields
* Add license to Readme (same format as the other components)
* created .npmignore
* travis stuff
1.1.1 / 2013-12-01
==================
* fix .once adding .on to the listener
* docs: Emitter#off()
* component: add `.repo` prop
1.1.0 / 2013-10-20
==================
* add `.addEventListener()` and `.removeEventListener()` aliases
1.0.1 / 2013-06-27
==================
* add support for legacy ie
1.0.0 / 2013-02-26
==================
* add `.off()` support for removing all listeners
0.0.6 / 2012-10-08
==================
* add `this._callbacks` initialization to prevent funky gotcha
0.0.5 / 2012-09-07
==================
* fix `Emitter.call(this)` usage
0.0.3 / 2012-07-11
==================
* add `.listeners()`
* rename `.has()` to `.hasListeners()`
0.0.2 / 2012-06-28
==================
* fix `.off()` with `.once()`-registered callbacks
(The MIT License)
Copyright (c) 2014 Component contributors <dev@component.io>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# Emitter [![Build Status](https://travis-ci.org/component/emitter.png)](https://travis-ci.org/component/emitter)
Event emitter component.
## Installation
```
$ component install component/emitter
```
## API
### Emitter(obj)
The `Emitter` may also be used as a mixin. For example
a "plain" object may become an emitter, or you may
extend an existing prototype.
As an `Emitter` instance:
```js
var Emitter = require('emitter');
var emitter = new Emitter;
emitter.emit('something');
```
As a mixin:
```js
var Emitter = require('emitter');
var user = { name: 'tobi' };
Emitter(user);
user.emit('im a user');
```
As a prototype mixin:
```js
var Emitter = require('emitter');
Emitter(User.prototype);
```
### Emitter#on(event, fn)
Register an `event` handler `fn`.
### Emitter#once(event, fn)
Register a single-shot `event` handler `fn`,
removed immediately after it is invoked the
first time.
### Emitter#off(event, fn)
* Pass `event` and `fn` to remove a listener.
* Pass `event` to remove all listeners on that event.
* Pass nothing to remove all listeners on all events.
### Emitter#emit(event, ...)
Emit an `event` with variable option args.
### Emitter#listeners(event)
Return an array of callbacks, or an empty array.
### Emitter#hasListeners(event)
Check if this emitter has `event` handlers.
## License
MIT
/**
* Expose `Emitter`.
*/
if (typeof module !== 'undefined') {
module.exports = Emitter;
}
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
// Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if (callbacks.length === 0) {
delete this._callbacks['$' + event];
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1)
, callbacks = this._callbacks['$' + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
{
"_from": "component-emitter@~1.3.0",
"_id": "component-emitter@1.3.0",
"_inBundle": false,
"_integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==",
"_location": "/component-emitter",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "component-emitter@~1.3.0",
"name": "component-emitter",
"escapedName": "component-emitter",
"rawSpec": "~1.3.0",
"saveSpec": null,
"fetchSpec": "~1.3.0"
},
"_requiredBy": [
"/socket.io-parser"
],
"_resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz",
"_shasum": "16e4070fba8ae29b679f2215853ee181ab2eabc0",
"_spec": "component-emitter@~1.3.0",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\socket.io-parser",
"bugs": {
"url": "https://github.com/component/emitter/issues"
},
"bundleDependencies": false,
"component": {
"scripts": {
"emitter/index.js": "index.js"
}
},
"deprecated": false,
"description": "Event emitter",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"files": [
"index.js",
"LICENSE"
],
"homepage": "https://github.com/component/emitter#readme",
"license": "MIT",
"main": "index.js",
"name": "component-emitter",
"repository": {
"type": "git",
"url": "git+https://github.com/component/emitter.git"
},
"scripts": {
"test": "make test"
},
"version": "1.3.0"
}
# contributing to `cors`
CORS is a node.js package for providing a [connect](http://www.senchalabs.org/connect/)/[express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options. Learn more about the project in [the README](README.md).
## The CORS Spec
[http://www.w3.org/TR/cors/](http://www.w3.org/TR/cors/)
## Pull Requests Welcome
* Include `'use strict';` in every javascript file.
* 2 space indentation.
* Please run the testing steps below before submitting.
## Testing
```bash
$ npm install
$ npm test
```
## Interactive Testing Harness
[http://node-cors-client.herokuapp.com](http://node-cors-client.herokuapp.com)
Related git repositories:
* [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
* [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
## License
[MIT License](http://www.opensource.org/licenses/mit-license.php)
2.8.5 / 2018-11-04
==================
* Fix setting `maxAge` option to `0`
2.8.4 / 2017-07-12
==================
* Work-around Safari bug in default pre-flight response
2.8.3 / 2017-03-29
==================
* Fix error when options delegate missing `methods` option
2.8.2 / 2017-03-28
==================
* Fix error when frozen options are passed
* Send "Vary: Origin" when using regular expressions
* Send "Vary: Access-Control-Request-Headers" when dynamic `allowedHeaders`
2.8.1 / 2016-09-08
==================
This release only changed documentation.
2.8.0 / 2016-08-23
==================
* Add `optionsSuccessStatus` option
2.7.2 / 2016-08-23
==================
* Fix error when Node.js running in strict mode
2.7.1 / 2015-05-28
==================
* Move module into expressjs organization
2.7.0 / 2015-05-28
==================
* Allow array of matching condition as `origin` option
* Allow regular expression as `origin` option
2.6.1 / 2015-05-28
==================
* Update `license` in package.json
2.6.0 / 2015-04-27
==================
* Add `preflightContinue` option
* Fix "Vary: Origin" header added for "*"
(The MIT License)
Copyright (c) 2013 Troy Goode <troygoode@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# cors
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options.
**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)**
* [Installation](#installation)
* [Usage](#usage)
* [Simple Usage](#simple-usage-enable-all-cors-requests)
* [Enable CORS for a Single Route](#enable-cors-for-a-single-route)
* [Configuring CORS](#configuring-cors)
* [Configuring CORS Asynchronously](#configuring-cors-asynchronously)
* [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)
* [Configuration Options](#configuration-options)
* [Demo](#demo)
* [License](#license)
* [Author](#author)
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install cors
```
## Usage
### Simple Usage (Enable *All* CORS Requests)
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
### Enable CORS for a Single Route
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
### Configuring CORS
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
### Configuring CORS w/ Dynamic Origin
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
If you do not want to block REST tools or server-to-server requests,
add a `!origin` check in the origin function like so:
```javascript
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
```
### Enabling CORS Pre-Flight
Certain CORS requests are considered 'complex' and require an initial
`OPTIONS` request (called the "pre-flight request"). An example of a
'complex' CORS request is one that uses an HTTP verb other than
GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable
pre-flighting, you must add a new OPTIONS handler for the route you want
to support:
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
You can also enable pre-flight across-the-board like so:
```javascript
app.options('*', cors()) // include before other routes
```
### Configuring CORS Asynchronously
```javascript
var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
```
## Configuration Options
* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values:
- `Boolean` - set `origin` to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS.
- `String` - set `origin` to a specific origin. For example if you set it to `"http://example.com"` only requests from "http://example.com" will be allowed.
- `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com".
- `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com".
- `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature `err [object], allow [bool]`) as the second.
* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`).
* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.
* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed.
* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.
* `preflightContinue`: Pass the CORS preflight response to the next handler.
* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.
The default configuration is the equivalent of:
```json
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
```
For details on the effect of each CORS header, read [this](http://www.html5rocks.com/en/tutorials/cors/) article on HTML5 Rocks.
## Demo
A demo that illustrates CORS working (and not working) using jQuery is available here: [http://node-cors-client.herokuapp.com/](http://node-cors-client.herokuapp.com/)
Code for that demo can be found here:
* Client: [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
* Server: [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
## License
[MIT License](http://www.opensource.org/licenses/mit-license.php)
## Author
[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))
[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg
[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master
[downloads-image]: https://img.shields.io/npm/dm/cors.svg
[downloads-url]: https://npmjs.org/package/cors
[npm-image]: https://img.shields.io/npm/v/cors.svg
[npm-url]: https://npmjs.org/package/cors
[travis-image]: https://img.shields.io/travis/expressjs/cors/master.svg
[travis-url]: https://travis-ci.org/expressjs/cors
(function () {
'use strict';
var assign = require('object-assign');
var vary = require('vary');
var defaults = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204
};
function isString(s) {
return typeof s === 'string' || s instanceof String;
}
function isOriginAllowed(origin, allowedOrigin) {
if (Array.isArray(allowedOrigin)) {
for (var i = 0; i < allowedOrigin.length; ++i) {
if (isOriginAllowed(origin, allowedOrigin[i])) {
return true;
}
}
return false;
} else if (isString(allowedOrigin)) {
return origin === allowedOrigin;
} else if (allowedOrigin instanceof RegExp) {
return allowedOrigin.test(origin);
} else {
return !!allowedOrigin;
}
}
function configureOrigin(options, req) {
var requestOrigin = req.headers.origin,
headers = [],
isAllowed;
if (!options.origin || options.origin === '*') {
// allow any origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: '*'
}]);
} else if (isString(options.origin)) {
// fixed origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: options.origin
}]);
headers.push([{
key: 'Vary',
value: 'Origin'
}]);
} else {
isAllowed = isOriginAllowed(requestOrigin, options.origin);
// reflect origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: isAllowed ? requestOrigin : false
}]);
headers.push([{
key: 'Vary',
value: 'Origin'
}]);
}
return headers;
}
function configureMethods(options) {
var methods = options.methods;
if (methods.join) {
methods = options.methods.join(','); // .methods is an array, so turn it into a string
}
return {
key: 'Access-Control-Allow-Methods',
value: methods
};
}
function configureCredentials(options) {
if (options.credentials === true) {
return {
key: 'Access-Control-Allow-Credentials',
value: 'true'
};
}
return null;
}
function configureAllowedHeaders(options, req) {
var allowedHeaders = options.allowedHeaders || options.headers;
var headers = [];
if (!allowedHeaders) {
allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
headers.push([{
key: 'Vary',
value: 'Access-Control-Request-Headers'
}]);
} else if (allowedHeaders.join) {
allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
}
if (allowedHeaders && allowedHeaders.length) {
headers.push([{
key: 'Access-Control-Allow-Headers',
value: allowedHeaders
}]);
}
return headers;
}
function configureExposedHeaders(options) {
var headers = options.exposedHeaders;
if (!headers) {
return null;
} else if (headers.join) {
headers = headers.join(','); // .headers is an array, so turn it into a string
}
if (headers && headers.length) {
return {
key: 'Access-Control-Expose-Headers',
value: headers
};
}
return null;
}
function configureMaxAge(options) {
var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString()
if (maxAge && maxAge.length) {
return {
key: 'Access-Control-Max-Age',
value: maxAge
};
}
return null;
}
function applyHeaders(headers, res) {
for (var i = 0, n = headers.length; i < n; i++) {
var header = headers[i];
if (header) {
if (Array.isArray(header)) {
applyHeaders(header, res);
} else if (header.key === 'Vary' && header.value) {
vary(res, header.value);
} else if (header.value) {
res.setHeader(header.key, header.value);
}
}
}
}
function cors(options, req, res, next) {
var headers = [],
method = req.method && req.method.toUpperCase && req.method.toUpperCase();
if (method === 'OPTIONS') {
// preflight
headers.push(configureOrigin(options, req));
headers.push(configureCredentials(options, req));
headers.push(configureMethods(options, req));
headers.push(configureAllowedHeaders(options, req));
headers.push(configureMaxAge(options, req));
headers.push(configureExposedHeaders(options, req));
applyHeaders(headers, res);
if (options.preflightContinue) {
next();
} else {
// Safari (and potentially other browsers) need content-length 0,
// for 204 or they just hang waiting for a body
res.statusCode = options.optionsSuccessStatus;
res.setHeader('Content-Length', '0');
res.end();
}
} else {
// actual response
headers.push(configureOrigin(options, req));
headers.push(configureCredentials(options, req));
headers.push(configureExposedHeaders(options, req));
applyHeaders(headers, res);
next();
}
}
function middlewareWrapper(o) {
// if options are static (either via defaults or custom options passed in), wrap in a function
var optionsCallback = null;
if (typeof o === 'function') {
optionsCallback = o;
} else {
optionsCallback = function (req, cb) {
cb(null, o);
};
}
return function corsMiddleware(req, res, next) {
optionsCallback(req, function (err, options) {
if (err) {
next(err);
} else {
var corsOptions = assign({}, defaults, options);
var originCallback = null;
if (corsOptions.origin && typeof corsOptions.origin === 'function') {
originCallback = corsOptions.origin;
} else if (corsOptions.origin) {
originCallback = function (origin, cb) {
cb(null, corsOptions.origin);
};
}
if (originCallback) {
originCallback(req.headers.origin, function (err2, origin) {
if (err2 || !origin) {
next(err2);
} else {
corsOptions.origin = origin;
cors(corsOptions, req, res, next);
}
});
} else {
next();
}
}
});
};
}
// can pass either an options hash, an options delegate, or nothing
module.exports = middlewareWrapper;
}());
{
"_from": "cors@~2.8.5",
"_id": "cors@2.8.5",
"_inBundle": false,
"_integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"_location": "/cors",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cors@~2.8.5",
"name": "cors",
"escapedName": "cors",
"rawSpec": "~2.8.5",
"saveSpec": null,
"fetchSpec": "~2.8.5"
},
"_requiredBy": [
"/engine.io"
],
"_resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"_shasum": "eac11da51592dd86b9f06f6e7ac293b3df875d29",
"_spec": "cors@~2.8.5",
"_where": "C:\\Users\\bshoo\\Desktop\\OSS\\Singer-Composer\\node_modules\\engine.io",
"author": {
"name": "Troy Goode",
"email": "troygoode@gmail.com",
"url": "https://github.com/troygoode/"
},
"bugs": {
"url": "https://github.com/expressjs/cors/issues"
},
"bundleDependencies": false,
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"deprecated": false,
"description": "Node.js CORS middleware",
"devDependencies": {
"after": "0.8.2",
"eslint": "2.13.1",
"express": "4.16.3",
"mocha": "5.2.0",
"nyc": "13.1.0",
"supertest": "3.3.0"
},
"engines": {
"node": ">= 0.10"
},
"files": [
"lib/index.js",
"CONTRIBUTING.md",
"HISTORY.md",
"LICENSE",
"README.md"
],
"homepage": "https://github.com/expressjs/cors#readme",
"keywords": [
"cors",
"express",
"connect",
"middleware"
],
"license": "MIT",
"main": "./lib/index.js",
"name": "cors",
"repository": {
"type": "git",
"url": "git+https://github.com/expressjs/cors.git"
},
"scripts": {
"lint": "eslint lib test",
"test": "npm run lint && nyc --reporter=html --reporter=text mocha --require test/support/env"
},
"version": "2.8.5"
}
## [5.0.2](https://github.com/socketio/engine.io-parser/compare/5.0.1...5.0.2) (2021-11-14)
### Bug Fixes
* add package name in nested package.json ([7e27159](https://github.com/socketio/engine.io-parser/commit/7e271596c3305fb4e4a9fbdcc7fd442e8ff71200))
* fix vite build for CommonJS users ([5f22ed0](https://github.com/socketio/engine.io-parser/commit/5f22ed0527cc80aa0cac415dfd12db2f94f0a855))
## [5.0.1](https://github.com/socketio/engine.io-parser/compare/5.0.0...5.0.1) (2021-10-15)
### Bug Fixes
* fix vite build ([900346e](https://github.com/socketio/engine.io-parser/commit/900346ea34ddc178d80eaabc8ea516d929457855))
# [5.0.0](https://github.com/socketio/engine.io-parser/compare/4.0.3...5.0.0) (2021-10-04)
This release includes the migration to TypeScript. The major bump is due to the new "exports" field in the package.json file.
See also: https://nodejs.org/api/packages.html#packages_package_entry_points
## [4.0.3](https://github.com/socketio/engine.io-parser/compare/4.0.2...4.0.3) (2021-08-29)
### Bug Fixes
* respect the offset and length of TypedArray objects ([6d7dd76](https://github.com/socketio/engine.io-parser/commit/6d7dd76130690afda6c214d5c04305d2bbc4eb4d))
## [4.0.2](https://github.com/socketio/engine.io-parser/compare/4.0.1...4.0.2) (2020-12-07)
### Bug Fixes
* add base64-arraybuffer as prod dependency ([2ccdeb2](https://github.com/socketio/engine.io-parser/commit/2ccdeb277955bed8742a29f2dcbbf57ca95eb12a))
## [2.2.1](https://github.com/socketio/engine.io-parser/compare/2.2.0...2.2.1) (2020-09-30)
## [4.0.1](https://github.com/socketio/engine.io-parser/compare/4.0.0...4.0.1) (2020-09-10)
### Bug Fixes
* use a terser-compatible representation of the separator ([886f9ea](https://github.com/socketio/engine.io-parser/commit/886f9ea7c4e717573152c31320f6fb6c6664061b))
# [4.0.0](https://github.com/socketio/engine.io-parser/compare/v4.0.0-alpha.1...4.0.0) (2020-09-08)
This major release contains the necessary changes for the version 4 of the Engine.IO protocol. More information about the new version can be found [there](https://github.com/socketio/engine.io-protocol#difference-between-v3-and-v4).
Encoding changes between v3 and v4:
- encodePacket with string
- input: `{ type: "message", data: "hello" }`
- output in v3: `"4hello"`
- output in v4: `"4hello"`
- encodePacket with binary
- input: `{ type: 'message', data: <Buffer 01 02 03> }`
- output in v3: `<Buffer 04 01 02 03>`
- output in v4: `<Buffer 01 02 03>`
- encodePayload with strings
- input: `[ { type: 'message', data: 'hello' }, { type: 'message', data: '€€€' } ]`
- output in v3: `"6:4hello4:4€€€"`
- output in v4: `"4hello\x1e4€€€"`
- encodePayload with string and binary
- input: `[ { type: 'message', data: 'hello' }, { type: 'message', data: <Buffer 01 02 03> } ]`
- output in v3: `<Buffer 00 06 ff 34 68 65 6c 6c 6f 01 04 ff 04 01 02 03>`
- output in v4: `"4hello\x1ebAQID"`
Please note that the parser is now dependency-free! This should help reduce the size of the browser bundle.
### Bug Fixes
* keep track of the buffer initial length ([8edf2d1](https://github.com/socketio/engine.io-parser/commit/8edf2d1478026da442f519c2d2521af43ba01832))
### Features
* restore the upgrade mechanism ([6efedfa](https://github.com/socketio/engine.io-parser/commit/6efedfa0f3048506a4ba99e70674ddf4c0732e0c))
# [4.0.0-alpha.1](https://github.com/socketio/engine.io-parser/compare/v4.0.0-alpha.0...v4.0.0-alpha.1) (2020-05-19)
### Features
* implement the version 4 of the protocol ([cab7db0](https://github.com/socketio/engine.io-parser/commit/cab7db0404e0a69f86a05ececd62c8c31f4d97d5))
# [4.0.0-alpha.0](https://github.com/socketio/engine.io-parser/compare/2.2.0...v4.0.0-alpha.0) (2020-02-04)
### Bug Fixes
* properly decode binary packets ([5085373](https://github.com/socketio/engine.io-parser/commit/50853738e0c6c16f9cee0d7887651155f4b78240))
### Features
* remove packet type when encoding binary packets ([a947ae5](https://github.com/socketio/engine.io-parser/commit/a947ae59a2844e4041db58ff36b270d1528b3bee))
### BREAKING CHANGES
* the packet containing binary data will now be sent without any transformation
Protocol v3: { type: 'message', data: <Buffer 01 02 03> } => <Buffer 04 01 02 03>
Protocol v4: { type: 'message', data: <Buffer 01 02 03> } => <Buffer 01 02 03>
# [2.2.0](https://github.com/socketio/engine.io-parser/compare/2.1.3...2.2.0) (2019-09-13)
* [refactor] Use `Buffer.allocUnsafe` instead of `new Buffer` (#104) ([aedf8eb](https://github.com/socketio/engine.io-parser/commit/aedf8eb29e8bf6aeb5c6cc68965d986c4c958ae2)), closes [#104](https://github.com/socketio/engine.io-parser/issues/104)
### BREAKING CHANGES
* drop support for Node.js 4 (since Buffer.allocUnsafe was added in v5.10.0)
Reference: https://nodejs.org/docs/latest/api/buffer.html#buffer_class_method_buffer_allocunsafe_size
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.